PageSourceSearch

https://portal.enlassa.ai/assets/index-CHBia7bu.js

js enlassa.ai collected 2026-10-05 15:18:47 UTC 1,606,109 bytes, 980 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/tenants--yBXDEZ8.js","assets/embed-DzZnFwh5.js","assets/embed-13eumTo2.css","assets/MarkdownMessage-C9y0smex.js","assets/MiniKPI-CQKWKkXA.js","assets/power-ozOlWZsW.js","assets/tenant-detail-DAbx3Pks.js","assets/coins-Cet4xwdr.js","assets/usage-7gnImsEQ.js","assets/wifi-CTq29JNf.js","assets/ai-keys-CzeeyLxH.js","assets/network-7wiTBd3L.js","assets/numbers-qNjC-nW6.js","assets/server-CH_lrceG.js","assets/stt-_3vKAz_6.js","assets/voices-D1l0MdTg.js","assets/Slider-CdNnJPwS.js","assets/rates-Dd37kzjL.js","assets/plans-VlNKAXNs.js","assets/recording-Ciro7U9e.js","assets/plug-zap-B2fygscI.js","assets/whatsapp-jFVQvQry.js","assets/workflows-DZWNEGch.js","assets/flow-pestanas-B6clLabv.js","assets/octagon-x-_kBPsfGi.js","assets/correo-BPufb6C1.js","assets/registro-QDuOJbr4.js","assets/email-avbmRqsq.js","assets/account-PRSP_Yeu.js","assets/voicemail-patterns-BBfyrYVA.js","assets/audit-DTsFaSIc.js","assets/filter-ucqfQxjB.js","assets/payments-BX1_xQY4.js","assets/margin-69L7eGby.js","assets/StatCard-Dra8Mc3z.js","assets/percent-moDD5b_X.js","assets/dashboard-DOBl1Cye.js","assets/rocket-B9uyk-s4.js","assets/churn-DFszf9A1.js","assets/RiskBadge-CrxI2F0U.js","assets/health-CybLcEA_.js","assets/comparatives-Cu3TzsZf.js","assets/seo-geo-BOS9IrYQ.js","assets/mouse-pointer-click-Q1jblQ3i.js","assets/playbook-BHYdh3Bk.js","assets/knowledge-DIzNnRar.js","assets/meetings-BakmkjMD.js","assets/correo-C3_Gaeex.js","assets/email-status-color-DzQlQ7Oh.js","assets/Timeline-CrsOWdJ-.js","assets/CursorPager-EFDBvtJg.js","assets/ellipsis-vertical-KSWCa49f.js","assets/mail-open-BeME3YfD.js","assets/correo.campanas._campaignId-BPJv81oF.js","assets/ColumnChartCard-ChwR9kII.js","assets/correo.editor-BH3uSzlB.js","assets/useEmailThemeDraft-kJsifZLO.js","assets/DatePicker-UFWBO349.js","assets/TimePicker-s4P94gZL.js","assets/redo-2-D2DPMbQL.js","assets/TemplateEditorPage-Du65Br7P.js","assets/contactos-CLZwwwaq.js","assets/campaigns-C3IYgpTd.js","assets/campaign-pipeline-D9O_qf6t.js","assets/campaigns.new-Bxno9Ntb.js","assets/CapacitySection-DP9RgrXx.js","assets/campaigns._campaignId-DZm24GvM.js","assets/meetings-B0_Ci28z.js","assets/meetings._meetingId-Clc_Wa2U.js","assets/file-down-DCnIXNec.js","assets/copilot-Bg1hiset.js","assets/whatsapp-plantillas-7Q_AAR4x.js","assets/presentacion-oRIiEdOz.js","assets/DeviceFrame-DOKyDF-p.js","assets/workflows._flowId-BJSo8-WE.js","assets/flow-catalogo-BE7dVnjq.js","assets/RegistroDeCorridas-BmhuVFv8.js","assets/MiniaturaDeFlujo-D_1I-svN.js","assets/TextListEditor-BU8pcF-Y.js","assets/timer-Dmfd5lNu.js","assets/workflows-BnuhLJ6X.css","assets/workflows.plantillas-DbjcmTsR.js","assets/workflows.corridas-C9oU_T4B.js","assets/whatsapp-plantillas.editor-Bgp6H8ej.js"])))=>i.map(i=>d[i]);
2import{aa as m,a4 as t,s as Xa,a9 as Ti,V as yj,an as Wg,Y as vj,$ as Ug,a3 as Fr,am as td,a2 as vs,I as Vg,a1 as he,_ as Le,N as Q,o as Ta,c as Il,m as sn,ai as M,X as nt,x as Tt,C as ct,h as Qa,Z as pm,k as Lt,Q as jj,ac as wj,i as pc,ah as Kg,T as Ra,L as je,e as Ut,b as Hg,g as Nt,B as Ie,ag as kj,U as Nj,l as Sj,a0 as Cj,F as _j,f as Qg,S as ge,q as Or,y as Ej,t as Aj,u as fr,w as hm,H as Gg,al as Rj,K as ad,P as Ts,p as Ap,ab as Tj,aj as Mj,af as wt,a7 as Pj,ae as zj,D as Rp,d as Dj,W as Ij,O as Lj,G as Fj,a8 as Oj,z as $j,ak as qj,a5 as Bj,a6 as Wj,a as du,j as nd,A as Ll,M as Do,n as Uj,r as Vj,E as Kj}from"./embed-DzZnFwh5.js";import{ay as Hj,I as Tp,E as st,m as Mi,i as cs,B as le,c as Io,l as Qj,M as Mp,z as Gj}from"./MarkdownMessage-C9y0smex.js";var mm=m.use,xr=typeof window<"u"?m.useLayoutEffect:m.useEffect;function sd(e){const a=m.useRef({value:e,prev:null}),n=a.current.value;return e!==n&&(a.current={value:e,prev:n}),a.current.prev}function Zj(e,a,n={},s={}){m.useEffect(()=>{if(!e.current||s.disabled||typeof IntersectionObserver!="function")return;const i=new IntersectionObserver(([r])=>{a(r)},n);return i.observe(e.current),()=>{i.disconnect()}},[a,n,s.disabled,e])}function Yj(e){const a=m.useRef(null);return m.useImperativeHandle(e,()=>a.current,[]),a}const Zg=!1;function $r(e){return e[e.length-1]}function Xj(e){return typeof e=="function"}function js(e,a){return Xj(e)?e(a):e}const Yg=Object.prototype.hasOwnProperty,fm=Object.prototype.propertyIsEnumerable;function Xg(e){for(const a in e)if(Yg.call(e,a))return!0;return!1}const Jj=()=>Object.create(null),hs=(e,a)=>Un(e,a,Jj);function Un(e,a,n=()=>({}),s=0){if(e===a)return e;if(s>500)return a;const i=a,r=bm(e)&&bm(i);if(!r&&!(Fl(e)&&Fl(i)))return i;const o=r?e:xm(e);if(!o)return i;const l=r?i:xm(i);if(!l)return i;const c=o.length,d=l.length,u=r?new Array(d):n();let p=0;for(let f=0;f<d;f++){const x=r?f:l[f],h=e[x],b=i[x];if(h===b){u[x]=h,(r?f<c:Yg.call(e,x))&&p++;continue}if(h===null||b===null||typeof h!="object"||typeof b!="object"){u[x]=b;continue}const g=Un(h,b,n,s+1);u[x]=g,g===h&&p++}return c===d&&p===c?e:u}function xm(e){const a=Object.getOwnPropertyNames(e);for(const i of a)if(!fm.call(e,i))return!1;const n=Object.getOwnPropertySymbols(e);if(n.length===0)return a;const s=a;for(const i of n){if(!fm.call(e,i))return!1;s.push(i)}return s}function Fl(e){if(!gm(e))return!1;const a=e.constructor;if(typeof a>"u")return!0;const n=a.prototype;return!(!gm(n)||!n.hasOwnProperty("isPrototypeOf"))}function gm(e){return Object.prototype.toString.call(e)==="[object Object]"}function bm(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ss(e,a,n){if(e===a)return!0;
2if(typeof e!=typeof a)return!1;if(Array.isArray(e)&&Array.isArray(a)){if(e.length!==a.length)return!1;for(let s=0,i=e.length;s<i;s++)if(!Ss(e[s],a[s],n))return!1;return!0}if(Fl(e)&&Fl(a)){const s=n?.ignoreUndefined??!0;if(n?.partial){for(const o in a)if((!s||a[o]!==void 0)&&!Ss(e[o],a[o],n))return!1;return!0}let i=0;if(!s)i=Object.keys(e).length;else for(const o in e)e[o]!==void 0&&i++;let r=0;for(const o in a)if((!s||a[o]!==void 0)&&(r++,r>i||!Ss(e[o],a[o],n)))return!1;return i===r}return!1}function gi(e){let a,n;const s=new Promise((i,r)=>{a=i,n=r});return s.status="pending",s.resolve=i=>{s.status="resolved",s.value=i,a(i),e?.(i)},s.reject=i=>{s.status="rejected",n(i)},s}function ew(e){return typeof e?.message!="string"?!1:e.message.startsWith("Failed to fetch dynamically imported module")||e.message.startsWith("error loading dynamically imported module")||e.message.startsWith("Importing a module script failed")}function qr(e){return!!(e&&typeof e=="object"&&typeof e.then=="function")}function tw(e){return e.replace(/[\x00-\x1f\x7f]/g,"")}function ym(e){let a;try{a=decodeURI(e)}catch{a=e.replaceAll(/%[0-9A-F]{2}/gi,n=>{try{return decodeURI(n)}catch{return n}})}return tw(a)}const aw=["http:","https:","mailto:","tel:"];function Ol(e,a){if(!e)return!1;try{const n=new URL(e);return!a.has(n.protocol)}catch{return!1}}function Gi(e){if(!e)return{path:e,handledProtocolRelativeURL:!1};if(!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith("//"))return{path:e,handledProtocolRelativeURL:!1};const a=/%25|%5C/gi;let n=0,s="",i;for(;(i=a.exec(e))!==null;)s+=ym(e.slice(n,i.index))+i[0],n=a.lastIndex;s=s+ym(n?e.slice(n):e);let r=!1;return s.startsWith("//")&&(r=!0,s="/"+s.replace(/^\/+/,"")),{path:s,handledProtocolRelativeURL:r}}function nw(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function sw(e,a){if(e===a)return!0;if(e.length!==a.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==a[n])return!1;return!0}function Cn(){throw new Error("Invariant failed")}function Br(e){const a=new Map;let n,s;const i=r=>{r.next&&(r.prev?(r.prev.next=r.next,r.next.prev=r.prev,r.next=void 0,s&&(s.next=r,r.prev=s)):(r.next.prev=void 0,n=r.next,r.next=void 0,s&&(r.prev=s,s.next=r)),s=r)};return{get(r){const o=a.get(r);if(o)return i(o),o.value},set(r,o){if(a.size>=e&&n){const c=n;a.delete(c.key),c.next&&(n=c.next,c.next.prev=void 0),c===s&&(s=void 0)}const l=a.get(r);if(l)l.value=o,i(l);else{const c={key:r,value:o,prev:s};s&&(s.next=c),s=c,n||(n=c),a.set(r,c)}},clear(){a.clear(),n=void 0,s=void 0}}}const Vn=4,Jg=5;function iw(e){const a=e.indexOf("{");if(a===-1)return null;const n=e.indexOf("}",a);return n===-1||a+1>=e.length?null:[a,n]}function eb(e,a,n=new Uint16Array(6)){const s=e.indexOf("/",a),i=s===-1?e.length:s,r=e.substring(a,i);if(!r||!r.includes("$"))return n[0]=0,n[1]=a,n[2]=a,n[3]=i,n[4]=i,n[5]=i,n;if(r==="$"){const l=e.length;return n[0]=2,n[1]=a,n[2]=a,n[3]=l,n[4]=l,n[5]=l,n}if(r.charCodeAt(0)===36)return n[0]=1,n[1]=a,n[2]=a+1,n[3]=i,n[4]=i,n[5]=i,n;const o=iw(r);if(o){const[l,c]=o,d=r.charCodeAt(l+1);if(d===45){if(l+2<r.length&&r.charCodeAt(l+2)===36){const u=l+3,p=c;if(u<p)return n[0]=3,n[1]=a+l,n[2]=a+u,n[3]=a+p,n[4]=a+c+1,n[5]=i,n}}else if(d===36){const u=l+1,p=l+2;return p===c?(n[0]=2,n[1]=a+l,n[2]=a+u,n[3]=a+p,n[4]=a+c+1,n[5]=e.length,n):(n[0]=1,n[1]=a+l,n[2]=a+p,n[3]=a+c,n[4]=a+c+1,n[5]=i,n)}}return n[0]=0,n[1]=a,n[2]=a,n[3]=i,n[4]=i,n[5]=i,n}function hc(e,a,n,s,i,r,o){o?.(n);let l=s;{const c=n.fullPath??n.from,d=c.length,u=n.options?.caseSensitive??e,p=n.options?.params?.parse??n.options?.parseParams;for(;l<d;){const x=eb(c,l,a);let h;const b=l,g=x[5];switch(l=g+1,r++,x[0]){case 0:{const v=c.substring(x[2],x[3]);if(u){const y=i.static?.get(v);if(y)h=y;else{i.static??=new Map;const k=ws(n.fullPath??n.from);k.parent=i,k.depth=r,h=k,i.static.set(v,k)}}else{const y=v.toLowerCase(),k=i.staticInsensitive?.get(y);if(k)h=k;else{i.staticInsensitive??=new Map;const w=ws(n.fullPath??n.from);w.parent=i,w.depth=r,h=w,i.staticInsensitive.set(y,w)}}break}case 1:{const v=c.substring(b,x[1]),y=c.substring(x[4],g),k=u&&!!(v||y),w=v?k?v:v.toLowerCase():void 0,j=y?k?y:y.toLowerCase():void 0,C=!p&&i.dynamic?.find(N=>!N.parse&&N.caseSensitive===k&&N.prefix===w&&N.suffix===j);if(C)h=C;else{const N=rd(1,n.fullPath??n.from,k,w,j);h=N,N.depth=r,N.parent=i,i.dynamic??=[],i.dynamic.push(N)}break}case 3:{const v=c.substring(b,x[1]),y=c.substring(x[4],g),k=u&&!!(v||y),w=v?k?v:v.toLowerCase():void 0,j=y?k?y:y.toLowerCase():void 0,C=!p&&i.optional?.find(N=>!N.parse&&N.caseSensitive===k&&N.prefix===w&&N.suffix===j);if(C)h=C;else{const N=rd(3,n.fullPath??n.from,k,w,j);
2h=N,N.parent=i,N.depth=r,i.optional??=[],i.optional.push(N)}break}case 2:{const v=c.substring(b,x[1]),y=c.substring(x[4],g),k=u&&!!(v||y),w=v?k?v:v.toLowerCase():void 0,j=y?k?y:y.toLowerCase():void 0,C=rd(2,n.fullPath??n.from,k,w,j);h=C,C.parent=i,C.depth=r,i.wildcard??=[],i.wildcard.push(C)}}i=h}if(p&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf("/")+1)===95){const x=ws(n.fullPath??n.from);x.kind=Jg,x.parent=i,r++,x.depth=r,i.pathless??=[],i.pathless.push(x),i=x}const f=(n.path||!n.children)&&!n.isRoot;if(f&&c.endsWith("/")){const x=ws(n.fullPath??n.from);x.kind=Vn,x.parent=i,r++,x.depth=r,i.index=x,i=x}i.parse=p??null,i.priority=n.options?.params?.priority??0,f&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(const c of n.children)hc(e,a,c,l,i,r,o)}function id(e,a){if(e.parse&&!a.parse)return-1;if(!e.parse&&a.parse)return 1;if(e.parse&&a.parse&&(e.priority||a.priority))return a.priority-e.priority;if(e.prefix&&a.prefix&&e.prefix!==a.prefix){if(e.prefix.startsWith(a.prefix))return-1;if(a.prefix.startsWith(e.prefix))return 1}if(e.suffix&&a.suffix&&e.suffix!==a.suffix){if(e.suffix.endsWith(a.suffix))return-1;if(a.suffix.endsWith(e.suffix))return 1}return e.prefix&&!a.prefix?-1:!e.prefix&&a.prefix?1:e.suffix&&!a.suffix?-1:!e.suffix&&a.suffix?1:e.caseSensitive&&!a.caseSensitive?-1:!e.caseSensitive&&a.caseSensitive?1:0}function On(e){if(e.pathless)for(const a of e.pathless)On(a);if(e.static)for(const a of e.static.values())On(a);if(e.staticInsensitive)for(const a of e.staticInsensitive.values())On(a);if(e.dynamic?.length){e.dynamic.sort(id);for(const a of e.dynamic)On(a)}if(e.optional?.length){e.optional.sort(id);for(const a of e.optional)On(a)}if(e.wildcard?.length){e.wildcard.sort(id);
2for(const a of e.wildcard)On(a)}}function ws(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function rd(e,a,n,s,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:a,parent:null,parse:null,priority:0,caseSensitive:n,prefix:s,suffix:i}}function rw(e,a){const n=ws("/"),s=new Uint16Array(6);for(const i of e)hc(!1,s,i,1,n,0);On(n),a.masksTree=n,a.flatCache=Br(1e3)}function ow(e,a){e||="/";const n=a.flatCache.get(e);if(n)return n;const s=Pp(e,a.masksTree);return a.flatCache.set(e,s),s}function lw(e,a,n,s,i){e||="/",s||="/";const r=a?`case\0${e}`:e;let o=i.singleCache.get(r);return o||(o=ws("/"),hc(a,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(r,o)),Pp(s,o,n)}function cw(e,a,n=!1){const s=n?e:`nofuzz\0${e}`,i=a.matchCache.get(s);if(i!==void 0)return i;e||="/";let r;try{r=Pp(e,a.segmentTree,n)}catch(o){if(o instanceof URIError)r=null;else throw o}return r&&(r.branch=ab(r.route)),a.matchCache.set(s,r),r}function dw(e){return e==="/"?e:e.replace(/\/{1,}$/,"")}function uw(e,a=!1,n){const s=ws(e.fullPath),i=new Uint16Array(6),r={},o={};let l=0;return hc(a,i,e,1,s,0,c=>{if(n?.(c,l),c.id in r&&Cn(),r[c.id]=c,l!==0&&c.path){const d=dw(c.fullPath);(!o[d]||c.fullPath.endsWith("/"))&&(o[d]=c)}l++}),On(s),{processedTree:{segmentTree:s,singleCache:Br(1e3),matchCache:Br(1e3),flatCache:null,masksTree:null},routesById:r,routesByPath:o}}function Pp(e,a,n=!1){const s=e.split("/"),i=hw(e,s,a,n);if(!i)return null;const[r]=tb(e,s,i);return{route:i.node.route,rawParams:r}}function tb(e,a,n){const s=pw(n.node);let i=null;const r=Object.create(null);let o=n.extract?.part??0,l=n.extract?.node??0,c=n.extract?.path??0,d=n.extract?.segment??0;for(;l<s.length;o++,l++,c++,d++){const u=s[l];if(u.kind===Vn)break;if(u.kind===Jg){d--,o--,c--;continue}const p=a[o],f=c;if(p&&(c+=p.length),u.kind===1){i??=n.node.fullPath.split("/");const x=i[d],h=u.prefix?.length??0;if(x.charCodeAt(h)===123){const b=u.suffix?.length??0,g=x.substring(h+2,x.length-b-1),v=p.substring(h,p.length-b);r[g]=decodeURIComponent(v)}else{const b=x.substring(1);r[b]=decodeURIComponent(p)}}else if(u.kind===3){if(n.skipped&1<<l){o--,c=f-1;continue}i??=n.node.fullPath.split("/");const x=i[d],h=u.prefix?.length??0,b=u.suffix?.length??0,g=x.substring(h+3,x.length-b-1),v=u.suffix||u.prefix?p.substring(h,p.length-b):p;v&&(r[g]=decodeURIComponent(v))}else if(u.kind===2){const x=u,h=e.substring(f+(x.prefix?.length??0),e.length-(x.suffix?.length??0)),b=decodeURIComponent(h);r["*"]=b,r._splat=b;break}}return n.rawParams&&Object.assign(r,n.rawParams),[r,{part:o,node:l,path:c,segment:d}]}function ab(e){const a=[e];for(;e.parentRoute;)e=e.parentRoute,a.push(e);return a.reverse(),a}function pw(e){const a=Array(e.depth+1);do a[e.depth]=e,e=e.parent;while(e);return a}function hw(e,a,n,s){if(e==="/"&&n.index)return{node:n.index,skipped:0};const i=!$r(a),r=i&&e!=="/",o=a.length-(i?1:0),l=[{node:n,index:1,skipped:0,depth:1,statics:0,dynamics:0,optionals:0}];let c=null,d=null;for(;l.length;){const u=l.pop(),{node:p,index:f,skipped:x,depth:h,statics:b,dynamics:g,optionals:v}=u;let{extract:y,rawParams:k}=u;if(p.kind===2&&p.route&&!Fo(d,u))continue;if(p.parse){if(!vm(e,a,u))continue;k=u.rawParams,y=u.extract}s&&p.route&&p.kind!==Vn&&Fo(c,u)&&(c=u);const w=f===o;if(w&&(p.route&&(!r||p.kind===Vn||p.kind===2)&&Fo(d,u)&&(d=u),!p.optional&&!p.wildcard&&!p.index&&!p.pathless))continue;const j=w?void 0:a[f];let C;if(w&&p.index){const N={node:p.index,index:f,skipped:x,depth:h+1,statics:b,dynamics:g,optionals:v,extract:y,rawParams:k};let S=!0;if(p.index.parse&&(vm(e,a,N)||(S=!1)),S){if(!g&&!v&&!x&&mw(b,o))return N;Fo(d,N)&&(d=N)}}if(p.wildcard)for(let N=p.wildcard.length-1;N>=0;N--){const S=p.wildcard[N],{prefix:_,suffix:R}=S;if(!(_&&(w||!(S.caseSensitive?j:C??=j.toLowerCase()).startsWith(_)))){if(R){if(w)continue;const A=a.slice(f).join("/").slice(-R.length);if((S.caseSensitive?A:A.toLowerCase())!==R)continue}l.push({node:S,index:o,skipped:x,depth:h+1,statics:b,dynamics:g,optionals:v,extract:y,rawParams:k})}}if(p.optional){const N=x|1<<h,S=h+1;for(let _=p.optional.length-1;_>=0;_--){const R=p.optional[_];l.push({node:R,index:f,skipped:N,depth:S,statics:b,dynamics:g,optionals:v,extract:y,rawParams:k})}if(!w)for(let _=p.optional.length-1;_>=0;_--){const R=p.optional[_],{prefix:A,suffix:E}=R;if(A||E){const I=R.caseSensitive?j:C??=j.toLowerCase();if(A&&!I.startsWith(A)||E&&!I.endsWith(E))continue}l.push({node:R,index:f+1,skipped:x,depth:S,statics:b,dynamics:g,optionals:v+Lo(o,f),extract:y,rawParams:k})}}if(!w&&p.dynamic&&j)for(let N=p.dynamic.length-1;N>=0;N--){const S=p.dynamic[N],{prefix:_,suffix:R}=S;if(_||R){const A=S.caseSensitive?j:C??=j.toLowerCase();if(_&&!A.startsWith(_)||R&&!A.endsWith(R))continue}l.push({node:S,index:f+1,skipped:x,depth:h+1,statics:b,dynamics:g+Lo(o,f),optionals:v,extract:y,rawParams:k})}if(!w&&p.staticInsensitive){const N=p.staticInsensitive.get(C??=j.toLowerCase());N&&l.push({node:N,index:f+1,skipped:x,depth:h+1,statics:b+Lo(o,f),dynamics:g,optionals:v,extract:y,rawParams:k})}if(!w&&p.static){const N=p.static.get(j);N&&l.push({node:N,index:f+1,skipped:x,depth:h+1,statics:b+Lo(o,f),dynamics:g,optionals:v,extract:y,rawParams:k})}if(p.pathless){const N=h+1;for(let S=p.pathless.length-1;S>=0;S--){const _=p.pathless[S];l.push({node:_,index:f,skipped:x,depth:N,statics:b,dynamics:g,optionals:v,extract:y,rawParams:k})}}}if(d)return d;if(s&&c){let u=c.index;for(let f=0;f<c.index;f++)u+=a[f].length;const p=u===e.length?"/":e.slice(u);return c.rawParams??=Object.create(null),c.rawParams["**"]=decodeURIComponent(p),c}return null}function Lo(e,a){return 2**(e-a-1)}function mw(e,a){return e===2**(a-1)-1}function vm(e,a,n){let s,i;try{[s,i]=tb(e,a,n)}catch{return null}if(n.rawParams=s,n.extract=i,!n.node.parse)return!0;try{if(n.node.parse(s)===!1)return null}catch{}return!0}function Fo(e,a){return e?a.statics>e.statics||a.statics===e.statics&&(a.dynamics>e.dynamics||a.dynamics===e.dynamics&&(a.optionals>e.optionals||a.optionals===e.optionals&&((a.node.kind===Vn)>
2(e.node.kind===Vn)||a.node.kind===Vn==(e.node.kind===Vn)&&a.depth>e.depth))):!0}function ml(e){return zp(e.filter(a=>a!==void 0).join("/"))}function zp(e){return e.replace(/\/{2,}/g,"/")}function nb(e){return e==="/"?e:e.replace(/^\/{1,}/,"")}function Nn(e){const a=e.length;return a>1&&e[a-1]==="/"?e.replace(/\/{1,}$/,""):e}function sb(e){return Nn(nb(e))}function $l(e,a){return e?.endsWith("/")&&e!=="/"&&e!==`${a}/`?e.slice(0,-1):e}function fw(e,a,n){return $l(e,n)===$l(a,n)}function xw({base:e,to:a,trailingSlash:n="never",cache:s}){const i=a.startsWith("/"),r=!i&&a===".";let o;if(s){o=i?a:r?e:e+"\0"+a;const d=s.get(o);if(d)return d}let l;if(r)l=e.split("/");else if(i)l=a.split("/");else{for(l=e.split("/");l.length>1&&$r(l)==="";)l.pop();const d=a.split("/");for(let u=0,p=d.length;u<p;u++){const f=d[u];f===""?u?u===p-1&&l.push(f):l=[f]:f===".."?l.pop():f==="."||l.push(f)}}l.length>1&&($r(l)===""?n==="never"&&l.pop():n==="always"&&l.push(""));const c=zp(l.join("/"))||"/";return o&&s&&s.set(o,c),c}function gw(e){const a=new Map(e.map(i=>[encodeURIComponent(i),i])),n=Array.from(a.keys()).map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),s=new RegExp(n,"g");return i=>i.replace(s,r=>a.get(r)??r)}function od(e,a,n){const s=a[e];return typeof s!="string"?s:e==="_splat"?/^[a-zA-Z0-9\-._~!/]*$/.test(s)?s:s.split("/").map(i=>wm(i,n)).join("/"):wm(s,n)}function jm({path:e,params:a,decoder:n,...s}){let i=!1;const r=Object.create(null);if(!e||e==="/")return{interpolatedPath:"/",usedParams:r,isMissingParams:i};if(!e.includes("$"))return{interpolatedPath:e,usedParams:r,isMissingParams:i};const o=e.length;let l=0,c,d="";for(;l<o;){const u=l;c=eb(e,u,c);const p=c[5];if(l=p+1,u===p)continue;const f=c[0];if(f===0){d+="/"+e.substring(u,p);continue}if(f===2){const x=a._splat;r._splat=x,r["*"]=x;const h=e.substring(u,c[1]),b=e.substring(c[4],p);if(!x){i=!0,(h||b)&&(d+="/"+h+b);continue}const g=od("_splat",a,n);d+="/"+h+g+b;continue}if(f===1){const x=e.substring(c[2],c[3]);!i&&!(x in a)&&(i=!0),r[x]=a[x];const h=e.substring(u,c[1]),b=e.substring(c[4],p),g=od(x,a,n)??"undefined";d+="/"+h+g+b;continue}if(f===3){const x=e.substring(c[2],c[3]),h=a[x];if(h==null)continue;r[x]=h;const b=e.substring(u,c[1]),g=e.substring(c[4],p),v=od(x,a,n)??"";d+="/"+b+v+g;continue}}return e.endsWith("/")&&(d+="/"),{usedParams:r,interpolatedPath:d||"/",isMissingParams:i}}function wm(e,a){const n=encodeURIComponent(e);return a?.(n)??n}function ta(e){return e?.isNotFound===!0}function bw(e,a=String){const n=new URLSearchParams;for(const s in e){const i=e[s];i!==void 0&&n.set(s,a(i))}return n.toString()}function ld(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function yw(e){const a=new URLSearchParams(e),n=Object.create(null);for(const[s,i]of a.entries()){const r=n[s];r==null?n[s]=ld(i):Array.isArray(r)?r.push(ld(i)):n[s]=[r,ld(i)]}return n}const vw=ww(JSON.parse),jw=kw(JSON.stringify,JSON.parse);function ww(e){return a=>{a[0]==="?"&&(a=a.substring(1));const n=yw(a);for(const s in n){const i=n[s];if(typeof i=="string")try{n[s]=e(i)}catch{}}return n}}function kw(e,a){const n=typeof a=="function";function s(i){if(typeof i=="object"&&i!==null)try{return e(i)}catch{}else if(n&&typeof i=="string")try{return a(i),e(i)}catch{}return i}return i=>{const r=bw(i,s);return r?`?${r}`:""}}const Cs="__root__";function Wa(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href=="string")try{new URL(e.href),e.reloadDocument=!0}catch{}const a=new Headers(e.headers);e.href&&a.get("Location")===null&&a.set("Location",e.href);const n=new Response(null,{status:e.statusCode,headers:a});if(n.options=e,e.throw)throw n;return n}function va(e){return e instanceof Response&&!!e.options}const uu=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},Nw=e=>e.stores.matchesId.get().some(a=>e.stores.matchStores.get(a)?.get()._forcePending),mc=(e,a)=>!!(e.preload&&!e.router.stores.matchStores.has(a)),_s=(e,a,n=!0)=>{const s={...e.router.options.context??{}},i=n?a:a-1;for(let r=0;r<=i;r++){const o=e.matches[r];if(!o)continue;const l=e.router.getMatch(o.id);
2l&&Object.assign(s,l.__routeContext,l.__beforeLoadContext)}return s},km=(e,a)=>{if(!e.matches.length)return;const n=a.routeId,s=e.matches.findIndex(o=>o.routeId===e.router.routeTree.id),i=s>=0?s:0;let r=n?e.matches.findIndex(o=>o.routeId===n):e.firstBadMatchIndex??e.matches.length-1;r<0&&(r=i);for(let o=r;o>=0;o--){const l=e.matches[o];if(e.router.looseRoutesById[l.routeId].options.notFoundComponent)return o}return n?r:i},Kn=(e,a,n)=>{if(!(!va(n)&&!ta(n)))throw va(n)&&n.redirectHandled&&!n.options.reloadDocument||(a&&(a._nonReactive.beforeLoadPromise?.resolve(),a._nonReactive.loaderPromise?.resolve(),a._nonReactive.beforeLoadPromise=void 0,a._nonReactive.loaderPromise=void 0,a._nonReactive.error=n,e.updateMatch(a.id,s=>({...s,status:va(n)?"redirected":ta(n)?"notFound":s.status==="pending"?"success":s.status,context:_s(e,a.index),isFetching:!1,error:n})),ta(n)&&!n.routeId&&(n.routeId=a.routeId),a._nonReactive.loadPromise?.resolve()),va(n)&&(e.rendered=!0,n.options._fromLocation=e.location,n.redirectHandled=!0,n=e.router.resolveRedirect(n))),n},ib=(e,a)=>{const n=e.router.getMatch(a);return!!(!n||n._nonReactive.dehydrated)},Nm=(e,a,n)=>{const s=_s(e,n);e.updateMatch(a,i=>({...i,context:s}))},Zi=(e,a,n,s)=>{const{id:i,routeId:r}=e.matches[a],o=e.router.looseRoutesById[r];if(n instanceof Promise)throw n;n.routerCode=s,e.firstBadMatchIndex??=a,Kn(e,e.router.getMatch(i),n);try{o.options.onError?.(n)}catch(l){n=l,Kn(e,e.router.getMatch(i),n)}e.updateMatch(i,l=>(l._nonReactive.beforeLoadPromise?.resolve(),l._nonReactive.beforeLoadPromise=void 0,l._nonReactive.loadPromise?.resolve(),{...l,error:n,status:"error",isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!va(n)&&!ta(n)&&(e.serialError??=n)},rb=(e,a,n,s)=>{if(s._nonReactive.pendingTimeout!==void 0)return;const i=n.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!mc(e,a)&&(n.options.loader||n.options.beforeLoad||lb(n))&&typeof i=="number"&&i!==1/0&&(n.options.pendingComponent??e.router.options?.defaultPendingComponent)){const r=setTimeout(()=>{uu(e)},i);s._nonReactive.pendingTimeout=r}},Sw=(e,a,n)=>{const s=e.router.getMatch(a);if(!s._nonReactive.beforeLoadPromise&&!s._nonReactive.loaderPromise)return;rb(e,a,n,s);const i=()=>{const r=e.router.getMatch(a);r.preload&&(r.status==="redirected"||r.status==="notFound")&&Kn(e,r,r.error)};return s._nonReactive.beforeLoadPromise?s._nonReactive.beforeLoadPromise.then(i):i()},Cw=(e,a,n,s)=>{const i=e.router.getMatch(a);let r=i._nonReactive.loadPromise;i._nonReactive.loadPromise=gi(()=>{r?.resolve(),r=void 0});const{paramsError:o,searchError:l}=i;o&&Zi(e,n,o,"PARSE_PARAMS"),l&&Zi(e,n,l,"VALIDATE_SEARCH"),rb(e,a,s,i);const c=new AbortController;let d=!1;const u=()=>{d||(d=!0,e.updateMatch(a,w=>({...w,isFetching:"beforeLoad",fetchCount:w.fetchCount+1,abortController:c})))},p=()=>{i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,e.updateMatch(a,w=>({...w,isFetching:!1}))};if(!s.options.beforeLoad){e.router.batch(()=>{u(),p()});return}i._nonReactive.beforeLoadPromise=gi();const f={..._s(e,n,!1),...i.__routeContext},{search:x,params:h,cause:b}=i,g=mc(e,a),v={search:x,abortController:c,params:h,preload:g,context:f,location:e.location,navigate:w=>e.router.navigate({...w,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:g?"preload":b,matches:e.matches,routeId:s.id,...e.router.options.additionalContext},y=w=>{if(w===void 0){e.router.batch(()=>{u(),p()});return}(va(w)||ta(w))&&(u(),Zi(e,n,w,"BEFORE_LOAD")),e.router.batch(()=>{u(),e.updateMatch(a,j=>({...j,__beforeLoadContext:w})),p()})};let k;
2try{if(k=s.options.beforeLoad(v),qr(k))return u(),k.catch(w=>{Zi(e,n,w,"BEFORE_LOAD")}).then(y)}catch(w){u(),Zi(e,n,w,"BEFORE_LOAD")}y(k)},_w=(e,a)=>{const{id:n,routeId:s}=e.matches[a],i=e.router.looseRoutesById[s],r=()=>l(),o=()=>Cw(e,n,a,i),l=()=>{if(ib(e,n))return;const c=Sw(e,n,i);return qr(c)?c.then(o):o()};return r()},Ew=(e,a,n)=>{const s=e.router.getMatch(a);if(!s||!n.options.head&&!n.options.scripts&&!n.options.headers)return;const i={ssr:e.router.options.ssr,matches:e.matches,match:s,params:s.params,loaderData:s.loaderData};return Promise.all([n.options.head?.(i),n.options.scripts?.(i),n.options.headers?.(i)]).then(([r,o,l])=>({meta:r?.meta,links:r?.links,headScripts:r?.scripts,headers:l,scripts:o,styles:r?.styles}))},ob=(e,a,n,s,i)=>{const r=a[s-1],{params:o,loaderDeps:l,abortController:c,cause:d}=e.router.getMatch(n),u=_s(e,s),p=mc(e,n);return{params:o,deps:l,preload:!!p,parentMatchPromise:r,abortController:c,context:u,location:e.location,navigate:f=>e.router.navigate({...f,_fromLocation:e.location}),cause:p?"preload":d,route:i,...e.router.options.additionalContext}},Sm=async(e,a,n,s,i)=>{try{const r=e.router.getMatch(n);try{(!(Zg??e.router.isServer)||r.ssr===!0)&&Wr(i);const o=i.options.loader,l=typeof o=="function"?o:o?.handler,c=l?.(ob(e,a,n,s,i)),d=!!l&&qr(c);if((d||i._lazyPromise||i._componentsPromise||i.options.head||i.options.scripts||i.options.headers||r._nonReactive.minPendingPromise)&&e.updateMatch(n,p=>({...p,isFetching:"loader"})),l){const p=d?await c:c;Kn(e,e.router.getMatch(n),p),p!==void 0&&e.updateMatch(n,f=>({...f,loaderData:p}))}i._lazyPromise&&await i._lazyPromise;const u=r._nonReactive.minPendingPromise;u&&await u,i._componentsPromise&&await i._componentsPromise,e.updateMatch(n,p=>({...p,error:void 0,context:_s(e,s),status:"success",isFetching:!1,updatedAt:Date.now()}))}catch(o){let l=o;if(l?.name==="AbortError"){if(r.abortController.signal.aborted){r._nonReactive.loaderPromise?.resolve(),r._nonReactive.loaderPromise=void 0;return}e.updateMatch(n,d=>({...d,status:d.status==="pending"?"success":d.status,isFetching:!1,context:_s(e,s)}));return}const c=r._nonReactive.minPendingPromise;c&&await c,ta(o)&&await i.options.notFoundComponent?.preload?.(),Kn(e,e.router.getMatch(n),o);try{i.options.onError?.(o)}catch(d){l=d,Kn(e,e.router.getMatch(n),d)}!va(l)&&!ta(l)&&await Wr(i,["errorComponent"]),e.updateMatch(n,d=>({...d,error:l,context:_s(e,s),status:"error",isFetching:!1}))}}catch(r){const o=e.router.getMatch(n);o&&(o._nonReactive.loaderPromise=void 0),Kn(e,o,r)}},Aw=async(e,a,n)=>{async function s(x,h,b,g,v){const y=Date.now()-h.updatedAt,k=x?v.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:v.options.staleTime??e.router.options.defaultStaleTime??0,w=v.options.shouldReload,j=typeof w=="function"?w(ob(e,a,i,n,v)):w,{status:C,invalid:N}=g,S=y>=k&&(!!e.forceStaleReload||g.cause==="enter"||b!==void 0&&b!==g.id);o=C==="success"&&(N||(j??S)),x&&v.options.preload===!1||(o&&!e.sync&&u?(l=!0,(async()=>{try{await Sm(e,a,i,n,v);const _=e.router.getMatch(i);_._nonReactive.loaderPromise?.resolve(),_._nonReactive.loadPromise?.resolve(),_._nonReactive.loaderPromise=void 0,_._nonReactive.loadPromise=void 0}catch(_){va(_)&&await e.router.navigate(_.options)}})()):C!=="success"||o?await Sm(e,a,i,n,v):Nm(e,i,n))}const{id:i,routeId:r}=e.matches[n];let o=!1,l=!1;const c=e.router.looseRoutesById[r],d=c.options.loader,u=((typeof d=="function"?void 0:d?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!=="blocking";if(ib(e,i)){if(!e.router.getMatch(i))return e.matches[n];Nm(e,i,n)}else{const x=e.router.getMatch(i),h=e.router.stores.matchesId.get()[n],b=(h&&e.router.stores.matchStores.get(h)||null)?.routeId===r?h:e.router.stores.matches.get().find(v=>v.routeId===r)?.id,g=mc(e,i);if(x._nonReactive.loaderPromise){if(x.status==="success"&&!e.sync&&!x.preload&&u)return x;await x._nonReactive.loaderPromise;const v=e.router.getMatch(i),y=v._nonReactive.error||v.error;y&&Kn(e,v,y),v.status==="pending"&&await s(g,x,b,v,c)}else{const v=g&&!e.router.stores.matchStores.has(i),y=e.router.getMatch(i);y._nonReactive.loaderPromise=gi(),v!==y.preload&&e.updateMatch(i,k=>({...k,preload:v})),await s(g,x,b,y,c)}}const p=e.router.getMatch(i);l||(p._nonReactive.loaderPromise?.resolve(),p._nonReactive.loadPromise?.resolve(),p._nonReactive.loadPromise=void 0),clearTimeout(p._nonReactive.pen
2dingTimeout),p._nonReactive.pendingTimeout=void 0,l||(p._nonReactive.loaderPromise=void 0),p._nonReactive.dehydrated=void 0;const f=l?p.isFetching:!1;return f!==p.isFetching||p.invalid!==!1?(e.updateMatch(i,x=>({...x,isFetching:f,invalid:!1})),e.router.getMatch(i)):p};async function Cm(e){const a=e,n=[];Nw(a.router)&&uu(a);let s;for(let f=0;f<a.matches.length;f++){try{const x=_w(a,f);qr(x)&&await x}catch(x){if(va(x))throw x;if(ta(x))s=x;else if(!a.preload)throw x;break}if(a.serialError||a.firstBadMatchIndex!=null)break}const i=a.firstBadMatchIndex??a.matches.length,r=s&&!a.preload?km(a,s):void 0,o=s&&a.preload?0:r!==void 0?Math.min(r+1,i):i;let l,c;for(let f=0;f<o;f++)n.push(Aw(a,n,f));try{await Promise.all(n)}catch{const f=await Promise.allSettled(n);for(const x of f){if(x.status!=="rejected")continue;const h=x.reason;if(va(h))throw h;ta(h)?l??=h:c??=h}if(c!==void 0)throw c}const d=l??(s&&!a.preload?s:void 0);let u=a.firstBadMatchIndex!==void 0?a.firstBadMatchIndex:a.matches.length-1;if(!d&&s&&a.preload)return a.matches;if(d){const f=km(a,d);f===void 0&&Cn();const x=a.matches[f],h=a.router.looseRoutesById[x.routeId],b=a.router.options?.defaultNotFoundComponent;!h.options.notFoundComponent&&b&&(h.options.notFoundComponent=b),d.routeId=x.routeId;const g=x.routeId===a.router.routeTree.id;a.updateMatch(x.id,v=>({...v,...g?{status:"success",globalNotFound:!0,error:void 0}:{status:"notFound",error:d},isFetching:!1})),u=f,await Wr(h,["notFoundComponent"])}else if(!a.preload){const f=a.matches[0];f.globalNotFound||a.router.getMatch(f.id)?.globalNotFound&&a.updateMatch(f.id,x=>({...x,globalNotFound:!1,error:void 0}))}if(a.serialError&&a.firstBadMatchIndex!==void 0){const f=a.router.looseRoutesById[a.matches[a.firstBadMatchIndex].routeId];await Wr(f,["errorComponent"])}for(let f=0;f<=u;f++){const{id:x,routeId:h}=a.matches[f],b=a.router.looseRoutesById[h];try{const g=Ew(a,x,b);if(g){const v=await g;a.updateMatch(x,y=>({...y,...v}))}}catch(g){console.error(`Error executing head for route ${h}:`,g)}}const p=uu(a);if(qr(p)&&await p,d)throw d;if(a.serialError&&!a.preload&&!a.onReady)throw a.serialError;return a.matches}function _m(e,a){const n=a.map(s=>e.options[s]?.preload?.()).filter(Boolean);if(n.length!==0)return Promise.all(n)}function Wr(e,a=fl){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(s=>{const{id:i,...r}=s.options;Object.assign(e.options,r),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);const n=()=>e._componentsLoaded?void 0:a===fl?(()=>{if(e._componentsPromise===void 0){const s=_m(e,fl);s?e._componentsPromise=s.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():_m(e,a);return e._lazyPromise?e._lazyPromise.then(n):n()}function lb(e){for(const a of fl)if(e.options[a]?.preload)return!0;return!1}const fl=["component","errorComponent","pendingComponent","notFoundComponent"];function Rw(e){return{input:({url:a})=>{for(const n of e)a=pu(n,a);return a},output:({url:a})=>{for(let n=e.length-1;n>=0;n--)a=cb(e[n],a);return a}}}function Tw(e){const a=sb(e.basepath),n=`/${a}`,s=e.caseSensitive?n:n.toLowerCase(),i=`${s}/`;return{input:({url:r})=>{const o=e.caseSensitive?r.pathname:r.pathname.toLowerCase();return o===s?r.pathname="/":o.startsWith(i)&&(r.pathname=r.pathname.slice(n.length)),r},output:({url:r})=>(r.pathname=ml(["/",a,r.pathname]),r)}}function pu(e,a){const n=e?.input?.({url:a});if(n){if(typeof n=="string")return new URL(n);if(n instanceof URL)return n}return a}function cb(e,a){const n=e?.output?.({url:a});if(n){if(typeof n=="string")return new URL(n);if(n instanceof URL)return n}return a}function Mw(e,a){const{createMutableStore:n,createReadonlyStore:s,batch:i,init:r}=a,o=new Map,l=new Map,c=new Map,d=n(e.status),u=n(e.loadedAt),p=n(e.isLoading),f=n(e.isTransitioning),x=n(e.location),h=n(e.resolvedLocation),b=n(e.statusCode),g=n(e.redirect),v=n([]),y=n([]),k=n([]),w=s(()=>cd(o,v.get())),j=s(()=>cd(l,y.get())),C=s(()=>cd(c,k.get())),N=s(()=>v.get()[0]),S=s(()=>v.get().some(W=>o.get(W)?.get().status==="pending")),_=s(()=>({locationHref:x.get().href,resolvedLocationHref:h.get()?.href,status:d.get()})),R=s(()=>({status:d.get(),loadedAt:u.get(),isLoading:p.get(),isTransitioning:f.get(),matches:w.get(),location:x.get(),resolvedLocation:h.get(),statusCode:b.get(),redirect:g.get()})),A=Br(64);function E(W){let V=A.get(W);return V||(V=s(()=>{const U=v.get();for(const X of U){const ie=o.get(X);if(ie&&ie.routeId===W)return ie.get()}}),A.set(W,V)),V}const I={status:d,loadedAt:u,isLoading:p,isTransitioning:f,location:x,resolvedLocation:h,statusCode:b,redirect:g,matchesId:v,pendingIds:y,cachedIds:k,matches:w,pendingMatches:j,cachedMatches:C,firstId:N,hasPending:S,matchRouteDeps:_,matchStores:o,pendingMatchStores:l,cac
2hedMatchStores:c,__store:R,getRouteMatchStore:E,setMatches:P,setPending:O,setCached:K};P(e.matches),r?.(I);function P(W){dd(W,o,v,n,i)}function O(W){dd(W,l,y,n,i)}function K(W){dd(W,c,k,n,i)}return I}function cd(e,a){const n=[];for(const s of a){const i=e.get(s);i&&n.push(i.get())}return n}function dd(e,a,n,s,i){const r=e.map(l=>l.id),o=new Set(r);i(()=>{for(const l of a.keys())o.has(l)||a.delete(l);for(const l of e){const c=a.get(l.id);if(!c){const d=s(l);d.routeId=l.routeId,a.set(l.id,d);continue}c.routeId=l.routeId,c.get()!==l&&c.set(l)}sw(n.get(),r)||n.set(r)})}var Qn="__TSR_index",Em="popstate",Am="beforeunload";function Pw(e){let a=e.getLocation();const n=new Set,s=o=>{a=e.getLocation(),n.forEach(l=>l({location:a,action:o}))},i=o=>{e.notifyOnIndexChange??!0?s(o):a=e.getLocation()},r=async({task:o,navigateOpts:l,...c})=>{if(l?.ignoreBlocker??!1){o();return}const d=e.getBlockers?.()??[],u=c.type==="PUSH"||c.type==="REPLACE";if(typeof document<"u"&&d.length&&u)for(const p of d){const f=ql(c.path,c.state);if(await p.blockerFn({currentLocation:a,nextLocation:f,action:c.type})){e.onBlocked?.();return}}o()};return{get location(){return a},get length(){return e.getLength()},subscribers:n,subscribe:o=>(n.add(o),()=>{n.delete(o)}),push:(o,l,c)=>{const d=a.state[Qn];l=Rm(d+1,l),r({task:()=>{e.pushState(o,l),s({type:"PUSH"})},navigateOpts:c,type:"PUSH",path:o,state:l})},replace:(o,l,c)=>{const d=a.state[Qn];l=Rm(d,l),r({task:()=>{e.replaceState(o,l),s({type:"REPLACE"})},navigateOpts:c,type:"REPLACE",path:o,state:l})},go:(o,l)=>{r({task:()=>{e.go(o),i({type:"GO",index:o})},navigateOpts:l,type:"GO"})},back:o=>{r({task:()=>{e.back(o?.ignoreBlocker??!1),i({type:"BACK"})},navigateOpts:o,type:"BACK"})},forward:o=>{r({task:()=>{e.forward(o?.ignoreBlocker??!1),i({type:"FORWARD"})},navigateOpts:o,type:"FORWARD"})},canGoBack:()=>a.state[Qn]!==0,createHref:o=>e.createHref(o),block:o=>{if(!e.setBlockers)return()=>{};const l=e.getBlockers?.()??[];return e.setBlockers([...l,o]),()=>{const c=e.getBlockers?.()??[];e.setBlockers?.(c.filter(d=>d!==o))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:s}}function Rm(e,a){a||(a={});const n=Dp();return{...a,key:n,__TSR_key:n,[Qn]:e}}function zw(e){const a=typeof document<"u"?window:void 0,n=a.history.pushState,s=a.history.replaceState;let i=[];const r=()=>i,o=S=>i=S,l=(S=>S),c=(()=>ql(`${a.location.pathname}${a.location.search}${a.location.hash}`,a.history.state));if(!a.history.state?.__TSR_key&&!a.history.state?.key){const S=Dp();a.history.replaceState({[Qn]:0,key:S,__TSR_key:S},"")}let d=c(),u,p=!1,f=!1,x=!1,h=!1;const b=()=>d;let g,v;const y=()=>{g&&(N._ignoreSubscribers=!0,(g.isPush?a.history.pushState:a.history.replaceState)(g.state,"",g.href),N._ignoreSubscribers=!1,g=void 0,v=void 0,u=void 0)},k=(S,_,R)=>{const A=l(_);v||(u=d),d=ql(_,R),g={href:A,state:R,isPush:g?.isPush||S==="push"},v||(v=Promise.resolve().then(()=>y()))},w=S=>{d=c(),N.notify({type:S})},j=async()=>{if(f){f=!1;return}const S=c(),_=S.state[Qn]-d.state[Qn],R=_===1,A=_===-1,E=!R&&!A||p;p=!1;const I=E?"GO":A?"BACK":"FORWARD",P=E?{type:"GO",index:_}:{type:A?"BACK":"FORWARD"};if(x)x=!1;else{const O=r();if(typeof document<"u"&&O.length){for(const K of O)if(await K.blockerFn({currentLocation:d,nextLocation:S,action:I})){f=!0,a.history.go(1),N.notify(P);return}}}d=c(),N.notify(P)},C=S=>{if(h){h=!1;return}let _=!1;const R=r();if(typeof document<"u"&&R.length)for(const A of R){const E=A.enableBeforeUnload??!0;if(E===!0){_=!0;break}if(typeof E=="function"&&E()===!0){_=!0;break}}if(_)return S.preventDefault(),S.returnValue=""},N=Pw({getLocation:b,getLength:()=>a.history.length,pushState:(S,_)=>k("push",S,_),replaceState:(S,_)=>k("replace",S,_),back:S=>(S&&(x=!0),h=!0,a.history.back()),forward:S=>{S&&(x=!0),h=!0,a.history.forward()},go:S=>{p=!0,a.history.go(S)},createHref:S=>l(S),flush:y,destroy:()=>{a.history.pushState=n,a.history.replaceState=s,a.removeEventListener(Am,C,{capture:!0}),a.removeEventListener(Em,j)},onBlocked:()=>{u&&d!==u&&(d=u)},getBlockers:r,setBlockers:o,notifyOnIndexChange:!1});return a.addEventListener(Am,C,{capture:!0}),a.addEventListener(Em,j),a.history.pushState=function(...S){const _=n.apply(a.history,S);return N._ignoreSubscribers||w("PUSH"),_},a.history.replaceState=function(...S){const _=s.apply(a.history,S);return N._ignoreSubscribers||w("REPLACE"),_},N}function Dw(e){let a=e.replace(/[\x00-\x1f\x7f]/g,"");return a.startsWith("//")&&(a="/"+a.replace(/^\/+/,"")),a}function ql(e,a){const n=Dw(e),s=n.indexOf("#"),i=n.indexOf("?"),r=Dp();return{href:n,pathname:n.substring(0,s>0?i>0?Math.min(s,i):s:i>0?i:n.length),hash:s>-1?n.substring(s):"",search:i>-1?n.slice(i,s===-1?void 0:s):"",state:a||{[Qn]:0,key:r,__TSR_key:r}}}function Dp(){return(Math.random()+1).toString(36).substring(7)}function mi(e,a){const n=a,s=e;return{fromLocation:n,toLocation:s,pathChanged:n?.pathname!==s.pathname,hrefChanged:n?.href!==s.href,hashChanged:n?.hash!==s.hash}}const hu=new WeakMap;var Iw=class{constructor(e,a){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this.resetNextScroll=!0,this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.isScrollRestoring=!1,this.isScrollRestorationSetup=!1,this.routeBranchCache=new WeakMap,this.startTransition=n=>
2n(),this.update=n=>{const s=this.options,i=this.basepath??s?.basepath??"/",r=this.basepath===void 0,o=s?.rewrite;if(this.options={...s,...n},this.isServer=this.options.isServer??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=gw(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=zw()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let u;this.resolvePathCache=Br(1e3),u=this.buildRouteTree(),this.setRoutes(u)}if(!this.stores&&this.latestLocation){const u=this.getStoreConfig(this);this.batch=u.batch,this.stores=Mw(Fw(this.latestLocation),u),Gw(this)}let l=!1;const c=this.options.basepath??"/",d=this.options.rewrite;if(r||i!==c||o!==d){this.basepath=c;const u=[],p=sb(c);p&&p!=="/"&&u.push(Tw({basepath:c})),d&&u.push(d),this.rewrite=u.length===0?void 0:u.length===1?u[0]:Rw(u),this.history&&this.updateLatestLocation(),l=!0}l&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<"u"&&"CSS"in window&&typeof window.CSS?.supports=="function"&&(this.isViewTransitionTypesSupported=window.CSS.supports("selector(:active-view-transition-type(a))"))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const n=uw(this.routeTree,this.options.caseSensitive,(s,i)=>{s.init({originalIndex:i})});return this.options.routeMasks&&rw(this.options.routeMasks,n.processedTree),n},this.subscribe=(n,s)=>{const i={eventType:n,fn:s};return this.subscribers.add(i),()=>{this.subscribers.delete(i)}},this.emit=n=>{this.subscribers.forEach(s=>{s.eventType===n.type&&s.fn(n)})},this.parseLocation=(n,s)=>{const i=({pathname:c,search:d,hash:u,href:p,state:f})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(c)){const v=this.options.parseSearch(d),y=this.options.stringifySearch(v);return{href:c+y+u,publicHref:c+y+u,pathname:Gi(c).path,external:!1,searchStr:y,search:hs(s?.search,v),hash:Gi(u.slice(1)).path,state:Un(s?.state,f)}}const x=new URL(p,this.origin),h=pu(this.rewrite,x),b=this.options.parseSearch(h.search),g=this.options.stringifySearch(b);return h.search=g,{href:h.href.replace(h.origin,""),publicHref:p,pathname:Gi(h.pathname).path,external:!!this.rewrite&&h.origin!==this.origin,searchStr:g,search:hs(s?.search,b),hash:Gi(h.hash.slice(1)).path,state:Un(s?.state,f)}},r=i(n),{__tempLocation:o,__tempKey:l}=r.state;if(o&&(!l||l===this.tempLocationKey)){const c=i(o);return c.state.key=r.state.key,c.state.__TSR_key=r.state.__TSR_key,delete c.state.__tempLocation,{...c,maskedLocation:r}}return r},this.resolvePathWithBase=(n,s)=>xw({base:n,to:s.includes("//")?zp(s):s,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(n,s,i)=>typeof n=="string"?this.matchRoutesInternal({pathname:n,search:s},i):this.matchRoutesInternal(n,s),this.getMatchedRoutes=n=>Ow({pathname:n,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=n=>{const s=this.getMatch(n);s&&(s.abortController.abort(),clearTimeout(s._nonReactive.pendingTimeout),s._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(n=>{this.cancelMatch(n)}),this.stores.matchesId.get().forEach(n=>{if(this.stores.pendingMatchStores.has(n))return;const s=this.stores.matchStores.get(n)?.get();s&&(s.status==="pending"||s.isFetching==="loader")&&this.cancelMatch(n)})},this.buildLocation=n=>{const s=(r={})=>{const o=r._fromLocation||this.pendingBuiltLocation||this.latestLocation,l=this.matchRoutesLightweight(o);r.from;const c=r.unsafeRelative==="path"?o.pathname:r.from??l.fullPath,d=r.to?`${r.to}`:void 0,u=l.search,p=Object.assign(Object.create(null),l.params),f=d?.charCodeAt(0)===47?"/":this.resolvePathWithBase(c,"."),x=d?this.resolvePathWithBase(f,d):f,h=r.params===!1||r.params===null?Ob
2ject.create(null):(r.params??!0)===!0?p:Object.assign(p,js(r.params,p)),b=this.routesByPath[Nn(x)];let g;if(b)g=this.getRouteBranch(b);else if(x.includes("$"))g=[];else{const A=this.getMatchedRoutes(x);g=A.matchedRoutes,this.options.notFoundRoute&&(!A.foundRoute||A.foundRoute.path!=="/"&&A.routeParams["**"])&&(g=[...g,this.options.notFoundRoute])}if(g.length&&Xg(h))for(const A of g){const E=A.options.params?.stringify??A.options.stringifyParams;if(E)try{Object.assign(h,E(h))}catch{}}const v=n.leaveParams?x:Gi(jm({path:x,params:h,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path;let y=u;if(n._includeValidateSearch&&this.options.search?.strict){const A={};g.forEach(E=>{if(E.options.validateSearch)try{Object.assign(A,xl(E.options.validateSearch,{...A,...y}))}catch{}}),y=A}y=$w({search:y,dest:r,destRoutes:g,_includeValidateSearch:n._includeValidateSearch}),y=hs(u,y);const k=this.options.stringifySearch(y),w=r.hash===!0?o.hash:r.hash?js(r.hash,o.hash):void 0,j=w?`#${w}`:"";let C=r.state===!0?o.state:r.state?js(r.state,o.state):{};C=Un(o.state,C);const N=`${v}${k}${j}`;let S,_,R=!1;if(this.rewrite){const A=new URL(N,this.origin),E=cb(this.rewrite,A);S=A.href.replace(A.origin,""),E.origin!==this.origin?(_=E.href,R=!0):_=E.pathname+E.search+E.hash}else S=nw(N),_=S;return{publicHref:_,href:S,pathname:v,search:y,searchStr:k,state:C,hash:w??"",external:R,unmaskOnReload:r.unmaskOnReload}},i=(r={},o)=>{const l=s(r);let c=o?s(o):void 0;if(!c){const d=Object.create(null);if(this.options.routeMasks){const u=ow(l.pathname,this.processedTree);if(u){Object.assign(d,u.rawParams);const{from:p,params:f,...x}=u.route,h=f===!1||f===null?Object.create(null):(f??!0)===!0?d:Object.assign(d,js(f,d));o={from:n.from,...x,params:h},c=s(o)}}}return c&&(l.maskedLocation=c),l};return n.mask?i(n,{from:n.from,...n.mask}):i(n)},this.commitLocation=async({viewTransition:n,ignoreBlocker:s,...i})=>{let r;const o=()=>{const d=["key","__TSR_key","__TSR_index","__hashScrollIntoViewOptions"];d.forEach(p=>{i.state[p]=this.latestLocation.state[p]});const u=Ss(i.state,this.latestLocation.state);return d.forEach(p=>{delete i.state[p]}),u},l=Nn(this.latestLocation.href)===Nn(i.href);let c=this.commitLocationPromise;if(this.commitLocationPromise=gi(()=>{c?.resolve(),c=void 0}),l&&o())this.load();else{let{maskedLocation:d,hashScrollIntoView:u,...p}=i;d&&(p={...d,state:{...d.state,__tempKey:void 0,__tempLocation:{...p,search:p.searchStr,state:{...p.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(p.unmaskOnReload??this.options.unmaskOnReload??!1)&&(p.state.__tempKey=this.tempLocationKey)),p.state.__hashScrollIntoViewOptions=u??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=n,r=i.replace?"REPLACE":"PUSH",this.history[r==="REPLACE"?"replace":"push"](p.publicHref,p.state,{ignoreBlocker:s})}return this.resetNextScroll=i.resetScroll??!0,this.history.subscribers.size||this.load(r?{action:{type:r}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:n,resetScroll:s,hashScrollIntoView:i,viewTransition:r,ignoreBlocker:o,href:l,...c}={})=>{if(l){const p=this.history.location.state.__TSR_index,f=ql(l,{__TSR_index:n?p:p+1}),x=new URL(f.pathname,this.origin);c.to=pu(this.rewrite,x).pathname,c.search=this.options.parseSearch(f.search),c.hash=f.hash.slice(1)}const d=this.buildLocation({...c,_includeValidateSearch:!0});this.pendingBuiltLocation=d;const u=this.commitLocation({...d,viewTransition:r,replace:n,resetScroll:s,hashScrollIntoView:i,ignoreBlocker:o});return Promise.resolve().then(()=>{this.pendingBuiltLocation===d&&(this.pendingBuiltLocation=void 0)}),u},this.navigate=async({to:n,reloadDocument:s,href:i,publicHref:r,...o})=>{let l=!1;if(i)try{new URL(`${i}`),l=!0}catch{}if(l&&!s&&(s=!0),s){if(n!==void 0||!i){const d=this.buildLocation({to:n,...o});i=i??d.publicHref,r=r??d.publicHref}const c=!l&&r?r:i;if(Ol(c,this.protocolAllowlist))return Promise.resolve();if(!o.ignoreBlocker){const d=this.history.getBlockers?.()??[];for(const u of d)if(u?.blockerFn&&await u.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return Promise.resolve()}return o.replace?window.location.replace(c):window.location.href=c,Promise.resolve()}return this.buildAndCommitLocation({...o,href:i,to:n,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();const n=this.matchRoutes(this.latestLocation),s=this.stores.cachedMatches.get().filter(i=>!n.some(r=>r.id===i.id));this.batch(()=>{this.stores.status.set("pending"),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(n),this.stores.setCached(s)})},this.load=async n=>{const s=n?.action?.type;let i,r,o;const l=this.stores.resolvedLocation.get()??this.stores.location.get();for(o=new Promise(d=>{this.startTransition(async()=>{try{this.beforeLoad(),s?hu.set(this.latestLocation,s):hu.delete(this.latestLocation);const u=this.latestLocation,p=mi(u,this.stores.resolvedLocation.get());
2this.stores.redirect.get()||this.emit({type:"onBeforeNavigate",...p}),this.emit({type:"onBeforeLoad",...p}),await Cm({router:this,sync:n?.sync,forceStaleReload:l.href===u.href,matches:this.stores.pendingMatches.get(),location:u,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let f=null,x=null,h=null,b=null;this.batch(()=>{const g=this.stores.pendingMatches.get(),v=g.length,y=this.stores.matches.get();f=v?y.filter(j=>!this.stores.pendingMatchStores.has(j.id)):null;const k=new Set;for(const j of this.stores.pendingMatchStores.values())j.routeId&&k.add(j.routeId);const w=new Set;for(const j of this.stores.matchStores.values())j.routeId&&w.add(j.routeId);x=v?y.filter(j=>!k.has(j.routeId)):null,h=v?g.filter(j=>!w.has(j.routeId)):null,b=v?g.filter(j=>w.has(j.routeId)):y,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),v&&(this.stores.setMatches(g),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...f.filter(j=>j.status!=="error"&&j.status!=="notFound"&&j.status!=="redirected")]),this.clearExpiredCache())});for(const[g,v]of[[x,"onLeave"],[h,"onEnter"],[b,"onStay"]])if(g)for(const y of g)this.looseRoutesById[y.routeId].options[v]?.(y)})})}})}catch(u){va(u)?(i=u,this.navigate({...i.options,replace:!0,ignoreBlocker:!0})):ta(u)&&(r=u);const p=i?i.status:r?404:this.stores.matches.get().some(f=>f.status==="error")?500:200;this.batch(()=>{this.stores.statusCode.set(p),this.stores.redirect.set(i)})}this.latestLoadPromise===o&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),d()})}),this.latestLoadPromise=o,await o;this.latestLoadPromise&&o!==this.latestLoadPromise;)await this.latestLoadPromise;let c;this.hasNotFoundMatch()?c=404:this.stores.matches.get().some(d=>d.status==="error")&&(c=500),c!==void 0&&this.stores.statusCode.set(c)},this.startViewTransition=n=>
2{const s=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,s&&typeof document<"u"&&"startViewTransition"in document&&typeof document.startViewTransition=="function"){let i;if(typeof s=="object"&&this.isViewTransitionTypesSupported){const r=this.latestLocation,o=this.stores.resolvedLocation.get(),l=typeof s.types=="function"?s.types(mi(r,o)):s.types;if(l===!1){n();return}i={update:n,types:l}}else i=n;document.startViewTransition(i)}else n()},this.updateMatch=(n,s)=>{this.startTransition(()=>{const i=this.stores.pendingMatchStores.get(n);if(i){i.set(s);return}const r=this.stores.matchStores.get(n);if(r){r.set(s);return}const o=this.stores.cachedMatchStores.get(n);if(o){const l=s(o.get());l.status==="redirected"?this.stores.cachedMatchStores.delete(n)&&this.stores.cachedIds.set(c=>c.filter(d=>d!==n)):o.set(l)}})},this.getMatch=n=>this.stores.cachedMatchStores.get(n)?.get()??this.stores.pendingMatchStores.get(n)?.get()??this.stores.matchStores.get(n)?.get(),this.invalidate=n=>{const s=i=>n?.filter?.(i)??!0?{...i,invalid:!0,...n?.forcePending||i.status==="error"||i.status==="notFound"?{status:"pending",error:void 0}:void 0}:i;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(s)),this.stores.setCached(this.stores.cachedMatches.get().map(s)),this.stores.setPending(this.stores.pendingMatches.get().map(s))}),this.shouldViewTransition=!1,this.load({sync:n?.sync})},this.getParsedLocationHref=n=>n.publicHref||"/",this.resolveRedirect=n=>{const s=n.headers.get("Location");if(!n.options.href||n.options._builtLocation){const i=n.options._builtLocation??this.buildLocation(n.options),r=this.getParsedLocationHref(i);n.options.href=r,n.headers.set("Location",r)}else if(s)try{const i=new URL(s);if(this.origin&&i.origin===this.origin){const r=i.pathname+i.search+i.hash;n.options.href=r,n.headers.set("Location",r)}}catch{}if(n.options.href&&!n.options._builtLocation&&Ol(n.options.href,this.protocolAllowlist))throw new Error("Redirect blocked: unsafe protocol");return n.headers.get("Location")||n.headers.set("Location",n.options.href),n},this.clearCache=n=>{const s=n?.filter;s!==void 0?this.stores.setCached(this.stores.cachedMatches.get().filter(i=>!s(i))):this.stores.setCached([])},this.clearExpiredCache=()=>{const n=Date.now(),s=i=>{const r=this.looseRoutesById[i.routeId];if(!r.options.loader)return!0;const o=(i.preload?r.options.preloadGcTime??this.options.defaultPreloadGcTime:r.options.gcTime??this.options.defaultGcTime)??300*1e3;return i.status==="error"?!0:n-i.updatedAt>=o};this.clearCache({filter:s})},this.loadRouteChunk=Wr,this.preloadRoute=async n=>{const s=n._builtLocation??this.buildLocation(n);let i=this.matchRoutes(s,{throwOnError:!0,preload:!0,dest:n});const r=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),o=new Set([...r,...this.stores.cachedIds.get()]),l=i.filter(c=>!o.has(c.id));if(l.length){const c=this.stores.cachedMatches.get();this.stores.setCached([...c,...l])}try{return i=await Cm({router:this,matches:i,location:s,preload:!0,updateMatch:(c,d)=>{r.has(c)?i=i.map(u=>u.id===c?d(u):u):this.updateMatch(c,d)}}),i}catch(c){if(va(c))return c.options.reloadDocument?void 0:await this.preloadRoute({...c.options,_fromLocation:s});ta(c)||console.error(c);return}},this.matchRoute=(n,s)=>{const i={...n,to:n.to?this.resolvePathWithBase(n.from||"",n.to):void 0,params:n.params||{},leaveParams:!0},r=this.buildLocation(i);if(s?.pending&&this.stores.status.get()!=="pending")return!1;const o=(s?.pending===void 0?!this.stores.isLoading.get():s.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),l=lw(r.pathname,s?.caseSensitive??!1,s?.fuzzy??!1,o.pathname,this.processedTree);return!l||n.params&&!Ss(l.rawParams,n.params,{partial:!0})?!1:s?.includeSearch??!0?Ss(o.search,r.search,{partial:!0})?l.rawParams:!1:l.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(n=>n.status==="notFound"||n.globalNotFound),this.getStoreConfig=a,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??"fuzzy",stringifySearch:e.stringifySearch??jw,parseSearch:e.parseSearch??vw,protocolAllowlist:e.protocolAllowlist??aw}),typeof document<"u"&&(self.__TSR_ROUTER__=this)}
2isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:a,processedTree:n}){this.routesById=e,this.routesByPath=a,this.processedTree=n;const s=this.options.notFoundRoute;s&&(s.init({originalIndex:99999999999}),this.routesById[s.id]=s)}getRouteBranch(e){let a=this.routeBranchCache.get(e);return a||(a=ab(e),this.routeBranchCache.set(e,a)),a}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,a){const n=this.getMatchedRoutes(e.pathname),{foundRoute:s,routeParams:i}=n;let{matchedRoutes:r}=n,o=!1;(s?s.path!=="/"&&i["**"]:Nn(e.pathname))&&(this.options.notFoundRoute?r=[...r,this.options.notFoundRoute]:o=!0);const l=o?Bw(this.options.notFoundMode,r):void 0,c=new Array(r.length),d=new Map;for(const u of this.stores.matchStores.values())u.routeId&&d.set(u.routeId,u.get());for(let u=0;u<r.length;u++){const p=r[u],f=c[u-1];let x,h,b;{const E=f?.search??e.search,I=f?._strictSearch??void 0;try{const P=xl(p.options.validateSearch,{...E})??void 0;x={...E,...P},h={...I,...P},b=void 0}catch(P){let O=P;if(P instanceof Bl||(O=new Bl(P.message,{cause:P})),a?.throwOnError)throw O;x=E,h={},b=O}}const g=p.options.loaderDeps?.({search:x})??"",v=g?JSON.stringify(g):"",{interpolatedPath:y,usedParams:k}=jm({path:p.fullPath,params:i,decoder:this.pathParamsDecoder,server:this.isServer}),w=p.id+y+v,j=this.getMatch(w),C=d.get(p.id),N=j?._strictParams??k;let S;if(!j)try{Tm(p,N)}catch(E){if(ta(E)||va(E)?S=E:S=new Lw(E.message,{cause:E}),a?.throwOnError)throw S}Object.assign(i,N);const _=C?"stay":"enter";let R;if(j)R={...j,cause:_,params:C?.params??i,_strictParams:N,search:hs(C?C.search:j.search,x),_strictSearch:h};else{const E=p.options.loader||p.options.beforeLoad||p.lazyFn||lb(p)?"pending":"success";R={id:w,ssr:p.options.ssr,index:u,routeId:p.id,params:C?.params??i,_strictParams:N,pathname:y,updatedAt:Date.now(),search:C?hs(C.search,x):x,_strictSearch:h,searchError:void 0,status:E,isFetching:!1,error:void 0,paramsError:S,__routeContext:void 0,_nonReactive:{loadPromise:gi()},__beforeLoadContext:void 0,context:{},abortController:new AbortController,fetchCount:0,cause:_,loaderDeps:C?Un(C.loaderDeps,g):g,invalid:!1,preload:!1,links:void 0,scripts:void 0,headScripts:void 0,meta:void 0,staticData:p.options.staticData||{},fullPath:p.fullPath}}a?.preload||(R.globalNotFound=l===p.id),R.searchError=b;const A=this.getParentContext(f);R.context={...A,...R.__routeContext,...R.__beforeLoadContext},c[u]=R}for(let u=0;u<c.length;u++){const p=c[u],f=this.looseRoutesById[p.routeId],x=this.getMatch(p.id),h=d.get(p.routeId);if(p.params=h?hs(h.params,i):i,!x){const b=c[u-1],g=this.getParentContext(b);if(f.options.context){const v={deps:p.loaderDeps,params:p.params,context:g??{},location:e,navigate:y=>this.navigate({...y,_fromLocation:e}),buildLocation:this.buildLocation,cause:p.cause,abortController:p.abortController,preload:!!p.preload,matches:c,routeId:f.id};p.__routeContext=f.options.context(v)??void 0}p.context={...g,...p.__routeContext,...p.__beforeLoadContext}}}return c}matchRoutesLightweight(e){const{matchedRoutes:a,routeParams:n}=this.getMatchedRoutes(e.pathname),s=$r(a),i={...e.search};for(const d of a)try{Object.assign(i,xl(d.options.validateSearch,i))}catch{}const r=$r(this.stores.matchesId.get()),o=r&&this.stores.matchStores.get(r)?.get(),l=o&&o.routeId===s.id&&o.pathname===e.pathname;let c;if(l)c=o.params;else{const d=Object.assign(Object.create(null),n);for(const u of a)try{Tm(u,d)}catch{}c=d}return{matchedRoutes:a,fullPath:s.fullPath,search:i,params:c}}},Bl=class extends Error{},Lw=class extends Error{};function Fw(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:"idle",resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function xl(e,a){if(e==null)return{};if("~standard"in e){const n=e["~standard"].validate(a);if(n instanceof Promise)throw new Bl("Async validation not supported");if(n.issues)throw new Bl(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return"parse"in e?e.parse(a):typeof e=="function"?e(a):{}}function Ow({pathname:e,routesById:a,processedTree:n}){const s=Object.create(null),i=Nn(e);let r;const o=cw(i,n,!0);return o&&(r=o.route,Object.assign(s,o.rawParams)),{matchedRoutes:o?.branch||[a.__root__],routeParam
2s:s,foundRoute:r}}function $w({search:e,dest:a,destRoutes:n,_includeValidateSearch:s}){return qw(n)(e,a,s??!1)}function qw(e){const a={dest:null,_includeValidateSearch:!1,middlewares:[]};for(const i of e){if("search"in i.options)i.options.search?.middlewares&&a.middlewares.push(...i.options.search.middlewares);else if(i.options.preSearchFilters||i.options.postSearchFilters){const r=({search:o,next:l})=>{let c=o;"preSearchFilters"in i.options&&i.options.preSearchFilters&&(c=i.options.preSearchFilters.reduce((u,p)=>p(u),o));const d=l(c);return"postSearchFilters"in i.options&&i.options.postSearchFilters?i.options.postSearchFilters.reduce((u,p)=>p(u),d):d};a.middlewares.push(r)}if(i.options.validateSearch){const r=({search:o,next:l})=>{const c=l(o);if(!a._includeValidateSearch)return c;try{return{...c,...xl(i.options.validateSearch,c)??void 0}}catch{return c}};a.middlewares.push(r)}}const n=({search:i})=>{const r=a.dest;return r.search?r.search===!0?i:js(r.search,i):{}};a.middlewares.push(n);const s=(i,r,o)=>{if(i>=o.length)return r;const l=o[i];return l({search:r,next:d=>s(i+1,d,o)})};return function(r,o,l){return a.dest=o,a._includeValidateSearch=l,s(0,r,a.middlewares)}}function Bw(e,a){if(e!=="root")for(let n=a.length-1;n>=0;n--){const s=a[n];if(s.children)return s.id}return Cs}function Tm(e,a){const n=e.options.params?.parse??e.options.parseParams;if(n){const s=n(a);if(s===!1)throw new Error("Route params.parse returned false for a matched route");Object.assign(a,s)}}function Ww(){try{return sessionStorage}catch{return}}const Uw="tsr-scroll-restoration-v1_3",db=Ww();function Vw(){try{return JSON.parse(db?.getItem("tsr-scroll-restoration-v1_3")||"{}")}catch{return{}}}function Kw(){try{db?.setItem(Uw,JSON.stringify(ii))}catch{}}const ii=Vw(),Mm="data-scroll-restoration-id",Hw=e=>e.state.__TSR_key||e.href;function Qw(e){const a=e.getAttribute(Mm);if(a)return`[${Mm}="${a}"]`;let n="",s=e,i;for(;i=s.parentNode;){let r=1,o=s;for(;o=o.previousElementSibling;)r++;const l=`${s.localName}:nth-child(${r})`;n=n?`${l} > ${n}`:l,s=i}return n}let Oo=!1;const ri="window";function mu(e){try{return typeof e=="function"?e():document.querySelector(e)}catch{}}function Pm(e){const a=[];for(const n of e){if(n===ri)continue;const s=mu(n);s&&a.push(s)}return a}function Gw(e,a){if(e.options.scrollRestoration&&(e.isScrollRestoring=!0),e.isScrollRestorationSetup)return;e.isScrollRestorationSetup=!0,Oo=!1;const n=e.options.getScrollRestorationKey||Hw,s=new Map,i=(l,c,d)=>{const u=s.get(l)||{};u.scrollX=c,u.scrollY=d,s.set(l,u)};history.scrollRestoration="manual";const r=l=>{if(!(Oo||!e.isScrollRestoring))if(l.target===document)i(ri,scrollX,scrollY);else{const c=l.target;i(c,c.scrollLeft,c.scrollTop)}},o=l=>{if(!e.isScrollRestoring)return;const c=ii[l]||={};for(const[d,u]of s)d===ri?c[ri]=u:d.isConnected&&(c[Qw(d)]=u)};document.addEventListener("scroll",r,!0),e.subscribe("onBeforeLoad",l=>{l.fromLocation&&o(n(l.fromLocation)),s.clear()}),addEventListener("pagehide",()=>{o(n(e.stores.resolvedLocation.get()??e.stores.location.get())),Kw()}),e.subscribe("onRendered",l=>{const c=e.options.scrollRestorationBehavior,d=e.options.scrollToTopSelectors,u=e.resetNextScroll;let p;if(s.clear(),u||(e.resetNextScroll=!0),typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return;const f=n(l.toLocation),x=l.fromLocation&&n(l.fromLocation);if(e.isScrollRestoring&&x&&x!==f){const h=ii[x];if(h){let b=ii[f];for(const g in h){if(g===ri){if(u)continue}else{const v=mu(g);if(!v||u&&d&&(p??=Pm(d),p.includes(v)))continue}b||(b=ii[f]={}),b[g]??=h[g]}}}Oo=!0;try{const h=l.toLocation.hash,b=l.toLocation.state.__hashScrollIntoViewOptions??!0;let g=!1;if(u){const v=hu.get(l.toLocation),y=h&&b&&(v==="PUSH"||v==="REPLACE"),k=e.isScrollRestoring?ii[f]:void 0;if(k)for(const w in k){const{scrollX:j,scrollY:C}=k[w];if(w===ri){if(y)continue;scrollTo({top:C,left:j,behavior:c}),g=!0}else{const N=mu(w);N&&(N.scrollLeft=j,N.scrollTop=C)}}if(!g&&!h){const w={top:0,left:0,behavior:c};if(scrollTo(w),d){p??=Pm(d);for(const j of p)j.scrollTo(w)}}}!g&&h&&b&&document.getElementById(h)?.scrollIntoView(b)}finally{Oo=!1}})}const Zw="Error preloading route! ☝️";var ub=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=a=>{this.originalIndex=a.originalIndex;const n=this.options,s=!n?.path&&!n?.id;this.parentRoute=this.options.getParentRoute?.(),s?this._path=Cs:this.parentRoute||Cn();let i=s?Cs:n?.path;i&&i!=="/"&&(i=nb(i));const r=n?.id||i;let o=s?Cs:ml([this.parentRoute.id==="__root__"?"":this.parentRoute.id,r]);i==="__root__"&&(i="/"),o!=="__root__"&&(o=ml(["/",o]));const l=o==="__root__"?"/":ml([this.parentRoute.fullPath,i]);this._path=i,this._id=o,this._fullPath=l,this._to=Nn(l)},this.addChildren=a=>this._addFileChildren(a),this._addFileChildren=a=>(Array.isArray(a)&&(this.children=a),typeof a=="object"&&a!==null&&(this.children=Object.values(a)),this),this._addFileTypes=()=>this,this.updateLoader=a=>(Object.assign(this.options,a),this),this.update=a=>(Object.assign(this.options,a),this),this.lazy=a=>(this.lazyFn=a,this),this.redirect=a=>Wa({from:this.fullPath,...a}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}},Yw=class extends ub{constructor(e){super(e)}};function Ip(e){const a=e.errorComponent??Lp;return t.jsx(Xw,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:n,reset:s})=>n?m.createElement(a,{error:n,reset:s}):e.children})}var Xw=class extends m.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,a){const n=e.getResetKey();return a.error&&a.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,a){this.props.onCatch&&this.props.onCatch(e,a)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function Lp({error:e}){const[a,n]=m.useState(!1);return t.jsxs("div",{style:{padding:".5rem",maxWidth:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[t.jsx("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),t.jsx("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>n(s=>!s),children:a?"Hide Error":"Show Error"})]}),t.jsx("div",{style:{height:".25rem"}}),a?t.jsx("div",{children:t.jsx("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:e.message?t.jsx("code",{children:e.message}):null})}):null]})}function Jw({children:e,fallback:a=null}
2){return pb()?t.jsx(Xa.Fragment,{children:e}):t.jsx(Xa.Fragment,{children:a})}function pb(){return Xa.useSyncExternalStore(ek,()=>!0,()=>!1)}function ek(){return()=>{}}var hb=m.createContext(null);function ha(e){return m.useContext(hb)}var fc=m.createContext(void 0),tk=m.createContext(void 0),Ct=(e=>(e[e.None=0]="None",e[e.Mutable=1]="Mutable",e[e.Watching=2]="Watching",e[e.RecursedCheck=4]="RecursedCheck",e[e.Recursed=8]="Recursed",e[e.Dirty=16]="Dirty",e[e.Pending=32]="Pending",e))(Ct||{});function ak({update:e,notify:a,unwatched:n}){return{link:s,unlink:i,propagate:r,checkDirty:o,shallowPropagate:l};function s(d,u,p){const f=u.depsTail;if(f!==void 0&&f.dep===d)return;const x=f!==void 0?f.nextDep:u.deps;if(x!==void 0&&x.dep===d){x.version=p,u.depsTail=x;return}const h=d.subsTail;if(h!==void 0&&h.version===p&&h.sub===u)return;const b=u.depsTail=d.subsTail={version:p,dep:d,sub:u,prevDep:f,nextDep:x,prevSub:h,nextSub:void 0};x!==void 0&&(x.prevDep=b),f!==void 0?f.nextDep=b:u.deps=b,h!==void 0?h.nextSub=b:d.subs=b}function i(d,u=d.sub){const p=d.dep,f=d.prevDep,x=d.nextDep,h=d.nextSub,b=d.prevSub;return x!==void 0?x.prevDep=f:u.depsTail=f,f!==void 0?f.nextDep=x:u.deps=x,h!==void 0?h.prevSub=b:p.subsTail=b,b!==void 0?b.nextSub=h:(p.subs=h)===void 0&&n(p),x}function r(d){let u=d.nextSub,p;e:do{const f=d.sub;let x=f.flags;if(x&60?x&12?x&4?!(x&48)&&c(d,f)?(f.flags=x|40,x&=1):x=0:f.flags=x&-9|32:x=0:f.flags=x|32,x&2&&a(f),x&1){const h=f.subs;if(h!==void 0){const b=(d=h).nextSub;b!==void 0&&(p={value:u,prev:p},u=b);continue}}if((d=u)!==void 0){u=d.nextSub;continue}for(;p!==void 0;)if(d=p.value,p=p.prev,d!==void 0){u=d.nextSub;continue e}break}while(!0)}function o(d,u){let p,f=0,x=!1;e:do{const h=d.dep,b=h.flags;if(u.flags&16)x=!0;else if((b&17)===17){if(e(h)){const g=h.subs;g.nextSub!==void 0&&l(g),x=!0}}else if((b&33)===33){(d.nextSub!==void 0||d.prevSub!==void 0)&&(p={value:d,prev:p}),d=h.deps,u=h,++f;continue}if(!x){const g=d.nextDep;if(g!==void 0){d=g;continue}}for(;f--;){const g=u.subs,v=g.nextSub!==void 0;if(v?(d=p.value,p=p.prev):d=g,x){if(e(u)){v&&l(g),u=d.sub;continue}x=!1}else u.flags&=-33;u=d.sub;const y=d.nextDep;if(y!==void 0){d=y;continue e}}return x}while(!0)}function l(d){do{const u=d.sub,p=u.flags;(p&48)===32&&(u.flags=p|16,(p&6)===2&&a(u))}while((d=d.nextSub)!==void 0)}function c(d,u){let p=u.depsTail;for(;p!==void 0;){if(p===d)return!0;p=p.prevDep}return!1}}function nk(e,a,n){const s=typeof e=="object",i=s?e:void 0;return{next:(s?e.next:e)?.bind(i),error:(s?e.error:a)?.bind(i),complete:(s?e.complete:n)?.bind(i)}}const fu=[];let gl=0;const{link:zm,unlink:sk,propagate:ik,checkDirty:mb,shallowPropagate:Dm}=ak({update(e){return e._update()},notify(e){fu[xu++]=e,e.flags&=~Ct.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=Ct.Mutable|Ct.Dirty,Wl(e))}});let $o=0,xu=0,cn,gu=0;function fb(e){try{++gu,e()}finally{--gu||xb()}}function Wl(e){const a=e.depsTail;let n=a!==void 0?a.nextDep:e.deps;for(;n!==void 0;)n=sk(n,e)}function xb(){if(!(gu>0)){for(;$o<xu;){const e=fu[$o];fu[$o++]=void 0,e.notify()}$o=0,xu=0}}function Im(e,a){const n=typeof e=="function",s=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?Ct.None:Ct.Mutable,get(){return cn!==void 0&&zm(i,cn,gl),i._snapshot},subscribe(r){const o=nk(r),l={current:!1},c=rk(()=>{i.get(),l.current?o.next?.(i._snapshot):l.current=!0});return{unsubscribe:()=>{c.stop()}}},_update(r){const o=cn,l=a?.compare??Object.is;if(n)cn=i,++gl,i.depsTail=void 0;else if(r===void 0)return!1;n&&(i.flags=Ct.Mutable|Ct.RecursedCheck);try{const c=i._snapshot,d=typeof r=="function"?r(c):r===void 0&&n?s(c):r;return c===void 0||!l(c,d)?(i._snapshot=d,!0):!1}finally{cn=o,n&&(i.flags&=~Ct.RecursedCheck),Wl(i)}}};return n?(i.flags=Ct.Mutable|Ct.Dirty,i.get=function(){const r=i.flags;if(r&Ct.Dirty||r&Ct.Pending&&mb(i.deps,i)){if(i._update()){const o=i.subs;o!==void 0&&Dm(o)}}else r&Ct.Pending&&(i.flags=r&~Ct.Pending);return cn!==void 0&&zm(i,cn,gl),i._snapshot}):i.set=function(r){if(i._update(r)){const o=i.subs;o!==void 0&&(ik(o),Dm(o),xb())}},i}function rk(e){const a=()=>{const s=cn;cn=n,++gl,n.depsTail=void 0,n.flags=Ct.Watching|Ct.RecursedCheck;try{return e()}finally{cn=s,n.flags&=~Ct.RecursedCheck,Wl(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:Ct.Watching|Ct.RecursedCheck,notify(){const s=this.flags;s&Ct.Dirty||s&Ct.Pending&&mb(this.deps,this)?a():this.flags=Ct.Watching},stop(){this.flags=Ct.None,this.depsTail=void 0,Wl(this)}};return a(),n}function ok(e,a){return e===a}function Ea(e,a,n=ok){const s=m.useCallback(o=>
2{if(!e)return()=>{};const{unsubscribe:l}=e.subscribe(o);return l},[e]),i=m.useCallback(()=>e?.get(),[e]);return Hj.useSyncExternalStoreWithSelector(s,i,i,a,n)}var lk={get:()=>{},subscribe:()=>({unsubscribe:()=>{}})};function Fs(e){const a=ha(),n=m.useContext(e.from?tk:fc),s=e.from??n,i=s?e.from?a.stores.getRouteMatchStore(s):a.stores.matchStores.get(s):void 0,r=m.useRef(void 0);return Ea(i??lk,o=>{if((e.shouldThrow??!0)&&!o&&Cn(),o===void 0)return;const l=e.select?e.select(o):o;if(e.structuralSharing??a.options.defaultStructuralSharing){const c=Un(r.current,l);return r.current=c,c}return l})}function gb(e){return Fs({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:a=>e.select?e.select(a.loaderData):a.loaderData})}function bb(e){const{select:a,...n}=e;return Fs({...n,select:s=>a?a(s.loaderDeps):s.loaderDeps})}function yb(e){return Fs({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:a=>{const n=e.strict===!1?a.params:a._strictParams;return e.select?e.select(n):n}})}function Os(e){return Fs({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:a=>e.select?e.select(a.search):a.search})}function dt(e){const a=ha();return m.useCallback(n=>a.navigate({...n,from:n.from??e?.from}),[e?.from,a])}function vb(e){return Fs({...e,select:a=>e.select?e.select(a.context):a.context})}function ck(e,a){const n=ha(),s=Yj(a),{activeProps:i,inactiveProps:r,activeOptions:o,to:l,preload:c,preloadDelay:d,preloadIntentProximity:u,hashScrollIntoView:p,replace:f,startTransition:x,resetScroll:h,viewTransition:b,children:g,target:v,disabled:y,style:k,className:w,onClick:j,onBlur:C,onFocus:N,onMouseEnter:S,onMouseLeave:_,onTouchStart:R,ignoreBlocker:A,params:E,search:I,hash:P,state:O,mask:K,reloadDocument:W,unsafeRelative:V,from:U,_fromLocation:X,...ie}=e,de=pb(),$=m.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),z=Ea(n.stores.location,Ge=>Ge,(Ge,yt)=>Ge.href===yt.href),D=m.useMemo(()=>{const Ge={_fromLocation:z,...$};return n.buildLocation(Ge)},[n,z,$]),F=D.maskedLocation?D.maskedLocation.publicHref:D.publicHref,G=D.maskedLocation?D.maskedLocation.external:D.external,te=m.useMemo(()=>fk(F,G,n.history,y),[y,G,F,n.history]),B=m.useMemo(()=>{if(te?.external)return Ol(te.href,n.protocolAllowlist)?void 0:te.href;if(!xk(l)&&!(typeof l!="string"||l.indexOf(":")===-1))try{return new URL(l),Ol(l,n.protocolAllowlist)?void 0:l}catch{}},[l,te,n.protocolAllowlist]),ne=m.useMemo(()=>{if(B)return!1;if(o?.exact){if(!fw(z.pathname,D.pathname,n.basepath))return!1}else{const Ge=$l(z.pathname,n.basepath),yt=$l(D.pathname,n.basepath);if(!(Ge.startsWith(yt)&&(Ge.length===yt.length||Ge[yt.length]==="/")))return!1}return(o?.includeSearch??!0)&&!Ss(z.search,D.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:o?.includeHash?de&&z.hash===D.hash:!0},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,z,B,de,D.hash,D.pathname,D.search,n.basepath]),me=ne?js(i,{})??dk:ud,Ee=ne?ud:js(r,{})??ud,L=[w,me.className,Ee.className].filter(Boolean).join(" "),re=(k||me.style||Ee.style)&&{...k,...me.style,...Ee.style},[ke,H]=m.useState(!1),fe=m.useRef(!1),Z=e.reloadDocument||B?!1:c??n.options.defaultPreload,ae=d??n.options.defaultPreloadDelay??0,pe=m.useCallback(()=>{n.preloadRoute({...$,_builtLocation:D}).catch(Ge=>{console.warn(Ge),console.warn(Zw)})},[n,$,D]);Zj(s,m.useCallback(Ge=>{Ge?.isIntersecting&&pe()},[pe]),mk,{disabled:!!y||Z!=="viewport"}),m.useEffect(()=>{fe.current||!y&&Z==="render"&&(pe(),fe.current=!0)},[y,pe,Z]);const ye=Ge=>{const yt=Ge.currentTarget.getAttribute("target"),ve=v!==void 0?v:yt;if(!y&&!gk(Ge)&&!Ge.defaultPrevented&&(!ve||ve==="_self")&&Ge.button===0){Ge.preventDefault(),Ti.flushSync(()=>{H(!0)});const Ke=n.subscribe("onResolved",()=>{Ke(),H(!1)});n.navigate({...$,replace:f,resetScroll:h,hashScrollIntoView:p,startTransition:x,viewTransition:b,ignoreBlocker:A})}};if(B)return{...ie,ref:s,href:B,...g&&{children:g},...v&&{target:v},...y&&{disabled:y},...k&&{style:k},...w&&{className:w},...j&&{onClick:j},...C&&{onBlur:C},...N&&{onFocus:N},...S&&{onMouseEnter:S},..._&&{onMouseLeave:_},...R&&{onTouchStart:R}};const qe=Ge=>{if(y||Z!=="intent")return;if(!ae){pe();return}const yt=Ge.currentTarget;if(Yi.has(yt))return;const ve=setTimeout(()=>{Yi.delete(yt),pe()},ae);Yi.set(yt,ve)},ut=Ge=>{y||Z!=="intent"||pe()},bt=Ge=>{if(y||!Z||!ae)return;const yt=Ge.currentTarget,ve=Yi.get(yt);ve&&(clearTimeout(ve),Yi.delete(yt))};return{...ie,...me,...Ee,href:te?.href,ref:s,onClick:Ks([j,ye]),onBlur:Ks([C,bt]),onFocus:Ks([N,qe]),onMouseEnter:Ks([S,qe]),onMouseLeave:Ks([_,bt]),onTouchStart:Ks([R,ut]),disabled:!!y,target:v,...re&&{style:re},...L&&{className:L},...y&&uk,...ne&&pk,...de&&ke&&hk}}var ud={},dk={className:"active"},uk={role:"link","aria-disabled":!0},pk={"data-status":"active","aria-current":"page"},hk={"data-transitioning":"transitioning"},Yi=new WeakMap,mk={rootMargin:"100px"},Ks=e=>a=>{for(const n of e)if(n){if(a.defaultPrevented)return;n(a)}};function fk(e,a,n,s){if(!s)return a?{href:e,external:!0}:{href:n.createHref(e)||"/",external:!1}}function xk(e){if(typeof e!="string")return!1;const a=e.charCodeAt(0);return a===47?e.charCodeAt(1)!==47:a===46}var et=m.forwardRef((e,a)=>{const{_asChild:n,...s}=e,{type:i,...r}=ck(s,a),o=typeof s.children=="function"?s.children({isActive:r["data-status"]==="active"}):s.children;if(!n){const{disabled:l,...c}=r;return m.createElement("a",c,o)}return m.createElement(n,r,o)});function gk(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var bk=class extends ub{constructor(e){super(e),this.useMatch=a=>Fs({select:a?.select,from:this.id,structuralSharing:a?.structuralSharing}),this.useRouteContext=a=>vb({...a,from:this.id}),this.useSearch=a=>Os({select:a?.select,structuralSharing:a?.structuralSharing,from:this.id}),this.useParams=a=>yb({select:a?.select,structuralSharing:a?.structuralSharing,from:this.id}),this.useLoaderDeps=a=>bb({...a,from:this.id}),this.useLoaderData=a=>gb({...a,from:this.id}),this.useNavigate=()=>dt({from:this.fullPath}),this.Link=Xa.forwardRef((a,n)=>t.jsx(et,{ref:n,from:this.fullPath,...a}))}};function we(e){return new bk(e)}var yk=class extends Yw{constructor(e){super(e),this.useMatch=a=>Fs({select:a?.select,from:this.id,structuralSharing:a?.structuralSharing}),this.useRouteContext=a=>vb({...a,from:this.id}),this.useSearch=a=>Os({select:a?.select,structuralSharing:a?.structuralSharing,from:this.id}),this.useParams=a=>yb({select:a?.select,structuralSharing:a?.structuralSharing,from:this.id}),this.useLoaderDeps=a=>bb({...a,from:this.id}),this.useLoaderData=a=>gb({...a,from:this.id}),this.useNavigate=()=>dt({from:this.fullPath}),this.Link=Xa.forwardRef((a,n)=>t.jsx(et,{ref:n,from:this.fullPath,...a}))}};function vk(e){return new yk(e)}function We(e,a){let n,s,i,r;const o=()=>(n||(n=e().then(c=>{n=void 0,s=c.default}).catch(c=>{if(i=c,ew(i)&&i instanceof Error&&typeof window<"u"&&typeof sessionStorage<"u"){const d=`tanstack_router_reload:${i.message}`;sessionStorage.getItem(d)||(sessionStorage.setItem(d,"1"),r=!0)}})),n),l=function(d){if(r)throw window.location.reload(),new Promise(()=>{});if(i)throw i;if(!s)if(mm)mm(o());else throw o();return m.createElement(s,d)};return l.preload=o,l}function jk(e){const a=ha(),n=`not-found-${Ea(a.stores.location,s=>s.pathname)}-${Ea(a.stores.status,s=>s)}`;return t.jsx(Ip,{getResetKey:()=>n,onCatch:(s,i)=>{if(ta(s))e.onCatch?.(s,i);else throw s},errorComponent:({error:s})=>{if(ta(s))return e.fallback?.(s);throw s},children:e.children})}function wk(){return t.jsx("p",{children:"Not Found"})}function oi(e){return t.jsx(t.Fragment,{children:e.children})}function jb(e,a,n){return a.options.notFoundComponent?t.jsx(a.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?t.jsx(e.options.defaultNotFoundComponent,{...n}):t.jsx(wk,{})}function kk(e){return null}function Nk(){return kk(ha()),null}
2var wb=m.memo(function({matchId:a}){const n=ha(),s=n.stores.matchStores.get(a);s||Cn();const i=Ea(n.stores.loadedAt,o=>o),r=Ea(s,o=>o);return t.jsx(Sk,{router:n,matchId:a,resetKey:i,matchState:m.useMemo(()=>{const o=r.routeId,l=n.routesById[o].parentRoute?.id;return{routeId:o,ssr:r.ssr,_displayPending:r._displayPending,parentRouteId:l}},[r._displayPending,r.routeId,r.ssr,n.routesById])})});function Sk({router:e,matchId:a,resetKey:n,matchState:s}){const i=e.routesById[s.routeId],r=i.options.pendingComponent??e.options.defaultPendingComponent,o=r?t.jsx(r,{}):null,l=i.options.errorComponent??e.options.defaultErrorComponent,c=i.options.onCatch??e.options.defaultOnCatch,d=i.isRoot?i.options.notFoundComponent??e.options.notFoundRoute?.options.component:i.options.notFoundComponent,u=s.ssr===!1||s.ssr==="data-only",p=(!i.isRoot||i.options.wrapInSuspense||u)&&(i.options.wrapInSuspense??r??(i.options.errorComponent?.preload||u))?m.Suspense:oi,f=l?Ip:oi,x=d?jk:oi;return t.jsxs(i.isRoot?i.options.shellComponent??oi:oi,{children:[t.jsx(fc.Provider,{value:a,children:t.jsx(p,{fallback:o,children:t.jsx(f,{getResetKey:()=>n,errorComponent:l||Lp,onCatch:(h,b)=>{if(ta(h))throw h.routeId??=s.routeId,h;c?.(h,b)},children:t.jsx(x,{fallback:h=>{if(h.routeId??=s.routeId,!d||h.routeId&&h.routeId!==s.routeId||!h.routeId&&!i.isRoot)throw h;return m.createElement(d,h)},children:u||s._displayPending?t.jsx(Jw,{fallback:o,children:t.jsx(Lm,{matchId:a})}):t.jsx(Lm,{matchId:a})})})})}),s.parentRouteId===Cs?t.jsxs(t.Fragment,{children:[t.jsx(Ck,{resetKey:n}),e.options.scrollRestoration&&Zg?t.jsx(Nk,{}):null]}):null]})}function Ck({resetKey:e}){const a=ha(),n=m.useRef(void 0);return xr(()=>{const s=a.latestLocation.href;(n.current===void 0||n.current!==s)&&(a.emit({type:"onRendered",...mi(a.stores.location.get(),a.stores.resolvedLocation.get())}),n.current=s)},[a.latestLocation.state.__TSR_key,e,a]),null}var Lm=m.memo(function({matchId:a}){const n=ha(),s=(u,p)=>n.getMatch(u.id)?._nonReactive[p]??u._nonReactive[p],i=n.stores.matchStores.get(a);i||Cn();const r=Ea(i,u=>u),o=r.routeId,l=n.routesById[o],c=m.useMemo(()=>{const u=(n.routesById[o].options.remountDeps??n.options.defaultRemountDeps)?.({routeId:o,loaderDeps:r.loaderDeps,params:r._strictParams,search:r._strictSearch});return u?JSON.stringify(u):void 0},[o,r.loaderDeps,r._strictParams,r._strictSearch,n.options.defaultRemountDeps,n.routesById]),d=m.useMemo(()=>{const u=l.options.component??n.options.defaultComponent;return u?t.jsx(u,{},c):t.jsx(Fp,{})},[c,l.options.component,n.options.defaultComponent]);if(r._displayPending)throw s(r,"displayPendingPromise");if(r._forcePending)throw s(r,"minPendingPromise");if(r.status==="pending"){const u=l.options.pendingMinMs??n.options.defaultPendingMinMs;if(u){const p=n.getMatch(r.id);if(p&&!p._nonReactive.minPendingPromise){const f=gi();p._nonReactive.minPendingPromise=f,setTimeout(()=>{f.resolve(),p._nonReactive.minPendingPromise=void 0},u)}}throw s(r,"loadPromise")}if(r.status==="notFound")return ta(r.error)||Cn(),jb(n,l,r.error);if(r.status==="redirected")throw va(r.error)||Cn(),s(r,"loadPromise");if(r.status==="error")throw r.error;return d}),Fp=m.memo(function(){const a=ha(),n=m.useContext(fc);let s,i=!1,r;{const d=n?a.stores.matchStores.get(n):void 0;[s,i]=Ea(d,u=>[u?.routeId,u?.globalNotFound??!1]),r=Ea(a.stores.matchesId,u=>u[u.findIndex(p=>p===n)+1])}const o=s?a.routesById[s]:void 0,l=a.options.defaultPendingComponent?t.jsx(a.options.defaultPendingComponent,{}):null;if(i)return o||Cn(),jb(a,o,void 0);if(!r)return null;const c=t.jsx(wb,{matchId:r});return s===Cs?t.jsx(m.Suspense,{fallback:l,children:c}):c});function _k(){const e=ha(),a=m.useRef({router:e,mounted:!1}),[n,s]=m.useState(!1),i=Ea(e.stores.isLoading,p=>p),r=Ea(e.stores.hasPending,p=>p),o=sd(i),l=i||n||r,c=sd(l),d=i||r,u=sd(d);return e.startTransition=p=>{s(!0),m.startTransition(()=>{p(),s(!1)})},m.useEffect(()=>{const p=e.history.subscribe(e.load),f=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return Nn(e.latestLocation.publicHref)!==Nn(f.publicHref)&&e.commitLocation({...f,replace:!0}),()=>{p()}},[e,e.history]),xr(()=>{if(typeof window<"u"&&e.ssr||a.current.router===e&&a.current.mounted)return;a.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(f){console.error(f)}})()},[e]),xr(()=>{o&&!i&&e.emit({type:"onLoad",...mi(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,i]),xr(()=>{u&&!d&&e.emit({type:"onBeforeRouteMount",...mi(e.stores.location.get(),e.stores.resolvedLocation.get())})},[d,u,e]),xr(()=>{if(c&&!l){const p=mi(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:"onResolved",...p}),fb(()=>{e.stores.status.set("idle"),e.stores.resolvedLocation.set(e.stores.location.get())})}},[l,c,e]),null}function Ek(){const e=ha(),a=e.routesById[Cs].options.pendingComponent??e.options.defaultPendingComponent,n=a?t.jsx(a,{}):null,s=t.jsxs(typeof document<"u"&&e.ssr?oi:m.Suspense,{fallback:n,children:[t.jsx(_k,{}),t.jsx(Ak,{})]});return e.options.InnerWrap?t.jsx(e.options.InnerWrap,{children:s}):s}function Ak(){const e=ha(),a=Ea(e.stores.firstId,i=>i),n=Ea(e.stores.loadedAt,i=>i),s=a?t.jsx(wb,{matchId:a}):null;return t.jsx(fc.Provider,{value:a,children:e.options.disableGlobalCatchBoundary?s:t.jsx(Ip,{getResetKey:()=>n,errorComponent:Lp,onCatch:void 0,children:s})})}var Rk=e=>({createMutableStore:Im,createReadonlyStore:Im,batch:fb}),Tk=e=>
2new Mk(e),Mk=class extends Iw{constructor(e){super(e,Rk)}};function Pk({router:e,children:a,...n}){Xg(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});const s=t.jsx(hb.Provider,{value:e,children:a});return e.options.Wrap?t.jsx(e.options.Wrap,{children:s}):s}function zk({router:e,...a}){return t.jsx(Pk,{router:e,...a,children:t.jsx(Ek,{})})}function Dk(e,a){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const n=!!(e.condition??!0),s=e.blockerFn;return{shouldBlockFn:async()=>n&&s!==void 0?await s():n,enableBeforeUnload:n,withResolver:s===void 0}}function Ik(e,a){const{shouldBlockFn:n,enableBeforeUnload:s=!0,disabled:i=!1,withResolver:r=!1}=Dk(e),o=ha(),{history:l}=o,[c,d]=m.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return m.useEffect(()=>{const u=async p=>{function f(v){const y=o.parseLocation(v),k=o.getMatchedRoutes(y.pathname);return k.foundRoute===void 0?{routeId:"__notFound__",fullPath:y.pathname,pathname:y.pathname,params:k.routeParams,search:o.options.parseSearch(v.search)}:{routeId:k.foundRoute.id,fullPath:k.foundRoute.fullPath,pathname:y.pathname,params:k.routeParams,search:o.options.parseSearch(v.search)}}const x=f(p.currentLocation),h=f(p.nextLocation);if(x.routeId==="__notFound__"&&h.routeId!=="__notFound__")return!1;const b=await n({action:p.action,current:x,next:h});if(!r)return b;if(!b)return!1;const g=await new Promise(v=>{d({status:"blocked",current:x,next:h,action:p.action,proceed:()=>v(!1),reset:()=>v(!0)})});return d({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),g};return i?void 0:l.block({blockerFn:u,enableBeforeUnload:s})},[n,s,i,r,l,o]),c}function bu(e){const a=ha({warn:e?.router===void 0}),n=e?.router||a,s=m.useRef(void 0);return Ea(n.stores.__store,i=>{if(e?.select){if(e.structuralSharing??n.options.defaultStructuralSharing){const r=Un(s.current,e.select(i));return s.current=r,r}return e.select(i)}return i})}var Pi=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Lk=class extends Pi{#e;#t;#a;constructor(){super(),this.#a=e=>{if(typeof window<"u"&&window.addEventListener){const a=()=>e();return window.addEventListener("visibilitychange",a,!1),()=>{window.removeEventListener("visibilitychange",a)}}}}onSubscribe(){this.#t||this.setEventListener(this.#a)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#a=e,this.#t?.(),this.#t=e(a=>{typeof a=="boolean"?this.setFocused(a):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(a=>{a(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Op=new Lk,Fk={setTimeout:(e,a)=>setTimeout(e,a),clearTimeout:e=>clearTimeout(e),setInterval:(e,a)=>setInterval(e,a),clearInterval:e=>clearInterval(e)},Ok=class{#e=Fk;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,a){return this.#e.setTimeout(e,a)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,a){return this.#e.setInterval(e,a)}clearInterval(e){this.#e.clearInterval(e)}},ks=new Ok;function $k(e){setTimeout(e,0)}var qk=typeof window>"u"||"Deno"in globalThis;function ra(){}function Bk(e,a){return typeof e=="function"?e(a):e}function yu(e){return typeof e=="number"&&e>=0&&e!==1/0}function kb(e,a){return Math.max(e+(a||0)-Date.now(),0)}function Gn(e,a){return typeof e=="function"?e(a):e}function Aa(e,a){return typeof e=="function"?e(a):e}function Fm(e,a){const{type:n="all",exact:s,fetchStatus:i,predicate:r,queryKey:o,stale:l}=e;if(o){if(s){if(a.queryHash!==$p(o,a.options))return!1}else if(!Ur(a.queryKey,o))return!1}if(n!=="all"){const c=a.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof l=="boolean"&&a.isStale()!==l||i&&i!==a.state.fetchStatus||r&&!r(a))}
vendor: 4,319 bytes, line 2
2function Om(e,a){const{exact:n,status:s,predicate:i,mutationKey:r}=e;if(r){if(!a.options.mutationKey)return!1;if(n){if(Ms(a.options.mutationKey)!==Ms(r))return!1}else if(!Ur(a.options.mutationKey,r))return!1}return!(s&&a.state.status!==s||i&&!i(a))}function $p(e,a){return(a?.queryKeyHashFn||Ms)(e)}function Ms(e){return JSON.stringify(e,(a,n)=>vu(n)?Object.keys(n).sort().reduce((s,i)=>(s[i]=n[i],s),{}):n)}function Ur(e,a){return e===a?!0:typeof e!=typeof a?!1:e&&a&&typeof e=="object"&&typeof a=="object"?Object.keys(a).every(n=>Ur(e[n],a[n])):!1}var Wk=Object.prototype.hasOwnProperty;function Nb(e,a,n=0){if(e===a)return e;if(n>500)return a;const s=$m(e)&&$m(a);if(!s&&!(vu(e)&&vu(a)))return a;const r=(s?e:Object.keys(e)).length,o=s?a:Object.keys(a),l=o.length,c=s?new Array(l):{};let d=0;for(let u=0;u<l;u++){const p=s?u:o[u],f=e[p],x=a[p];if(f===x){c[p]=f,(s?u<r:Wk.call(e,p))&&d++;continue}if(f===null||x===null||typeof f!="object"||typeof x!="object"){c[p]=x;continue}const h=Nb(f,x,n+1);c[p]=h,h===f&&d++}return r===l&&d===r?e:c}function Ul(e,a){if(!a||Object.keys(e).length!==Object.keys(a).length)return!1;for(const n in e)if(e[n]!==a[n])return!1;return!0}function $m(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function vu(e){if(!qm(e))return!1;const a=e.constructor;if(a===void 0)return!0;const n=a.prototype;return!(!qm(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function qm(e){return Object.prototype.toString.call(e)==="[object Object]"}function Uk(e){return new Promise(a=>{ks.setTimeout(a,e)})}function ju(e,a,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,a):n.structuralSharing!==!1?Nb(e,a):a}function xc(e){return e}function Vk(e,a,n=0){const s=[...e,a];return n&&s.length>n?s.slice(1):s}function Kk(e,a,n=0){const s=[a,...e];return n&&s.length>n?s.slice(0,-1):s}var qp=Symbol();function Sb(e,a){return!e.queryFn&&a?.initialPromise?()=>a.initialPromise:!e.queryFn||e.queryFn===qp?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Bp(e,a){return typeof e=="function"?e(...a):!!e}function Hk(e,a,n){let s=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=a(),s||(s=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var Vr=(()=>{let e=()=>qk;return{isServer(){return e()},setIsServer(a){e=a}}})();function wu(){let e,a;const n=new Promise((i,r)=>{e=i,a=r});n.status="pending",n.catch(()=>{});function s(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{s({status:"fulfilled",value:i}),e(i)},n.reject=i=>{s({status:"rejected",reason:i}),a(i)},n}var Qk=$k;function Gk(){let e=[],a=0,n=l=>{l()},s=l=>{l()},i=Qk;const r=l=>{a?e.push(l):i(()=>{n(l)})},o=()=>{const l=e;e=[],l.length&&i(()=>{s(()=>{l.forEach(c=>{n(c)})})})};return{batch:l=>{let c;a++;try{c=l()}finally{a--,a||o()}return c},batchCalls:l=>(...c)=>{r(()=>{l(...c)})},schedule:r,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{s=l},setScheduler:l=>{i=l}}}var Ht=Gk(),Zk=class extends Pi{#e=!0;#t;#a;constructor(){super(),this.#a=e=>{if(typeof window<"u"&&window.addEventListener){const a=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",a,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",a),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#a)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#a=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},Vl=new Zk;function Yk(e){return Math.min(1e3*2**e,3e4)}function Cb(e){return(e??"online")==="online"?Vl.isOnline():!0}var ku=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function _b(e){let a=!1,n=0,s;const i=wu(),r=()=>i.status!=="pending",o=b=>{if(!r()){const g=new ku(b);f(g),e.onCancel?.(g)}},l=()=>{a=!0},c=()=>{a=!1},d=()=>Op.isFocused()&&(e.networkMode==="always"||Vl.isOnline())&&e.canRun(),u=()=>Cb(e.networkMode)&&e.canRun(),p=b=>{r()||(s?.(),i.resolve(b))},f=b=>{r()||(s?.(),i.reject(b))},x=()=>new Promise(b=>{s=g=>{(r()||d())&&b(g)},e.onPause?.()}).then(()=>{s=void 0,r()||e.onContinue?.()}),h=()=>
2{if(r())return;let b;const g=n===0?e.initialPromise:void 0;try{b=g??e.fn()}catch(v){b=Promise.reject(v)}Promise.resolve(b).then(p).catch(v=>{if(r())return;const y=e.retry??(Vr.isServer()?0:3),k=e.retryDelay??Yk,w=typeof k=="function"?k(n,v):k,j=y===!0||typeof y=="number"&&n<y||typeof y=="function"&&y(n,v);if(a||!j){f(v);return}n++,e.onFail?.(n,v),Uk(w).then(()=>d()?void 0:x()).then(()=>{a?f(v):h()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(s?.(),i),cancelRetry:l,continueRetry:c,canStart:u,start:()=>(u()?h():x().then(h),i)}}var Eb=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),yu(this.gcTime)&&(this.#e=ks.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Vr.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(ks.clearTimeout(this.#e),this.#e=void 0)}};function Xk(e){return{onFetch:(a,n)=>{const s=a.options,i=a.fetchOptions?.meta?.fetchMore?.direction,r=a.state.data?.pages||[],o=a.state.data?.pageParams||[];let l={pages:[],pageParams:[]},c=0;const d=async()=>{let u=!1;const p=h=>{Hk(h,()=>a.signal,()=>u=!0)},f=Sb(a.options,a.fetchOptions),x=async(h,b,g)=>{if(u)return Promise.reject(a.signal.reason);if(b==null&&h.pages.length)return Promise.resolve(h);const y=(()=>{const C={client:a.client,queryKey:a.queryKey,pageParam:b,direction:g?"backward":"forward",meta:a.options.meta};return p(C),C})(),k=await f(y),{maxPages:w}=a.options,j=g?Kk:Vk;return{pages:j(h.pages,k,w),pageParams:j(h.pageParams,b,w)}};if(i&&r.length){const h=i==="backward",b=h?Ab:Nu,g={pages:r,pageParams:o},v=b(s,g);l=await x(g,v,h)}else{const h=e??r.length;do{const b=c===0?o[0]??s.initialPageParam:Nu(s,l);if(c>0&&b==null)break;l=await x(l,b),c++}while(c<h)}return l};a.options.persister?a.fetchFn=()=>a.options.persister?.(d,{client:a.client,queryKey:a.queryKey,meta:a.options.meta,signal:a.signal},n):a.fetchFn=d}}}function Nu(e,{pages:a,pageParams:n}){const s=a.length-1;return a.length>0?e.getNextPageParam(a[s],a,n[s],n):void 0}function Ab(e,{pages:a,pageParams:n}){return a.length>0?e.getPreviousPageParam?.(a[0],a,n[0],n):void 0}function Jk(e,a){return a?Nu(e,a)!=null:!1}function eN(e,a){return!a||!e.getPreviousPageParam?!1:Ab(e,a)!=null}var tN=class extends Eb{#e;#t;#a;#n;#i;#s;#o;#r;constructor(e){super(),this.#r=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#n=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Wm(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#s?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const a=Wm(this.options);a.data!==void 0&&(this.setState(Bm(a.data,a.dataUpdatedAt)),this.#t=a)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,a){const n=ju(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:a?.updatedAt,manual:a?.manual}),n}setState(e){this.#l({type:"setState",state:e})}cancel(e){const a=this.#s?.promise;return this.#s?.cancel(e),a?a.then(ra).catch(ra):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Aa(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===qp||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Gn(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!kb(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(a=>a.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(a=>a.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(a=>a!==e),this.observers.length||(this.#s&&(this.#r||this.#d()?this.#s.c
vendor: 9,367 bytes, line 2
2ancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#d(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({type:"invalidate"})}async fetch(e,a){if(this.state.fetchStatus!=="idle"&&this.#s?.status()!=="rejected"){if(this.state.data!==void 0&&a?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(d=>d.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#r=!0,n.signal)})},i=()=>{const c=Sb(this.options,a),u=(()=>{const p={client:this.#i,queryKey:this.queryKey,meta:this.meta};return s(p),p})();return this.#r=!1,this.options.persister?this.options.persister(c,u,this):c(u)},o=(()=>{const c={fetchOptions:a,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return s(c),c})();(this.#e==="infinite"?Xk(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#a=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#l({type:"fetch",meta:o.fetchOptions?.meta}),this.#s=_b({initialPromise:a?.initialPromise,fn:o.fetchFn,onCancel:c=>{c instanceof ku&&c.revert&&this.setState({...this.#a,fetchStatus:"idle"}),n.abort()},onFail:(c,d)=>{this.#l({type:"failed",failureCount:c,error:d})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const c=await this.#s.start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof ku){if(c.silent)return this.#s.promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw this.#l({type:"error",error:c}),this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}#l(e){const a=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Rb(n.data,this.options),fetchMeta:e.meta??null};case"success":const s={...n,...Bm(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#a=e.manual?s:void 0,s;case"error":const i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=a(this.state),Ht.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Rb(e,a){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Cb(a.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Bm(e,a){return{data:e,dataUpdatedAt:a??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Wm(e){const a=typeof e.initialData=="function"?e.initialData():e.initialData,n=a!==void 0,s=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:a,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Tb=class extends Pi{constructor(e,a){super(),this.options=a,this.#e=e,this.#r=null,this.#o=wu(),this.bindMethods(),this.setOptions(a)}#e;#t=void 0;#a=void 0;#n=void 0;#i;#s;#o;#r;#d;#l;#m;#u;#p;#c;#f=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Um(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Su(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Su(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#v(),this.#j(),this.#t.removeObserver(this)}setOptions(e){const a=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Aa(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#w(),this.#t.setOptions(this.options),a._defaulted&&!Ul(this.options,a)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const s=this.hasListeners();s&&Vm(this.#t,n,this.options,a)&&this.#h(),this.updateResult(),s&&(this.#t!==n||Aa(this.options.enabled,this.#t)!==Aa(a.enabled,this.#t)||Gn(this.options.staleTime,this.#t)!==Gn(a.staleTime,this.#t))&&this.#x();const i=this.#g();s&&(this.#t!==n||Aa(this.options.enabled,this.#t)!==Aa(a.enabled,this.#t)||i!==this.#c)&&this.#b(i)}getOptimisticResult(e){const a=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(a,e);return nN(this,n)&&(this.#n=n,this.#s=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#n}trackResult(e,a){return new Proxy(e,{get:(n,s)=>(this.trackProp(s),a?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,s))})}trackProp(e){this.#f.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const a=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,a);return n.fetch().then(()=>this.createResult(n,a))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#h(e){this.#w();let a=this.#t.fetch(this.options,e);return e?.throwOnError||(a=a.catch(ra)),a}#x(){this.#v();const e=Gn(this.options.staleTime,this.#t);if(Vr.isServer()||this.#n.isStale||!yu(e))return;const n=kb(this.#n.dataUpdatedAt,e)+1;this.#u=ks.setTimeout(()=>{this.#n.isStale||this.updateResult()},n)}#g(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(e){this.#j(),this.#c=e,!(Vr.isServer()||Aa(this.options.enabled,this.#t)===!1||!yu(this.#c)||this.#c===0)&&(this.#p=ks.setInterval(()=>{(this.options.refetchIntervalInBackground||Op.isFocused())&&this.#h()},this.#c))}#y(){this.#x(),this.#b(this.#g())}#v(){this.#u!==void 0&&(ks.clearTimeout(this.#u),this.#u=void 0)}#j(){this.#p!==void 0&&(ks.clearInterval(this.#p),this.#p=void 0)}createResult(e,a){const n=this.#t,s=this.options,i=this.#n,r=this.#i,o=this.#s,c=e!==n?e.state:this.#a,{state:d}=e;let u={...d},p=!1,f;if(a._optimisticResults){const S=this.hasListeners(),_=!S&&Um(e,a),R=S&&Vm(e,n,a,s);(_||R)&&(u={...u,...Rb(d.data,e.options)}),a._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:x,errorUpdatedAt:h,status:b}=u;f=u.data;let g=!1;if(a.placeholderData!==void 0&&f===void 0&&b==="pending"){let S;i?.isPlaceholderData&&a.placeholderData===o?.placeholderData?(S=i.data,g=!0):S=typeof a.placeholderData=="function"?a.placeholderData(this.#m?.state.data,this.#m):a.placeholderData,S!==void 0&&(b="success",f=ju(i?.data,S,a),p=!0)}if(a.select&&f!==void 0&&!g)if(i&&f===r?.data&&a.select===this.#d)f=this.#l;else try{this.#d=a.select,f=a.select(f),f=ju(i?.data,f,a),this.#l=f,this.#r=null}catch(S){this.#r=S}this.#r&&(x=this.#r,f=this.#l,h=Date.now(),b="error");const v=u.fetchStatus==="fetching",y=b==="pending",k=b==="error",w=y&&v,j=f!==void 0,N={status:b,fetchStatus:u.fetchStatus,isPending:y,isSuccess:b==="success",isError:k,isInitialLoading:w,isLoading:w,data:f,dataUpdatedAt:u.dataUpdatedAt,error:x,errorUpdatedAt:h,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:v,isRefetching:v&&!y,isLoadingError:k&&!j,isPaused:u.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:k&&j,isStale:Wp(e,a),refetch:this.refetch,promise:this.#o,isEnabled:Aa(a.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const S=N.data!==void 0,_=N.status==="error"&&!S,R=I=>{_?I.reject(N.error):S&&I.resolve(N.data)},A=()=>{const I=this.#o=N.promise=wu();R(I)},E=this.#o;switch(E.status){case"pending":e.queryHash===n.queryHash&&R(E);break;case"fulfilled":(_||N.data!==E.value)&&A();break;case"rejected":(!_||N.error!==E.reason)&&A();break}}return N}updateResult(){const e=this.#n,a=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#s=this.options,this.#i.data!==void 0&&(this.#m=this.#t),Ul(a,e))return;this.#n=a;const n=()=>
2{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!this.#f.size)return!0;const r=new Set(i??this.#f);return this.options.throwOnError&&r.add("error"),Object.keys(this.#n).some(o=>{const l=o;return this.#n[l]!==e[l]&&r.has(l)})};this.#k({listeners:n()})}#w(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const a=this.#t;this.#t=e,this.#a=e.state,this.hasListeners()&&(a?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#k(e){Ht.batch(()=>{e.listeners&&this.listeners.forEach(a=>{a(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function aN(e,a){return Aa(a.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&Aa(a.retryOnMount,e)===!1)}function Um(e,a){return aN(e,a)||e.state.data!==void 0&&Su(e,a,a.refetchOnMount)}function Su(e,a,n){if(Aa(a.enabled,e)!==!1&&Gn(a.staleTime,e)!=="static"){const s=typeof n=="function"?n(e):n;return s==="always"||s!==!1&&Wp(e,a)}return!1}function Vm(e,a,n,s){return(e!==a||Aa(s.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Wp(e,n)}function Wp(e,a){return Aa(a.enabled,e)!==!1&&e.isStaleByTime(Gn(a.staleTime,e))}function nN(e,a){return!Ul(e.getCurrentResult(),a)}var sN=class extends Tb{constructor(e,a){super(e,a)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,a){const{state:n}=e,s=super.createResult(e,a),{isFetching:i,isRefetching:r,isError:o,isRefetchError:l}=s,c=n.fetchMeta?.fetchMore?.direction,d=o&&c==="forward",u=i&&c==="forward",p=o&&c==="backward",f=i&&c==="backward";return{...s,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Jk(a,n.data),hasPreviousPage:eN(a,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:l&&!d&&!p,isRefetching:r&&!u&&!f}}},iN=class extends Eb{#e;#t;#a;#n;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#a=e.mutationCache,this.#t=[],this.state=e.state||Mb(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(a=>a!==e),this.scheduleGc(),this.#a.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#a.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const a=()=>{this.#i({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=_b({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(r,o)=>{this.#i({type:"failed",failureCount:r,error:o})},onPause:()=>{this.#i({type:"pause"})},onContinue:a,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#a.canRun(this)});const s=this.state.status==="pending",i=!this.#n.canStart();try{if(s)a();else{this.#i({type:"pending",variables:e,isPaused:i}),this.#a.config.onMutate&&await this.#a.config.onMutate(e,this,n);const o=await this.options.onMutate?.(e,n);o!==this.state.context&&this.#i({type:"pending",context:o,variables:e,isPaused:i})}const r=await this.#n.start();return await this.#a.config.onSuccess?.(r,e,this.state.context,this,n),await this.options.onSuccess?.(r,e,this.state.context,n),await this.#a.config.onSettled?.(r,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(r,null,e,this.state.context,n),this.#i({type:"success",data:r}),r}catch(r){try{await this.#a.config.onError?.(r,e,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onError?.(r,e,this.state.context,n)}catch(o){Promise.reject(o)}try{await this.#a.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,r,e,this.state.context,n)}catch(o){Promise.reject(o)}throw this.#i({type:"error",error:r}),r}finally{this.#a.runNext(this)}}#i(e){const a=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};
2case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=a(this.state),Ht.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#a.notify({mutation:this,type:"updated",action:e})})}};function Mb(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var rN=class extends Pi{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#a=0}#e;#t;#a;build(e,a,n){const s=new iN({client:e,mutationCache:this,mutationId:++this.#a,options:e.defaultMutationOptions(a),state:n});return this.add(s),s}add(e){this.#e.add(e);const a=qo(e);if(typeof a=="string"){const n=this.#t.get(a);n?n.push(e):this.#t.set(a,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const a=qo(e);if(typeof a=="string"){const n=this.#t.get(a);if(n)if(n.length>1){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}else n[0]===e&&this.#t.delete(a)}}this.notify({type:"removed",mutation:e})}canRun(e){const a=qo(e);if(typeof a=="string"){const s=this.#t.get(a)?.find(i=>i.state.status==="pending");return!s||s===e}else return!0}runNext(e){const a=qo(e);return typeof a=="string"?this.#t.get(a)?.find(s=>s!==e&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Ht.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const a={exact:!0,...e};return this.getAll().find(n=>Om(a,n))}findAll(e={}){return this.getAll().filter(a=>Om(e,a))}notify(e){Ht.batch(()=>{this.listeners.forEach(a=>{a(e)})})}resumePausedMutations(){const e=this.getAll().filter(a=>a.state.isPaused);return Ht.batch(()=>Promise.all(e.map(a=>a.continue().catch(ra))))}};function qo(e){return e.options.scope?.id}var oN=class extends Pi{#e;#t=void 0;#a;#n;constructor(e,a){super(),this.#e=e,this.setOptions(a),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const a=this.options;this.options=this.#e.defaultMutationOptions(e),Ul(this.options,a)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#a,observer:this}),a?.mutationKey&&this.options.mutationKey&&Ms(a.mutationKey)!==Ms(this.options.mutationKey)?this.reset():this.#a?.state.status==="pending"&&this.#a.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#a?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#s(e)}getCurrentResult(){return this.#t}reset(){this.#a?.removeObserver(this),this.#a=void 0,this.#i(),this.#s()}mutate(e,a){return this.#n=a,this.#a?.removeObserver(this),this.#a=this.#e.getMutationCache().build(this.#e,this.options),this.#a.addObserver(this),this.#a.execute(e)}#i(){const e=this.#a?.state??Mb();this.#t={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#s(e){Ht.batch(()=>{if(this.#n&&this.hasListeners()){const a=this.#t.variables,n=this.#t.context,s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,a,n,s)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(e.data,null,a,n,s)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,a,n,s)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(void 0,e.error,a,n,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(a=>{a(this.#t)})})}},lN=class extends Pi{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,a,n){const s=a.queryKey,i=a.queryHash??$p(s,a);let r=this.get(i);return r||(r=new tN({client:e,queryKey:s,queryHash:i,options:e.defaultQueryOptions(a),state:n,defaultOptions:e.getQueryDefaults(s)}),this.add(r)),r}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const a=this.#e.get(e.queryHash);a&&(e.destroy(),a===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ht.batch(()=>
vendor: 4,961 bytes, line 2
2{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const a={exact:!0,...e};return this.getAll().find(n=>Fm(a,n))}findAll(e={}){const a=this.getAll();return Object.keys(e).length>0?a.filter(n=>Fm(e,n)):a}notify(e){Ht.batch(()=>{this.listeners.forEach(a=>{a(e)})})}onFocus(){Ht.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ht.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},cN=class{#e;#t;#a;#n;#i;#s;#o;#r;constructor(e={}){this.#e=e.queryCache||new lN,this.#t=e.mutationCache||new rN,this.#a=e.defaultOptions||{},this.#n=new Map,this.#i=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#o=Op.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#r=Vl.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#o?.(),this.#o=void 0,this.#r?.(),this.#r=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const a=this.defaultQueryOptions({queryKey:e});return this.#e.get(a.queryHash)?.state.data}ensureQueryData(e){const a=this.defaultQueryOptions(e),n=this.#e.build(this,a),s=n.state.data;return s===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Gn(a.staleTime,n))&&this.prefetchQuery(a),Promise.resolve(s))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:a,state:n})=>{const s=n.data;return[a,s]})}setQueryData(e,a,n){const s=this.defaultQueryOptions({queryKey:e}),r=this.#e.get(s.queryHash)?.state.data,o=Bk(a,r);if(o!==void 0)return this.#e.build(this,s).setData(o,{...n,manual:!0})}setQueriesData(e,a,n){return Ht.batch(()=>this.#e.findAll(e).map(({queryKey:s})=>[s,this.setQueryData(s,a,n)]))}getQueryState(e){const a=this.defaultQueryOptions({queryKey:e});return this.#e.get(a.queryHash)?.state}removeQueries(e){const a=this.#e;Ht.batch(()=>{a.findAll(e).forEach(n=>{a.remove(n)})})}resetQueries(e,a){const n=this.#e;return Ht.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...e},a)))}cancelQueries(e,a={}){const n={revert:!0,...a},s=Ht.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(s).then(ra).catch(ra)}invalidateQueries(e,a={}){return Ht.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},a)))}refetchQueries(e,a={}){const n={...a,cancelRefetch:a.cancelRefetch??!0},s=Ht.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let r=i.fetch(void 0,n);return n.throwOnError||(r=r.catch(ra)),i.state.fetchStatus==="paused"?Promise.resolve():r}));return Promise.all(s).then(ra)}fetchQuery(e){const a=this.defaultQueryOptions(e);a.retry===void 0&&(a.retry=!1);const n=this.#e.build(this,a);return n.isStaleByTime(Gn(a.staleTime,n))?n.fetch(a):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(ra).catch(ra)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(ra).catch(ra)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Vl.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#a}setDefaultOptions(e){this.#a=e}setQueryDefaults(e,a){this.#n.set(Ms(e),{queryKey:e,defaultOptions:a})}getQueryDefaults(e){const a=[...this.#n.values()],n={};return a.forEach(s=>{Ur(e,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(e,a){this.#i.set(Ms(e),{mutationKey:e,defaultOptions:a})}getMutationDefaults(e){const a=[...this.#i.values()],n={};return a.forEach(s=>{Ur(e,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const a={...this.#a.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return a.queryHash||(a.queryHash=$p(a.queryKey,a)),a.refetchOnReconnect===void 0&&(a.refetchOnReconnect=a.networkMode!=="always"),a.throwOnError===void 0&&(a.throwOnError=!!a.suspense),!a.networkMode&&a.persister&&(a.networkMode="offlineFirst"),a.queryFn===qp&&(a.enabled=!1),a}defaultMutationOptions(e){return e?._defaulted?e:{...this.#a.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Pb=m.createContext(void 0),xe=e=>{const a=m.useContext(Pb);if(!a)throw new Error("No QueryClient set, use QueryClientProvider to set one");return a},dN=({client:e,children:a})=>(m.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),t.jsx(Pb.Provider,{value:e,children:a})),zb=m.createContext(!1),uN=()=>m.useContext(zb);zb.Provider;function pN(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}
2var hN=m.createContext(pN()),mN=()=>m.useContext(hN),fN=(e,a,n)=>{const s=n?.state.error&&typeof e.throwOnError=="function"?Bp(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||s)&&(a.isReset()||(e.retryOnMount=!1))},xN=e=>{m.useEffect(()=>{e.clearReset()},[e])},gN=({result:e,errorResetBoundary:a,throwOnError:n,query:s,suspense:i})=>e.isError&&!a.isReset()&&!e.isFetching&&s&&(i&&e.data===void 0||Bp(n,[e.error,s])),bN=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),s=e.staleTime;e.staleTime=typeof s=="function"?(...i)=>n(s(...i)):n(s),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},yN=(e,a)=>e.isLoading&&e.isFetching&&!a,vN=(e,a)=>e?.suspense&&a.isPending,Km=(e,a,n)=>a.fetchOptimistic(e).catch(()=>{n.clearReset()});function Db(e,a,n){const s=uN(),i=mN(),r=xe(),o=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=r.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=s?"isRestoring":c?"optimistic":void 0,bN(o),fN(o,i,l),xN(i);const d=!r.getQueryCache().get(o.queryHash),[u]=m.useState(()=>new a(r,o)),p=u.getOptimisticResult(o),f=!s&&c;if(m.useSyncExternalStore(m.useCallback(x=>{const h=f?u.subscribe(Ht.batchCalls(x)):ra;return u.updateResult(),h},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),m.useEffect(()=>{u.setOptions(o)},[o,u]),vN(o,p))throw Km(o,u,i);if(gN({result:p,errorResetBoundary:i,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw p.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(o,p),o.experimental_prefetchInRender&&!Vr.isServer()&&yN(p,s)&&(d?Km(o,u,i):l?.promise)?.catch(ra).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?p:u.trackResult(p)}function se(e,a){return Db(e,Tb)}function oe(e,a){const n=xe(),[s]=m.useState(()=>new oN(n,e));m.useEffect(()=>{s.setOptions(e)},[s,e]);const i=m.useSyncExternalStore(m.useCallback(o=>s.subscribe(Ht.batchCalls(o)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),r=m.useCallback((o,l)=>{s.mutate(o,l).catch(ra)},[s]);if(i.error&&Bp(s.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:r,mutateAsync:i.mutate}}function Hm(e,a){return Db(e,sN)}var pd,Qm;function jN(){return Qm||(Qm=1,pd={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),pd}var wN=jN();const kN=yj(wN);var NN=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function Gm(e){var a={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},n=e.match(/<\/?([^\s]+?)[/\s>]/);if(n&&(a.name=n[1],(kN[n[1]]||e.charAt(e.length-2)==="/")&&(a.voidElement=!0),a.name.startsWith("!--"))){var s=e.indexOf("-->");return{type:"comment",comment:s!==-1?e.slice(4,s):""}}for(var i=new RegExp(NN),r=null;(r=i.exec(e))!==null;)if(r[0].trim())if(r[1]){var o=r[1].trim(),l=[o,""];o.indexOf("=")>-1&&(l=o.split("=")),a.attrs[l[0]]=l[1],i.lastIndex--}else r[2]&&(a.attrs[r[2]]=r[3].trim().substring(1,r[3].length-1));return a}var SN=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,CN=/^\s*$/,_N=Object.create(null);function Ib(e,a){switch(a.type){case"text":return e+a.content;case"tag":return e+="<"+a.name+(a.attrs?(function(n){var s=[];for(var i in n)s.push(i+'="'+n[i]+'"');return s.length?" "+s.join(" "):""})(a.attrs):"")+(a.voidElement?"/>":">"),a.voidElement?e:e+a.children.reduce(Ib,"")+"</"+a.name+">";case"comment":return e+"<!--"+a.comment+"-->"}}var EN={parse:function(e,a){a||(a={}),a.components||(a.components=_N);var n,s=[],i=[],r=-1,o=!1;if(e.indexOf("<")!==0){var l=e.indexOf("<");s.push({type:"text",content:l===-1?e:e.substring(0,l)})}return e.replace(SN,function(c,d){if(o){if(c!=="</"+n.name+">")return;o=!1}var u,p=c.charAt(1)!=="/",f=c.startsWith("<!--"),x=d+c.length,h=e.charAt(x);if(f){var b=Gm(c);return r<0?(s.push(b),s):((u=i[r]).children.push(b),s)}if(p&&(r++,(n=Gm(c)).type==="tag"&&a.components[n.name]&&(n.type="component",o=!0),n.voidElement||o||!h||h==="<"||n.children.push({type:"text",content:e.slice(x,e.indexOf("<",x))}),r===0&&s.push(n),(u=i[r-1])&&u.children.push(n),i[r]=n),(!p||n.voidElement)&&(r>-1&&(n.voidElement||n.name===c.slice(2,-1))&&(r--,n=r===-1?s:i[r]),!o&&h!=="<"&&h)){u=r===-1?s:i[r].children;var g=e.indexOf("<",x),v=e.slice(x,g===-1?void 0:g);CN.test(v)&&(v=" "),(g>-1&&r+u.length>=0||v!==" ")&&u.push({type:"text",content:v})}}),s}
2,stringify:function(e){return e.reduce(function(a,n){return a+Ib("",n)},"")}};const hd=(e,a)=>{if(!e)return!1;const n=e.props?.children??e.children;return a?n.length>0:!!n},md=e=>{if(!e)return[];const a=e.props?.children??e.children;return e.props?.i18nIsDynamicList?di(a):a},AN=e=>Array.isArray(e)&&e.every(m.isValidElement),di=e=>Array.isArray(e)?e:[e],RN=(e,a)=>{const n={...a};return n.props=Object.assign(e.props,a.props),n},Lb=(e,a,n,s)=>{if(!e)return"";let i="";const r=di(e),o=a?.transSupportBasicHtmlNodes?a.transKeepBasicHtmlNodesFor??[]:[];return r.forEach((l,c)=>{if(Fr(l)){i+=`${l}`;return}if(m.isValidElement(l)){const{props:d,type:u}=l,p=Object.keys(d).length,f=o.indexOf(u)>-1,x=d.children;if(!x&&f&&!p){i+=`<${u}/>`;return}if(!x&&(!f||p)||d.i18nIsDynamicList){i+=`<${c}></${c}>`;return}if(f&&p===1&&Fr(x)){i+=`<${u}>${x}</${u}>`;return}const h=Lb(x,a,n,s);i+=`<${c}>${h}</${c}>`;return}if(l===null){td(n,"TRANS_NULL_VALUE","Passed in a null value as child",{i18nKey:s});return}if(vs(l)){const{format:d,...u}=l,p=Object.keys(u);if(p.length===1){const f=d?`${p[0]}, ${d}`:p[0];i+=`{{${f}}}`;return}td(n,"TRANS_INVALID_OBJ","Invalid child - Object should only have keys {{ value, format }} (format is optional).",{i18nKey:s,child:l});return}td(n,"TRANS_INVALID_VAR","Passed in a variable like {number} - pass variables for interpolation as full objects like {{number}}.",{i18nKey:s,child:l})}),i},TN=(e,a,n,s,i,r,o)=>{if(n==="")return[];const l=i.transKeepBasicHtmlNodesFor||[],c=n&&new RegExp(l.map(v=>`<${v}`).join("|")).test(n);if(!e&&!a&&!c&&!o)return[n];const d=a??{},u=v=>{di(v).forEach(k=>{Fr(k)||(hd(k)?u(md(k)):vs(k)&&!m.isValidElement(k)&&Object.assign(d,k))})};u(e);const p=EN.parse(`<0>${n}</0>`),f={...d,...r},x=(v,y,k)=>{const w=md(v),j=b(w,y.children,k);return AN(w)&&j.length===0||v.props?.i18nIsDynamicList?w:j},h=(v,y,k,w,j)=>{v.dummy?(v.children=y,k.push(m.cloneElement(v,{key:w},j?void 0:y))):k.push(...m.Children.map([v],C=>{const N={...C.props};return delete N.i18nIsDynamicList,m.createElement(C.type,{...N,key:w,ref:C.props.ref??C.ref},j?null:y)}))},b=(v,y,k)=>{const w=di(v);return di(y).reduce((C,N,S)=>{const _=N.children?.[0]?.content&&s.services.interpolator.interpolate(N.children[0].content,f,s.language);if(N.type==="tag"){let R=w[parseInt(N.name,10)];!R&&a&&(R=a[N.name]),k.length===1&&!R&&(R=k[0][N.name]),R||(R={});const A=Object.keys(N.attrs).length!==0?RN({props:N.attrs},R):R,E=m.isValidElement(A),I=E&&hd(N,!0)&&!N.voidElement,P=c&&vs(A)&&A.dummy&&!E,O=vs(a)&&Object.hasOwnProperty.call(a,N.name);if(Fr(A)){const K=s.services.interpolator.interpolate(A,f,s.language);C.push(K)}else if(hd(A)||I){const K=x(A,N,k);h(A,K,C,S)}else if(P){const K=b(w,N.children,k);h(A,K,C,S)}else if(Number.isNaN(parseFloat(N.name)))if(O){const K=x(A,N,k);h(A,K,C,S,N.voidElement)}else if(i.transSupportBasicHtmlNodes&&l.indexOf(N.name)>-1)if(N.voidElement)C.push(m.createElement(N.name,{key:`${N.name}-${S}`}));else{const K=b(w,N.children,k);C.push(m.createElement(N.name,{key:`${N.name}-${S}`},K))}else if(N.voidElement)C.push(`<${N.name} />`);else{const K=b(w,N.children,k);C.push(`<${N.name}>${K}</${N.name}>`)}else if(vs(A)&&!E){const K=N.children[0]?_:null;K&&C.push(K)}else h(A,_,C,S,N.children.length!==1||!_)}else if(N.type==="text"){const R=i.transWrapTextNodes,A=o?i.unescape(s.services.interpolator.interpolate(N.content,f,s.language)):s.services.interpolator.interpolate(N.content,f,s.language);R?C.push(m.createElement(R,{key:`${N.name}-${S}`},A)):C.push(A)}return C},[])},g=b([{dummy:!0,children:e||[]}],p,di(e||[]));return md(g[0])},Fb=(e,a,n)=>{const s=e.key||a,i=m.cloneElement(e,{key:s});if(!i.props||!i.props.children||n.indexOf(`${a}/>`)<0&&n.indexOf(`${a} />`)<0)return i;function r(){return m.createElement(m.Fragment,null,i)}return m.createElement(r,{key:s})},MN=(e,a)=>e.map((n,s)=>Fb(n,s,a)),PN=(e,a)=>{const n={};return Object.keys(e).forEach(s=>{Object.assign(n,{[s]:Fb(e[s],s,a)})}),n},zN=(e,a,n,s)=>e?Array.isArray(e)?MN(e,a):vs(e)?PN(e,a):(Wg(n,"TRANS_INVALID_COMPONENTS",'<Trans /> "components" prop expects an object or array',{i18nKey:s}),null):null,DN=e=>!vs(e)||Array.isArray(e)?!1:Object.keys(e).reduce((a,n)=>a&&Number.isNaN(Number.parseFloat(n)),!0);function IN({children:e,count:a,parent:n,i18nKey:s,context:i,tOptions:r={}
2,values:o,defaults:l,components:c,ns:d,i18n:u,t:p,shouldUnescape:f,...x}){const h=u||Ug();if(!h)return Wg(h,"NO_I18NEXT_INSTANCE","Trans: You need to pass in an i18next instance using i18nextReactModule",{i18nKey:s}),e;const b=p||h.t.bind(h)||(P=>P),g={...vj(),...h.options?.react};let v=d||b.ns||h.options?.defaultNS;v=Fr(v)?[v]:v||["translation"];const y=Lb(e,g,h,s),k=l||y||g.transEmptyNodeValue||s,{hashTransKey:w}=g,j=s||(w?w(y||k):y||k);h.options?.interpolation?.defaultVariables&&(o=o&&Object.keys(o).length>0?{...o,...h.options.interpolation.defaultVariables}:{...h.options.interpolation.defaultVariables});const C=o||a!==void 0&&!h.options?.interpolation?.alwaysFormat||!e?r.interpolation:{interpolation:{...r.interpolation,prefix:"#$?",suffix:"?$#"}},N={...r,context:i||r.context,count:a,...o,...C,defaultValue:k,ns:v},S=j?b(j,N):k,_=zN(c,S,h,s);let R=_||e,A=null;DN(_)&&(A=_,R=e);const E=TN(R,A,S,h,g,N,f),I=n??g.defaultTransParent;return I?m.createElement(I,x,E):E}function wa({children:e,count:a,parent:n,i18nKey:s,context:i,tOptions:r={},values:o,defaults:l,components:c,ns:d,i18n:u,t:p,shouldUnescape:f,...x}){const{i18n:h,defaultNS:b}=m.useContext(Vg)||{},g=u||h||Ug(),v=p||g?.t.bind(g);return IN({children:e,count:a,parent:n,i18nKey:s,context:i,tOptions:r,values:o,defaults:l,components:c,ns:d||v?.ns||b||g?.options?.defaultNS,i18n:g,t:p,shouldUnescape:f,...x})}function LN({i18n:e,defaultNS:a,children:n}){const s=m.useMemo(()=>({i18n:e,defaultNS:a}),[e,a]);return m.createElement(Vg.Provider,{value:s},n)}const Zm=e=>{let a;const n=new Set,s=(d,u)=>{const p=typeof d=="function"?d(a):d;if(!Object.is(p,a)){const f=a;a=u??(typeof p!="object"||p===null)?p:Object.assign({}
2,a,p),n.forEach(x=>x(a,f))}},i=()=>a,l={setState:s,getState:i,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=a=e(s,i,l);return l},FN=(e=>e?Zm(e):Zm),ON=e=>e;function $N(e,a=ON){const n=Xa.useSyncExternalStore(e.subscribe,Xa.useCallback(()=>a(e.getState()),[e,a]),Xa.useCallback(()=>a(e.getInitialState()),[e,a]));return Xa.useDebugValue(n),n}const Ym=e=>{const a=FN(e),n=s=>$N(a,s);return Object.assign(n,a),n},ds=(e=>e?Ym(e):Ym);function qN(e,a){let n;try{n=e()}catch{return}return{getItem:i=>{var r;const o=c=>c===null?null:JSON.parse(c,void 0),l=(r=n.getItem(i))!=null?r:null;return l instanceof Promise?l.then(o):o(l)},setItem:(i,r)=>n.setItem(i,JSON.stringify(r,void 0)),removeItem:i=>n.removeItem(i)}}const Cu=e=>a=>{try{const n=e(a);return n instanceof Promise?n:{then(s){return Cu(s)(n)},catch(s){return this}}}catch(n){return{then(s){return this},catch(s){return Cu(s)(n)}}}},BN=(e,a)=>(n,s,i)=>{let r={storage:qN(()=>window.localStorage),partialize:g=>g,version:0,merge:(g,v)=>({...v,...g}),...a},o=!1,l=0;const c=new Set,d=new Set;let u=r.storage;if(!u)return e((...g)=>{console.warn(`[zustand persist middleware] Unable to update item '${r.name}', the given storage is currently unavailable.`),n(...g)},s,i);const p=()=>{const g=r.partialize({...s()});return u.setItem(r.name,{state:g,version:r.version})},f=i.setState;i.setState=(g,v)=>(f(g,v),p());const x=e((...g)=>(n(...g),p()),s,i);i.getInitialState=()=>x;let h;const b=()=>{var g,v;if(!u)return;const y=++l;o=!1,c.forEach(w=>{var j;return w((j=s())!=null?j:x)});const k=((v=r.onRehydrateStorage)==null?void 0:v.call(r,(g=s())!=null?g:x))||void 0;return Cu(u.getItem.bind(u))(r.name).then(w=>{if(w)if(typeof w.version=="number"&&w.version!==r.version){if(r.migrate){const j=r.migrate(w.state,w.version);return j instanceof Promise?j.then(C=>[!0,C]):[!0,j]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,w.state];return[!1,void 0]}).then(w=>{var j;if(y!==l)return;const[C,N]=w;if(h=r.merge(N,(j=s())!=null?j:x),n(h,!0),C)return p()}).then(()=>{y===l&&(k?.(s(),void 0),h=s(),o=!0,d.forEach(w=>w(h)))}).catch(w=>{y===l&&k?.(void 0,w)})};return i.persist={setOptions:g=>{r={...r,...g},g.storage&&(u=g.storage)},clearStorage:()=>{u?.removeItem(r.name)},getOptions:()=>r,rehydrate:()=>b(),hasHydrated:()=>o,onHydrate:g=>(c.add(g),()=>{c.delete(g)}),onFinishHydration:g=>(d.add(g),()=>{d.delete(g)})},r.skipHydration||b(),h||x},oo=BN;function WN(){return typeof navigator<"u"&&typeof navigator.language=="string"&&navigator.language.toLowerCase().startsWith("en")?"en":"es"}function _u(e){return e==="auto"?WN():e}function bl(e){he.changeLanguage(e),typeof document<"u"&&document.documentElement.setAttribute("lang",e)}const Ua=ds()(oo((e,a)=>({mode:"auto",resolved:_u("auto"),setMode:n=>{const s=_u(n);bl(s),e({mode:n,resolved:s})},toggle:()=>{const n=a().resolved==="en"?"es":"en";bl(n),e({mode:n,resolved:n})},applyTenantDefault:n=>{if(a().mode!=="auto")return;const s=n==="en"?"en":"es";bl(s),e({resolved:s})}}),{name:"conectaia.lang",partialize:e=>({mode:e.mode})}));{const e=Ua.getState(),a=_u(e.mode);bl(a),a!==e.resolved&&Ua.setState({resolved:a})}const Pe=ds()(oo((e,a)=>({accessToken:null,refreshToken:null,user:null,setSession:n=>{try{sessionStorage.removeItem(Vp)}catch{}e({accessToken:n.accessToken,refreshToken:n.refreshToken,user:n.user})},setTokens:(n,s)=>e({accessToken:n,refreshToken:s}),setUser:n=>e({user:n}),logout:()=>{const n=a().accessToken;n&&Le(async()=>{const{api:s}=await Promise.resolve().then(()=>Wy);return{api:s}},void 0).then(({api:s})=>s.post("/auth/logout",{},{headers:{Authorization:`Bearer ${n}`},_retry:!0}).catch(()=>{})),rt.getState().stop(),Le(async()=>{const{disconnectSocket:s}=await Promise.resolve().then(()=>zv);return{disconnectSocket:s}},void 0).then(({disconnectSocket:s})=>s()),Le(async()=>{const{disconnectSocketMessaging:s}=await Promise.resolve().then(()=>Fv);return{disconnectSocketMessaging:s}},void 0).then(({disconnectSocketMessaging:s})=>s()),e({accessToken:null,refreshToken:null,user:null})},isAuthenticated:()=>!!a().accessToken}),{name:"conectaia.auth"})),rt=ds()(oo((e,a)=>({accessToken:null,user:null,orgName:null,expiresAt:null,start:n=>e({accessToken:n.accessToken,user:n.user,orgName:n.orgName,expiresAt:Date.now()+n.expiresInSeconds*1e3}),stop:()=>e({accessToken:null,user:null,orgName:null,expiresAt:null}),isActive:()=>{const n=a();return n.accessToken?!!n.expiresAt&&n.expiresAt>Date.now():!1}}),{name:"conectaia.imp"}));function Up(){const e=rt.getState();return e.isActive()?e.user:Pe.getState().user}const Vp="cia.onboarding.skipped";
2function UN(){try{sessionStorage.setItem(Vp,"1")}catch{}}function VN(){try{return sessionStorage.getItem(Vp)==="1"}catch{return!1}}function gc(e){return!!e&&e.role==="admin"&&!e.imp&&!!e.organizationId&&e.onboardingState!=null&&e.onboardingState!=="completed"&&!VN()}function lo(e){return e?.role==="superadmin"?"/admin/dashboard":gc(e)?"/onboarding":"/dashboard"}async function KN(){const e=rt.getState();if(e.isActive()&&e.accessToken)try{const{api:a}=await Le(async()=>{const{api:n}=await Promise.resolve().then(()=>Wy);return{api:n}},void 0);await a.post("/auth/impersonation/end",{},{headers:{Authorization:`Bearer ${e.accessToken}`},_retry:!0})}catch{}Le(async()=>{const{disconnectSocket:a}=await Promise.resolve().then(()=>zv);return{disconnectSocket:a}},void 0).then(({disconnectSocket:a})=>a()),Le(async()=>{const{disconnectSocketMessaging:a}=await Promise.resolve().then(()=>Fv);return{disconnectSocketMessaging:a}},void 0).then(({disconnectSocketMessaging:a})=>a()),e.stop()}const Ob=new Set(["agents.view","calls.view","campaigns.view","knowledge.view","meetings.view","appointments.view","whatsapp.view","contacts.view","email.view","workflows.view","phoneNumbers.view","integrations.view","organization.view","billing.view","team.view","webhooks.view","secrets.view","voices.view","reports.view","copilot.use","playground.use"]),HN=new Set([...Ob,"agents.operate","calls.operate","campaigns.operate","knowledge.operate","meetings.operate","meetings.export","appointments.operate","calls.export","whatsapp.operate","contacts.operate","email.operate","workflows.operate"]);function lt(e,a){if(!e)return!1;if(e.role==="admin"||e.role==="superadmin")return!0;const n=e.permissions;return Array.isArray(n)?n.includes(a):e.role==="operator"?HN.has(a):e.role==="viewer"?Ob.has(a):!1}function $b(e,a){return a.some(n=>lt(e,n))}const Xt=Object.freeze({NOMBRE:512,CUERPO:1024,ENCABEZADO:60,PIE:60,BOTONES:10,BOTON_TEXTO:25,VARIABLES:10}),Xq=Object.freeze({MIN:10,MAX:600}),qb=["marketing","utility","authentication","service"],fd=["utility","marketing","authentication"],xd=["es","es_AR","es_CO","es_MX","es_ES","en","en_US","en_GB","pt_BR","pt_PT"];function Jq(e){const a=String(e??"").trim();return a&&!xd.includes(a)?[...xd,a]:[...xd]}function eB(e){const a=String(e??"").trim();return qb.includes(a)&&!fd.includes(a)?[...fd,a]:[...fd]}const QN=/\{\{\s*(\d+)\s*\}\}/g;function Nr(e){const a=[];for(const n of String(e??"").matchAll(QN))a.push(Number(n[1]));return a}function GN(e){const a=String(e??"").trim();return a?a.length>Xt.NOMBRE?{motivo:"nombre_muy_largo",params:{tope:Xt.NOMBRE}}:/^[a-z0-9_]+$/.test(a)?null:{motivo:"nombre_invalido"}:{motivo:"nombre_vacio"}}function ZN(e){const a=String(e??"").trim();if(!a)return{error:{motivo:"cuerpo_vacio"},variables:0};if(a.length>Xt.CUERPO)return{error:{motivo:"cuerpo_muy_largo",params:{tope:Xt.CUERPO}},variables:0};const n=Nr(a);if(n.length>Xt.VARIABLES)return{error:{motivo:"demasiadas_variables",params:{tope:Xt.VARIABLES,cantidad:n.length}},variables:0};const s=[...new Set(n)].sort((r,o)=>r-o);for(let r=0;r<s.length;r++)if(s[r]!==r+1)return{error:{motivo:"variables_desordenadas",params:{encontradas:s.map(o=>`{{${o}}}`).join(", "),falta:`{{${r+1}}}`}},variables:0};const i=a.replace(/\s+/g," ");return/^\{\{\s*\d+\s*\}\}/.test(i)?{error:{motivo:"empieza_con_variable"},variables:0}:/\{\{\s*\d+\s*\}\}$/.test(i)?{error:{motivo:"termina_con_variable"},variables:0}:/\}\}\s*\{\{/.test(i)?{error:{motivo:"variables_pegadas"},variables:0}:{error:null,variables:s.length}}function YN(e){const a=Array.isArray(e)?e.map(i=>String(i??"").trim()):[];if(a.length>Xt.BOTONES)return{motivo:"demasiados_botones",params:{tope:Xt.BOTONES}};if(a.some(i=>!i))return{motivo:"boton_vacio"};const n=a.find(i=>i.length>Xt.BOTON_TEXTO);return n?{motivo:"boton_muy_largo",params:{texto:n,tope:Xt.BOTON_TEXTO}}:new Set(a.map(i=>i.toLocaleLowerCase())).size!==a.length?{motivo:"boton_repetido"}:null}function tB(e){const a=e?.componentes??{cuerpo:""},n={},s=GN(e?.nombre??"");s&&(n.nombre=s);const i=ZN(a.cuerpo);i.error&&(n.cuerpo=i.error),String(a.encabezado??"").trim().length>Xt.ENCABEZADO&&(n.encabezado={motivo:"encabezado_muy_largo",params:{tope:Xt.ENCABEZADO}}),String(a.pie??"").trim().length>Xt.PIE&&(n.pie={motivo:"pie_muy_largo",params:{tope:Xt.PIE}});const r=YN(a.botones);r&&(n.botones=r);const l=["nombre","cuerpo","encabezado","pie","botones"].map(c=>n[c]).find(Boolean)??null;return{ok:!l,variables:l?0:i.variables,errores:n,primero:l}}function aB(e){const a=[...Nr(e.encabezado),...Nr(e.cuerpo),...Nr(e.pie)];
2return[...new Set(a)].sort((n,s)=>n-s)}function nB(e){const a=Nr(e);return a.length?Math.max(...a)+1:1}function sB(e){return String(e??"").normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9\s]/g," ").trim().split(/\s+/).filter(n=>n.length>2).slice(0,4).join("_").slice(0,60)||"plantilla"}function iB(e){return String(e??"").normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,Xt.NOMBRE)}function rB(e,a,n,s){const i=String(e??"").replace(/_\d+$/,"")||"plantilla",r=new Set(a.filter(o=>o.language===n&&o.accountId===s).map(o=>o.name));for(let o=2;o<1e3;o++){const l=`${i}_${o}`.slice(0,Xt.NOMBRE);if(!r.has(l))return l}return`${i}_${Date.now().toString(36)}`.slice(0,Xt.NOMBRE)}function oB(e,a,n,s,i){const r=String(a??"").trim();return e.some(o=>o.id!==i&&o.name===r&&o.language===n&&o.accountId===s)}const zn=e=>String(e??"").trim();function lB(e,a){if(!a)return[];const n=[];zn(e.encabezado)!==zn(a.encabezado)&&n.push("encabezado"),zn(e.cuerpo)!==zn(a.cuerpo)&&n.push("cuerpo"),zn(e.pie)!==zn(a.pie)&&n.push("pie");const s=(e.botones??[]).map(zn).join("\0"),i=(a.botones??[]).map(zn).join("\0");return s!==i&&n.push("botones"),n}const Bb=["todas","usable","pending","draft","rejected","paused"];function XN(e){return typeof e=="string"&&Bb.includes(e)}function Kp(e,a){switch(a){case"todas":return!0;case"usable":return e.usable===!0;case"paused":return e.status==="paused"||e.status==="disabled";default:return e.status===a}}function JN(e){return e.category??e.categoryRequested}function ui(e,a){const s=(typeof e=="string"?e:typeof e=="number"&&Number.isFinite(e)?String(e):"").trim().slice(0,a);return s||void 0}const Kl=/^[A-Za-z0-9_-]{1,64}$/,eS=/^[A-Za-z]{2,3}(?:_[A-Za-z0-9]{2,4})?$/;function tS(e){const a={},n=ui(e.q,120);n&&(a.q=n),XN(e.estado)&&e.estado!=="todas"&&(a.estado=e.estado),typeof e.categoria=="string"&&qb.includes(e.categoria)&&(a.categoria=e.categoria);const s=ui(e.cuenta,64);s&&Kl.test(s)&&(a.cuenta=s);const i=ui(e.idioma,16);i&&eS.test(i)&&(a.idioma=i);const r=ui(e.p,64);return r&&Kl.test(r)&&(a.p=r),a}function aS(e){const a={},n=ui(e.desde,64);n&&Kl.test(n)&&(a.desde=n);const s=ui(e.cuenta,64);return s&&Kl.test(s)&&(a.cuenta=s),a}function Xm(e){return String(e??"").normalize("NFD").replace(/[̀-ͯ]/g,"").toLocaleLowerCase().trim()}function nS(e,a){const n=Xm(a);if(!n)return!0;const s=r=>r?[r.encabezado??"",r.cuerpo??"",r.pie??"",...r.botones??[]]:[];return Xm([e.name,...s(e.enviado),...s(e.aprobado)].join(`
3`)).includes(n)}function Wb(e,a){return a.categoria&&JN(e)!==a.categoria||a.idioma&&e.language!==a.idioma||a.cuenta&&e.accountId!==a.cuenta?!1:nS(e,a.q??"")}function cB(e,a){const n=a.estado??"todas";return e.filter(s=>Kp(s,n)&&Wb(s,a))}function dB(e,a){const n=e.filter(i=>Wb(i,a)),s={};for(const i of Bb)s[i]=n.filter(r=>Kp(r,i)).length;return s}function uB(e){return[e.categoria,e.idioma,e.cuenta].filter(Boolean).length}function pB(e){return{total:e.length,aprobadas:e.filter(a=>a.status==="approved").length,enRevision:e.filter(a=>a.status==="pending").length}}function hB(e,a,n){const s=Math.max(1,Math.ceil(e.length/n)),i=Math.min(Math.max(0,a),s-1);return{items:e.slice(i*n,i*n+n),pagina:i}}function sS(e,a){const n=[{id:"ver"}];return a.gestionar&&(e.status==="draft"||e.status==="rejected")&&n.push({id:"enviar"}),a.gestionar&&e.status==="draft"&&n.push({id:"editar"}),a.gestionar&&n.push({id:"duplicar"}),a.operar&&e.usable&&n.push({id:"usarEnLaBandeja"}),a.gestionar&&n.push(e.status==="pending"?{id:"eliminar",danger:!0,motivo:"enRevision"}:{id:"eliminar",danger:!0}),n}function mB(e,a){const n=new Set(sS(e,a).filter(i=>!i.motivo).map(i=>i.id)),s=e.status==="draft"?"enviar":e.status==="rejected"||e.status==="disabled"?"duplicar":e.usable?"usarEnLaBandeja":null;return s&&n.has(s)?s:null}const iS=Object.freeze({draft:"neutral",pending:"warning",approved:"success",rejected:"danger",paused:"warning",disabled:"danger",unknown:"neutral"});function fB(e){return iS[e]??"neutral"}const xB=Object.freeze({green:"success",yellow:"warning",red:"danger",unknown:"neutral"});function rS(e){const a=e.filter(n=>!n.usable);for(const n of["pending","rejected","paused","draft"])if(a.some(s=>Kp(s,n)))return n}function oS(e){if(!Array.isArray(e.usadaEnCampanas))return{tipo:"desconocido"};const a=Math.max(e.usadaEnCampanas.length,Number(e.usadaEnCampanasTotal??0)||0);return a===0?{tipo:"ninguna"}:{tipo:"campanas",campanas:e.usadaEnCampanas,total:a,restantes:a-e.usadaEnCampanas.length}}const Ub=["lienzo","disparadores","corridas","versiones","metricas"],Jm="lienzo";function gB(e){return[...Ub]}function bB(e,a){return typeof e!="string"?Jm:a.includes(e)?e:Jm}function lS(e){const a=e.tab;
3return typeof a=="string"&&Ub.includes(a)?{tab:a}:{}}function cS(e){return e.publicado?e.enabled?"encendido":"apagado":"borrador"}const dS=Object.freeze({encendido:{tono:"success",conIcono:!0},apagado:{tono:"neutral",conIcono:!0},borrador:{tono:"info",conIcono:!1}});function yB(e){return e.sinGuardar?{clave:"guardaPrimero"}:e.sePuedePublicar?null:{clave:"faltanProblemas",n:Math.max(1,e.errores)}}function vB(e){return e.enabled||e.publicado?null:"publicaPrimero"}function jB(e){return!e.versionPublicada||!e.sinPublicar?null:{numero:e.versionPublicada.numero}}function wB(e){const a=[];return e.puedeEditar&&a.push({accion:"renombrar",grupo:"editar"}),e.puedeEditar&&a.push({accion:"duplicar",grupo:"editar"}),a.push({accion:"exportar",grupo:"archivo"}),e.puedeEditar&&a.push({accion:"importar",grupo:"archivo"}),e.puedeEditar&&a.push({accion:"eliminar",grupo:"peligro",danger:!0,...e.corridasVivas>0?{motivo:"hayCorridasVivas"}:{}}),a}const kB=["whatsapp","correo","voz","web","cualquiera"],Qe={raiz:()=>["flows"],lista:()=>["flows","lista"],detalle:e=>["flows","detalle",e],versiones:e=>["flows","versiones",e],version:(e,a)=>["flows","version",e,a],corridasDe:e=>["flows","corridas",e],corridasDeConFiltros:(e,a)=>["flows","corridas",e,a],corridasGlobales:()=>["flows","corridas-globales"],corridasGlobalesConFiltros:e=>["flows","corridas-globales",e],corrida:e=>["flows","corrida",e],metricas:(e,a)=>["flows","metricas",e,a],plantillas:()=>["flows","plantillas"],diagnostico:(e,a)=>["flows","diagnostico",e,a],ajustesDeLaPlataforma:()=>["flows","plataforma"],porConversacion:(e,a="")=>["flows","por-conversacion",e,a],porConversacionTodas:()=>["flows","por-conversacion"]},aa={crear:()=>[Qe.lista()],editar:e=>[Qe.detalle(e),Qe.lista()],guardarBorrador:e=>[Qe.lista(),["flows","version",e]],publicar:e=>[Qe.detalle(e),Qe.versiones(e),Qe.lista(),["flows","version",e]],encender:e=>[Qe.detalle(e),Qe.lista()],eliminar:()=>[Qe.lista()],duplicar:()=>[Qe.lista()],importar:()=>[Qe.lista()],desdePlantilla:()=>[Qe.lista()],disparador:e=>[Qe.detalle(e),Qe.lista()],lanzar:e=>[Qe.corridasDe(e),Qe.corridasGlobales(),Qe.lista(),Qe.porConversacionTodas()],cancelarCorrida:e=>[Qe.corrida(e),["flows","corridas"],Qe.corridasGlobales(),Qe.lista(),Qe.porConversacionTodas()],restaurarVersion:e=>[Qe.detalle(e),["flows","version",e],Qe.lista()],ajustesDeLaPlataforma:()=>[Qe.ajustesDeLaPlataforma()]},uS="enlassa-flow/1",pS=2*1024*1024;function hS(e){return`${e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"flujo"}.enlassa-flow.json`}function mS(e){let a;try{a=JSON.parse(e)}catch{return{ok:!1,motivo:"no_es_json"}}if(!a||typeof a!="object"||Array.isArray(a))return{ok:!1,motivo:"no_es_un_flujo"};const n=a;return typeof n.formato!="string"||typeof n.name!="string"||!n.draft||typeof n.draft!="object"?{ok:!1,motivo:"no_es_un_flujo"}:n.formato!==uS?{ok:!1,motivo:"otro_formato"}:{ok:!0,datos:n}}/**
4 * @license lucide-react v0.469.0 - ISC
5 *
6 * This source code is licensed under the ISC license.
7 * See the LICENSE file in the root directory of this source tree.
8 */const Hp=Q("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/**
9 * @license lucide-react v0.469.0 - ISC
10 *
11 * This source code is licensed under the ISC license.
12 * See the LICENSE file in the root directory of this source tree.
13 */const fS=Q("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
14 * @license lucide-react v0.469.0 - ISC
15 *
16 * This source code is licensed under the ISC license.
17 * See the LICENSE file in the root directory of this source tree.
18 */const xS=Q("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/**
19 * @license lucide-react v0.469.0 - ISC
20 *
21 * This source code is licensed under the ISC license.
22 * See the LICENSE file in the root directory of this source tree.
23 */const bc=Q("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/**
24 * @license lucide-react v0.469.0 - ISC
25 *
26 * This source code is licensed under the ISC license.
27 * See the LICENSE file in the root directory of this source tree.
28 */const Vb=Q("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/**
29 * @license lucide-react v0.469.0 - ISC
30 *
31 * This source code is licensed under the ISC license.
32 * See the LICENSE file in the root directory of this source tree.
33 */const Kb=Q("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/**
34 * @license lucide-react v0.469.0 - ISC
35 *
36 * This source code is licensed under the ISC license.
37 * See the LICENSE file in the root directory of this source tree.
38 */const gS=Q("ArrowRightLeft",[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);/**
39 * @license lucide-react v0.469.0 - ISC
40 *
41 * This source code is licensed under the ISC license.
42 * See the LICENSE file in the root directory of this source tree.
43 */const oa=Q("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
44 * @license lucide-react v0.469.0 - ISC
45 *
46 * This source code is licensed under the ISC license.
47 * See the LICENSE file in the root directory of this source tree.
48 */const nn=Q("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/**
49 * @license lucide-react v0.469.0 - ISC
50 *
51 * This source code is licensed under the ISC license.
52 * See the LICENSE file in the root directory of this source tree.
53 */const Hb=Q("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/**
54 * @license lucide-react v0.469.0 - ISC
55 *
56 * This source code is licensed under the ISC license.
57 * See the LICENSE file in the root directory of this source tree.
58 */const Qp=Q("BellOff",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]]);/**
59 * @license lucide-react v0.469.0 - ISC
60 *
61 * This source code is licensed under the ISC license.
62 * See the LICENSE file in the root directory of this source tree.
63 */const Gp=Q("BellRing",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M22 8c0-2.3-.8-4.3-2-6",key:"5bb3ad"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}],["path",{d:"M4 2C2.8 3.7 2 5.7 2 8",key:"tap9e0"}]]);/**
64 * @license lucide-react v0.469.0 - ISC
65 *
66 * This source code is licensed under the ISC license.
67 * See the LICENSE file in the root directory of this source tree.
68 */const Qb=Q("Bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]);/**
69 * @license lucide-react v0.469.0 - ISC
70 *
71 * This source code is licensed under the ISC license.
72 * See the LICENSE file in the root directory of this source tree.
73 */const bS=Q("Binary",[["rect",{x:"14",y:"14",width:"4",height:"6",rx:"2",key:"p02svl"}],["rect",{x:"6",y:"4",width:"4",height:"6",rx:"2",key:"xm4xkj"}],["path",{d:"M6 20h4",key:"1i6q5t"}],["path",{d:"M14 10h4",key:"ru81e7"}],["path",{d:"M6 14h2v6",key:"16z9wg"}],["path",{d:"M14 4h2v6",key:"1idq9u"}]]);/**
74 * @license lucide-react v0.469.0 - ISC
75 *
76 * This source code is licensed under the ISC license.
77 * See the LICENSE file in the root directory of this source tree.
78 */const ua=Q("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/**
79 * @license lucide-react v0.469.0 - ISC
80 *
81 * This source code is licensed under the ISC license.
82 * See the LICENSE file in the root directory of this source tree.
83 */const Ft=Q("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/**
84 * @license lucide-react v0.469.0 - ISC
85 *
86 * This source code is licensed under the ISC license.
87 * See the LICENSE file in the root directory of this source tree.
88 */const yS=Q("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/**
89 * @license lucide-react v0.469.0 - ISC
90 *
91 * This source code is licensed under the ISC license.
92 * See the LICENSE file in the root directory of this source tree.
93 */const Sr=Q("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]);/**
94 * @license lucide-react v0.469.0 - ISC
95 *
96 * This source code is licensed under the ISC license.
97 * See the LICENSE file in the root directory of this source tree.
98 */const yc=Q("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}
98],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
99 * @license lucide-react v0.469.0 - ISC
100 *
101 * This source code is licensed under the ISC license.
102 * See the LICENSE file in the root directory of this source tree.
103 */const Zn=Q("CalendarCheck",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m9 16 2 2 4-4",key:"19s6y9"}]]);/**
104 * @license lucide-react v0.469.0 - ISC
105 *
106 * This source code is licensed under the ISC license.
107 * See the LICENSE file in the root directory of this source tree.
108 */const Ps=Q("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]);/**
109 * @license lucide-react v0.469.0 - ISC
110 *
111 * This source code is licensed under the ISC license.
112 * See the LICENSE file in the root directory of this source tree.
113 */const vS=Q("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
114 * @license lucide-react v0.469.0 - ISC
115 *
116 * This source code is licensed under the ISC license.
117 * See the LICENSE file in the root directory of this source tree.
118 */const us=Q("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/**
119 * @license lucide-react v0.469.0 - ISC
120 *
121 * This source code is licensed under the ISC license.
122 * See the LICENSE file in the root directory of this source tree.
123 */const jS=Q("ChartNoAxesColumn",[["line",{x1:"18",x2:"18",y1:"20",y2:"10",key:"1xfpm4"}],["line",{x1:"12",x2:"12",y1:"20",y2:"4",key:"be30l9"}],["line",{x1:"6",x2:"6",y1:"20",y2:"14",key:"1r4le6"}]]);/**
124 * @license lucide-react v0.469.0 - ISC
125 *
126 * This source code is licensed under the ISC license.
127 * See the LICENSE file in the root directory of this source tree.
128 */const gn=Q("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/**
129 * @license lucide-react v0.469.0 - ISC
130 *
131 * This source code is licensed under the ISC license.
132 * See the LICENSE file in the root directory of this source tree.
133 */const ca=Q("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
134 * @license lucide-react v0.469.0 - ISC
135 *
136 * This source code is licensed under the ISC license.
137 * See the LICENSE file in the root directory of this source tree.
138 */const Rn=Q("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
139 * @license lucide-react v0.469.0 - ISC
140 *
141 * This source code is licensed under the ISC license.
142 * See the LICENSE file in the root directory of this source tree.
143 */const wS=Q("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
144 * @license lucide-react v0.469.0 - ISC
145 *
146 * This source code is licensed under the ISC license.
147 * See the LICENSE file in the root directory of this source tree.
148 */const kS=Q("CircleDashed",[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]]);/**
149 * @license lucide-react v0.469.0 - ISC
150 *
151 * This source code is licensed under the ISC license.
152 * See the LICENSE file in the root directory of this source tree.
153 */const vc=Q("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"}]]);/**
154 * @license lucide-react v0.469.0 - ISC
155 *
156 * This source code is licensed under the ISC license.
157 * See the LICENSE file in the root directory of this source tree.
158 */const NS=Q("CirclePlay",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/**
159 * @license lucide-react v0.469.0 - ISC
160 *
161 * This source code is licensed under the ISC license.
162 * See the LICENSE file in the root directory of this source tree.
163 */const SS=Q("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]]);/**
164 * @license lucide-react v0.469.0 - ISC
165 *
166 * This source code is licensed under the ISC license.
167 * See the LICENSE file in the root directory of this source tree.
168 */const CS=Q("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/**
169 * @license lucide-react v0.469.0 - ISC
170 *
171 * This source code is licensed under the ISC license.
172 * See the LICENSE file in the root directory of this source tree.
173 */const _S=Q("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/**
174 * @license lucide-react v0.469.0 - ISC
175 *
176 * This source code is licensed under the ISC license.
177 * See the LICENSE file in the root directory of this source tree.
178 */const Gb=Q("CloudUpload",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]]);/**
179 * @license lucide-react v0.469.0 - ISC
180 *
181 * This source code is licensed under the ISC license.
182 * See the LICENSE file in the root directory of this source tree.
183 */const Zb=Q("CodeXml",[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]]);/**
184 * @license lucide-react v0.469.0 - ISC
185 *
186 * This source code is licensed under the ISC license.
187 * See the LICENSE file in the root directory of this source tree.
188 */const ES=Q("Command",[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]]);/**
189 * @license lucide-react v0.469.0 - ISC
190 *
191 * This source code is licensed under the ISC license.
192 * See the LICENSE file in the root directory of this source tree.
193 */const bn=Q("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"}]]);/**
194 * @license lucide-react v0.469.0 - ISC
195 *
196 * This source code is licensed under the ISC license.
197 * See the LICENSE file in the root directory of this source tree.
198 */const AS=Q("CornerDownLeft",[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]]);/**
199 * @license lucide-react v0.469.0 - ISC
200 *
201 * This source code is licensed under the ISC license.
202 * See the LICENSE file in the root directory of this source tree.
203 */const Yb=Q("CornerUpLeft",[["polyline",{points:"9 14 4 9 9 4",key:"881910"}],["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}]]);/**
204 * @license lucide-react v0.469.0 - ISC
205 *
206 * This source code is licensed under the ISC license.
207 * See the LICENSE file in the root directory of this source tree.
208 */const Xb=Q("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}
208],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]]);/**
209 * @license lucide-react v0.469.0 - ISC
210 *
211 * This source code is licensed under the ISC license.
212 * See the LICENSE file in the root directory of this source tree.
213 */const $s=Q("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/**
214 * @license lucide-react v0.469.0 - ISC
215 *
216 * This source code is licensed under the ISC license.
217 * See the LICENSE file in the root directory of this source tree.
218 */const RS=Q("Crosshair",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]]);/**
219 * @license lucide-react v0.469.0 - ISC
220 *
221 * This source code is licensed under the ISC license.
222 * See the LICENSE file in the root directory of this source tree.
223 */const Jb=Q("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/**
224 * @license lucide-react v0.469.0 - ISC
225 *
226 * This source code is licensed under the ISC license.
227 * See the LICENSE file in the root directory of this source tree.
228 */const TS=Q("Disc3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M6 12c0-1.7.7-3.2 1.8-4.2",key:"oqkarx"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M18 12c0 1.7-.7 3.2-1.8 4.2",key:"1eah9h"}]]);/**
229 * @license lucide-react v0.469.0 - ISC
230 *
231 * This source code is licensed under the ISC license.
232 * See the LICENSE file in the root directory of this source tree.
233 */const jc=Q("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
234 * @license lucide-react v0.469.0 - ISC
235 *
236 * This source code is licensed under the ISC license.
237 * See the LICENSE file in the root directory of this source tree.
238 */const MS=Q("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/**
239 * @license lucide-react v0.469.0 - ISC
240 *
241 * This source code is licensed under the ISC license.
242 * See the LICENSE file in the root directory of this source tree.
243 */const Tn=Q("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"}]]);/**
244 * @license lucide-react v0.469.0 - ISC
245 *
246 * This source code is licensed under the ISC license.
247 * See the LICENSE file in the root directory of this source tree.
248 */const zi=Q("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/**
249 * @license lucide-react v0.469.0 - ISC
250 *
251 * This source code is licensed under the ISC license.
252 * See the LICENSE file in the root directory of this source tree.
253 */const PS=Q("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/**
254 * @license lucide-react v0.469.0 - ISC
255 *
256 * This source code is licensed under the ISC license.
257 * See the LICENSE file in the root directory of this source tree.
258 */const Ja=Q("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"}]]);/**
259 * @license lucide-react v0.469.0 - ISC
260 *
261 * This source code is licensed under the ISC license.
262 * See the LICENSE file in the root directory of this source tree.
263 */const zS=Q("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/**
264 * @license lucide-react v0.469.0 - ISC
265 *
266 * This source code is licensed under the ISC license.
267 * See the LICENSE file in the root directory of this source tree.
268 */const qs=Q("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
269 * @license lucide-react v0.469.0 - ISC
270 *
271 * This source code is licensed under the ISC license.
272 * See the LICENSE file in the root directory of this source tree.
273 */const DS=Q("Feather",[["path",{d:"M12.67 19a2 2 0 0 0 1.416-.588l6.154-6.172a6 6 0 0 0-8.49-8.49L5.586 9.914A2 2 0 0 0 5 11.328V18a1 1 0 0 0 1 1z",ke
273y:"18jl4k"}],["path",{d:"M16 8 2 22",key:"vp34q"}],["path",{d:"M17.5 15H9",key:"1oz8nu"}]]);/**
274 * @license lucide-react v0.469.0 - ISC
275 *
276 * This source code is licensed under the ISC license.
277 * See the LICENSE file in the root directory of this source tree.
278 */const Zp=Q("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"}]]);/**
279 * @license lucide-react v0.469.0 - ISC
280 *
281 * This source code is licensed under the ISC license.
282 * See the LICENSE file in the root directory of this source tree.
283 */const IS=Q("FileSearch",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"ms7g94"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}],["circle",{cx:"5",cy:"14",r:"3",key:"ufru5t"}]]);/**
284 * @license lucide-react v0.469.0 - ISC
285 *
286 * This source code is licensed under the ISC license.
287 * See the LICENSE file in the root directory of this source tree.
288 */const Eu=Q("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"}]]);/**
289 * @license lucide-react v0.469.0 - ISC
290 *
291 * This source code is licensed under the ISC license.
292 * See the LICENSE file in the root directory of this source tree.
293 */const ey=Q("FileStack",[["path",{d:"M21 7h-3a2 2 0 0 1-2-2V2",key:"9rb54x"}],["path",{d:"M21 6v6.5c0 .8-.7 1.5-1.5 1.5h-7c-.8 0-1.5-.7-1.5-1.5v-9c0-.8.7-1.5 1.5-1.5H17Z",key:"1059l0"}],["path",{d:"M7 8v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H15",key:"16874u"}],["path",{d:"M3 12v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H11",key:"k2ox98"}]]);/**
294 * @license lucide-react v0.469.0 - ISC
295 *
296 * This source code is licensed under the ISC license.
297 * See the LICENSE file in the root directory of this source tree.
298 */const _n=Q("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"}]]);/**
299 * @license lucide-react v0.469.0 - ISC
300 *
301 * This source code is licensed under the ISC license.
302 * See the LICENSE file in the root directory of this source tree.
303 */const LS=Q("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);/**
304 * @license lucide-react v0.469.0 - ISC
305 *
306 * This source code is licensed under the ISC license.
307 * See the LICENSE file in the root directory of this source tree.
308 */const Yp=Q("FlaskConical",[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]]);/**
309 * @license lucide-react v0.469.0 - ISC
310 *
311 * This source code is licensed under the ISC license.
312 * See the LICENSE file in the root directory of this source tree.
313 */const co=Q("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/**
314 * @license lucide-react v0.469.0 - ISC
315 *
316 * This source code is licensed under the ISC license.
317 * See the LICENSE file in the root directory of this source tree.
318 */const FS=Q("GitCompare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]);/**
319 * @license lucide-react v0.469.0 - ISC
320 *
321 * This source code is licensed under the ISC license.
322 * See the LICENSE file in the root directory of this source tree.
323 */const Va=Q("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/**
324 * @license lucide-react v0.469.0 - ISC
325 *
326 * This source code is licensed under the ISC license.
327 * See the LICENSE file in the root directory of this source tree.
328 */const OS=Q("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
329 * @license lucide-react v0.469.0 - ISC
330 *
331 * This source code is licensed under the ISC license.
332 * See the LICENSE file in the root directory of this source tree.
333 */const ty=Q("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}
333]]);/**
334 * @license lucide-react v0.469.0 - ISC
335 *
336 * This source code is licensed under the ISC license.
337 * See the LICENSE file in the root directory of this source tree.
338 */const Xp=Q("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/**
339 * @license lucide-react v0.469.0 - ISC
340 *
341 * This source code is licensed under the ISC license.
342 * See the LICENSE file in the root directory of this source tree.
343 */const ay=Q("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/**
344 * @license lucide-react v0.469.0 - ISC
345 *
346 * This source code is licensed under the ISC license.
347 * See the LICENSE file in the root directory of this source tree.
348 */const $S=Q("HeartPulse",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"1uw2ng"}]]);/**
349 * @license lucide-react v0.469.0 - ISC
350 *
351 * This source code is licensed under the ISC license.
352 * See the LICENSE file in the root directory of this source tree.
353 */const wc=Q("History",[["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"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
354 * @license lucide-react v0.469.0 - ISC
355 *
356 * This source code is licensed under the ISC license.
357 * See the LICENSE file in the root directory of this source tree.
358 */const Au=Q("Hourglass",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]]);/**
359 * @license lucide-react v0.469.0 - ISC
360 *
361 * This source code is licensed under the ISC license.
362 * See the LICENSE file in the root directory of this source tree.
363 */const qS=Q("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/**
364 * @license lucide-react v0.469.0 - ISC
365 *
366 * This source code is licensed under the ISC license.
367 * See the LICENSE file in the root directory of this source tree.
368 */const BS=Q("Import",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m8 11 4 4 4-4",key:"1dohi6"}],["path",{d:"M8 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-4",key:"1ywtjm"}]]);/**
369 * @license lucide-react v0.469.0 - ISC
370 *
371 * This source code is licensed under the ISC license.
372 * See the LICENSE file in the root directory of this source tree.
373 */const Ka=Q("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/**
374 * @license lucide-react v0.469.0 - ISC
375 *
376 * This source code is licensed under the ISC license.
377 * See the LICENSE file in the root directory of this source tree.
378 */const WS=Q("Layers",[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]]);/**
379 * @license lucide-react v0.469.0 - ISC
380 *
381 * This source code is licensed under the ISC license.
382 * See the LICENSE file in the root directory of this source tree.
383 */const ny=Q("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/**
384 * @license lucide-react v0.469.0 - ISC
385 *
386 * This source code is licensed under the ISC license.
387 * See the LICENSE file in the root directory of this source tree.
388 */const US=Q("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/**
389 * @license lucide-react v0.469.0 - ISC
390 *
391 * This source code is licensed under the ISC license.
392 * See the LICENSE file in the root directory of this source tree.
393 */const bi=Q("LayoutTemplate",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"9",height:"7",x:"3",y:"14",rx:"1",key:"jqznyg"}],["rect",{width:"5",height:"7",x:"16",y:"14",rx:"1",key:"q5h2i8"}]]);/**
394 * @license lucide-react v0.469.0 - ISC
395 *
396 * This source code is licensed under the ISC license.
397 * See the LICENSE file in the root directory of this source tree.
398 */const VS=Q("LibraryBig",[["rect",{width:"8",height:"18",x:"3",y:"3",rx:"1",key:"oynpb5"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",key:"1qboyk"}]]);/**
399 * @license lucide-react v0.469.0 - ISC
400 *
401 * This source code is licensed under the ISC license.
402 * See the LICENSE file in the root directory of this source tree.
403 */const Jp=Q("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/**
404 * @license lucide-react v0.469.0 - ISC
405 *
406 * This source code is licensed under the ISC license.
407 * See the LICENSE file in the root directory of this source tree.
408 */const KS=Q("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/**
409 * @license lucide-react v0.469.0 - ISC
410 *
411 * This source code is licensed under the ISC license.
412 * See the LICENSE file in the root directory of this source tree.
413 */const sy=Q("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/**
414 * @license lucide-react v0.469.0 - ISC
415 *
416 * This source code is licensed under the ISC license.
417 * See the LICENSE file in the root directory of this source tree.
418 */const yi=Q("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
419 * @license lucide-react v0.469.0 - ISC
420 *
421 * This source code is licensed under the ISC license.
422 * See the LICENSE file in the root directory of this source tree.
423 */const eh=Q("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"}]]);/**
424 * @license lucide-react v0.469.0 - ISC
425 *
426 * This source code is licensed under the ISC license.
427 * See the LICENSE file in the root directory of this source tree.
428 */const HS=Q("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/**
429 * @license lucide-react v0.469.0 - ISC
430 *
431 * This source code is licensed under the ISC license.
432 * See the LICENSE file in the root directory of this source tree.
433 */const Kr=Q("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
434 * @license lucide-react v0.469.0 - ISC
435 *
436 * This source code is licensed under the ISC license.
437 * See the LICENSE file in the root directory of this source tree.
438 */const kc=Q("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/**
439 * @license lucide-react v0.469.0 - ISC
440 *
441 * This source code is licensed under the ISC license.
442 * See the LICENSE file in the root directory of this source tree.
443 */const QS=Q("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"}]]);/**
444 * @license lucide-react v0.469.0 - ISC
445 *
446 * This source code is licensed under the ISC license.
447 * See the LICENSE file in the root directory of this source tree.
448 */const GS=Q("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["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"}]]);/**
449 * @license lucide-react v0.469.0 - ISC
450 *
451 * This source code is licensed under the ISC license.
452 * See the LICENSE file in the root directory of this source tree.
453 */const Ba=Q("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
454 * @license lucide-react v0.469.0 - ISC
455 *
456 * This source code is licensed under the ISC license.
457 * See the LICENSE file in the root directory of this source tree.
458 */const ZS=Q("MessageSquareDot",[["path",{d:"M11.7 3H5a2 2 0 0 0-2 2v16l4-4h12a2 2 0 0 0 2-2v-2.7",key:"uodpkb"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}]]);/**
459 * @license lucide-react v0.469.0 - ISC
460 *
461 * This source code is licensed under the ISC license.
462 * See the LICENSE file in the root directory of this source tree.
463 */const ef=Q("MessageSquareText",[["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"}],["path",{d:"M13 8H7",key:"14i4kc"}],["path",{d:"M17 12H7",key:"16if0g"}]]);/**
464 * @license lucide-react v0.469.0 - ISC
465 *
466 * This source code is licensed under the ISC license.
467 * See the LICENSE file in the root directory of this source tree.
468 */const YS=Q("MessagesSquare",[["path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z",key:"p1xzt8"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1",key:"1cx29u"}]]);/**
469 * @license lucide-react v0.469.0 - ISC
470 *
471 * This source code is licensed under the ISC license.
472 * See the LICENSE file in the root directory of this source tree.
473 */const Cr=Q("MicVocal",[["path",{d:"m11 7.601-5.994 8.19a1 1 0 0 0 .1 1.298l.817.818a1 1 0 0 0 1.314.087L15.09 12",key:"80a601"}],["path",{d:"M16.5 21.174C15.5 20.5 14.372 20 13 20c-2.058 0-3.928 2.356-6 2-2.072-.356-2.775-3.369-1.5-4.5",key:"j0ngtp"}],["circle",{cx:"16",cy:"7",r:"5",key:"d08jfb"}]]);/**
474 * @license lucide-react v0.469.0 - ISC
475 *
476 * This source code is licensed under the ISC license.
477 * See the LICENSE file in the root directory of this source tree.
478 */const th=Q("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/**
479 * @license lucide-react v0.469.0 - ISC
480 *
481 * This source code is licensed under the ISC license.
482 * See the LICENSE file in the root directory of this source tree.
483 */const XS=Q("MonitorPlay",[["path",{d:"M10 7.75a.75.75 0 0 1 1.142-.638l3.664 2.249a.75.75 0 0 1 0 1.278l-3.664 2.25a.75.75 0 0 1-1.142-.64z",key:"1pctta"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}]]);/**
484 * @license lucide-react v0.469.0 - ISC
485 *
486 * This source code is licensed under the ISC license.
487 * See the LICENSE file in the root directory of this source tree.
488 */const iy=Q("MonitorSmartphone",[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]]);/**
489 * @license lucide-react v0.469.0 - ISC
490 *
491 * This source code is licensed under the ISC license.
492 * See the LICENSE file in the root directory of this source tree.
493 */const JS=Q("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"}]]);/**
494 * @license lucide-react v0.469.0 - ISC
495 *
496 * This source code is licensed under the ISC license.
497 * See the LICENSE file in the root directory of this source tree.
498 */const Hr=Q("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
499 * @license lucide-react v0.469.0 - ISC
500 *
501 * This source code is licensed under the ISC license.
502 * See the LICENSE file in the root directory of this source tree.
503 */const Ru=Q("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/**
504 * @license lucide-react v0.469.0 - ISC
505 *
506 * This source code is licensed under the ISC license.
507 * See the LICENSE file in the root directory of this source tree.
508 */const Tu=Q("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/**
509 * @license lucide-react v0.469.0 - ISC
510 *
511 * This source code is licensed under the ISC license.
512 * See the LICENSE file in the root directory of this source tree.
513 */const ry=Q("OctagonAlert",[["path",{d:"M12 16h.01",key:"1drbdi"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z",key:"1fd625"}]]);/**
514 * @license lucide-react v0.469.0 - ISC
515 *
516 * This source code is licensed under the ISC license.
517 * See the LICENSE file in the root directory of this source tree.
518 */const e2=Q("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.48
5186",key:"1pkts6"}]]);/**
519 * @license lucide-react v0.469.0 - ISC
520 *
521 * This source code is licensed under the ISC license.
522 * See the LICENSE file in the root directory of this source tree.
523 */const Nc=Q("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"}]]);/**
524 * @license lucide-react v0.469.0 - ISC
525 *
526 * This source code is licensed under the ISC license.
527 * See the LICENSE file in the root directory of this source tree.
528 */const qt=Q("Pencil",[["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"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/**
529 * @license lucide-react v0.469.0 - ISC
530 *
531 * This source code is licensed under the ISC license.
532 * See the LICENSE file in the root directory of this source tree.
533 */const dn=Q("PhoneCall",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 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.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}],["path",{d:"M14.05 2a9 9 0 0 1 8 7.94",key:"vmijpz"}],["path",{d:"M14.05 6A5 5 0 0 1 18 10",key:"13nbpp"}]]);/**
534 * @license lucide-react v0.469.0 - ISC
535 *
536 * This source code is licensed under the ISC license.
537 * See the LICENSE file in the root directory of this source tree.
538 */const uo=Q("PhoneForwarded",[["polyline",{points:"18 2 22 6 18 10",key:"6vjanh"}],["line",{x1:"14",x2:"22",y1:"6",y2:"6",key:"1jsywh"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 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.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
539 * @license lucide-react v0.469.0 - ISC
540 *
541 * This source code is licensed under the ISC license.
542 * See the LICENSE file in the root directory of this source tree.
543 */const yn=Q("PhoneIncoming",[["polyline",{points:"16 2 16 8 22 8",key:"1ygljm"}],["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 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.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
544 * @license lucide-react v0.469.0 - ISC
545 *
546 * This source code is licensed under the ISC license.
547 * See the LICENSE file in the root directory of this source tree.
548 */const ka=Q("PhoneOutgoing",[["polyline",{points:"22 8 22 2 16 2",key:"1g204g"}],["line",{x1:"16",x2:"22",y1:"8",y2:"2",key:"1ggias"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 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.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
549 * @license lucide-react v0.469.0 - ISC
550 *
551 * This source code is licensed under the ISC license.
552 * See the LICENSE file in the root directory of this source tree.
553 */const Ma=Q("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 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.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
554 * @license lucide-react v0.469.0 - ISC
555 *
556 * This source code is licensed under the ISC license.
557 * See the LICENSE file in the root directory of this source tree.
558 */const rn=Q("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
559 * @license lucide-react v0.469.0 - ISC
560 *
561 * This source code is licensed under the ISC license.
562 * See the LICENSE file in the root directory of this source tree.
563 */const t2=Q("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}
563],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/**
564 * @license lucide-react v0.469.0 - ISC
565 *
566 * This source code is licensed under the ISC license.
567 * See the LICENSE file in the root directory of this source tree.
568 */const Fe=Q("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
569 * @license lucide-react v0.469.0 - ISC
570 *
571 * This source code is licensed under the ISC license.
572 * See the LICENSE file in the root directory of this source tree.
573 */const a2=Q("Printer",[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]]);/**
574 * @license lucide-react v0.469.0 - ISC
575 *
576 * This source code is licensed under the ISC license.
577 * See the LICENSE file in the root directory of this source tree.
578 */const vi=Q("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/**
579 * @license lucide-react v0.469.0 - ISC
580 *
581 * This source code is licensed under the ISC license.
582 * See the LICENSE file in the root directory of this source tree.
583 */const oy=Q("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/**
584 * @license lucide-react v0.469.0 - ISC
585 *
586 * This source code is licensed under the ISC license.
587 * See the LICENSE file in the root directory of this source tree.
588 */const Di=Q("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"}]]);/**
589 * @license lucide-react v0.469.0 - ISC
590 *
591 * This source code is licensed under the ISC license.
592 * See the LICENSE file in the root directory of this source tree.
593 */const n2=Q("Repeat2",[["path",{d:"m2 9 3-3 3 3",key:"1ltn5i"}],["path",{d:"M13 18H7a2 2 0 0 1-2-2V6",key:"1r6tfw"}],["path",{d:"m22 15-3 3-3-3",key:"4rnwn2"}],["path",{d:"M11 6h6a2 2 0 0 1 2 2v10",key:"2f72bc"}]]);/**
594 * @license lucide-react v0.469.0 - ISC
595 *
596 * This source code is licensed under the ISC license.
597 * See the LICENSE file in the root directory of this source tree.
598 */const po=Q("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"}]]);/**
599 * @license lucide-react v0.469.0 - ISC
600 *
601 * This source code is licensed under the ISC license.
602 * See the LICENSE file in the root directory of this source tree.
603 */const Na=Q("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/**
604 * @license lucide-react v0.469.0 - ISC
605 *
606 * This source code is licensed under the ISC license.
607 * See the LICENSE file in the root directory of this source tree.
608 */const ly=Q("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
609 * @license lucide-react v0.469.0 - ISC
610 *
611 * This source code is licensed under the ISC license.
612 * See the LICENSE file in the root directory of this source tree.
613 */const Qr=Q("ScrollText",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/**
614 * @license lucide-react v0.469.0 - ISC
615 *
616 * This source code is licensed under the ISC license.
617 * See the LICENSE file in the root directory of this source tree.
618 */const cy=Q("SearchX",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["path",{d:"m8.5 8.5 5 5",key:"a8mexj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
619 * @license lucide-react v0.469.0 - ISC
620 *
621 * This source code is licensed under the ISC license.
622 * See the LICENSE file in the root directory of this source tree.
623 */const Mn=Q("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
624 * @license lucide-react v0.469.0 - ISC
625 *
626 * This source code is licensed under the ISC license.
627 * See the LICENSE file in the root directory of this source tree.
628 */const Gr=Q("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/**
629 * @license lucide-react v0.469.0 - ISC
630 *
631 * This source code is licensed under the ISC license.
632 * See the LICENSE file in the root directory of this source tree.
633 */const s2=Q("ServerCrash",[["path",{d:"M6 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2",key:"4b9dqc"}],["path",{d:"M6 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-2",key:"22nnkd"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m13 6-4 6h6l-4 6",key:"14hqih"}]]);/**
634 * @license lucide-react v0.469.0 - ISC
635 *
636 * This source code is licensed under the ISC license.
637 * See the LICENSE file in the root directory of this source tree.
638 */const dy=Q("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/**
639 * @license lucide-react v0.469.0 - ISC
640 *
641 * This source code is licensed under the ISC license.
642 * See the LICENSE file in the root directory of this source tree.
643 */const uy=Q("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"}]]);/**
644 * @license lucide-react v0.469.0 - ISC
645 *
646 * This source code is licensed under the ISC license.
647 * See the LICENSE file in the root directory of this source tree.
648 */const Sc=Q("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",ke
648y:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/**
649 * @license lucide-react v0.469.0 - ISC
650 *
651 * This source code is licensed under the ISC license.
652 * See the LICENSE file in the root directory of this source tree.
653 */const ho=Q("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
654 * @license lucide-react v0.469.0 - ISC
655 *
656 * This source code is licensed under the ISC license.
657 * See the LICENSE file in the root directory of this source tree.
658 */const i2=Q("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/**
659 * @license lucide-react v0.469.0 - ISC
660 *
661 * This source code is licensed under the ISC license.
662 * See the LICENSE file in the root directory of this source tree.
663 */const Cc=Q("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/**
664 * @license lucide-react v0.469.0 - ISC
665 *
666 * This source code is licensed under the ISC license.
667 * See the LICENSE file in the root directory of this source tree.
668 */const Mu=Q("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/**
669 * @license lucide-react v0.469.0 - ISC
670 *
671 * This source code is licensed under the ISC license.
672 * See the LICENSE file in the root directory of this source tree.
673 */const r2=Q("Shuffle",[["path",{d:"m18 14 4 4-4 4",key:"10pe0f"}],["path",{d:"m18 2 4 4-4 4",key:"pucp1d"}],["path",{d:"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22",key:"1ailkh"}],["path",{d:"M2 6h1.972a4 4 0 0 1 3.6 2.2",key:"km57vx"}],["path",{d:"M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45",key:"os18l9"}]]);/**
674 * @license lucide-react v0.469.0 - ISC
675 *
676 * This source code is licensed under the ISC license.
677 * See the LICENSE file in the root directory of this source tree.
678 */const o2=Q("SmartphoneNfc",[["rect",{width:"7",height:"12",x:"2",y:"6",rx:"1",key:"5nje8w"}],["path",{d:"M13 8.32a7.43 7.43 0 0 1 0 7.36",key:"1g306n"}],["path",{d:"M16.46 6.21a11.76 11.76 0 0 1 0 11.58",key:"uqvjvo"}],["path",{d:"M19.91 4.1a15.91 15.91 0 0 1 .01 15.8",key:"ujntz3"}]]);/**
679 * @license lucide-react v0.469.0 - ISC
680 *
681 * This source code is licensed under the ISC license.
682 * See the LICENSE file in the root directory of this source tree.
683 */const ji=Q("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/**
684 * @license lucide-react v0.469.0 - ISC
685 *
686 * This source code is licensed under the ISC license.
687 * See the LICENSE file in the root directory of this source tree.
688 */const py=Q("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/**
689 * @license lucide-react v0.469.0 - ISC
690 *
691 * This source code is licensed under the ISC license.
692 * See the LICENSE file in the root directory of this source tree.
693 */const _t=Q("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
694 * @license lucide-react v0.469.0 - ISC
695 *
696 * This source code is licensed under the ISC license.
697 * See the LICENSE file in the root directory of this source tree.
698 */const l2=Q("Speaker",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["circle",{cx:"12",cy:"14",r:"4",key:"1jruaj"}],["path",{d:"M12 14h.01",key:"1etili"}]]);/**
699 * @license lucide-react v0.469.0 - ISC
700 *
701 * This source code is licensed under the ISC license.
702 * See the LICENSE file in the root directory of this source tree.
703 */const ah=Q("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
704 * @license lucide-react v0.469.0 - ISC
705 *
706 * This source code is licensed under the ISC license.
707 * See the LICENSE file in the root directory of this source tree.
708 */const Ii=Q("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/**
709 * @license lucide-react v0.469.0 - ISC
710 *
711 * This source code is licensed under the ISC license.
712 * See the LICENSE file in the root directory of this source tree.
713 */const c2=Q("Stethoscope",[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]]);/**
714 * @license lucide-react v0.469.0 - ISC
715 *
716 * This source code is licensed under the ISC license.
717 * See the LICENSE file in the root directory of this source tree.
718 */const hy=Q("StickyNote",[["path",{d:"M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z",key:"qazsjp"}],["path",{d:"M15 3v4a2 2 0 0 0 2 2h4",key:"40519r"}]]);/**
719 * @license lucide-react v0.469.0 - ISC
720 *
721 * This source code is licensed under the ISC license.
722 * See the LICENSE file in the root directory of this source tree.
723 */const Zr=Q("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"}]]);/**
724 * @license lucide-react v0.469.0 - ISC
725 *
726 * This source code is licensed under the ISC license.
727 * See the LICENSE file in the root directory of this source tree.
728 */const d2=Q("Sunrise",[["path",{d:"M12 2v8",key:"1q4o3n"}],["path",{d:"m4.93 10.93 1.41 1.41",key:"2a7f42"}],["path",{d:"M2 18h2",key:"j10viu"}],["path",{d:"M20 18h2",key:"wocana"}],["path",{d:"m19.07 10.93-1.41 1.41",key:"15zs5n"}],["path",{d:"M22 22H2",key:"19qnx5"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M16 18a4 4 0 0 0-8 0",key:"1lzouq"}]]);/**
729 * @license lucide-react v0.469.0 - ISC
730 *
731 * This source code is licensed under the ISC license.
732 * See the LICENSE file in the root directory of this source tree.
733 */const Hl=Q("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
734 * @license lucide-react v0.469.0 - ISC
735 *
736 * This source code is licensed under the ISC license.
737 * See the LICENSE file in the root directory of this source tree.
738 */const Pu=Q("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
739 * @license lucide-react v0.469.0 - ISC
740 *
741 * This source code is licensed under the ISC license.
742 * See the LICENSE file in the root directory of this source tree.
743 */const u2=Q("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"}]]);/**
744 * @license lucide-react v0.469.0 - ISC
745 *
746 * This source code is licensed under the ISC license.
747 * See the LICENSE file in the root directory of this source tree.
748 */const p2=Q("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"}]]);/**
749 * @license lucide-react v0.469.0 - ISC
750 *
751 * This source code is licensed under the ISC license.
752 * See the LICENSE file in the root directory of this source tree.
753 */const h2=Q("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
754 * @license lucide-react v0.469.0 - ISC
755 *
756 * This source code is licensed under the ISC license.
757 * See the LICENSE file in the root directory of this source tree.
758 */const mt=Q("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"}]]);/**
759 * @license lucide-react v0.469.0 - ISC
760 *
761 * This source code is licensed under the ISC license.
762 * See the LICENSE file in the root directory of this source tree.
763 */const m2=Q("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/**
764 * @license lucide-react v0.469.0 - ISC
765 *
766 * This source code is licensed under the ISC license.
767 * See the LICENSE file in the root directory of this source tree.
768 */const f2=Q("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
769 * @license lucide-react v0.469.0 - ISC
770 *
771 * This source code is licensed under the ISC license.
772 * See the LICENSE file in the root directory of this source tree.
773 */const x2=Q("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/**
774 * @license lucide-react v0.469.0 - ISC
775 *
776 * This source code is licensed under the ISC license.
777 * See the LICENSE file in the root directory of this source tree.
778 */const g2=Q("Unlink",[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]]);/**
779 * @license lucide-react v0.469.0 - ISC
780 *
781 * This source code is licensed under the ISC license.
782 * See the LICENSE file in the root directory of this source tree.
783 */const wi=Q("Unplug",[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]]);/**
784 * @license lucide-react v0.469.0 - ISC
785 *
786 * This source code is licensed under the ISC license.
787 * See the LICENSE file in the root directory of this source tree.
788 */const b2=Q("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"}]]);/**
789 * @license lucide-react v0.469.0 - ISC
790 *
791 * This source code is licensed under the ISC license.
792 * See the LICENSE file in the root directory of this source tree.
793 */const nh=Q("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}
793],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/**
794 * @license lucide-react v0.469.0 - ISC
795 *
796 * This source code is licensed under the ISC license.
797 * See the LICENSE file in the root directory of this source tree.
798 */const y2=Q("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/**
799 * @license lucide-react v0.469.0 - ISC
800 *
801 * This source code is licensed under the ISC license.
802 * See the LICENSE file in the root directory of this source tree.
803 */const v2=Q("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/**
804 * @license lucide-react v0.469.0 - ISC
805 *
806 * This source code is licensed under the ISC license.
807 * See the LICENSE file in the root directory of this source tree.
808 */const En=Q("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);/**
809 * @license lucide-react v0.469.0 - ISC
810 *
811 * This source code is licensed under the ISC license.
812 * See the LICENSE file in the root directory of this source tree.
813 */const mo=Q("UserX",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]);/**
814 * @license lucide-react v0.469.0 - ISC
815 *
816 * This source code is licensed under the ISC license.
817 * See the LICENSE file in the root directory of this source tree.
818 */const my=Q("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
819 * @license lucide-react v0.469.0 - ISC
820 *
821 * This source code is licensed under the ISC license.
822 * See the LICENSE file in the root directory of this source tree.
823 */const Bs=Q("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/**
824 * @license lucide-react v0.469.0 - ISC
825 *
826 * This source code is licensed under the ISC license.
827 * See the LICENSE file in the root directory of this source tree.
828 */const j2=Q("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/**
829 * @license lucide-react v0.469.0 - ISC
830 *
831 * This source code is licensed under the ISC license.
832 * See the LICENSE file in the root directory of this source tree.
833 */const sh=Q("Voicemail",[["circle",{cx:"6",cy:"12",r:"4",key:"1ehtga"}],["circle",{cx:"18",cy:"12",r:"4",key:"4vafl8"}],["line",{x1:"6",x2:"18",y1:"16",y2:"16",key:"pmt8us"}]]);/**
834 * @license lucide-react v0.469.0 - ISC
835 *
836 * This source code is licensed under the ISC license.
837 * See the LICENSE file in the root directory of this source tree.
838 */const w2=Q("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"}]]);/**
839 * @license lucide-react v0.469.0 - ISC
840 *
841 * This source code is licensed under the ISC license.
842 * See the LICENSE file in the root directory of this source tree.
843 */const _c=Q("Wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]);/**
844 * @license lucide-react v0.469.0 - ISC
845 *
846 * This source code is licensed under the ISC license.
847 * See the LICENSE file in the root directory of this source tree.
848 */const zs=Q("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]);/**
849 * @license lucide-react v0.469.0 - ISC
850 *
851 * This source code is licensed under the ISC license.
852 * See the LICENSE file in the root directory of this source tree.
853 */const k2=Q("Webcam",[["circle",{cx:"12",cy:"10",r:"8",key:"1gshiw"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 22h10",key:"10w4w3"}],["path",{d:"M12 22v-4",key:"1utk9m"}]]);/**
854 * @license lucide-react v0.469.0 - ISC
855 *
856 * This source code is licensed under the ISC license.
857 * See the LICENSE file in the root directory of this source tree.
858 */const Ec=Q("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);/**
859 * @license lucide-react v0.469.0 - ISC
860 *
861 * This source code is licensed under the ISC license.
862 * See the LICENSE file in the root directory of this source tree.
863 */const N2=Q("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}
863],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/**
864 * @license lucide-react v0.469.0 - ISC
865 *
866 * This source code is licensed under the ISC license.
867 * See the LICENSE file in the root directory of this source tree.
868 */const en=Q("Workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]);/**
869 * @license lucide-react v0.469.0 - ISC
870 *
871 * This source code is licensed under the ISC license.
872 * See the LICENSE file in the root directory of this source tree.
873 */const ih=Q("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);/**
874 * @license lucide-react v0.469.0 - ISC
875 *
876 * This source code is licensed under the ISC license.
877 * See the LICENSE file in the root directory of this source tree.
878 */const fy=Q("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),xy=ds()(oo(e=>({sidebarCollapsed:!1,toggleSidebar:()=>e(a=>({sidebarCollapsed:!a.sidebarCollapsed})),setSidebarCollapsed:a=>e({sidebarCollapsed:a}),mobileOpen:!1,setMobileOpen:a=>e({mobileOpen:a}),toggleMobile:()=>e(a=>({mobileOpen:!a.mobileOpen}))}),{name:"conectaia.ui",partialize:e=>({sidebarCollapsed:e.sidebarCollapsed})}));function S2(e=1024){const a=`(max-width: ${e}px)`,[n,s]=m.useState(()=>typeof window<"u"&&window.matchMedia(a).matches);return m.useEffect(()=>{const i=window.matchMedia(a),r=()=>s(i.matches);return r(),i.addEventListener("change",r),()=>i.removeEventListener("change",r)},[a]),n}const C2=["channels"],gy=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)"):null;function by(){return gy?.matches?"dark":"light"}function zu(e){return e==="system"?by():e}function gd(e){if(typeof document>"u"){e();return}const a=document.documentElement;a.setAttribute("data-theme-switching",""),e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>a.removeAttribute("data-theme-switching"))})}const xt=ds()(oo((e,a)=>({mode:"system",resolved:zu("system"),setMode:n=>gd(()=>e({mode:n,resolved:zu(n)})),toggle:()=>{const n=a().resolved==="dark"?"light":"dark";gd(()=>e({mode:n,resolved:n}))},syncSystem:()=>{a().mode==="system"&&gd(()=>e({resolved:by()}))}}),{name:"conectaia.theme",partialize:e=>({mode:e.mode})}));xt.setState(e=>({resolved:zu(e.mode)}));gy?.addEventListener?.("change",()=>xt.getState().syncSystem());function yy(e,a){return function(){return e.apply(a,arguments)}}const{toString:_2}=Object.prototype,{getPrototypeOf:Ac}=Object,{iterator:Rc,toStringTag:vy}=Symbol,Tc=(e=>a=>{const n=_2.call(a);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),on=e=>(e=e.toLowerCase(),a=>Tc(a)===e),Mc=e=>a=>typeof a===e,{isArray:Li}=Array,ki=Mc("undefined");function fo(e){return e!==null&&!ki(e)&&e.constructor!==null&&!ki(e.constructor)&&Sa(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const jy=on("ArrayBuffer");function E2(e){let a;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?a=ArrayBuffer.isView(e):a=e&&e.buffer&&jy(e.buffer),a}const A2=Mc("string"),Sa=Mc("function"),wy=Mc("number"),xo=e=>e!==null&&typeof e=="object",R2=e=>e===!0||e===!1,yl=e=>{if(Tc(e)!=="object")return!1;const a=Ac(e);return(a===null||a===Object.prototype||Object.getPrototypeOf(a)===null)&&!(vy in e)&&!(Rc in e)},T2=e=>{if(!xo(e)||fo(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},M2=on("Date"),P2=on("File"),z2=e=>!!(e&&typeof e.uri<"u"),D2=e=>e&&typeof e.getParts<"u",I2=on("Blob"),L2=on("FileList"),F2=e=>xo(e)&&Sa(e.pipe);function O2(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const tf=O2(),af=typeof tf.FormData<"u"?tf.FormData:void 0,$2=e=>{if(!e)return!1;if(af&&e instanceof af)return!0;const a=Ac(e);if(!a||a===Object.prototype||!Sa(e.append))return!1;const n=Tc(e);return n==="formdata"||n==="object"&&Sa(e.toString)&&e.toString()==="[object FormData]"}
vendor: 5,463 bytes, lines 878-879
878,q2=on("URLSearchParams"),[B2,W2,U2,V2]=["ReadableStream","Request","Response","Headers"].map(on),K2=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function go(e,a,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let s,i;if(typeof e!="object"&&(e=[e]),Li(e))for(s=0,i=e.length;s<i;s++)a.call(null,e[s],s,e);else{if(fo(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),o=r.length;let l;for(s=0;s<o;s++)l=r[s],a.call(null,e[l],l,e)}}function ky(e,a){if(fo(e))return null;a=a.toLowerCase();const n=Object.keys(e);let s=n.length,i;for(;s-- >0;)if(i=n[s],a===i.toLowerCase())return i;return null}const Ns=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ny=e=>!ki(e)&&e!==Ns;function Du(...e){const{caseless:a,skipUndefined:n}=Ny(this)&&this||{},s={},i=(r,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;const l=a&&ky(s,o)||o,c=Iu(s,l)?s[l]:void 0;yl(c)&&yl(r)?s[l]=Du(c,r):yl(r)?s[l]=Du({},r):Li(r)?s[l]=r.slice():(!n||!ki(r))&&(s[l]=r)};for(let r=0,o=e.length;r<o;r++)e[r]&&go(e[r],i);return s}const H2=(e,a,n,{allOwnKeys:s}={})=>(go(a,(i,r)=>{n&&Sa(i)?Object.defineProperty(e,r,{__proto__:null,value:yy(i,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,r,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:s}),e),Q2=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),G2=(e,a,n,s)=>{e.prototype=Object.create(a.prototype,s),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:a.prototype}),n&&Object.assign(e.prototype,n)},Z2=(e,a,n,s)=>{let i,r,o;const l={};if(a=a||{},e==null)return a;do{for(i=Object.getOwnPropertyNames(e),r=i.length;r-- >0;)o=i[r],(!s||s(o,e,a))&&!l[o]&&(a[o]=e[o],l[o]=!0);e=n!==!1&&Ac(e)}while(e&&(!n||n(e,a))&&e!==Object.prototype);return a},Y2=(e,a,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=a.length;const s=e.indexOf(a,n);return s!==-1&&s===n},X2=e=>{if(!e)return null;if(Li(e))return e;let a=e.length;if(!wy(a))return null;const n=new Array(a);for(;a-- >0;)n[a]=e[a];return n},J2=(e=>a=>e&&a instanceof e)(typeof Uint8Array<"u"&&Ac(Uint8Array)),eC=(e,a)=>{const s=(e&&e[Rc]).call(e);let i;for(;(i=s.next())&&!i.done;){const r=i.value;a.call(e,r[0],r[1])}},tC=(e,a)=>{let n;const s=[];for(;(n=e.exec(a))!==null;)s.push(n);return s},aC=on("HTMLFormElement"),nC=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,s,i){return s.toUpperCase()+i}),Iu=(({hasOwnProperty:e})=>(a,n)=>e.call(a,n))(Object.prototype),sC=on("RegExp"),Sy=(e,a)=>{const n=Object.getOwnPropertyDescriptors(e),s={};go(n,(i,r)=>{let o;(o=a(i,r,e))!==!1&&(s[r]=o||i)}),Object.defineProperties(e,s)},iC=e=>{Sy(e,(a,n)=>{if(Sa(e)&&["arguments","caller","callee"].includes(n))return!1;const s=e[n];if(Sa(s)){if(a.enumerable=!1,"writable"in a){a.writable=!1;return}a.set||(a.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},rC=(e,a)=>{const n={},s=i=>{i.forEach(r=>{n[r]=!0})};return Li(e)?s(e):s(String(e).split(a)),n},oC=()=>{},lC=(e,a)=>e!=null&&Number.isFinite(e=+e)?e:a;function cC(e){return!!(e&&Sa(e.append)&&e[vy]==="FormData"&&e[Rc])}const dC=e=>{const a=new WeakSet,n=s=>{if(xo(s)){if(a.has(s))return;if(fo(s))return s;if(!("toJSON"in s)){a.add(s);const i=Li(s)?[]:{};return go(s,(r,o)=>{const l=n(r);!ki(l)&&(i[o]=l)}),a.delete(s),i}}return s};return n(e)},uC=on("AsyncFunction"),pC=e=>e&&(xo(e)||Sa(e))&&Sa(e.then)&&Sa(e.catch),Cy=((e,a)=>e?setImmediate:a?((n,s)=>(Ns.addEventListener("message",({source:i,data:r})=>{i===Ns&&r===n&&s.length&&s.shift()()},!1),i=>{s.push(i),Ns.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Sa(Ns.postMessage)),hC=typeof queueMicrotask<"u"?queueMicrotask.bind(Ns):typeof process<"u"&&process.nextTick||Cy,mC=e=>e!=null&&Sa(e[Rc]),Y={isArray:Li,isArrayBuffer:jy,isBuffer:fo,isFormData:$2,isArrayBufferView:E2,isString:A2,isNumber:wy,isBoolean:R2,isObject:xo,isPlainObject:yl,isEmptyObject:T2,isReadableStream:B2,isRequest:W2,isResponse:U2,isHeaders:V2,isUndefined:ki,isDate:M2,isFile:P2,isReactNativeBlob:z2,isReactNative:D2,isBlob:I2,isRegExp:sC,isFunction:Sa,isStream:F2,isURLSearchParams:q2,isTypedArray:J2,isFileList:L2,forEach:go,merge:Du,extend:H2,trim:K2,stripBOM:Q2,inherits:G2,toFlatObject:Z2,kindOf:Tc,kindOfTest:on,endsWith:Y2,toArray:X2,forEachEntry:eC,matchAll:tC,isHTMLForm:aC,hasOwnProperty:Iu,hasOwnProp:Iu,reduceDescriptors:Sy,freezeMethods:iC,toObjectSet:rC,toCamelCase:nC,noop:oC,toFiniteNumber:lC,findKey:ky,global:Ns,isContextDefined:Ny,isSpecCompliantForm:cC,toJSONObject:dC,isAsyncFn:uC,isThenable:pC,setImmediate:Cy,asap:hC,isIterable:mC},fC=Y.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),xC=e=>{const a={};let n,s,i;return e&&e.split(`
879`).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),s=o.substring(i+1).trim(),!(!n||a[n]&&fC[n])&&(n==="set-cookie"?a[n]?a[n].push(s):a[n]=[s]:a[n]=a[n]?a[n]+", "+s:s)}),a};function gC(e){let a=0,n=e.length;for(;a<n;){const s=e.charCodeAt(a);if(s!==9&&s!==32)break;a+=1}for(;n>a;){const s=e.charCodeAt(n-1);if(s!==9&&s!==32)break;n-=1}return a===0&&n===e.length?e:e.slice(a,n)}
vendor: 32,732 bytes, lines 879-886
879const bC=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),yC=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function rh(e,a){return Y.isArray(e)?e.map(n=>rh(n,a)):gC(String(e).replace(a,""))}const vC=e=>rh(e,bC),jC=e=>rh(e,yC);function _y(e){const a=Object.create(null);return Y.forEach(e.toJSON(),(n,s)=>{a[s]=jC(n)}),a}const nf=Symbol("internals");function Xi(e){return e&&String(e).trim().toLowerCase()}function vl(e){return e===!1||e==null?e:Y.isArray(e)?e.map(vl):vC(String(e))}function wC(e){const a=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(e);)a[s[1]]=s[2];return a}const kC=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function bd(e,a,n,s,i){if(Y.isFunction(s))return s.call(this,a,n);if(i&&(a=n),!!Y.isString(a)){if(Y.isString(s))return a.indexOf(s)!==-1;if(Y.isRegExp(s))return s.test(a)}}function NC(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(a,n,s)=>n.toUpperCase()+s)}function SC(e,a){const n=Y.toCamelCase(" "+a);["get","set","has"].forEach(s=>{Object.defineProperty(e,s+n,{__proto__:null,value:function(i,r,o){return this[s].call(this,a,i,r,o)},configurable:!0})})}let da=class{constructor(a){a&&this.set(a)}set(a,n,s){const i=this;function r(l,c,d){const u=Xi(c);if(!u)throw new Error("header name must be a non-empty string");const p=Y.findKey(i,u);(!p||i[p]===void 0||d===!0||d===void 0&&i[p]!==!1)&&(i[p||c]=vl(l))}const o=(l,c)=>Y.forEach(l,(d,u)=>r(d,u,c));if(Y.isPlainObject(a)||a instanceof this.constructor)o(a,n);else if(Y.isString(a)&&(a=a.trim())&&!kC(a))o(xC(a),n);else if(Y.isObject(a)&&Y.isIterable(a)){let l={},c,d;for(const u of a){if(!Y.isArray(u))throw TypeError("Object iterator must return a key-value pair");l[d=u[0]]=(c=l[d])?Y.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}o(l,n)}else a!=null&&r(n,a,s);return this}get(a,n){if(a=Xi(a),a){const s=Y.findKey(this,a);if(s){const i=this[s];if(!n)return i;if(n===!0)return wC(i);if(Y.isFunction(n))return n.call(this,i,s);if(Y.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(a,n){if(a=Xi(a),a){const s=Y.findKey(this,a);return!!(s&&this[s]!==void 0&&(!n||bd(this,this[s],s,n)))}return!1}delete(a,n){const s=this;let i=!1;function r(o){if(o=Xi(o),o){const l=Y.findKey(s,o);l&&(!n||bd(s,s[l],l,n))&&(delete s[l],i=!0)}}return Y.isArray(a)?a.forEach(r):r(a),i}clear(a){const n=Object.keys(this);let s=n.length,i=!1;for(;s--;){const r=n[s];(!a||bd(this,this[r],r,a,!0))&&(delete this[r],i=!0)}return i}normalize(a){const n=this,s={};return Y.forEach(this,(i,r)=>{const o=Y.findKey(s,r);if(o){n[o]=vl(i),delete n[r];return}const l=a?NC(r):String(r).trim();l!==r&&delete n[r],n[l]=vl(i),s[l]=!0}),this}concat(...a){return this.constructor.concat(this,...a)}toJSON(a){const n=Object.create(null);return Y.forEach(this,(s,i)=>{s!=null&&s!==!1&&(n[i]=a&&Y.isArray(s)?s.join(", "):s)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([a,n])=>a+": "+n).join(`
880`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(a){return a instanceof this?a:new this(a)}static concat(a,...n){const s=new this(a);return n.forEach(i=>s.set(i)),s}static accessor(a){const s=(this[nf]=this[nf]={accessors:{}}).accessors,i=this.prototype;function r(o){const l=Xi(o);s[l]||(SC(i,o),s[l]=!0)}return Y.isArray(a)?a.forEach(r):r(a),this}};da.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Y.reduceDescriptors(da.prototype,({value:e},a)=>{let n=a[0].toUpperCase()+a.slice(1);return{get:()=>e,set(s){this[n]=s}}});Y.freezeMethods(da);const CC="[REDACTED ****]";function _C(e){if(Y.hasOwnProp(e,"toJSON"))return!0;let a=Object.getPrototypeOf(e);for(;a&&a!==Object.prototype;){if(Y.hasOwnProp(a,"toJSON"))return!0;a=Object.getPrototypeOf(a)}return!1}function EC(e,a){const n=new Set(a.map(r=>String(r).toLowerCase())),s=[],i=r=>{if(r===null||typeof r!="object"||Y.isBuffer(r))return r;if(s.indexOf(r)!==-1)return;r instanceof da&&(r=r.toJSON()),s.push(r);let o;if(Y.isArray(r))o=[],r.forEach((l,c)=>{const d=i(l);Y.isUndefined(d)||(o[c]=d)});else{if(!Y.isPlainObject(r)&&_C(r))return s.pop(),r;o=Object.create(null);for(const[l,c]of Object.entries(r)){const d=n.has(l.toLowerCase())?CC:i(c);Y.isUndefined(d)||(o[l]=d)}}return s.pop(),o};return i(e)}let Ae=class Ey extends Error{static from(a,n,s,i,r,o){const l=new Ey(a.message,n||a.code,s,i,r);return l.cause=a,l.name=a.name,a.status!=null&&l.status==null&&(l.status=a.status),o&&Object.assign(l,o),l}constructor(a,n,s,i,r){super(a),Object.defineProperty(this,"message",{__proto__:null,value:a,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),s&&(this.config=s),i&&(this.request=i),r&&(this.response=r,this.status=r.status)}toJSON(){const a=this.config,n=a&&Y.hasOwnProp(a,"redact")?a.redact:void 0,s=Y.isArray(n)&&n.length>0?EC(a,n):Y.toJSONObject(a);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:s,code:this.code,status:this.status}}};Ae.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";Ae.ERR_BAD_OPTION="ERR_BAD_OPTION";Ae.ECONNABORTED="ECONNABORTED";Ae.ETIMEDOUT="ETIMEDOUT";Ae.ECONNREFUSED="ECONNREFUSED";Ae.ERR_NETWORK="ERR_NETWORK";Ae.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";Ae.ERR_DEPRECATED="ERR_DEPRECATED";Ae.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";Ae.ERR_BAD_REQUEST="ERR_BAD_REQUEST";Ae.ERR_CANCELED="ERR_CANCELED";Ae.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";Ae.ERR_INVALID_URL="ERR_INVALID_URL";Ae.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const AC=null;function Lu(e){return Y.isPlainObject(e)||Y.isArray(e)}function Ay(e){return Y.endsWith(e,"[]")?e.slice(0,-2):e}function yd(e,a,n){return e?e.concat(a).map(function(i,r){return i=Ay(i),!n&&r?"["+i+"]":i}).join(n?".":""):a}function RC(e){return Y.isArray(e)&&!e.some(Lu)}const TC=Y.toFlatObject(Y,{},null,function(a){return/^is[A-Z]/.test(a)});function Pc(e,a,n){if(!Y.isObject(e))throw new TypeError("target must be an object");a=a||new FormData,n=Y.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,v){return!Y.isUndefined(v[g])});const s=n.metaTokens,i=n.visitor||p,r=n.dots,o=n.indexes,l=n.Blob||typeof Blob<"u"&&Blob,c=n.maxDepth===void 0?100:n.maxDepth,d=l&&Y.isSpecCompliantForm(a);if(!Y.isFunction(i))throw new TypeError("visitor must be a function");function u(b){if(b===null)return"";if(Y.isDate(b))return b.toISOString();if(Y.isBoolean(b))return b.toString();if(!d&&Y.isBlob(b))throw new Ae("Blob is not supported. Use a Buffer instead.");return Y.isArrayBuffer(b)||Y.isTypedArray(b)?d&&typeof Blob=="function"?new Blob([b]):Buffer.from(b):b}function p(b,g,v){let y=b;if(Y.isReactNative(a)&&Y.isReactNativeBlob(b))return a.append(yd(v,g,r),u(b)),!1;if(b&&!v&&typeof b=="object"){if(Y.endsWith(g,"{}"))g=s?g:g.slice(0,-2),b=JSON.stringify(b);else if(Y.isArray(b)&&RC(b)||(Y.isFileList(b)||Y.endsWith(g,"[]"))&&(y=Y.toArray(b)))return g=Ay(g),y.forEach(function(w,j){!(Y.isUndefined(w)||w===null)&&a.append(o===!0?yd([g],j,r):o===null?g:g+"[]",u(w))}),!1}return Lu(b)?!0:(a.append(yd(v,g,r),u(b)),!1)}const f=[],x=Object.assign(TC,{defaultVisitor:p,convertValue:u,isVisitable:Lu});function h(b,g,v=0){if(!Y.isUndefined(b)){if(v>c)throw new Ae("Object is too deeply nested ("+v+" levels). Max depth: "+c,Ae.ERR_FORM_DATA_DEPTH_EXCEEDED);if(f.indexOf(b)!==-1)throw Error("Circular reference detected in "+g.join("."));f.push(b),Y.forEach(b,function(k,w){(!(Y.isUndefined(k)||k===null)&&i.call(a,k,Y.isString(w)?w.trim():w,g,x))===!0&&h(k,g?g.concat(w):[w],v+1)}),f.pop()}}if(!Y.isObject(e))throw new TypeError("data must be an object");return h(e),a}function sf(e){const a={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(s){return a[s]})}function oh(e,a){this._pairs=[],e&&Pc(e,this,a)}const Ry=oh.prototype;Ry.append=function(a,n){this._pairs.push([a,n])};Ry.toString=function(a){const n=a?function(s){return a.call(this,s,sf)}:sf;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function MC(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ty(e,a,n){if(!a)return e;const s=n&&n.encode||MC,i=Y.isFunction(n)?{serialize:n}:n,r=i&&i.serialize;let o;if(r?o=r(a,i):o=Y.isURLSearchParams(a)?a.toString():new oh(a,i).toString(s),o){const l=e.indexOf("#");l!==-1&&(e=e.slice(0,l)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class rf{constructor(){this.handlers=[]}use(a,n,s){return this.handlers.push({fulfilled:a,rejected:n,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(a){this.handlers[a]&&(this.handlers[a]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(a){Y.forEach(this.handlers,function(s){s!==null&&a(s)})}}const lh={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},PC=typeof URLSearchParams<"u"?URLSearchParams:oh,zC=typeof FormData<"u"?FormData:null,DC=typeof Blob<"u"?Blob:null,IC={isBrowser:!0,classes:{URLSearchParams:PC,FormData:zC,Blob:DC},protocols:["http","https","file","blob","url","data"]},ch=typeof window<"u"&&typeof document<"u",Fu=typeof navigator=="object"&&navigator||void 0,LC=ch&&(!Fu||["ReactNative","NativeScript","NS"].indexOf(Fu.product)<0),FC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",OC=ch&&window.location.href||"http://localhost",$C=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ch,hasStandardBrowserEnv:LC,hasStandardBrowserWebWorkerEnv:FC,navigator:Fu,origin:OC},Symbol.toStringTag,{value:"Module"})),ea={...$C,...IC};function qC(e,a){return Pc(e,new ea.classes.URLSearchParams,{visitor:function(n,s,i,r){return ea.isNode&&Y.isBuffer(n)?(this.append(s,n.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...a})}function BC(e){return Y.matchAll(/\w+|\[(\w*)]/g,e).map(a=>a[0]==="[]"?"":a[1]||a[0])}function WC(e){const a={},n=Object.keys(e);let s;const i=n.length;let r;for(s=0;s<i;s++)r=n[s],a[r]=e[r];return a}function My(e){function a(n,s,i,r){let o=n[r++];if(o==="__proto__")return!0;const l=Number.isFinite(+o),c=r>=n.length;return o=!o&&Y.isArray(i)?i.length:o,c?(Y.hasOwnProp(i,o)?i[o]=Y.isArray(i[o])?i[o].concat(s):[i[o],s]:i[o]=s,!l):((!Y.hasOwnProp(i,o)||!Y.isObject(i[o]))&&(i[o]=[]),a(n,s,i[o],r)&&Y.isArray(i[o])&&(i[o]=WC(i[o])),!l)}if(Y.isFormData(e)&&Y.isFunction(e.entries)){const n={};return Y.forEachEntry(e,(s,i)=>{a(BC(s),i,n,0)}),n}return null}const Hs=(e,a)=>e!=null&&Y.hasOwnProp(e,a)?e[a]:void 0;function UC(e,a,n){if(Y.isString(e))try{return(a||JSON.parse)(e),Y.trim(e)}catch(s){if(s.name!=="SyntaxError")throw s}return(n||JSON.stringify)(e)}const bo={transitional:lh,adapter:["xhr","http","fetch"],transformRequest:[function(a,n){const s=n.getContentType()||"",i=s.indexOf("application/json")>-1,r=Y.isObject(a);if(r&&Y.isHTMLForm(a)&&(a=new FormData(a)),Y.isFormData(a))return i?JSON.stringify(My(a)):a;if(Y.isArrayBuffer(a)||Y.isBuffer(a)||Y.isStream(a)||Y.isFile(a)||Y.isBlob(a)||Y.isReadableStream(a))return a;if(Y.isArrayBufferView(a))return a.buffer;if(Y.isURLSearchParams(a))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),a.toString();let l;if(r){const c=Hs(this,"formSerializer");if(s.indexOf("application/x-www-form-urlencoded")>-1)return qC(a,c).toString();if((l=Y.isFileList(a))||s.indexOf("multipart/form-data")>-1){const d=Hs(this,"env"),u=d&&d.FormData;return Pc(l?{"files[]":a}:a,u&&new u,c)}}return r||i?(n.setContentType("application/json",!1),UC(a)):a}],transformResponse:[function(a){const n=Hs(this,"transitional")||bo.transitional,s=n&&n.forcedJSONParsing,i=Hs(this,"responseType"),r=i==="json";if(Y.isResponse(a)||Y.isReadableStream(a))return a;if(a&&Y.isString(a)&&(s&&!i||r)){const l=!(n&&n.silentJSONParsing)&&r;try{return JSON.parse(a,Hs(this,"parseReviver"))}catch(c){if(l)throw c.name==="SyntaxError"?Ae.from(c,Ae.ERR_BAD_RESPONSE,this,null,Hs(this,"response")):c}}return a}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ea.classes.FormData,Blob:ea.classes.Blob},validateStatus:function(a){return a>=200&&a<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Y.forEach(["delete","get","head","post","put","patch","query"],e=>{bo.headers[e]={}});function vd(e,a){const n=this||bo,s=a||n,i=da.from(s.headers);let r=s.data;return Y.forEach(e,function(l){r=l.call(n,r,i.normalize(),a?a.status:void 0)}),i.normalize(),r}function Py(e){return!!(e&&e.__CANCEL__)}let yo=class extends Ae{constructor(a,n,s){super(a??"canceled",Ae.ERR_CANCELED,n,s),this.name="CanceledError",this.__CANCEL__=!0}};function zy(e,a,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?e(n):a(new Ae("Request failed with status code "+n.status,n.status>=400&&n.status<500?Ae.ERR_BAD_REQUEST:Ae.ERR_BAD_RESPONSE,n.config,n.request,n))}function VC(e){const a=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return a&&a[1]||""}function KC(e,a){e=e||10;const n=new Array(e),s=new Array(e);let i=0,r=0,o;return a=a!==void 0?a:1e3,function(c){const d=Date.now(),u=s[r];o||(o=d),n[i]=c,s[i]=d;let p=r,f=0;for(;p!==i;)f+=n[p++],p=p%e;if(i=(i+1)%e,i===r&&(r=(r+1)%e),d-o<a)return;const x=u&&d-u;return x?Math.round(f*1e3/x):void 0}}function HC(e,a){let n=0,s=1e3/a,i,r;const o=(d,u=Date.now())=>{n=u,i=null,r&&(clearTimeout(r),r=null),e(...d)};return[(...d)=>{const u=Date.now(),p=u-n;p>=s?o(d,u):(i=d,r||(r=setTimeout(()=>{r=null,o(i)},s-p)))},()=>i&&o(i)]}const Ql=(e,a,n=3)=>{let s=0;const i=KC(50,250);return HC(r=>{if(!r||typeof r.loaded!="number")return;const o=r.loaded,l=r.lengthComputable?r.total:void 0,c=l!=null?Math.min(o,l):o,d=Math.max(0,c-s),u=i(d);s=Math.max(s,c);const p={loaded:c,total:l,progress:l?c/l:void 0,bytes:d,rate:u||void 0,estimated:u&&l?(l-c)/u:void 0,event:r,lengthComputable:l!=null,[a?"download":"upload"]:!0};e(p)},n)},of=(e,a)=>{const n=e!=null;return[s=>a[0]({lengthComputable:n,total:e,loaded:s}),a[1]]},lf=e=>(...a)=>Y.asap(()=>e(...a)),QC=ea.hasStandardBrowserEnv?((e,a)=>n=>(n=new URL(n,ea.origin),e.protocol===n.protocol&&e.host===n.host&&(a||e.port===n.port)))(new URL(ea.origin),ea.navigator&&/(msie|trident)/i.test(ea.navigator.userAgent)):()=>!0,GC=ea.hasStandardBrowserEnv?{write(e,a,n,s,i,r,o){if(typeof document>"u")return;const l=[`${e}=${encodeURIComponent(a)}`];Y.isNumber(n)&&l.push(`expires=${new Date(n).toUTCString()}`),Y.isString(s)&&l.push(`path=${s}`),Y.isString(i)&&l.push(`domain=${i}`),r===!0&&l.push("secure"),Y.isString(o)&&l.push(`SameSite=${o}`),document.cookie=l.join("; ")},read(e){if(typeof document>"u")return null;const a=document.cookie.split(";");for(let n=0;n<a.length;n++){const s=a[n].replace(/^\s+/,""),i=s.indexOf("=");if(i!==-1&&s.slice(0,i)===e)return decodeURIComponent(s.slice(i+1))}return null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function ZC(e){return typeof e!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function YC(e,a){return a?e.replace(/\/?\/$/,"")+"/"+a.replace(/^\/+/,""):e}function Dy(e,a,n){let s=!ZC(a);return e&&(s||n===!1)?YC(e,a):a}const cf=e=>e instanceof da?{...e}:e;function Ds(e,a){a=a||{};const n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function s(d,u,p,f){return Y.isPlainObject(d)&&Y.isPlainObject(u)?Y.merge.call({caseless:f},d,u):Y.isPlainObject(u)?Y.merge({},u):Y.isArray(u)?u.slice():u}function i(d,u,p,f){if(Y.isUndefined(u)){if(!Y.isUndefined(d))return s(void 0,d,p,f)}else return s(d,u,p,f)}function r(d,u){if(!Y.isUndefined(u))return s(void 0,u)}function o(d,u){if(Y.isUndefined(u)){if(!Y.isUndefined(d))return s(void 0,d)}else return s(void 0,u)}function l(d,u,p){if(Y.hasOwnProp(a,p))return s(d,u);if(Y.hasOwnProp(e,p))return s(void 0,d)}const c={url:r,method:r,data:r,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,allowedSocketPaths:o,responseEncoding:o,validateStatus:l,headers:(d,u,p)=>i(cf(d),cf(u),p,!0)};return Y.forEach(Object.keys({...e,...a}),function(u){if(u==="__proto__"||u==="constructor"||u==="prototype")return;const p=Y.hasOwnProp(c,u)?c[u]:i,f=Y.hasOwnProp(e,u)?e[u]:void 0,x=Y.hasOwnProp(a,u)?a[u]:void 0,h=p(f,x,u);Y.isUndefined(h)&&p!==l||(n[u]=h)}),n}const XC=["content-type","content-length"];function JC(e,a,n){if(n!=="content-only"){e.set(a);return}Object.entries(a).forEach(([s,i])=>{XC.includes(s.toLowerCase())&&e.set(s,i)})}const e5=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(a,n)=>String.fromCharCode(parseInt(n,16))),Iy=e=>{const a=Ds({},e),n=f=>Y.hasOwnProp(a,f)?a[f]:void 0,s=n("data");let i=n("withXSRFToken");const r=n("xsrfHeaderName"),o=n("xsrfCookieName");let l=n("headers");const c=n("auth"),d=n("baseURL"),u=n("allowAbsoluteUrls"),p=n("url");if(a.headers=l=da.from(l),a.url=Ty(Dy(d,p,u),e.params,e.paramsSerializer),c&&l.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?e5(c.password):""))),Y.isFormData(s)&&(ea.hasStandardBrowserEnv||ea.hasStandardBrowserWebWorkerEnv?l.setContentType(void 0):Y.isFunction(s.getHeaders)&&JC(l,s.getHeaders(),n("formDataHeaderPolicy"))),ea.hasStandardBrowserEnv&&(Y.isFunction(i)&&(i=i(a)),i===!0||i==null&&QC(a.url))){const x=r&&o&&GC.read(o);x&&l.set(r,x)}return a},t5=typeof XMLHttpRequest<"u",a5=t5&&function(e){return new Promise(function(n,s){const i=Iy(e);let r=i.data;const o=da.from(i.headers).normalize();let{responseType:l,onUploadProgress:c,onDownloadProgress:d}=i,u,p,f,x,h;function b(){x&&x(),h&&h(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let g=new XMLHttpRequest;g.open(i.method.toUpperCase(),i.url,!0),g.timeout=i.timeout;function v(){if(!g)return;const k=da.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),j={data:!l||l==="text"||l==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:k,config:e,request:g};zy(function(N){n(N),b()},function(N){s(N),b()},j),g=null}"onloadend"in g?g.onloadend=v:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.startsWith("file:"))||setTimeout(v)},g.onabort=function(){g&&(s(new Ae("Request aborted",Ae.ECONNABORTED,e,g)),b(),g=null)},g.onerror=function(w){const j=w&&w.message?w.message:"Network Error",C=new Ae(j,Ae.ERR_NETWORK,e,g);C.event=w||null,s(C),b(),g=null},g.ontimeout=function(){let w=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const j=i.transitional||lh;i.timeoutErrorMessage&&(w=i.timeoutErrorMessage),s(new Ae(w,j.clarifyTimeoutError?Ae.ETIMEDOUT:Ae.ECONNABORTED,e,g)),b(),g=null},r===void 0&&o.setContentType(null),"setRequestHeader"in g&&Y.forEach(_y(o),function(w,j){g.setRequestHeader(j,w)}),Y.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),l&&l!=="json"&&(g.responseType=i.responseType),d&&([f,h]=Ql(d,!0),g.addEventListener("progress",f)),c&&g.upload&&([p,x]=Ql(c),g.upload.addEventListener("progress",p),g.upload.addEventListener("loadend",x)),(i.cancelToken||i.signal)&&(u=k=>{g&&(s(!k||k.type?new yo(null,e,g):k),g.abort(),b(),g=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));const y=VC(i.url);if(y&&!ea.protocols.includes(y)){s(new Ae("Unsupported protocol "+y+":",Ae.ERR_BAD_REQUEST,e));return}g.send(r||null)})},n5=(e,a)=>{if(e=e?e.filter(Boolean):[],!a&&!e.length)return;const n=new AbortController;let s=!1;const i=function(c){if(!s){s=!0,o();const d=c instanceof Error?c:this.reason;n.abort(d instanceof Ae?d:new yo(d instanceof Error?d.message:d))}};let r=a&&setTimeout(()=>{r=null,i(new Ae(`timeout of ${a}ms exceeded`,Ae.ETIMEDOUT))},a);const o=()=>{e&&(r&&clearTimeout(r),r=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(i):c.removeEventListener("abort",i)}),e=null)};e.forEach(c=>c.addEventListener("abort",i));const{signal:l}=n;return l.unsubscribe=()=>Y.asap(o),l},s5=function*(e,a){let n=e.byteLength;if(n<a){yield e;return}let s=0,i;for(;s<n;)i=s+a,yield e.slice(s,i),s=i},i5=async function*(e,a){for await(const n of r5(e))yield*s5(n,a)},r5=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const a=e.getReader();try{for(;;){const{done:n,value:s}=await a.read();if(n)break;yield s}}finally{await a.cancel()}},df=(e,a,n,s)=>{const i=i5(e,a);let r=0,o,l=c=>{o||(o=!0,s&&s(c))};return new ReadableStream({async pull(c){try{const{done:d,value:u}=await i.next();if(d){l(),c.close();return}let p=u.byteLength;if(n){let f=r+=p;n(f)}c.enqueue(new Uint8Array(u))}catch(d){throw l(d),d}},cancel(c){return l(c),i.return()}},{highWaterMark:2})};function o5(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;const a=e.indexOf(",");if(a<0)return 0;const n=e.slice(5,a),s=e.slice(a+1);if(/;base64/i.test(n)){let o=s.length;const l=s.length;for(let x=0;x<l;x++)if(s.charCodeAt(x)===37&&x+2<l){const h=s.charCodeAt(x+1),b=s.charCodeAt(x+2);(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102)&&(b>=48&&b<=57||b>=65&&b<=70||b>=97&&b<=102)&&(o-=2,x+=2)}let c=0,d=l-1;const u=x=>x>=2&&s.charCodeAt(x-2)===37&&s.charCodeAt(x-1)===51&&(s.charCodeAt(x)===68||s.charCodeAt(x)===100);d>=0&&(s.charCodeAt(d)===61?(c++,d--):u(d)&&(c++,d-=3)),c===1&&d>=0&&(s.charCodeAt(d)===61||u(d))&&c++;const f=Math.floor(o/4)*3-(c||0);return f>0?f:0}if(typeof Buffer<"u"&&typeof Buffer.byteLength=="function")return Buffer.byteLength(s,"utf8");let r=0;for(let o=0,l=s.length;o<l;o++){const c=s.charCodeAt(o);if(c<128)r+=1;else if(c<2048)r+=2;else if(c>=55296&&c<=56319&&o+1<l){const d=s.charCodeAt(o+1);d>=56320&&d<=57343?(r+=4,o++):r+=3}else r+=3}return r}const dh="1.16.1",uf=64*1024,{isFunction:Bo}=Y,pf=(e,...a)=>{try{return!!e(...a)}catch{return!1}},l5=e=>{const a=Y.global!==void 0&&Y.global!==null?Y.global:globalThis,{ReadableStream:n,TextEncoder:s}=a;e=Y.merge.call({skipUndefined:!0},{Request:a.Request,Response:a.Response},e);const{fetch:i,Request:r,Response:o}=e,l=i?Bo(i):typeof fetch=="function",c=Bo(r),d=Bo(o);if(!l)return!1;const u=l&&Bo(n),p=l&&(typeof s=="function"?(v=>y=>v.encode(y))(new s):async v=>new Uint8Array(await new r(v).arrayBuffer())),f=c&&u&&pf(()=>{let v=!1;const y=new r(ea.origin,{body:new n,method:"POST",get duplex(){return v=!0,"half"}}),k=y.headers.has("Content-Type");return y.body!=null&&y.body.cancel(),v&&!k}),x=d&&u&&pf(()=>Y.isReadableStream(new o("").body)),h={stream:x&&(v=>v.body)};l&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!h[v]&&(h[v]=(y,k)=>{let w=y&&y[v];if(w)return w.call(y);throw new Ae(`Response type '${v}' is not supported`,Ae.ERR_NOT_SUPPORT,k)})});const b=async v=>{if(v==null)return 0;if(Y.isBlob(v))return v.size;if(Y.isSpecCompliantForm(v))return(await new r(ea.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if(Y.isArrayBufferView(v)||Y.isArrayBuffer(v))return v.byteLength;if(Y.isURLSearchParams(v)&&(v=v+""),Y.isString(v))return(await p(v)).byteLength},g=async(v,y)=>{const k=Y.toFiniteNumber(v.getContentLength());return k??b(y)};return async v=>{let{url:y,method:k,data:w,signal:j,cancelToken:C,timeout:N,onDownloadProgress:S,onUploadProgress:_,responseType:R,headers:A,withCredentials:E="same-origin",fetchOptions:I,maxContentLength:P,maxBodyLength:O}=Iy(v);const K=Y.isNumber(P)&&P>-1,W=Y.isNumber(O)&&O>-1;let V=i||fetch;R=R?(R+"").toLowerCase():"text";let U=n5([j,C&&C.toAbortSignal()],N),X=null;const ie=U&&U.unsubscribe&&(()=>{U.unsubscribe()});let de;try{if(K&&typeof y=="string"&&y.startsWith("data:")&&o5(y)>P)throw new Ae("maxContentLength size of "+P+" exceeded",Ae.ERR_BAD_RESPONSE,v,X);if(W&&k!=="get"&&k!=="head"){const te=await g(A,w);if(typeof te=="number"&&isFinite(te)&&te>O)throw new Ae("Request body larger than maxBodyLength limit",Ae.ERR_BAD_REQUEST,v,X)}if(_&&f&&k!=="get"&&k!=="head"&&(de=await g(A,w))!==0){let te=new r(y,{method:"POST",body:w,duplex:"half"}),B;if(Y.isFormData(w)&&(B=te.headers.get("content-type"))&&A.setContentType(B),te.body){const[ne,me]=of(de,Ql(lf(_)));w=df(te.body,uf,ne,me)}}Y.isString(E)||(E=E?"include":"omit");const $=c&&"credentials"in r.prototype;if(Y.isFormData(w)){const te=A.getContentType();te&&/^multipart\/form-data/i.test(te)&&!/boundary=/i.test(te)&&A.delete("content-type")}A.set("User-Agent","axios/"+dh,!1);const z={...I,signal:U,method:k.toUpperCase(),headers:_y(A.normalize()),body:w,duplex:"half",credentials:$?E:void 0};X=c&&new r(y,z);let D=await(c?V(X,I):V(y,z));if(K){const te=Y.toFiniteNumber(D.headers.get("content-length"));if(te!=null&&te>P)throw new Ae("maxContentLength size of "+P+" exceeded",Ae.ERR_BAD_RESPONSE,v,X)}const F=x&&(R==="stream"||R==="response");if(x&&D.body&&(S||K||F&&ie)){const te={};["status","statusText","headers"].forEach(re=>{te[re]=D[re]});const B=Y.toFiniteNumber(D.headers.get("content-length")),[ne,me]=S&&of(B,Ql(lf(S),!0))||[];let Ee=0;const L=re=>{if(K&&(Ee=re,Ee>P))throw new Ae("maxContentLength size of "+P+" exceeded",Ae.ERR_BAD_RESPONSE,v,X);ne&&ne(re)};D=new o(df(D.body,uf,L,()=>{me&&me(),ie&&ie()}),te)}R=R||"text";let G=await h[Y.findKey(h,R)||"text"](D,v);if(K&&!x&&!F){let te;if(G!=null&&(typeof G.byteLength=="number"?te=G.byteLength:typeof G.size=="number"?te=G.size:typeof G=="string"&&(te=typeof s=="function"?new s().encode(G).byteLength:G.length)),typeof te=="number"&&te>P)throw new Ae("maxContentLength size of "+P+" exceeded",Ae.ERR_BAD_RESPONSE,v,X)}return!F&&ie&&ie(),await new Promise((te,B)=>{zy(te,B,{data:G,headers:da.from(D.headers),status:D.status,statusText:D.statusText,config:v,request:X})})}catch($){if(ie&&ie(),U&&U.aborted&&U.reason instanceof Ae){const z=U.reason;throw z.config=v,X&&(z.request=X),$!==z&&(z.cause=$),z}throw $&&$.name==="TypeError"&&/Load failed|fetch/i.test($.message)?Object.assign(new Ae("Network Error",Ae.ERR_NETWORK,v,X,$&&$.response),{cause:$.cause||$}):Ae.from($,$&&$.code,v,X,$&&$.response)}}},c5=new Map,Ly=e=>{let a=e&&e.env||{};const{fetch:n,Request:s,Response:i}=a,r=[s,i,n];let o=r.length,l=o,c,d,u=c5;for(;l--;)c=r[l],d=u.get(c),d===void 0&&u.set(c,d=l?new Map:l5(a)),u=d;return d};Ly();const uh={http:AC,xhr:a5,fetch:{get:Ly}};Y.forEach(uh,(e,a)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:a})}catch{}Object.defineProperty(e,"adapterName",{__proto__:null,value:a})}});const hf=e=>`- ${e}`,d5=e=>Y.isFunction(e)||e===null||e===!1;function u5(e,a){e=Y.isArray(e)?e:[e];const{length:n}=e;let s,i;const r={};for(let o=0;o<n;o++){s=e[o];let l;if(i=s,!d5(s)&&(i=uh[(l=String(s)).toLowerCase()],i===void 0))throw new Ae(`Unknown adapter '${l}'`);if(i&&(Y.isFunction(i)||(i=i.get(a))))break;r[l||"#"+o]=i}if(!i){const o=Object.entries(r).map(([c,d])=>`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build"));let l=n?o.length>1?`since :
881`+o.map(hf).join(`
882`):" "+hf(o[0]):"as no adapter specified";throw new Ae("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return i}const Fy={getAdapter:u5,adapters:uh};function jd(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new yo(null,e)}function mf(e){return jd(e),e.headers=da.from(e.headers),e.data=vd.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Fy.getAdapter(e.adapter||bo.adapter,e)(e).then(function(s){jd(e),e.response=s;try{s.data=vd.call(e,e.transformResponse,s)}finally{delete e.response}return s.headers=da.from(s.headers),s},function(s){if(!Py(s)&&(jd(e),s&&s.response)){e.response=s.response;try{s.response.data=vd.call(e,e.transformResponse,s.response)}finally{delete e.response}s.response.headers=da.from(s.response.headers)}return Promise.reject(s)})}const zc={};["object","boolean","number","function","string","symbol"].forEach((e,a)=>{zc[e]=function(s){return typeof s===e||"a"+(a<1?"n ":" ")+e}});const ff={};zc.transitional=function(a,n,s){function i(r,o){return"[Axios v"+dh+"] Transitional option '"+r+"'"+o+(s?". "+s:"")}return(r,o,l)=>{if(a===!1)throw new Ae(i(o," has been removed"+(n?" in "+n:"")),Ae.ERR_DEPRECATED);return n&&!ff[o]&&(ff[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),a?a(r,o,l):!0}};zc.spelling=function(a){return(n,s)=>(console.warn(`${s} is likely a misspelling of ${a}`),!0)};function p5(e,a,n){if(typeof e!="object")throw new Ae("options must be an object",Ae.ERR_BAD_OPTION_VALUE);const s=Object.keys(e);let i=s.length;for(;i-- >0;){const r=s[i],o=Object.prototype.hasOwnProperty.call(a,r)?a[r]:void 0;if(o){const l=e[r],c=l===void 0||o(l,r,e);if(c!==!0)throw new Ae("option "+r+" must be "+c,Ae.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ae("Unknown option "+r,Ae.ERR_BAD_OPTION)}}const jl={assertOptions:p5,validators:zc},La=jl.validators;let Es=class{constructor(a){this.defaults=a||{},this.interceptors={request:new rf,response:new rf}}async request(a,n){try{return await this._request(a,n)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const r=(()=>{if(!i.stack)return"";const o=i.stack.indexOf(`
883`);return o===-1?"":i.stack.slice(o+1)})();try{if(!s.stack)s.stack=r;else if(r){const o=r.indexOf(`
884`),l=o===-1?-1:r.indexOf(`
885`,o+1),c=l===-1?"":r.slice(l+1);String(s.stack).endsWith(c)||(s.stack+=`
886`+r)}}catch{}}throw s}}_request(a,n){typeof a=="string"?(n=n||{},n.url=a):n=a||{},n=Ds(this.defaults,n);const{transitional:s,paramsSerializer:i,headers:r}=n;s!==void 0&&jl.assertOptions(s,{silentJSONParsing:La.transitional(La.boolean),forcedJSONParsing:La.transitional(La.boolean),clarifyTimeoutError:La.transitional(La.boolean),legacyInterceptorReqResOrdering:La.transitional(La.boolean)},!1),i!=null&&(Y.isFunction(i)?n.paramsSerializer={serialize:i}:jl.assertOptions(i,{encode:La.function,serialize:La.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),jl.assertOptions(n,{baseUrl:La.spelling("baseURL"),withXsrfToken:La.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=r&&Y.merge(r.common,r[n.method]);r&&Y.forEach(["delete","get","head","post","put","patch","query","common"],h=>{delete r[h]}),n.headers=da.concat(o,r);const l=[];let c=!0;this.interceptors.request.forEach(function(b){if(typeof b.runWhen=="function"&&b.runWhen(n)===!1)return;c=c&&b.synchronous;const g=n.transitional||lh;g&&g.legacyInterceptorReqResOrdering?l.unshift(b.fulfilled,b.rejected):l.push(b.fulfilled,b.rejected)});const d=[];this.interceptors.response.forEach(function(b){d.push(b.fulfilled,b.rejected)});let u,p=0,f;if(!c){const h=[mf.bind(this),void 0];for(h.unshift(...l),h.push(...d),f=h.length,u=Promise.resolve(n);p<f;)u=u.then(h[p++],h[p++]);return u}f=l.length;let x=n;for(;p<f;){const h=l[p++],b=l[p++];try{x=h(x)}catch(g){b.call(this,g);break}}try{u=mf.call(this,x)}catch(h){return Promise.reject(h)}for(p=0,f=d.length;p<f;)u=u.then(d[p++],d[p++]);return u}getUri(a){a=Ds(this.defaults,a);const n=Dy(a.baseURL,a.url,a.allowAbsoluteUrls);return Ty(n,a.params,a.paramsSerializer)}};Y.forEach(["delete","get","head","options"],function(a){Es.prototype[a]=function(n,s){return this.request(Ds(s||{},{method:a,url:n,data:(s||{}).data}))}});Y.forEach(["post","put","patch","query"],function(a){function n(s){return function(r,o,l){return this.request(Ds(l||{},{method:a,headers:s?{"Content-Type":"multipart/form-data"}:{},url:r,data:o}))}}Es.prototype[a]=n(),a!=="query"&&(Es.prototype[a+"Form"]=n(!0))});let h5=class Oy{constructor(a){if(typeof a!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(r){n=r});const s=this;this.promise.then(i=>{if(!s._listeners)return;let r=s._listeners.length;for(;r-- >0;)s._listeners[r](i);s._listeners=null}),this.promise.then=i=>{let r;const o=new Promise(l=>{s.subscribe(l),r=l}).then(i);return o.cancel=function(){s.unsubscribe(r)},o},a(function(r,o,l){s.reason||(s.reason=new yo(r,o,l),n(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}
886subscribe(a){if(this.reason){a(this.reason);return}this._listeners?this._listeners.push(a):this._listeners=[a]}unsubscribe(a){if(!this._listeners)return;const n=this._listeners.indexOf(a);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const a=new AbortController,n=s=>{a.abort(s)};return this.subscribe(n),a.signal.unsubscribe=()=>this.unsubscribe(n),a.signal}static source(){let a;return{token:new Oy(function(i){a=i}),cancel:a}}};function m5(e){return function(n){return e.apply(null,n)}}function f5(e){return Y.isObject(e)&&e.isAxiosError===!0}const Ou={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Ou).forEach(([e,a])=>{Ou[a]=e});function $y(e){const a=new Es(e),n=yy(Es.prototype.request,a);return Y.extend(n,Es.prototype,a,{allOwnKeys:!0}),Y.extend(n,a,null,{allOwnKeys:!0}),n.create=function(i){return $y(Ds(e,i))},n}const Dt=$y(bo);Dt.Axios=Es;Dt.CanceledError=yo;Dt.CancelToken=h5;Dt.isCancel=Py;Dt.VERSION=dh;Dt.toFormData=Pc;Dt.AxiosError=Ae;Dt.Cancel=Dt.CanceledError;Dt.all=function(a){return Promise.all(a)};Dt.spread=m5;Dt.isAxiosError=f5;Dt.mergeConfig=Ds;Dt.AxiosHeaders=da;Dt.formToJSON=e=>My(Y.isHTMLForm(e)?new FormData(e):e);Dt.getAdapter=Fy.getAdapter;Dt.HttpStatusCode=Ou;Dt.default=Dt;const{Axios:_B,AxiosError:EB,CanceledError:AB,isCancel:RB,CancelToken:TB,VERSION:MB,all:PB,Cancel:zB,isAxiosError:DB,spread:IB,toFormData:LB,AxiosHeaders:FB,HttpStatusCode:OB,formToJSON:$B,getAdapter:qB,mergeConfig:BB,create:WB}=Dt,x5=new Set(["trial_exhausted","payment_suspended","quota_exhausted","spend_cap_reached","plan_quota_exceeded","meeting_cap_reached","suspended","wa_share_reached","email_share_reached","email_trial_marketing","email_trial_cap"]);function qy(e){return typeof e=="string"&&x5.has(e)}const wl=ds(e=>({open:!1,reason:null,show:a=>{qy(a)&&e({open:!0,reason:a})},close:()=>e({open:!1})})),By="https://api.enlassa.ai/api/v1",T=Dt.create({baseURL:By,timeout:15e3});T.interceptors.request.use(e=>{e.headers["X-Lang"]=Ua.getState().resolved;const a=rt.getState();if(a.isActive()&&a.accessToken&&!e._sesionReal)return e.headers.Authorization=`Bearer ${a.accessToken}`,e._viaImp=!0,e;const n=Pe.getState().accessToken;return n&&(e.headers.Authorization=`Bearer ${n}`),e});let wd=!1,Ji=[];function g5(){rt.getState().stop(),window.location.href="/admin/tenants?vista360=expirada"}T.interceptors.response.use(e=>e,async e=>{const a=e.config;if(!a||a._retry)return Promise.reject(e);if(e.response?.status===401&&a.url!=="/auth/refresh"){if(a._viaImp)return g5(),Promise.reject(e);if(a._retry=!0,wd)return new Promise(n=>{Ji.push(s=>{s?(a.headers.Authorization=`Bearer ${s}`,n(T(a))):n(Promise.reject(e))})});wd=!0;try{const n=Pe.getState().refreshToken;if(!n)throw new Error("No refresh token");const{data:s}=await Dt.post(`${By}/auth/refresh`,{refreshToken:n});return Pe.getState().setTokens(s.accessToken,s.refreshToken),Ji.forEac
886h(i=>i(s.accessToken)),Ji=[],a.headers.Authorization=`Bearer ${s.accessToken}`,T(a)}catch(n){return Pe.getState().logout(),Ji.forEach(s=>s(null)),Ji=[],window.location.href="/login",Promise.reject(n)}finally{wd=!1}}return qy(e.response?.data?.reason)&&wl.getState().show((e.response?.data).reason),Promise.reject(e)});const Wy=Object.freeze(Object.defineProperty({__proto__:null,api:T},Symbol.toStringTag,{value:"Module"}));function tt(){const e=Pe(o=>o.user),a=rt(o=>o.user),n=rt(o=>o.accessToken),s=rt(o=>o.expiresAt),r=!!n&&!!s&&s>Date.now()?a:e;return{user:r,can:o=>lt(r,o)}}const Uy=[{sectionKey:"sections.operation",items:[{to:"/dashboard",labelKey:"items.home",icon:ny},{to:"/agents",labelKey:"items.agents",icon:Ft,permission:"agents.view"},{to:"/live",labelKey:"items.live",icon:vi,live:!0,permission:"calls.view"},{to:"/history",labelKey:"items.calls",icon:dn,permission:"calls.view"},{to:"/campaigns",labelKey:"items.campaigns",icon:kc,permission:"campaigns.view"},{to:"/meetings",labelKey:"items.meetings",icon:Ps,permission:"meetings.view"},{to:"/citas",labelKey:"items.appointments",icon:Zn,soon:!0,permission:"appointments.view"},{to:"/copilot",labelKey:"items.copilot",icon:_t,beta:!0,permission:"copilot.use"},{to:"/whatsapp/bandeja",labelKey:"items.whatsappInbox",icon:Tp,permission:"whatsapp.view"},{to:"/whatsapp/plantillas",labelKey:"items.whatsappTemplates",icon:bi,permission:"whatsapp.view"},{to:"/whatsapp",labelKey:"items.whatsapp",icon:Ba,permission:"whatsapp.view"},{to:"/correo",labelKey:"items.email",icon:Kr,soon:!0,permission:"email.view"},{to:"/contactos",labelKey:"items.contacts",icon:Bs,soon:!0,permission:"contacts.view"}]},{sectionKey:"sections.build",items:[{to:"/playground",labelKey:"items.playground",icon:NS,permission:"playground.use"},{to:"/workflows",labelKey:"items.workflows",icon:en,permission:"workflows.view"},{to:"/knowledge",labelKey:"items.knowledge",icon:ua,permission:"knowledge.view"},{to:"/trunks",labelKey:"items.numbers",icon:yn,permission:"phoneNumbers.view"},{to:"/integraciones",labelKey:"items.integrations",icon:en,permissionAny:["webhooks.view","integrations.view"]},{to:"/secrets",labelKey:"items.secrets",icon:yi,permission:"secrets.view"}]}],Vy=[{sectionKey:"sections.platform",items:[{to:"/admin/dashboard",labelKey:"items.panel",icon:ny},{to:"/admin/tenants",labelKey:"items.tenants",icon:yc},{to:"/admin/plans",labelKey:"items.plans",icon:$s},{to:"/admin/usage",labelKey:"items.usage",icon:co},{to:"/reports",labelKey:"items.reports",icon:us},{to:"/admin/audit",labelKey:"items.audit",icon:Qr},{to:"/admin/margin",labelKey:"items.margin",icon:m2},{to:"/admin/churn",labelKey:"items.churnRisk",icon:ry},{to:"/admin/health",labelKey:"items.health",icon:$S},{to:"/admin/comparatives",labelKey:"items.comparatives",icon:FS},{to:"/admin/seo-geo",labelKey:"items.seoGeo",icon:Mn},{to:"/onboarding",labelKey:"items.onboardingQa",icon:_t},{to:"/admin/account",labelKey:"items.account",icon:y2}]},{sectionKey:"sections.globalConfig",items:[{to:"/admin/registro",labelKey:"items.registro",icon:MS},{to:"/admin/ai-keys",labelKey:"items.aiKeys",icon:Ka},{to:"/admin/network",labelKey:"items.network",icon:Tu},{to:"/admin/numbers",labelKey:"items.numbers",icon:yn},{to:"/admin/stt",labelKey:"items.sttGlobal",icon:Ta},{to:"/admin/voices",labelKey:"items.voices",icon:Il},{to:"/admin/rates",labelKey:"items.rates",icon:jc},{to:"/admin/voicemail-patterns",labelKey:"items.voicemailDetection",icon:sh},{to:"/admin/recording",labelKey:"items.recordings",icon:TS},{to:"/admin/email",labelKey:"items.emailSmtp",icon:Kr},{to:"/admin/payments",labelKey:"items.payments",icon:_c},{to:"/admin/playbook",labelKey:"items.playbook",icon:VS},{to:"/admin/knowledge",labelKey:"items.kbGlobal",icon:ua},{to:"/admin/meetings",labelKey:"items.meetingsAdmin",icon:Ps},{to:"/admin/whatsapp",labelKey:"items.whatsappAdmin",icon:sn},{to:"/admin/workflows",labelKey:"items.workflowsAdmin",icon:en},{to:"/admin/correo",labelKey:"items.correoAdmin",icon:Kr}]}];function Ky(e,a){return a.permissionAny?$b(e,a.permissionAny):!a.permission||lt(e,a.permission)}function b5(e,a){let n=null;for(const s of a){const i=s.split("?")[0];if(!i||i==="/")continue;(e===i||e.startsWith(i.endsWith("/")?i:`${i}/`))&&(n===null||i.length>n.split("?")[0].length)&&(n=s)}return n}const y5=561/282;function v5({size:e=22,className:a}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",className:a,children:t.jsxs("g",{transform:"translate(12.5,15) scale(0.05)",fill:"none",strokeLinecap:"round",strokeWidth:"44",children:[t.jsx("path",{d:"M-190,150 C-50,-40 230,-95 330,-35",
886stroke:"var(--cia-cta-500)"}),t.jsx("path",{d:"M-150,75 C-20,-75 235,-110 315,-55",stroke:"var(--cia-ok-500)"}),t.jsx("path",{d:"M-110,10 C0,-95 180,-110 265,-65",stroke:"var(--cia-sky-500)"})]})})}function Dc({height:e=22,iconOnly:a=!1,forceDark:n=!1,className:s}){if(a)return t.jsx(v5,{size:e,className:s});const i=Math.round(e*y5),r=Math.round(e*.56),o=Math.round(e*.73),l={height:e,width:"auto"};return t.jsxs("span",{className:s,style:{display:"inline-flex",alignItems:"center",gap:11},children:[n?t.jsx("img",{src:"/logo-enlassa-dark.png",alt:"Enlassa",width:i,height:e,style:l}):t.jsxs(t.Fragment,{children:[t.jsx("img",{src:"/logo-enlassa-dark.png",alt:"Enlassa",className:"en-logo-dark",width:i,height:e,style:l}),t.jsx("img",{src:"/logo-enlassa-light.png",alt:"Enlassa",className:"en-logo-light",width:i,height:e,style:l})]}),t.jsx("span",{"aria-hidden":!0,style:{width:1,height:o,background:"linear-gradient(180deg,transparent,var(--cia-text-4),transparent)"}}),t.jsx("span",{style:{fontFamily:"var(--cia-font-mono)",fontWeight:600,fontSize:r,letterSpacing:"0.04em",lineHeight:1,color:"var(--cia-cta-500)"},children:"AI"})]})}const $u=new Set;let j5=0;function J(e){const a={id:++j5,tone:"info",duration:5e3,...e};$u.forEach(n=>n(a))}const xf={ok:{color:"var(--cia-ok-500)",ink:"var(--cia-ok-ink)",Icon:ct},info:{color:"var(--cia-brand-500)",ink:"var(--cia-info-ink)",Icon:_t},warn:{color:"var(--cia-warn-500)",ink:"var(--cia-warn-ink)",Icon:Tt},bad:{color:"var(--cia-bad-500)",ink:"var(--cia-bad-ink)",Icon:nt}};function Hy(){const{t:e}=M("ds"),[a,n]=m.useState([]),s=m.useRef({}),i=m.useCallback(r=>{const o=s.current[r];o&&(clearTimeout(o),delete s.current[r]),n(l=>l.filter(c=>c.id!==r))},[]);return m.useEffect(()=>{const r=l=>{n(c=>[...c,l]),l.duration>0&&(s.current[l.id]=setTimeout(()=>i(l.id),l.duration))};$u.add(r);const o=s.current;return()=>{$u.delete(r),Object.values(o).forEach(clearTimeout)}},[i]),a.length===0?null:t.jsx("div",{className:"cia-toast-host","aria-live":"polite","aria-atomic":"false",children:a.map(r=>{const o=xf[r.tone]??xf.info,l=r.icon??o.Icon;return t.jsxs("div",{className:"cia-toast",role:"status",style:{display:"flex",alignItems:"flex-start",gap:12,width:340,maxWidth:"calc(100vw - 40px)",padding:"13px 14px",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r-lg)",boxShadow:"var(--cia-shadow-lg)",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)"},children:[t.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:8,flex:"none",background:`color-mix(in oklab, ${o.color} 14%, transparent)`,color:o.ink},children:t.jsx(l,{size:15,"aria-hidden":"true"})}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[t.jsx("span",{style:{fontSize:13.5,fontWeight:500,lineHeight:1.3},children:r.title}),r.desc&&t.jsx("span",{style:{fontSize:12,lineHeight:1.45,color:"var(--cia-text-3)"},children:r.desc})]}),r.action&&t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{flex:"none",color:o.ink,fontWeight:500,height:26},onClick:()=>{r.action?.onClick(),i(r.id)},children:r.action.label}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-icon",style:{flex:"none",width:24,height:24},onClick:()=>i(r.id),"aria-label":e("toast.close"),children:t.jsx(nt,{size:13,"aria-hidden":"true"})}),r.duration>0&&t.jsx("span",{className:"cia-toast-bar","aria-hidden":"true",style:{position:"absolute",left:12,right:12,bottom:6,height:2,borderRadius:2,background:`color-mix(in oklab, ${o.color} 30%, transparent)`,transformOrigin:"left",animation:`cia-toast-bar ${r.duration}ms linear forwards`}})]},r.id)})})}function gf({active:e=!1,color:a="var(--cia-brand-500)",bars:n=80,height:s=22}){return t.jsx("div",{style:{display:"flex",gap:2,height:s,alignItems:"center"},children:Array.from({length:n}).map((i,r)=>{const o=Math.sin((r+.5)/n*Math.PI),l=2+o*1.5,c=3+o*14;return t.jsx("span",{className:e?"cia-wbar":void 0,style:{flex:1,height:e?c:l,background:e?a:"var(--cia-border-2)",borderRadius:1.5,animationDuration:e?`${.5+r%7*.06}s`:void 0,animationDelay:e?`${r*25}ms`:void 0}},r)})})}function w5({active:e=!0,color:a="var(--cia-ok-500)",bars:n=4,height:s=12}){return t.jsx("div",{style:{display:"flex",gap:2,height:s,alignItems:"center"},"aria-hidden":"true",children:Array.from({length:n}).map((i,r)=>t.jsx("span",{className:e?"cia-wbar":void 0,style:{width:2,height:s,borderRadius:2,background:e?a:"var(--cia-border-2)",transform:e?void 0:"scaleY(0.5)",animationDuration:e?`${.5+r%4*.08}s`:void 0,animationDelay:e?`${r*90}ms`:void 0}},r))})}function Qy({active:e=!1,speaking:a=!1,bars:n=40,height:s=40,color:i="var(--cia-brand-500)"}){return t.jsx("div",{className:"cia-row",style:{gap:2.5,height:s,alignItems:"center",justifyContent:"center"},"aria-hidden":"true",children:Array.from({length:n}).map((r,o)=>{const l=Math.sin(o/(n-1)*Math.PI),c=e?6+l*(a?28:16):3+l*4;return t.jsx("span",{className:e?"cia-wbar":void 0,style:{flex:1,maxWidth:5,height:`${c}px`,background:e?i:"var(--cia-border-2)",borderRadius:2,animationDelay:`${o*30}ms`,animationDuration:`${.5+o%6*.06}s`}},o)})})}function Gy({k:e,v:a,highlight:n,mono:s=!0}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:12,flex:1,color:"var(--cia-text-3)",minWidth:0},children:e}),t.jsx("span",{className:s?"cia-mono":void 0,style:{fontSize:12.5,fontWeight:n?600:400,color:n?"var(--cia-cta-500)":"var(--cia-text)",textAlign:"right",wordBreak:"break-word"},children:a})]})}function k5({status:e,label:a,at:n,latencyMs:s}){const{t:i}=M("ds"),r=e==="success"?"var(--cia-ok-500)":e==="error"?"var(--cia-bad-500)":"var(--cia-text-3)",o=e==="success"?ct:e==="error"?nt:Qa;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,minWidth:0},children:[t.jsx(o,{size:12,style:{color:r,flex:"none"},className:e==="running"?"cia-spin":void 0,"aria-hidden":"true"}),n&&t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,width:34,flex:"none",color:"var(--cia-text-3)"},children:n}),t.jsx("span",{className:"cia-mono",style:{color:"var(--cia-brand-500)",flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),s!=null&&t.jsxs("span",{className:"cia-mono",style:{fontSize:10.5,flex:"none",color:"var(--cia-text-3)"},children:[s,"ms"]}),e==="running"&&t.jsx("span",{className:"cia-badge",style:{height:16,fontSize:9.5,flex:"none"},children:i("actionLine.waiting")})]})}function N5({size:e=116,icon:a}){const n=a??Ma;return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:e,height:e,borderRadius:"50%",position:"relative",color:"#fff"},"aria-hidden":"true",children:[t.jsx("span",{className:"cia-orb-aura",style:{position:"absolute",inset:-3,borderRadius:"50%",background:"conic-gradient(from 0deg, var(--cia-brand-500), var(--cia-cta-500), var(--cia-ok-500), var(--cia-sky-500), var(--cia-brand-500))",filter:"blur(7px)",opacity:.85}}),t.jsx("span",{style:{position:"absolute",inset:6,borderRadius:"50%",background:"radial-gradient(circle at 32% 28%, color-mix(in oklab, var(--cia-cta-500) 90%, white), color-mix(in oklab, var(--cia-brand-600) 80%, black))",boxShadow:"inset 0 2px 8px rgba(255,255,255,0.25), inset 0 -8px 16px rgba(0,0,0,0.35)"}}),t.jsx(n,{size:Math.round(e*.33),strokeWidth:1.5,style:{position:"relative",zIndex:1}}),t.jsx("span",{className:"cia-orb-ring",style:{position:"absolute",inset:-10,borderRadius:"50%",border:"1.5px solid var(--cia-cta-500)",opacity:.4}})]})}const S5={ok:"var(--cia-ok-500)",warn:"var(--cia-warn-500)",bad:"var(--cia-bad-500)",brand:"var(--cia-brand-500)"};function C5(){const[e,a]=m.useState(!1);return m.useEffect(()=>{const n=window.matchMedia("(prefers-reduced-motion: reduce)");a(n.matches);const s=()=>a(n.matches);
886return n.addEventListener("change",s),()=>n.removeEventListener("change",s)},[]),e}function Yr({active:e=!1,tone:a="ok",size:n=44}){const s=C5(),i=e?S5[a]:"var(--cia-text-4)";return t.jsxs("svg",{width:n,height:n,viewBox:"0 0 44 44","aria-hidden":"true",style:{flex:"none"},children:[t.jsx("circle",{cx:"22",cy:"22",r:"18",fill:"none",stroke:e?i:"var(--cia-border-2)",strokeWidth:"2",strokeDasharray:e?void 0:"3 3"}),t.jsx("circle",{cx:"22",cy:"22",r:"6",fill:i}),e&&!s&&t.jsxs("circle",{cx:"22",cy:"22",r:"6",fill:i,opacity:"0.5",children:[t.jsx("animate",{attributeName:"r",values:"6;18;6",dur:"2.4s",repeatCount:"indefinite"}),t.jsx("animate",{attributeName:"opacity",values:"0.5;0;0.5",dur:"2.4s",repeatCount:"indefinite"})]})]})}function Ic({value:e,variant:a="auto",height:n=8}){const s=a!=="auto"?a:e>1?"over":e>=.8?"warn":"ok",i=s==="over"?"cia-progress-fill-over":s==="warn"?"cia-progress-fill-warn":"",r=Math.max(0,Math.min(100,e*100));return t.jsx("div",{className:"cia-progress-track",style:{height:n},role:"progressbar","aria-valuenow":Math.round(r),"aria-valuemin":0,"aria-valuemax":100,children:t.jsx("div",{className:`cia-progress-fill ${i}`,style:{width:`${r}%`}})})}function qu({value:e=0,indeterminate:a=!1,height:n=8,label:s,showValue:i=!1}){const r=Math.max(0,Math.min(100,Math.round(e))),o=s??he.t("ds:progress.label",{defaultValue:"Progreso"}),[l,c]=m.useState(0);return m.useEffect(()=>{if(!a||typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;const u=setInterval(()=>c(p=>(p+1)%100),60);return()=>clearInterval(u)},[a]),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,width:"100%"},children:[t.jsx("div",{className:"cia-progress-track",style:{height:n,flex:1,overflow:"hidden"},role:"progressbar","aria-label":o,...a?{}:{"aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100},children:t.jsx("div",{className:"cia-progress-fill",style:a?{width:"35%",marginLeft:`${Math.abs(50-l)*1.3}%`,transition:"margin-left 60ms linear"}:{width:`${r}%`}})}),i&&!a&&t.jsxs("span",{style:{fontSize:12,fontFamily:"var(--cia-font-sans)",color:"var(--cia-text-3)",minWidth:34,textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[r,"%"]})]})}let _5=0;function E5({value:e,variant:a="auto",size:n=168,thickness:s=14,centerTop:i,label:r}){const{t:o}=M("ds"),[l]=m.useState(()=>`cia-gauge-${++_5}`),c=a!=="auto"?a:e>1?"over":e>=.8?"warn":"ok",d=c==="over"?"var(--cia-bad-500)":c==="warn"?"var(--cia-warn-500)":`url(#${l})`,u=50-s/2,p=2*Math.PI*u,f=Math.max(0,Math.min(1,e)),[x,h]=m.useState(0);m.useEffect(()=>{const v=requestAnimationFrame(()=>h(f));return()=>cancelAnimationFrame(v)},[f]);const b=p*(1-x),g=Math.round(e*100);return t.jsxs("div",{role:"img","aria-label":o("gauge.consumedAria",{pct:g}),style:{position:"relative",width:n,height:n,flex:"none"},children:[t.jsxs("svg",{width:n,height:n,viewBox:"0 0 100 100",style:{transform:"rotate(-90deg)"},children:[t.jsx("defs",{children:t.jsxs("linearGradient",{id:l,x1:"0",y1:"0",x2:"1",y2:"1",children:[t.jsx("stop",{offset:"0%",stopColor:"var(--cia-brand-500)"}),t.jsx("stop",{offset:"100%",stopColor:"var(--cia-cta-500)"})]})}),t.jsx("circle",{cx:"50",cy:"50",r:u,fill:"none",stroke:"var(--cia-bg-soft)",strokeWidth:s}),t.jsx("circle",{cx:"50",cy:"50",r:u,fill:"none",stroke:d,strokeWidth:s,strokeLinecap:"round",strokeDasharray:p,strokeDashoffset:b,style:{transition:"stroke-dashoffset var(--cia-dur-slow) var(--cia-ease-smooth)"}})]}),t.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:2,textAlign:"center"},children:[t.jsx("span",{style:{fontSize:n*.2,fontWeight:700,lineHeight:1,fontVariantNumeric:"tabular-nums"},children:i??`${g}%`}),r&&t.jsx("span",{className:"cia-eyebrow",style:{color:"var(--cia-text-3)"},children:r})]})]})}function ot({open:e,onClose:a,title:n,eyebrow:s,children:i,footer:r,maxWidth:o=460,hideClose:l}){const{t:c}=M("ds"),d=m.useId(),u=`${d}-title`,p=m.useRef(null),f=m.useRef(null),x=m.useRef(null),h=m.useRef(a);if(m.useEffect(()=>{h.current=a}),m.useEffect(()=>{if(!e)return;const v=wj(d),y=w=>
886{w.key==="Escape"&&jj(d)&&h.current()};window.addEventListener("keydown",y);const k=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{window.removeEventListener("keydown",y),document.body.style.overflow=k,v()}},[e,d]),m.useEffect(()=>{if(!e)return;x.current=document.activeElement;const v=p.current,y=v?.querySelector("[data-cia-autofocus]:not([disabled])")??null,k=pm(f.current)[0]??null,w=y??k??v,j=requestAnimationFrame(()=>w?.focus());return()=>{cancelAnimationFrame(j),x.current?.focus?.()}},[e]),m.useEffect(()=>{if(!e)return;const v=y=>{if(y.key!=="Tab")return;const k=pm(p.current);if(k.length===0){y.preventDefault();return}const w=k[0],j=k[k.length-1];y.shiftKey&&document.activeElement===w?(y.preventDefault(),j.focus()):!y.shiftKey&&document.activeElement===j&&(y.preventDefault(),w.focus())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[e]),!e)return null;const b=typeof document<"u"?document.querySelector(".cia[data-theme]")?.getAttribute("data-theme")??void 0:void 0,g=t.jsx("div",{className:"cia cia-modal-overlay","data-theme":b,onClick:a,children:t.jsxs("div",{ref:p,className:"cia-modal-card cia-scroll",style:{maxWidth:o},role:"dialog","aria-modal":"true","aria-labelledby":n?u:void 0,tabIndex:-1,onClick:v=>v.stopPropagation(),children:[(n||s||!l)&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:14},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[s&&t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:3},children:s}),n&&t.jsx("h2",{id:u,style:{margin:0,fontSize:17,fontWeight:600,letterSpacing:"-0.01em"},children:n})]}),!l&&t.jsx(Lt,{icon:t.jsx(nt,{}),size:"sm",label:c("modal.close"),onClick:a,tooltipPosition:"bottom"})]}),t.jsx("div",{ref:f,children:i}),r&&t.jsx("div",{className:"cia-modal-foot",children:r})]})});return typeof document<"u"?Ti.createPortal(g,document.body):g}const bf=8;function Fi({items:e,active:a,onChange:n}){const{t:s}=M("ds"),i=m.useRef(null),r=m.useRef([]),o=m.useRef(null),l=m.useRef(e);l.current=e;const c=m.useRef(a);c.current=a;const[d,u]=m.useState(!1),[p,f]=m.useState({overflow:!1,atStart:!0,atEnd:!0});m.useLayoutEffect(()=>{const v=window.matchMedia("(prefers-reduced-motion: reduce)");u(v.matches);const y=()=>u(v.matches);return v.addEventListener("change",y),()=>v.removeEventListener("change",y)},[]);const x=v=>{const y=i.current;if(!y)return;const k=l.current.findIndex(N=>N.id===c.current),w=k>=0?r.current[k]:null,j=o.current;if(w&&v){const N=w.offsetLeft-bf,S=w.offsetLeft+w.offsetWidth+bf;N<y.scrollLeft?y.scrollLeft=Math.max(0,N):S>y.scrollLeft+y.clientWidth&&(y.scrollLeft=S-y.clientWidth)}w&&j&&(j.style.transform=`translateX(${w.offsetLeft}px) scaleX(${Math.max(1,w.offsetWidth)})`,j.style.opacity="1");const C=y.scrollWidth-y.clientWidth;f({overflow:C>1,atStart:y.scrollLeft<=1,atEnd:y.scrollLeft>=C-1})};m.useLayoutEffect(()=>{const v=i.current;if(!v)return;x(!0);const y=()=>x(!0),k=()=>x(!1),w=new ResizeObserver(y);return w.observe(v),r.current.forEach(j=>j&&w.observe(j)),v.addEventListener("scroll",k,{passive:!0}),window.addEventListener("resize",y),()=>{w.disconnect(),v.removeEventListener("scroll",k),window.removeEventListener("resize",y)}},[e.length]),m.useLayoutEffect(()=>{x(!0)},[a]);const h=v=>{const y=e[v];y&&(n(y.id,"teclado"),r.current[v]?.focus({preventScroll:!0}))},b=(v,y)=>{switch(v.key){case"ArrowRight":v.preventDefault(),h((y+1)%e.length);return;case"ArrowLeft":v.preventDefault(),h((y-1+e.length)%e.length);return;case"Home":v.preventDefault(),h(0);return;case"End":v.preventDefault(),h(e.length-1);return;default:return}},g=v=>{const y=i.current;y&&y.scrollBy({left:v*y.clientWidth*.75,behavior:d?"auto":"smooth"})};return t.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",gap:2},children:[p.overflow&&t.jsx("button",{type:"button",tabIndex:-1,"aria-label":s("tabs.scrollPrev"),disabled:p.atStart,onClick:()=>g(-1),className:"cia-tabs-arrow",children:t.jsx(gn,{"aria-hidden":"true"})}),t.jsxs("div",{ref:i,role:"tablist",className:"cia-tabs-rail",style:{display:"flex",gap:2,borderBottom:"1px solid var(--cia-border)",overflowX:"auto",position:"relative",flex:1,minWidth:0},children:[e.map((v,y)=>{const k=v.id===a,w=v.icon;return t.jsxs("button",{ref:j=>{r.current[y]=j},type:"button",role:"tab","aria-selected":k,"aria-controls":v.panelId,tabIndex:k?0:-1,onClick:()=>n(v.id,"puntero"),onKeyDown:j=>b(j,y),style:{background:"none",border:0,cursor:"pointer",font:"inherit",fontSize:13,whiteSpace:"nowrap",padding:"0 12px",minHeight:"var(--cia-control-h-lg)",color:k?"var(--cia-text)":"var(--cia-text-2)",fontWeight:k?600:400,borderBottom:"2px s
886olid transparent",marginBottom:-1,display:"flex",alignItems:"center",gap:6},children:[w?t.jsx("span",{className:"cia-tabs-glyph","aria-hidden":"true",children:t.jsx(w,{})}):null,t.jsxs("span",{className:"cia-tabs-label",children:[t.jsx("span",{className:"cia-tabs-label-text",children:v.label}),t.jsx("span",{className:"cia-tabs-label-ghost","aria-hidden":"true",children:v.label})]}),t.jsx(pc,{value:v.count})]},v.id)}),t.jsx("span",{ref:o,"aria-hidden":"true",style:{position:"absolute",bottom:-1,left:0,width:1,height:2,borderRadius:1,background:"var(--cia-brand-500)",transformOrigin:"0 50%",opacity:0,pointerEvents:"none",transition:d?"none":"transform var(--cia-dur) var(--cia-ease-snappy)"}})]}),p.overflow&&t.jsx("button",{type:"button",tabIndex:-1,"aria-label":s("tabs.scrollNext"),disabled:p.atEnd,onClick:()=>g(1),className:"cia-tabs-arrow",children:t.jsx(ca,{"aria-hidden":"true"})})]})}function hn({value:e,onChange:a,options:n,groups:s,label:i,description:r,placeholder:o,disabled:l,disabledReason:c,id:d,ariaLabel:u,ariaLabelledBy:p,ariaDescribedBy:f,style:x}){const h=Kg(),b=m.useId(),g=m.useId(),v=d??(i?g:h?.controlId),y=l??h?.disabled??!1,k=c??(h?.disabled?h.disabledReason:void 0),w=y&&!!k,j=w&&!!c&&!h?.disabledReason,C=[f??(i?void 0:h?.describedBy),j?b:null].filter(Boolean).join(" ")||void 0,N=A=>{w&&(A.preventDefault(),A.currentTarget.focus())},S=A=>{w&&(A.key==="Tab"||A.key==="Escape"||A.ctrlKey||A.metaKey||(A.key.length===1||A5.has(A.key))&&A.preventDefault())},_=t.jsxs("select",{id:v,className:"cia-select",value:e,"aria-disabled":w||void 0,disabled:w?void 0:y,"aria-label":i?void 0:u,"aria-labelledby":i||u?void 0:p??h?.labelId,"aria-describedby":C,onMouseDown:N,onKeyDown:S,onChange:A=>{w||a(A.target.value)},children:[o!==void 0?t.jsx("option",{value:"",children:o}):null,(n??[]).map(A=>t.jsx("option",{value:A.value,disabled:A.disabled,children:A.label},A.value)),(s??[]).map(A=>t.jsx("optgroup",{label:A.label,children:A.options.map(E=>t.jsx("option",{value:E.value,disabled:E.disabled,children:E.label},E.value))},A.label))]}),R=j?t.jsxs(t.Fragment,{children:[t.jsx(Ra,{label:c,children:_}),t.jsx("span",{id:b,className:"cia-sr-only",children:c})]}):_;return!i&&!r?t.jsx("div",{style:x,children:R}):t.jsxs("div",{className:"cia-select-campo",style:x,children:[i?t.jsx("label",{className:"cia-select-label",htmlFor:v,children:i}):null,R,r?t.jsx("p",{className:"cia-select-desc",children:r}):null]})}const A5=new Set(["Enter","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"]),yf={azul:"var(--cia-tag-azul)",naranja:"var(--cia-tag-naranja)",verde:"var(--cia-tag-verde)",ambar:"var(--cia-tag-ambar)",rojo:"var(--cia-tag-rojo)",gris:"var(--cia-tag-gris)"};function Zy(e){return yf[e??""]??yf.gris}function ps({label:e,tone:a,count:n,onRemove:s,removeLabel:i,onClick:r,active:o,disabled:l,className:c,style:d}){const u=Zy(a),p={display:"inline-flex",alignItems:"center",gap:6,minHeight:24,padding:s?"2px 4px 2px 9px":"2px 9px",borderRadius:"var(--cia-r-pill)",fontSize:11.5,fontWeight:600,fontFamily:"var(--cia-font-sans)",lineHeight:1.4,maxWidth:"100%",color:"var(--cia-text-2)",background:o?`color-mix(in oklab, ${u} 16%, transparent)`:"var(--cia-bg-soft)",border:`1px solid ${o?u:"var(--cia-border-2)"}`,...d},f=t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":!0,style:{width:7,height:7,borderRadius:"50%",background:u,flex:"0 0 auto"}}),t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:e}),n==null?null:t.jsx("span",{style:{color:"var(--cia-text-3)",fontVariantNumeric:"tabular-nums"},children:n})]});return r?t.jsx("button",{type:"button",className:c,onClick:r,disabled:l,"aria-pressed":o??!1,style:{...p,cursor:l?"default":"pointer"},children:f}):t.jsxs("span",{className:c,style:p,children:[f,s?t.jsx("button",{type:"button",onClick:s,disabled:l,"aria-label":i??e,title:i??e,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,border:"none",borderRadius:"50%",background:"transparent",color:"var(--cia-text-3)",cursor:l?"default":"pointer"},children:t.jsx(nt,{size:12,"aria-hidden":!0})}):null]})}function vt({checked:e,onChange:a,disabled:n,label:s,id:i,ariaLabelledBy:r,ariaDescribedBy:o,disabledReason:l}){const c=Kg(),d=m.useId(),[u,p]=m.useState(!1),f=m.useRef(!0);m.useEffect(()=>()=>{f.current=!1},[]);const x=n??c?.disabled??!1,h=l??(c?.disabled?c.disabledReason:void 0),b=x&&!!h,g=b&&!!l&&!c?.disabledReason,v=[o??c?.describedBy,g?d:null].filter(
886Boolean).join(" ")||void 0,y=()=>{if(x||u)return;const C=a(!e);C&&typeof C.then=="function"&&(p(!0),Promise.resolve(C).finally(()=>{f.current&&p(!1)}))},k={position:"relative",display:"inline-flex",alignItems:"center",width:40,height:22,flexShrink:0,padding:0,border:"1px solid var(--cia-control-off)",boxSizing:"border-box",borderRadius:"var(--cia-r-pill)",cursor:u?"wait":x?"not-allowed":"pointer",opacity:x?.55:1,background:e?"var(--cia-control-on)":"var(--cia-control-off)",transition:"background var(--cia-dur-fast) var(--cia-ease-smooth)"},w={position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--cia-control-knob)",boxSizing:"border-box",boxShadow:"var(--cia-shadow-sm)",transition:"left var(--cia-dur-fast) var(--cia-ease-smooth)"},j=t.jsx("button",{type:"button",role:"switch",id:i??c?.controlId,className:"cia-switch","data-pending":u||void 0,"aria-checked":e,"aria-busy":u||void 0,"aria-label":s,"aria-labelledby":r??(s?void 0:c?.labelId),"aria-describedby":v,"aria-disabled":b||void 0,disabled:b?void 0:x,onClick:y,style:k,children:t.jsx("span",{style:w})});return g?t.jsxs(t.Fragment,{children:[t.jsx(Ra,{label:l,children:j}),t.jsx("span",{id:d,className:"cia-sr-only",children:l})]}):j}function R5(e,a){if(a<=7)return Array.from({length:a},(r,o)=>o+1);const n=[1],s=Math.max(2,e-1),i=Math.min(a-1,e+1);s>2&&n.push("…");for(let r=s;r<=i;r++)n.push(r);return i<a-1&&n.push("…"),n.push(a),n}function Yy({page:e,pageSize:a,total:n,pageSizeOptions:s=[10,15,20],onPageChange:i,onPageSizeChange:r,itemLabel:o}){const{t:l}=M("ds"),c=o??l("pagination.itemLabel"),d=Math.max(1,Math.ceil(n/a)),u=Math.min(e,d-1)+1,p=n===0?0:e*a+1,f=Math.min(n,(e+1)*a),x=R5(u,d);return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:12,padding:"12px 2px",fontSize:13,color:"var(--cia-text-3)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14,flexWrap:"wrap"},children:[t.jsx("span",{children:n===0?l("pagination.empty",{item:c}):t.jsxs(t.Fragment,{children:[t.jsxs("strong",{style:{color:"var(--cia-text)"},children:[p,"–",f]})," ",l("pagination.of")," ",t.jsx("strong",{style:{color:"var(--cia-text)"},children:n})," ",c]})}),t.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx("span",{children:l("pagination.show")}),t.jsx("select",{className:"select",value:a,onChange:h=>r(Number(h.target.value)),style:{height:32,padding:"0 6px",fontSize:13},"aria-label":l("pagination.perPageAria"),children:s.map(h=>t.jsx("option",{value:h,children:h},h))})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx("button",{type:"button",className:"cia-pager-btn",onClick:()=>i(e-1),disabled:e<=0,"aria-label":l("pagination.prev"),children:t.jsx(gn,{size:16})}),x.map((h,b)=>h==="…"?t.jsx("span",{className:"cia-pager-ellipsis","aria-hidden":"true",children:"…"},`e${b}`):t.jsx("button",{type:"button",className:"cia-pager-btn","data-active":h===u,"aria-current":h===u?"page":void 0,"aria-label":l("pagination.pageN",{n:h}),onClick:()=>i(h-1),children:h},h)),t.jsx("button",{type:"button",className:"cia-pager-btn",onClick:()=>i(e+1),disabled:u>=d,"aria-label":l("pagination.next"),children:t.jsx(ca,{size:16})})]})]})}function ph({value:e,onChange:a,placeholder:n,width:s=240,size:i="md",trailing:r,"aria-label":o,inputRef:l,onKeyDown:c,autoFocus:d}){const{t:u}=M("ds"),p=n??u("search.placeholder");return t.jsxs("div",{className:"cia-search","data-size":i,"data-trailing":r?"":void 0,style:{width:s},children:[t.jsx("span",{className:"cia-search-icon","aria-hidden":"true",style:{display:"inline-flex"},children:t.jsx(Mn,{})}),t.jsx("input",{ref:l,type:"search",value:e,onChange:f=>a(f.target.value),onKeyDown:c,placeholder:p,"aria-label":o||p,autoFocus:d}),e&&t.jsx("button",{type:"button",className:"cia-search-clear",onClick:()=>a(""),"aria-label":u("search.clear"),children:t.jsx(nt,{size:11,strokeWidth:2.5})}),r?t.jsx("span",{className:"cia-search-trailing",children:r}):null]})}function T5(e){if(!e)return null;const a=new Date(e);return isNaN(a.getTime())?null:a.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function Xy(e){return e==="agent"?"linear-gradient(135deg, var(--cia-cta-500), var(--cia-brand-600))":e==="user"?"linear-gradient(135deg, var(--cia-sky-500), var(--cia-brand-500))":"var(--cia-bg-tint)"}function M5({tc:e,label:a,dense:n}){const{t:s}=M("ds"),[i,r]=m.useState(!1),o=e.status==="success"?"var(--cia-ok-500)":e.status==="error"?"var(--cia-bad-500)":"var(--cia-text-3)",l=e.status==="success"?ct:e.status==="error"?nt:je,c=e.args&&Object.keys(e.args).length>0||e.result!=null&&e.result!=="",d=n?"6px 9px":"8px 11px";return t.jsx("div",{style:{display:"flex",justifyContent:"center"},className:"cia-fade-up",children:t.jsxs("div",{style:{width:"100%",maxWidth:440,borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)",overflow:"hidden"},children:[t.jsxs("button",{type:"button",onClick:()=>c&&r(u=>!u),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:d,background:"transparent",border:0,font:"inherit",textAlign:"left",cursor:c?"pointer":"default",color:"var(--cia-text)"},children:[t.jsx(ih,{size:13,style:{color:"var(--cia-brand-500)",flex:"none"},"aria-hidden":"true"}),t.jsx("span",{style:{fontSize:12,fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),t.jsx(l,{size:13,style:{color:o,flex:"none"},className:e.status==="running"?"cia-spin":void 0,"aria-hidden":"true"}),t.jsxs("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:8,flex:"none"},children:[e.requestedAt&&e.at&&t.jsx("span",{className:"cia-mono",style:{fontSize:10,
886color:"var(--cia-text-4)"},children:s("transcript.requestedBefore",{seconds:Math.max(1,Math.round((new Date(e.at).getTime()-new Date(e.requestedAt).getTime())/1e3))})}),e.latencyMs!=null&&t.jsxs("span",{className:"cia-mono",style:{fontSize:10,color:"var(--cia-text-3)"},children:[e.latencyMs,"ms"]}),c&&t.jsx(ca,{size:13,style:{color:"var(--cia-text-3)",transform:i?"rotate(90deg)":"none",transition:"transform var(--cia-dur-fast) var(--cia-ease-smooth)"},"aria-hidden":"true"})]})]}),i&&c&&t.jsxs("div",{style:{padding:"4px 11px 11px",display:"flex",flexDirection:"column",gap:8,borderTop:"1px solid var(--cia-border)"},children:[e.args&&Object.keys(e.args).length>0&&t.jsx(vf,{title:s("transcript.args"),body:JSON.stringify(e.args,null,2)}),e.result!=null&&e.result!==""&&t.jsx(vf,{title:s("transcript.result"),body:String(e.result)})]})]})})}function vf({title:e,body:a}){return t.jsxs("div",{children:[t.jsx("div",{className:"cia-mono",style:{fontSize:9.5,letterSpacing:"0.06em",color:"var(--cia-text-3)",marginBottom:3,textTransform:"uppercase"},children:e}),t.jsx("pre",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-2)",whiteSpace:"pre-wrap",wordBreak:"break-all",lineHeight:1.5,margin:0},children:a})]})}function P5({text:e}){return t.jsxs("div",{className:"cia-fade-up",style:{display:"flex",alignItems:"center",gap:10,padding:"2px 0"},children:[t.jsx("span",{style:{flex:1,height:1,background:"var(--cia-border)"}}),t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)",whiteSpace:"nowrap"},children:e}),t.jsx("span",{style:{flex:1,height:1,background:"var(--cia-border)"}})]})}const z5={fontSize:9,letterSpacing:"0.04em",lineHeight:"14px",padding:"0 6px",borderRadius:"var(--cia-r-pill)",border:"1px solid var(--cia-border-2)",background:"var(--cia-bg-soft)",color:"var(--cia-text-2)",whiteSpace:"nowrap",flex:"none"};function D5({m:e,agentName:a,userLabel:n,showTimestamps:s,dense:i}){const{t:r}=M("ds"),o=e.role==="agent",l=i?24:28,c=(o?a:n).toUpperCase(),d=(o?a:n).trim().charAt(0).toUpperCase()||(o?"A":"U"),u=s?T5(e.timestamp):null,p=e.provisional===!0,f=o&&e.interrupted===!0,x=!o&&e.backchannel===!0;return t.jsxs("div",{className:"cia-fade-up",style:{display:"flex",alignItems:"flex-start",gap:10},"aria-busy":p||void 0,children:[s&&t.jsx("span",{className:"cia-mono",style:{fontSize:9.5,color:"var(--cia-text-4)",width:i?34:42,flex:"none",textAlign:"right",lineHeight:`${l}px`,whiteSpace:"nowrap"},children:u??(p?"·":"")}),t.jsx("div",{style:{width:l,height:l,borderRadius:"50%",flex:"none",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:i?10:11,fontWeight:600,background:Xy(e.role),boxShadow:"var(--cia-shadow-sm)",opacity:x?.5:1},"aria-hidden":"true",children:d}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,flex:1,minWidth:0},children:[t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:9.5,letterSpacing:"0.06em",lineHeight:`${l}px`,color:"var(--cia-text-2)"},children:c}),f&&t.jsx("span",{className:"cia-mono",style:z5,title:r("transcript.interruptedHint"),children:r("transcript.interrupted")}),x&&t.jsx("span",{className:"cia-mono",style:{fontSize:9.5,color:"var(--cia-text-2)",whiteSpace:"nowrap"},title:r("transcript.backchannelHint"),children:r("transcript.backchannel")})]}),t.jsxs("span",{style:{fontSize:i?12.5:13.5,lineHeight:1.55,color:p||x?"var(--cia-text-2)":"var(--cia-text)",opacity:p?.75:1,transition:"opacity var(--cia-dur-fast) var(--cia-ease-smooth)",whiteSpace:"pre-wrap",wordBreak:"break-word",marginTop:-4},title:p?r("transcript.provisional"):x?r("transcript.backchannelHint"):void 0,children:[e.text,p&&t.jsx("span",{className:"cia-thinking-caret","aria-hidden":"true"})]})]})]})}function vo({messages:e,toolCalls:a,toolLabel:n=h=>h,agentName:s,userLabel:i,typing:r=!1,typingLabel:o,showTimestamps:l=!0,autoScroll:c=!1,dense:d=!1,liveRegion:u=!1,emptyText:p,className:f="",style:x}){const{t:h}=M("ds"),b=s??h("transcript.agent"),g=i??h("transcript.user"),v=p??h("transcript.empty"),y=m.useRef(null),k=e.length?e[e.length-1].text.length:0;m.useEffect(()=>{c&&y.current?.scrollIntoView({behavior:"smooth"})},[e.length,k,a?.length,r,c]);const w=[];e.forEach((N,S)=>w.push({kind:"msg",t:new Date(N.timestamp??0).getTime()||0,m:N,key:N.id??`m${S}`}
886)),(a??[]).forEach(N=>w.push({kind:"tool",t:new Date(N.at??0).getTime()||0,tc:N,key:`t${N.id}`})),w.sort((N,S)=>N.t-S.t);const j=w.length===0&&!r;let C=null;return j&&(C=t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"32px 16px",textAlign:"center",color:"var(--cia-text-3)"},children:[t.jsx(sn,{size:20,strokeWidth:1.5,style:{color:"var(--cia-text-4)"},"aria-hidden":"true"}),t.jsx("span",{style:{fontSize:12.5},children:v})]})),t.jsxs("div",{className:f,style:{display:"flex",flexDirection:"column",gap:d?12:16,...x},...u?{role:"log","aria-live":"polite","aria-relevant":"additions text"}:{},children:[C,w.map(N=>N.kind==="tool"?t.jsx(M5,{tc:N.tc,label:n(N.tc.name),dense:d},N.key):N.m.role==="system"?t.jsx(P5,{text:N.m.text},N.key):t.jsx(D5,{m:N.m,agentName:b,userLabel:g,showTimestamps:l,dense:d},N.key)),r&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},"aria-live":"polite",children:[t.jsx("div",{style:{width:d?24:28,height:d?24:28,borderRadius:"50%",flex:"none",background:Xy("agent"),boxShadow:"var(--cia-shadow-sm)"},"aria-hidden":"true"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx("span",{className:"cia-typing-dot",style:{animationDelay:"0ms"}}),t.jsx("span",{className:"cia-typing-dot",style:{animationDelay:"160ms"}}),t.jsx("span",{className:"cia-typing-dot",style:{animationDelay:"320ms"}}),o&&t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-3)",marginLeft:4},children:o})]})]}),t.jsx("div",{ref:y})]})}function I5({data:e,color:a="var(--cia-brand-500)",height:n=36,width:s=88}){const i="cia-spark-"+m.useId().replace(/:/g,"");if(!e||e.length<2)return t.jsx("svg",{width:s,height:n,"aria-hidden":!0});const r=Math.max(...e),o=Math.min(...e),l=r-o||1,c=s/(e.length-1),u=e.map((f,x)=>[x*c,n-(f-o)/l*(n-4)-2]).map((f,x)=>`${x===0?"M":"L"}${f[0].toFixed(1)},${f[1].toFixed(1)}`).join(" "),p=`${u} L${s},${n} L0,${n} Z`;return t.jsxs("svg",{width:s,height:n,style:{display:"block"},"aria-hidden":!0,children:[t.jsx("defs",{children:t.jsxs("linearGradient",{id:i,x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{offset:"0%",stopColor:a,stopOpacity:"0.25"}),t.jsx("stop",{offset:"100%",stopColor:a,stopOpacity:"0"})]})}),t.jsx("path",{d:p,fill:`url(#${i})`}),t.jsx("path",{d:u,stroke:a,strokeWidth:"1.5",fill:"none",strokeLinejoin:"round",strokeLinecap:"round"})]})}const jf={left:"left",center:"center",right:"right"};function hh({columns:e,rows:a,rowKey:n="id",onRowClick:s,empty:i,stickyHeader:r=!0,maxHeight:o,dividers:l=!0}){const{t:c}=M("ds"),[d,u]=m.useState(null),[p,f]=m.useState(null);function x(y){d!==y?(u(y),f("asc")):p==="asc"?f("desc"):(u(null),f(null))}const h=m.useMemo(()=>!d||!p?a:[...a].sort((y,k)=>{const w=y[d],j=k[d],C=typeof w=="number"&&typeof j=="number"?w-j:String(w??"").localeCompare(String(j??""),"es",{numeric:!0});return p==="asc"?C:-C}),[a,d,p]);if(!h.length)return t.jsx("div",{style:{padding:"32px 0",display:"flex",justifyContent:"center"},children:i??t.jsx(st,{mini:!0,title:c("chart.noData")})});const b={width:"100%",overflowX:"auto",overflowY:o?"auto":"visible",maxHeight:o??void 0,borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border)"},g={padding:"10px 14px",textAlign:"left",fontSize:11,fontFamily:"var(--cia-font-mono)",fontWeight:500,letterSpacing:"0.06em",textTransform:"uppercase",color:"var(--cia-text-3)",background:"var(--cia-bg-soft)",borderBottom:"1px solid var(--cia-border)",whiteSpace:"nowrap"},v={padding:"11px 14px",fontSize:13,color:"var(--cia-text)",verticalAlign:"middle"};return t.jsx("div",{className:"cia-scroll cia-scroll-x",style:b,children:t.jsxs("table",{role:"table",style:{width:"100%",borderCollapse:"collapse",tableLayout:"auto"},children:[t.jsx("thead",{children:t.jsx("tr",{children:e.map(y=>{const k=d===y.key,w=k?p==="asc"?Rn:Ut:wS;return t.jsx("th",{scope:"col",style:{...g,textAlign:y.align?jf[y.align]:"left",width:y.width,position:r?"sticky":void 0,top:r?0:void 0,zIndex:r?1:void 0,cursor:y.sortable?"pointer":void 0,userSelect:y.sortable?"none":void 0},onClick:y.sortable?()=>x(y.key):void 0,tabIndex:y.sortable?0:void 0,onKeyDown:y.sortable?j=>(j.key==="Enter"||j.key===" ")&&x(y.key):void 0,"aria-sort":y.sortable&&k?p==="asc"?"ascending":"descending":void 0,children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[y.header,y.sortable&&t.jsx(w,{size:11,"aria-hidden":!0,style:{opacity:k?1:.45}})]})},y.key)})})}),t.jsx("tbody",{children:h.map(y=>{const k=String(y[n]??JSON.stringify(y));return t.jsx("tr",{className:s?"cia-row-hover":"",style:{cursor:s?"pointer":void 0},onClick:s?()=>s(y):void 0,onKeyDown:s?w=>(w.key==="Enter"||w.key===" ")&&s(y):void 0,tabIndex:s?0:void 0,role:s?"button":void 0,children:e.map((w,j)=>t.jsx("td",{style:{...v,textAlign:w.align?jf[w.align]:"left",borderBottom:l?"1px solid var(--cia-border)":void 0,paddingLeft:j===0?16:14},children:w.render?w.render(y[w.key],y):y[w.key]!=null?String(y[w.key]):t.jsx("span",{style:{color:"var(--cia-text-4)"},children:"—"})},w.key))},k)})})]})})}const kd={margin:0,fontSize:22,fontWeight:700,lineHeight:1.15,letterSpacing:"-0.025em",color:"var(--cia-text)"};function Jy({eyebrow:e,title:a,subtitle:n,icon:s,actions:i,spacing:r="default",titleAddon:o,titleEditor:l,density:c="default"}){return c==="compact"?t.jsxs("div",{className:"cia-fade-up cia-aph-compacta",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--cia-space-md)",flexWrap:"wrap",minWidth:0},children:[t.jsxs("div",{className:"cia-aph-compacta-izq",style:{display:"flex",alignItems:"center",gap:"var(--cia-space-md)",minWidth:0,flex:"1 1 320px"},children:[e?t.jsxs("div",{className:"cia-aph-compacta-miga",style:{display:"inline-flex",alignItems:"center",gap:"var(--cia-space-md)",fontSize:"var(--cia-fs-sm)"},children:[e,t.jsx("span",{className:"cia-aph-compacta-raya","aria-hidden":!0,style:{width:1,height:20,background:"var(--cia-border-2)",flex:"none"}})]}):null,t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--cia-space-md)",minWidth:0,flex:"1 1 0"},children:[s?t.jsx("span",{style:{display:"inline-grid",placeItems:"center",width:"var(--cia-control-h-sm)",height:"var(--cia-control-h-sm)",borderRadius:"var(--cia-r-md)",background:"color-mix(in oklab, var(--cia-brand-500) 12%, transparent)",flex:"none"},children:t.jsx(s,{"aria-hidden":!0,style:{width:"var(--cia-icon-md)",height:"var(--cia-icon-md)",strokeWidth:"var(--cia-icon-stroke)",color:"var(--cia-brand-500)"}})}):null,t.jsxs("div",{className:"cia-aph-titulo",style:{minWidth:0},children:[l?t.jsxs(t.Fragment,{children:[t.jsx("h1",{className:"cia-sr-only",children:a}),l]}):t.jsx("h1",{style:{...kd,fontSize:18,lineHeight:1.25,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},title:a,children:a}),o]})]})]}),i?t.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,flexShrink:0},children:i}):null]}):t.jsxs("div",{className:"cia-fade-up",style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16,marginBottom:r==="tabs"?"var(--cia-space-md)":24,flexWrap:"wrap"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",ga
886p:14,minWidth:0},children:[s&&t.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:40,height:40,borderRadius:"var(--cia-r)",background:"color-mix(in oklab, var(--cia-brand-500) 12%, transparent)",flex:"none",marginTop:2},children:t.jsx(s,{size:20,style:{color:"var(--cia-brand-500)"},"aria-hidden":!0})}),t.jsxs("div",{style:{minWidth:0},children:[e&&t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:4},children:e}),o||l?t.jsxs("div",{className:"cia-aph-titulo",children:[l?t.jsxs(t.Fragment,{children:[t.jsx("h1",{className:"cia-sr-only",children:a}),l]}):t.jsx("h1",{style:kd,children:a}),o]}):t.jsx("h1",{style:kd,children:a}),n&&t.jsx("p",{style:{margin:"5px 0 0",fontSize:13.5,color:"var(--cia-text-3)",lineHeight:1.5},children:n})]})]}),i&&t.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,flexShrink:0},children:i})]})}const L5={ok:"var(--cia-ok-500)",warn:"var(--cia-warn-500)",bad:"var(--cia-bad-500)",brand:"var(--cia-brand-500)"};function F5({value:e,size:a=120,thickness:n=10,tone:s,centerTop:i,label:r}){const{t:o}=M("ds"),l=Math.max(0,Math.min(1,e||0)),c=Math.round(l*100),d=l>=.95?"ok":l>=.8?"warn":"bad",u=L5[s??d],p=(a-n)/2,f=2*Math.PI*p,x=f*(1-l);return t.jsxs("div",{style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:8},children:[t.jsxs("div",{style:{position:"relative",width:a,height:a},children:[t.jsxs("svg",{width:a,height:a,viewBox:`0 0 ${a} ${a}`,"aria-label":o("ring.validAria",{pct:c}),role:"img",children:[t.jsx("circle",{cx:a/2,cy:a/2,r:p,fill:"none",stroke:"var(--cia-border-2)",strokeWidth:n}),t.jsx("circle",{cx:a/2,cy:a/2,r:p,fill:"none",stroke:u,strokeWidth:n,strokeLinecap:"round",strokeDasharray:f,strokeDashoffset:x,transform:`rotate(-90 ${a/2} ${a/2})`,style:{transition:"stroke-dashoffset var(--cia-dur-slow) var(--cia-ease-snappy)"}})]}),t.jsx("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:2},children:t.jsx("span",{style:{fontSize:a*.26,fontWeight:700,color:"var(--cia-text)",letterSpacing:"var(--cia-tracking-tight)"},children:i??`${c}%`})})]}),r&&t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-3)",textAlign:"center"},children:r})]})}function Wo(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function O5(e){const a=Array.from(e.dataTransfer?.items??[]);return a.length===0?Array.from(e.dataTransfer?.files??[]):a.filter(n=>n.kind==="file"&&n.webkitGetAsEntry?.()?.isDirectory!==!0).map(n=>n.getAsFile()).filter(n=>n!=null)}function ev({onFile:e,onFiles:a,multiple:n=!1,accept:s=".csv,.xlsx,.xls,.txt",file:i,onClear:r,error:o,hint:l,disabled:c}){const{t:d}=M("ds"),u=l??d("dropzone.hint"),p=m.useRef(null),[f,x]=m.useState(!1),h=m.useRef(0),b=j=>{j.length&&(n?a?.(j):j[0]&&(e??(C=>a?.([C])))(j[0]))},g=j=>{Wo(j)&&(j.preventDefault(),!c&&(h.current+=1,x(!0)))},v=j=>{Wo(j)&&(j.preventDefault(),j.dataTransfer.dropEffect=c?"none":"copy")},y=j=>{Wo(j)&&(c||(h.current=Math.max(0,h.current-1),h.current===0&&x(!1)))},k=j=>{Wo(j)&&(j.preventDefault(),h.current=0,x(!1),!c&&b(O5(j)))},w=o?"var(--cia-bad-500)":f?"var(--cia-cta-500)":"var(--cia-border-2)";return t.jsxs("div",{children:[t.jsxs("div",{role:"button",tabIndex:0,"aria-label":d("dropzone.aria"),onClick:()=>!c&&p.current?.click(),onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&!c&&p.current?.click()},onDragEnter:g,onDragOver:v,onDragLeave:y,onDrop:k,style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"32px 20px",textAlign:"center",cursor:c?"not-allowed":"pointer",opacity:c?.6:1,border:`2px dashed ${w}`,borderRadius:"var(--cia-r-lg)",background:f?"color-mix(in oklab, var(--cia-cta-500) 8%, var(--cia-bg-sunken))":"var(--cia-bg-sunken)",transition:"border-color var(--cia-dur) var(--cia-ease-snappy), background var(--cia-dur) var(--cia-ease-snappy), box-shadow var(--cia-dur)",boxShadow:f?"0 0 0 4px color-mix(in oklab, var(--cia-cta-500) 16%, transparent)":"none"},children:[t.jsx("input",{ref:p,type:"file",accept:s,multiple:n,hidden:!0,onChange:j=>{b(Array.from(j.target.files??[])),j.target.value=""}}),i&&!n?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(_n,{size:18,style:{color:"var(--cia-brand-500)"},"aria-hidden":!0}),t.jsx("span",{style:{fontSize:13.5,fontWeight:600,color:"var(--cia-text)"},children:i.name}),r&&t.jsx("button",{type:"button","aria-label":d("dropzone.remove"),onClick:j=>{j.stopPropagation(),r()}
886,style:{border:"none",background:"transparent",cursor:"pointer",color:"var(--cia-text-3)",display:"inline-flex"},children:t.jsx(nt,{size:15})})]}):t.jsxs(t.Fragment,{children:[t.jsx(Gb,{size:30,style:{color:f?"var(--cia-cta-500)":"var(--cia-brand-500)"},"aria-hidden":!0}),t.jsx("p",{style:{margin:0,fontSize:14,fontWeight:600,color:"var(--cia-text)"},children:d(n?"dropzone.ctaMulti":"dropzone.cta")}),t.jsx("p",{style:{margin:0,fontSize:12,color:"var(--cia-text-3)"},children:u})]})]}),o&&t.jsx("p",{style:{margin:"8px 2px 0",fontSize:12,color:"var(--cia-bad-500)"},children:o})]})}function $5({steps:e,current:a,onStepClick:n}){return t.jsx("ol",{style:{display:"flex",alignItems:"center",gap:0,listStyle:"none",margin:0,padding:0,width:"100%"},children:e.map((s,i)=>{const r=i<a,o=i===a,l=r?"var(--cia-ok-500)":o?"var(--cia-brand-500)":"var(--cia-text-4)",c=!!n&&i<=a;return t.jsxs("li",{style:{display:"flex",alignItems:"center",flex:i<e.length-1?1:"0 0 auto"},children:[t.jsxs("button",{type:"button",disabled:!c,onClick:()=>c&&n?.(i),"aria-current":o?"step":void 0,style:{display:"inline-flex",alignItems:"center",gap:9,border:"none",background:"transparent",padding:0,cursor:c?"pointer":"default"},children:[t.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"var(--cia-r-pill)",fontSize:13,fontWeight:600,flex:"none",color:r||o?"#fff":"var(--cia-text-3)",background:r?"var(--cia-ok-500)":o?"var(--cia-brand-500)":"var(--cia-bg-soft)",border:`1px solid ${r?"var(--cia-ok-500)":o?"var(--cia-brand-500)":"var(--cia-border-2)"}`,transition:"all var(--cia-dur) var(--cia-ease-snappy)"},children:r?t.jsx(ct,{size:15,"aria-hidden":!0}):i+1}),t.jsx("span",{className:"cia-stepper-label",style:{fontSize:13,fontWeight:o?600:500,color:l,whiteSpace:"nowrap",transition:"color var(--cia-dur)"},children:s.label})]}),i<e.length-1&&t.jsx("span",{"aria-hidden":!0,style:{flex:1,height:2,margin:"0 12px",borderRadius:2,background:r?"var(--cia-ok-500)":"var(--cia-border-2)",transition:"background var(--cia-dur) var(--cia-ease-snappy)"}})]},s.id)})})}function Yn({options:e,value:a,onChange:n,ariaLabel:s,size:i="sm"}){const r=i==="md"?36:30,o=l=>{const c=e.filter(p=>!p.disabled);if(c.length<2)return;const d=c.findIndex(p=>p.value===a),u=c[(d+l+c.length)%c.length];u&&n(u.value)};return t.jsx("div",{role:"radiogroup","aria-label":s,onKeyDown:l=>{l.key==="ArrowRight"||l.key==="ArrowDown"?(l.preventDefault(),o(1)):(l.key==="ArrowLeft"||l.key==="ArrowUp")&&(l.preventDefault(),o(-1))},style:{display:"inline-flex",padding:2,gap:2,borderRadius:"var(--cia-r-pill)",background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)"},children:e.map(l=>{const c=l.value===a,d=!l.label;return t.jsxs("button",{type:"button",role:"radio","aria-checked":c,"aria-label":d?l.ariaLabel:void 0,disabled:l.disabled,title:l.title,tabIndex:c?0:-1,onClick:()=>!l.disabled&&n(l.value),style:{height:r,width:d?r:void 0,padding:d?0:"0 12px",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,border:"none",borderRadius:"var(--cia-r-pill)",fontSize:12.5,fontWeight:c?600:500,lineHeight:1,cursor:l.disabled?"not-allowed":"pointer",opacity:l.disabled?.45:1,background:c?"var(--cia-bg-elev)":"transparent",color:c?"var(--cia-select-ink)":"var(--cia-text-2)",boxShadow:c?"var(--cia-shadow-sm)":"none"},children:[l.icon,l.label]},l.value)})})}function tv({insertar:e,value:a,onChange:n,onSubmit:s,onStop:i,placeholder:r,disabled:o=!1,loading:l=!1,maxRows:c=8,leadingActions:d,trailingActions:u,header:p,layout:f="inline",disabledReason:x,noticeReplacesField:h=!1}){const{t:b}=M("ds"),g=r??b("composer.placeholder"),v=m.useRef(null),y=f==="apilado",k=typeof window<"u"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1,w=m.useRef(0);m.useEffect(()=>{if(!e||e.nonce===w.current)return;w.current=e.nonce;const z=v.current,D=z?.selectionStart??a.length,F=z?.selectionEnd??D;n(a.slice(0,D)+e.texto+a.slice(F)),requestAnimationFrame(()=>{const G=D+e.texto.length;z?.focus(),z?.setSelectionRange(G,G)})},[e]);const j=22,C=j+20,N=j*c+20,[S,_]=m.useState(!1);m.useEffect(()=>{const z=v.current;if(!z)return;const D=z.style.height||`${C}
886px`;z.style.height="auto";const F=z.scrollHeight,G=Math.min(F,N);_(F>N),z.style.height=D;const te=requestAnimationFrame(()=>{z.style.transition=k?"none":"height 120ms var(--cia-ease-snappy)",z.style.height=`${G}px`});return()=>cancelAnimationFrame(te)},[a,N,C,k]);const R=m.useRef(!1),A=m.useRef(a),E=m.useRef(l);m.useEffect(()=>{a!==A.current&&(R.current=!1),E.current&&!l&&(R.current=!1),A.current=a,E.current=l},[a,l]);const I=()=>{l||!a.trim()||R.current||(R.current=!0,s(a.trim()))},P=z=>{z.nativeEvent.isComposing||z.keyCode===229||z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),I())},O=z=>{z.preventDefault(),I()},K=o||l&&!i,W=h&&o&&!!p,V=!l&&a.trim().length>0,U=m.useRef(V),[X,ie]=m.useState(!1);m.useEffect(()=>{if(V&&!U.current&&!k){ie(!0);const z=window.setTimeout(()=>ie(!1),220);return U.current=V,()=>window.clearTimeout(z)}U.current=V},[V,k]);const de=l&&i?t.jsx("button",{type:"button",onClick:i,"aria-label":b("composer.stopAria"),title:b("composer.stopTitle"),className:"cia-composer-send",style:{background:"color-mix(in oklab, var(--cia-bad-500) 14%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-bad-500) 28%, transparent)",color:"var(--cia-bad-ink)",cursor:"pointer"},children:t.jsx(ah,{fill:"currentColor","aria-hidden":"true"})}):t.jsx("button",{type:"submit",disabled:!V,"aria-label":b("composer.sendAria"),title:b(V?"composer.sendTitle":"composer.sendTitleEmpty"),className:X?"cia-composer-send cia-composer-send-pop":"cia-composer-send","data-listo":V||void 0,style:{background:V?"var(--cia-brand-500)":"var(--cia-bg-soft)",border:"1px solid",borderColor:V?"var(--cia-brand-600)":"var(--cia-border)",color:V?"var(--cia-on-brand)":"var(--cia-text-4)",cursor:V?"pointer":"default"},children:t.jsx(Hg,{"aria-hidden":"true"})}),$=t.jsx("textarea",{ref:v,value:a,onChange:z=>n(z.target.value),onKeyDown:P,placeholder:g,disabled:K,rows:1,"aria-label":b("composer.messageAria"),style:{flex:1,resize:"none",border:"none",outline:"none",background:"transparent",fontFamily:"var(--cia-font-sans)",fontSize:13.5,color:"var(--cia-text)",lineHeight:j/13.5,minHeight:C,maxHeight:N,padding:0,overflowY:S?"auto":"hidden",letterSpacing:"var(--cia-tracking-tight)",opacity:K?.5:1,width:y?"100%":void 0}});return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsxs("form",{onSubmit:O,style:W?{display:"flex",flexDirection:"column"}:y?{display:"flex",flexDirection:"column",gap:8,padding:"10px 12px 8px",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r-xl)",boxShadow:"var(--cia-shadow-sm)",transition:"border-color 0.15s ease, box-shadow 0.15s ease"}:{display:"flex",alignItems:"flex-end",gap:8,padding:"10px 12px",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r-lg)",boxShadow:"var(--cia-shadow-sm)",transition:"border-color 0.15s ease, box-shadow 0.15s ease"},onFocus:z=>{if(W)return;const D=z.currentTarget;D.style.borderColor="var(--cia-brand-500)",D.style.boxShadow="0 0 0 3px var(--cia-ring)"},onBlur:z=>{if(!W&&!z.currentTarget.contains(z.relatedTarget)){const D=z.currentTarget;D.style.borderColor="var(--cia-border-2)",D.style.boxShadow="var(--cia-shadow-sm)"}},children:[p&&t.jsx("div",{className:"cia-composer-header-enter",style:{flex:"none"},children:p}),W?null:y?t.jsxs(t.Fragment,{children:[$,t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:d}),t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[u,de]})]})]}):t.jsxs(t.Fragment,{children:[d&&t.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4,flex:"none"},children:d}),$,de]})]}),o&&x&&!W&&t.jsx("div",{role:"status","aria-live":"polite",style:{fontSize:11.5,lineHeight:1.45,color:"var(--cia-text-2)",padding:"0 4px"},children:x}),t.jsx("style",{children:`
887        @keyframes cia-composer-header-in {
888          from { opacity: 0; transform: translateY(-4px); }
889          to   { opacity: 1; transform: none; }
890        }
891        .cia-composer-header-enter { animation: cia-composer-header-in 160ms var(--cia-ease-snappy) both; }
892        @keyframes cia-composer-send-pop {
893          0%   { transform: scale(0.86); }
894          55%  { transform: scale(1.06); }
895          100% { transform: scale(1); }
896        }
897        .cia-composer-send-pop { animation: cia-composer-send-pop 220ms var(--cia-ease-out-expo); }
898        .cia-composer-send {
899          display: inline-flex; align-items: center; justify-content: center; flex: none;
900          width: var(--cia-control-h-md); height: var(--cia-control-h-md); padding: 0;
901          border-radius: var(--cia-r-md);
902          transition: transform var(--cia-dur-press) var(--cia-ease-press);
903        }
904        .cia-composer-send svg {
905          width: var(--cia-icon-md); height: var(--cia-icon-md); stroke-width: var(--cia-icon-stroke);
906        }
907        .cia-composer-send:active:not(:disabled) { transform: scale(var(--cia-press-scale)); }
908        /* El hover oscurece el azul, sin moverlo ni transicionar el fondo. \`!important\` porque el
909           fondo del estado va inline (depende de \`canSend\`) y un inline le gana a cualquier regla. */
910        @media (hover: hover) and (pointer: fine) {
911          .cia-composer-send[data-listo]:hover { background: var(--cia-brand-600) !important; }
912        }
913        @media (prefers-reduced-motion: reduce) {
914          .cia-composer-header-enter { animation: none !important; }
915          .cia-composer-send-pop { animation: none !important; }
916        }
917      `})]})}function q5(e,a){const n=(e??"").split(`
918`),s=(a??"").split(`
919`),i=n.length,r=s.length,o=Array.from({length:i+1},()=>new Array(r+1).fill(0));for(let u=1;u<=i;u++)for(let p=1;p<=r;p++)o[u][p]=n[u-1]===s[p-1]?o[u-1][p-1]+1:Math.max(o[u-1][p],o[u][p-1]);const l=[];let c=i,d=r;for(;c>0||d>0;)c>0&&d>0&&n[c-1]===s[d-1]?(l.unshift({op:"equal",text:n[c-1]}),c--,d--):d>0&&(c===0||o[c][d-1]>=o[c-1][d])?(l.unshift({op:"insert",text:s[d-1]}),d--):(l.unshift({op:"delete",text:n[c-1]}),c--);return l}function B5(e){let a=-1,n=!1;return{lines:e.map(i=>i.op==="equal"?(n=!1,i):(n||(a++,n=!0),{...i,hunk:a})),hunkCount:a+1}}function W5(e,a){const n=[];for(const s of e)s.op==="equal"?n.push(s.text):s.op==="delete"?a[s.hunk]||n.push(s.text):a[s.hunk]&&n.push(s.text);return n.join(`
920`)}const U5={equal:{bg:"transparent",border:"transparent",color:"var(--cia-text-2)",prefix:" "},delete:{bg:"color-mix(in oklab, var(--cia-bad-500) 10%, transparent)",border:"color-mix(in oklab, var(--cia-bad-500) 20%, transparent)",color:"var(--cia-bad-500)",prefix:"−"},insert:{bg:"color-mix(in oklab, var(--cia-ok-500) 10%, transparent)",border:"color-mix(in oklab, var(--cia-ok-500) 20%, transparent)",color:"var(--cia-ok-500)",prefix:"+"}},V5={equal:"diff.ariaEqual",delete:"diff.ariaDelete",insert:"diff.ariaInsert"};function av({before:e,after:a,onResultChange:n}){const{t:s}=M("ds"),{lines:i,hunkCount:r}=m.useMemo(()=>B5(q5(e,a)),[e,a]),[o,l]=m.useState(()=>new Array(r).fill(!0));m.useEffect(()=>{l(new Array(r).fill(!0))},[r,e,a]),m.useEffect(()=>{n?.(W5(i,o))},[o,i]);
920const c=o.filter(Boolean).length,d=r>0,u=(g,v)=>l(y=>y.map((k,w)=>w===g?v:k)),p=g=>l(new Array(r).fill(g)),f={fontFamily:"var(--cia-font-mono)",fontSize:12.5,lineHeight:1.6,letterSpacing:"var(--cia-tracking-mono)",border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r)",overflow:"auto",background:"var(--cia-bg-soft)",maxHeight:420};let x=0,h=0,b=-1;return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8,flexWrap:"wrap"},children:[d?t.jsx("span",{style:{fontSize:12,fontFamily:"var(--cia-font-mono)",letterSpacing:"var(--cia-tracking-mono)",color:"var(--cia-text-3)"},"aria-live":"polite",children:s("diff.changesAccepted",{count:r,accepted:c})}):t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-4)"},children:s("diff.noChanges")}),t.jsx("div",{style:{flex:1}}),d&&t.jsxs(t.Fragment,{children:[t.jsx(wf,{label:s("diff.keepAll"),onClick:()=>p(!0),variant:"ok"}),t.jsx(wf,{label:s("diff.undoAll"),onClick:()=>p(!1),variant:"bad"})]})]}),t.jsx("div",{style:f,role:"region","aria-label":s("diff.regionAria"),children:t.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",tableLayout:"fixed"},"aria-label":s("diff.tableAria"),children:[t.jsxs("colgroup",{children:[t.jsx("col",{style:{width:34}}),t.jsx("col",{style:{width:34}}),t.jsx("col",{style:{width:18}}),t.jsx("col",{})]}),t.jsx("tbody",{children:i.map((g,v)=>{const y=U5[g.op],k=[];if(g.op!=="equal"&&g.hunk!==b){b=g.hunk;const R=g.hunk,A=o[R];k.push(t.jsx("tr",{children:t.jsx("td",{colSpan:4,style:{padding:"6px 10px",background:"var(--cia-bg-elev)",borderTop:v===0?"none":"1px solid var(--cia-border)",borderBottom:"1px solid var(--cia-border)"},children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsxs("span",{style:{fontSize:11,fontFamily:"var(--cia-font-mono)",letterSpacing:"var(--cia-tracking-mono)",color:A?"var(--cia-ok-600)":"var(--cia-text-4)",fontWeight:600},children:[s("diff.changeN",{n:R+1,total:r}),!A&&s("diff.keepsOriginal")]}),t.jsx("div",{style:{flex:1}}),t.jsx(kf,{label:s("diff.keep"),icon:t.jsx(ct,{size:11,"aria-hidden":"true"}),active:A,variant:"ok",onClick:()=>u(R,!0)}),t.jsx(kf,{label:s("diff.undo"),icon:t.jsx(x2,{size:11,"aria-hidden":"true"}),active:!A,variant:"bad",onClick:()=>u(R,!1)})]})})},`h-${R}`))}let w,j;g.op==="equal"?(x++,h++,w=x,j=h):g.op==="delete"?(x++,w=x):(h++,j=h);const C=g.op!=="equal"&&!o[g.hunk],N=C&&g.op==="insert",S=C&&g.op==="delete",_={padding:"1px 6px",textAlign:"right",color:"var(--cia-text-4)",userSelect:"none",fontSize:11,verticalAlign:"top",background:y.bg,opacity:N?.45:1};return k.push(t.jsxs("tr",{"aria-label":s(V5[g.op]),style:{background:y.bg,borderLeft:`3px solid ${S?"var(--cia-text-4)":y.border}`,opacity:N?.45:1},children:[t.jsx("td",{style:_,children:w??""}),t.jsx("td",{style:_,children:j??""}),t.jsx("td",{style:{padding:"1px 4px",color:y.color,fontWeight:g.op!=="equal"?600:400,userSelect:"none",verticalAlign:"top"},"aria-hidden":"true",children:y.prefix}),t.jsx("td",{style:{padding:"1px 12px 1px 4px",whiteSpace:"pre-wrap",wordBreak:"break-all",color:g.op==="equal"?"var(--cia-text)":y.color,verticalAlign:"top",textDecoration:N?"line-through":"none"},children:g.text||" "})]},v)),k})})]})})]})}function wf({label:e,onClick:a,variant:n}){const s=n==="ok"?"var(--cia-ok-600)":"var(--cia-bad-500)";return t.jsx("button",{type:"button",onClick:a,style:{height:26,padding:"0 10px",borderRadius:"var(--cia-r-sm)",border:`1px solid color-mix(in oklab, ${s} 30%, transparent)`,background:"transparent",color:s,fontFamily:"var(--cia-font-sans)",fontSize:11.5,fontWeight:500,cursor:"pointer",letterSpacing:"var(--cia-tracking-tight)",transition:"background var(--cia-dur-fast) ease"},onMouseEnter:i=>{i.currentTarget.style.background=`color-mix(in oklab, ${s} 10%, transparent)`},onMouseLeave:i=>{i.currentTarget.style.background="transparent"},children:e})}function kf({label:e,icon:a,active:n,variant:s,onClick:i}){const r=s==="ok"?"var(--cia-ok-600)":"var(--cia-bad-500)";return t.jsxs("button",{type:"button",onClick:i,"aria-pressed":n,style:{display:"inline-flex",alignItems:"center",gap:4,height:24,padding:"0 9px",borderRadius:"var(--cia-r-sm)",border:`1px solid ${n?`color-mix(in oklab, ${r} 45%, transparent)`:"var(--cia-border-2)"}`,background:n?`color-mix(in oklab, ${r} 14%, transparent)`:"transparent",color:n?r:"var(--cia-text-4)",fontFamily:"var(--cia-font-sans)",fontSize:11.5,fontWeight:n?600:500,cursor:"pointer",letterSpacing:"var(--cia-tracking-tight)",transition:"all var(--cia-dur-fast) ease"},children:[a,e]})}const K5="copilot",Ni=e=>`${K5}
920:proposal.${e}`;function nv(e){const a={...e.vars??{}};for(const[n,s]of Object.entries(e.tvars??{}))a[n]=he.t(Ni(s),{defaultValue:s});return a}function H5(e,a,n){const s=e?.i18n;if(!s?.titleKey)return{title:a,text:n};const i=nv(s),r=he.t(Ni(s.titleKey),{defaultValue:a,...i}),o=s.textKey?he.t(Ni(s.textKey),{defaultValue:n,...i}):n;return{title:r,text:o}}function sv(e,a){return e?.textKey?he.t(Ni(e.textKey),{defaultValue:a,...nv(e)}):a}const Q5={campaña:"campaign",acción:"action",nombre:"name",rol:"role",eventos:"events",email:"email",url:"url",número:"number",agente:"agent",programada:"scheduled",presupuesto:"budget",canales:"channels",contraseña:"password",correo:"email",páginas:"pages",sitio:"site"};function iv(e){const a=Q5[e];return a?he.t(Ni(`field.${a}`),{defaultValue:e}):e}const G5={Lanzar:"campaignAction.launch",Pausar:"campaignAction.pause",Reanudar:"campaignAction.resume",Detener:"campaignAction.stop","enviada por email":"value.passwordSentEmail","definida por el usuario":"value.passwordUserSet"};function rv(e){if(typeof e!="string")return e==null?"":JSON.stringify(e);const a=G5[e];return a?he.t(Ni(a),{defaultValue:e}):e}const Z5=new Set(["executed","rejected","expired","failed"]);function ov(e){if(e.kind==="prompt_diff")return{before:e.before,after:e.after,rationale:e.rationale};if(e.kind==="create_agent"){const a=e.fields?.systemPrompt;if(typeof a=="string"&&a.trim())return{before:"",after:a}}return null}function Y5({preview:e,onPromptResult:a,isDone:n}){const{t:s}=M("ds"),i=ov(e);if(i!==null)return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[i.rationale&&t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)",lineHeight:1.5},children:i.rationale}),t.jsx(av,{before:i.before,after:i.after,onResultChange:n?void 0:a})]});if(e.kind==="create_agent"||e.kind==="update_agent"||e.kind==="fields"){const o=Object.entries(e.fields??{}).filter(([,l])=>l!=null);return o.length?t.jsxs("div",{style:{background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r)",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[o.slice(0,8).map(([l,c])=>t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline",fontSize:12.5},children:[t.jsx("span",{style:{fontFamily:"var(--cia-font-mono)",fontSize:11,color:"var(--cia-text-3)",flex:"none",minWidth:110,letterSpacing:"var(--cia-tracking-mono)"},children:iv(l)}),t.jsx("span",{style:{color:"var(--cia-text)",flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:rv(c)})]},l)),o.length>8&&t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:s("action.moreFields",{count:o.length-8})})]}):null}return Object.entries(e).filter(([o])=>o!=="kind").length?t.jsx("div",{style:{background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r)",padding:"10px 12px",fontFamily:"var(--cia-font-mono)",fontSize:12,color:"var(--cia-text-2)",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowX:"auto"},children:JSON.stringify(e,null,2)}):null}function X5({status:e}){const{t:a}=M("ds"),n={pending:{label:a("action.status.pending"),color:"var(--cia-warn-ink)",icon:null},approved:{label:a("action.status.approved"),color:"var(--cia-brand-500)",icon:null},executing:{label:a("action.status.executing"),color:"var(--cia-brand-500)",icon:t.jsx(je,{size:12,style:{animation:"spin 1s linear infinite"}})},executed:{label:a("action.status.executed"),color:"var(--cia-ok-500)",icon:t.jsx(Nt,{size:12})},rejected:{label:a("action.status.rejected"),color:"var(--cia-text-4)",icon:t.jsx(Hb,{size:12})},expired:{label:a("action.status.expired"),color:"var(--cia-text-4)",icon:null},failed:{label:a("action.status.failed"),color:"var(--cia-bad-500)",icon:t.jsx(Tt,{size:12})}},s=n[e]??n.pending;return t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11.5,color:s.color,fontFamily:"var(--cia-font-mono)",letterSpacing:"var(--cia-tracking-mono)"},children:[s.icon,s.label]})}const J5=new Set(["signingSecret","secret","password","tempPassword","apiKey","token"]);
920function e_({resultRef:e}){const{t:a}=M("ds"),n=Object.entries(e).filter(([,s])=>s!=null);return n.length?t.jsx("div",{style:{background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r)",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:n.map(([s,i])=>{const r=J5.has(s);return t.jsxs("div",{style:{display:"flex",flexDirection:r?"column":"row",gap:r?4:8,alignItems:r?"stretch":"baseline",fontSize:12.5},children:[t.jsx("span",{style:{fontFamily:"var(--cia-font-mono)",fontSize:11,color:"var(--cia-text-3)",flex:"none",minWidth:110,letterSpacing:"var(--cia-tracking-mono)"},children:iv(s)}),r?t.jsxs("div",{children:[t.jsx("code",{style:{display:"block",fontFamily:"var(--cia-font-mono)",fontSize:12,color:"var(--cia-text)",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r-sm)",padding:"6px 8px",wordBreak:"break-all",userSelect:"all"},children:String(i)}),t.jsx("span",{style:{fontSize:11,color:"var(--cia-warn-ink)",marginTop:3,display:"block"},children:a("action.copyNow")})]}):t.jsx("span",{style:{color:"var(--cia-text)",flex:1,minWidth:0,wordBreak:"break-word"},children:rv(i)})]},s)})}):null}function t_({action:e,onConfirm:a,onConfirmWithOverride:n,onReject:s,isExecuting:i}){const{t:r}=M("ds"),o=Z5.has(e.status),l=e.status==="executing"||i,{title:c,text:d}=H5(e.preview,e.title,e.previewText),u=ov(e.preview),[p,f]=m.useState(u?.after??""),x=e.toolName==="update_agent_prompt"?"newPrompt":e.toolName==="create_agent"?"systemPrompt":null,h=()=>{if(n&&x&&u!==null){n(e.id,{[x]:p});return}a?.(e.id)},b={background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r-lg)",padding:"14px 16px",display:"flex",flexDirection:"column",gap:12,boxShadow:"var(--cia-shadow-sm)",opacity:o&&e.status!=="executed"?.65:1,transition:"opacity 0.2s ease"};return t.jsxs("div",{style:b,role:"region","aria-label":r("action.regionAria",{title:c}),children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,borderRadius:8,background:"color-mix(in oklab, var(--cia-brand-500) 12%, transparent)",color:"var(--cia-brand-500)",flex:"none",fontSize:14},"aria-hidden":"true",children:"⚡"}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontWeight:600,fontSize:13.5,color:"var(--cia-text)",letterSpacing:"-0.01em",marginBottom:2},children:c}),t.jsx("div",{style:{fontSize:12.5,color:"var(--cia-text-3)",lineHeight:1.45},children:d})]}),t.jsx(X5,{status:e.status})]}),t.jsx(Y5,{preview:e.preview,onPromptResult:f,isDone:o}),e.status==="failed"&&e.error&&t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,padding:"8px 10px",background:"color-mix(in oklab, var(--cia-bad-500) 10%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-bad-500) 24%, transparent)",borderRadius:"var(--cia-r)",fontSize:12.5,color:"var(--cia-bad-500)"},children:[t.jsx(Tt,{size:13,style:{flex:"none",marginTop:1},"aria-hidden":"true"}),e.error]}),e.status==="pending"&&t.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[t.jsxs("button",{type:"button",onClick:()=>s?.(e.id),disabled:l,"aria-label":r("action.rejectAria"),style:{display:"inline-flex",alignItems:"center",gap:6,height:32,padding:"0 12px",fontFamily:"inherit",fontSize:12.5,fontWeight:500,background:"transparent",color:"var(--cia-text-3)",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r-sm)",cursor:l?"default":"pointer",opacity:l?.5:1,letterSpacing:"var(--cia-tracking-tight)",transition:"background-color 0.15s ease"},onMouseEnter:g=>{l||(g.currentTarget.style.background="var(--cia-bg-soft)")},onMouseLeave:g=>{g.currentTarget.style.background="transparent"},children:[t.jsx(nt,{size:13,"aria-hidden":"true"}),r("action.reject")]}),t.jsxs("button",{type:"button",onClick:h,disabled:l,"aria-label":r("action.confirmAria"),style:{display:"inline-flex",alignItems:"center",gap:6,height:32,padding:"0 14px",fontFamily:"inherit",fontSize:12.5,fontWeight:500,background:l?"var(--cia-bg-soft)":"var(--cia-cta-500)",color:l?"var(--cia-text-3)":"white",border:"1px solid",borderColor:l?"var(--cia-border-2)":"var(--cia-cta-600)",borderRadius:"var(--cia-r-sm)",cursor:l?"default":"pointer",boxShadow:l?"none":"inset 0 1px 0 rgba(255,255,255,.20), 0 4px 12px -4px color-mix(in oklab, var(--cia-cta-500) 55%, transparent)",letterSpacing:"var(--cia-tracking-tight)",transition:"background-color 0.15s ease, transform 0.15s ease"},onMouseEnter:g=>{if(!l){const v=g.currentTarget;v.style.background="var(--cia-cta-600)",v.style.transform="translateY(-1px)"}},onMouseLeave:g=>{if(!l){const v=g.currentTarget;
920v.style.background="var(--cia-cta-500)",v.style.transform=""}},children:[l?t.jsx(je,{size:13,style:{animation:"spin 1s linear infinite"},"aria-hidden":"true"}):t.jsx(ct,{size:13,"aria-hidden":"true"}),r(l?"action.executing":"action.confirm")]})]}),e.status==="executed"&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12.5,color:"var(--cia-ok-500)"},children:[t.jsx(Nt,{size:14,"aria-hidden":"true"}),r("action.applied")]}),typeof e.resultRef=="object"&&e.resultRef!==null&&t.jsx(e_,{resultRef:e.resultRef})]})]})}function Te(){return(he.language||"es").startsWith("en")?"en-US":"es-CO"}function Ca(e){if(!e||e<0)return"00:00";const a=Math.floor(e/60),n=e%60;return`${String(a).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function Be(e){return e?new Date(e).toLocaleString(Te(),{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"}):he.t("format:dash")}function ts(e){if(!e)return he.t("format:dash");const a=new Date(e),n=(Date.now()-a.getTime())/1e3;return n<60?he.t("format:justNow"):n<3600?he.t("format:minAgo",{count:Math.round(n/60)}):n<86400?he.t("format:hAgo",{count:Math.round(n/3600)}):Be(e)}function UB(e,a=Date.now()){if(!e)return he.t("format:dash");const n=new Date(e).getTime();if(!Number.isFinite(n))return he.t("format:dash");const s=Math.round((n-a)/1e3),i=Math.abs(s),r=new Intl.RelativeTimeFormat(Te(),{numeric:"auto"});return i<60?r.format(s,"second"):i<3600?r.format(Math.round(s/60),"minute"):i<86400?r.format(Math.round(s/3600),"hour"):i<30*86400?r.format(Math.round(s/86400),"day"):r.format(Math.round(s/(30*86400)),"month")}function a_(e){return e?he.t(`format:endReason.${e}`,{defaultValue:e}):he.t("format:dash")}function VB(e,a){if(e==null||!isFinite(e))return he.t("format:dash");try{return e.toLocaleString(Te(),{style:"currency",currency:a})}catch{return`${e} ${a}`}}function lv(e){return((e.direction==="outbound"?e.calleeNumber:e.callerNumber)||"").replace(/^sip[_:]/i,"").trim()}function As(e){const a=(e||"").replace(/^sip[_:]/i,"").trim();return a?a.startsWith("+")?a:/^\d{8,}$/.test(a)?`+${a}`:a:"—"}function n_(e,a=new Date){const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return e;const s=new Date(Number(n[1]),Number(n[2])-1,Number(n[3])),i=new Date(a.getFullYear(),a.getMonth(),a.getDate()),r=Math.round((i.getTime()-s.getTime())/864e5);if(r===0)return he.t("ds:conversations.today");if(r===1)return he.t("ds:conversations.yesterday");if(r>1&&r<7)return new Intl.DateTimeFormat(Te(),{weekday:"long"}).format(s);const o=s.getFullYear()===a.getFullYear();return new Intl.DateTimeFormat(Te(),{day:"numeric",month:"long",year:o?void 0:"numeric"}).format(s)}function kn(e){if(!e)return he.t("format:dash");const a=new Date(e);return isNaN(a.getTime())?he.t("format:dash"):new Intl.DateTimeFormat(Te(),{day:"numeric",month:"short"}).format(a)}function cv(e,a=new Date){const n=new Date(e);if(isNaN(n.getTime()))return he.t("format:dash");const s=new Date(a.getFullYear(),a.getMonth(),a.getDate()),i=new Date(n.getFullYear(),n.getMonth(),n.getDate()),r=Math.round((s.getTime()-i.getTime())/864e5);return r===0?n.toLocaleTimeString(Te(),{hour:"2-digit",minute:"2-digit"}):r===1?he.t("ds:conversations.yesterday"):r>1&&r<7?new Intl.DateTimeFormat(Te(),{weekday:"short"}).format(n):new Intl.DateTimeFormat(Te(),{day:"2-digit",month:"2-digit"}).format(n)}let s_=0;function mn({checked:e,onChange:a,indeterminate:n=!1,label:s,description:i,disabled:r=!1,id:o,ariaLabel:l,onClickCapture:c,style:d}){const u=o??`cia-cb-${++s_}`,p=m.useRef(null);return m.useEffect(()=>{p.current&&(p.current.indeterminate=n&&!e)},[n,e]),t.jsxs("div",{style:{display:"inline-flex",alignItems:"flex-start",gap:10,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,...d},children:[t.jsxs("div",{style:{position:"relative",width:18,height:18,flex:"none",marginTop:s?1:0},children:[t.jsx("input",{ref:p,type:"checkbox",id:u,checked:e,disabled:r,onChange:f=>a(f.target.checked),onClick:c,style:{position:"absolute",inset:0,opacity:0,width:"100%",height:"100%",cursor:r?"not-allowed":"pointer",margin:0,zIndex:1},"aria-checked":n&&!e?"mixed":e,...l&&!s?{"aria-label":l}:{}}),t.jsxs("div",{"aria-hidden":"true",style:{position:"absolute",inset:0,borderRadius:"var(--cia-r-sm)",border:e||n?"2px solid var(--cia-control-checked)":"2px solid var(--cia-control-off)",background:e||n?"var(--cia-control-checked)":"var(--cia-bg)",transition:"background var(--cia-dur-fast) ease, border-color var(--cia-dur-fast) ease",display:"flex",alignItems:"center",justifyContent:"center"},children:[e&&t.jsx("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M1 4L3.5 6.5L9 1",stroke:"#fff",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})}),!e&&n&&t.jsx("span",{style:{display:"block",width:9,height:2,borderRadius:1,background:"#fff"}})]})]}),(s||i)&&t.jsxs("label",{htmlFor:u,style:{cursor:r?"not-allowed":"pointer",display:"flex",flexDirection:"column",gap:2},children:[s&&t.jsx("span",{style:{fontSize:13,fontFamily:"var(--cia-font-sans)",fontWeight:500,color:"var(--cia-text)",lineHeight:1.4,letterSpacing:"var(--cia-tracking-tight)"},children:s}),i&&t.jsx("span",{style:{fontSize:12,fontFamily:"var(--cia-font-sans)",color:"var(--cia-text-3)",lineHeight:1.5},children:i})]})]})}const i_={neutral:"var(--cia-text-4)",brand:"var(--cia-brand-500)",ok:"var(--cia-ok-500)",warn:"var(--cia-warn-500)",bad:"var(--cia-bad-500)"};function r_(e,a){const n=new Date,s=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),i=s-864e5,r=s-6*864e5,o=[{label:a("conversations.today"),items:[]},{label:a("conversations.yesterday"),items:[]},{label:a("conversations.last7"),items:[]},{label:a("conversations.older"),items:[]}];for(const l of e){const c=new Date(l.at).getTime();c>=s?o[0].items.push(l):c>=i?o[1].items.push(l):c>=r?o[2].items.push(l):o[3].items.push(l)}return o.filter(l=>l.items.length>0)}function o_(e,a){const n=new Date(e),i=new Date().getTime()-n.getTime();return i<6e4?a("conversations.now"):i<36e5?a("conversations.agoMin",{n:Math.floor(i/6e4)}):i<864e5?n.toLocaleTimeString(Te(),{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString(Te(),{day:"numeric",month:"short"})}const l_=12;function c_({items:e,activeId:a,onSelect:n,onNew:s,loading:i,title:r,newLabel:o,emptyTitle:l,emptyHint:c,header:d,variant:u="default",grouped:p,selectable:f,selectedIds:x,onToggleSelect:h,seleccionAlTope:b,onEndReached:g,hasMore:v,loadingMore:y}){const{t:k}=M("ds"),w=u==="bandeja",C=!w||p===!0?r_(e,k):[{label:"",items:e}],N=o??k("conversations.new"),S=m.useRef(null),_=m.useRef(null),R=m.useRef(g);R.current=g;const A=w&&!!g&&v===!0;m.useEffect(()=>{if(!A)return;const U=S.current,X=_.current;if(!U||!X)return;const ie=new IntersectionObserver(de=>{de[0]?.isIntersecting&&!y&&R.current?.()},{root:U,rootMargin:"160px"});return ie.observe(X),()=>ie.disconnect()},[A,y]);const E=m.useRef(new Map),[I,P]=m.useState(null),O=m.useMemo(()=>C.flatMap(U=>U.items.map(X=>X.id)),[C]),K=I&&O.includes(I)?I:a??O[0]??null,W=U=>{if(O.length===0)return;const X=U.target.getAttribute("data-thread-id"),ie=X?O.indexOf(X):-1;let de=-1;if(U.key==="ArrowDown")de=ie<0?0:Math.min(O.length-1,ie+1);else if(U.key==="ArrowUp")de=ie<0?O.length-1:Math.max(0,ie-1);else if(U.key==="Home")de=0;else if(U.key==="End")de=O.length-1;else return;U.preventDefault();const $=O[de];P($),E.current.get($)?.focus()},V=U=>X=>{X?E.current.set(U,X):E.current.delete(U)};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:w?"transparent":"var(--cia-bg-soft)",borderRight:w?void 0:"1px solid var(--cia-border)"},children:[r===!1&&!s&&!d?null:t.jsxs("div",{style:{padding:"16px 14px 12px",borderBottom:"1px solid var(--cia-border)",display:"flex",flexDirection:"column",gap:10},children:[r===!1&&!s?null:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[r===!1?null:t.jsx("div",{style:{flex:1},children:t.jsx("div",{style:{fontSize:12,fontFamily:"var(--cia-font-mono)",letterSpacing:"0.07em",textTransform:"uppercase",color:"var(--cia-text-3)",fontWeight:500},children:r??k("conversations.title")})}),s&&t.jsx("button",{type:"button",onClick:s,"aria-label":k("conversations.newAria"),title:N,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"var(--cia-r-sm)",background:"transparent",border:"1px solid var(--cia-border-2)",color:"var(--cia-text-3)",cursor:"pointer",transition:"background-color 0.15s ease, color 0.15s ease"},onMouseEnter:U=>{const X=U.currentTarget;X.style.background="var(--cia-bg-tint)",X.style.color="var(--cia-brand-500)"},onMouseLeave:U=>{const X=U.currentTarget;X.style.background="transparent",X.style.color="var(--cia-text-3)"},children:t.jsx(Fe,{size:15,"aria-hidden":"true"})})]}),d]}),t.jsxs("div",{ref:S,role:"listbox","aria-label":k("conversations.historyAria"),onKeyDown:W,className:w?"cia-stagger in":void 0,style:{flex:1,overflowY:"auto",padding:w?"8px":"6px 6px",display:"flex",flexDirection:"column",gap:w?6:2},children:[i&&t.jsx("div",{style:{padding:"12px 8px",display:"flex",flexDirection:"column",gap:6},children:[80,60,70].map((U,X)=>t.jsx("div",{className:"cia-skeleton",style:{height:38,borderRadius:8,width:`${U}%`},"aria-hidden":"true"},X))}),!i&&e.length===0&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"32px 16px",textAlign:"center"},children:[t.jsx(sn,{size:24,strokeWidth:1.5,style:{color:"var(--cia-text-4)"},"aria-hidden":"true"}),t.jsxs("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)",lineHeight:1.5},children:[l??k("conversations.emptyTitle"),t.jsx("br",{}),c??k("conversations.emptyHint")]})]}),!i&&C.map((U,X)=>t.jsxs("div",{style:w?{display:"flex",flexDirection:"column",gap:2}:void 0,children:[U.label&&t.jsx("div",{style:{padding:"8px 8px 3px",fontSize:10.5,fontFamily:"var(--cia-font-mono)",letterSpacing:"0.07em",textTransform:"uppercase",color:"var(--cia-text-3)",fontWeight:500},children:U.label}),U.items.map((ie,de)=>{const $=ie.id===a,z=O.indexOf(ie.id),D=ie.id===K?0:-1;return w?t.jsx(u_,{item:ie,isActive:$,tabIndex:D,onSelect:n,setRowRef:V,tr:k,staggerIndex:z<l_?z:void 0,selectable:f,selected:x?.has(ie.id)??!1,onToggleSelect:h,disabledPorTope:!!b&&!(x?.has(ie.id)??!1)},ie.id):t.jsx(d_,{item:ie,isActive:$,tabIndex:D,onSelect:n,setRowRef:V,tr:k},ie.id)})]},U.label||X)),w&&y&&t.jsx("div",{style:{padding:"4px 2px",display:"flex",flexDirection:"column",gap:6},"aria-hidden":"true",children:[1,2].map(U=>t.jsx("div",{className:"cia-skeleton",style:{height:64,borderRadius:"var(--cia-r-sm)"}},U))}),A&&t.jsx("div",{ref:_,"aria-hidden":"true",style:{height:1}})]}),s&&t.jsx("div",{style:{padding:"10px 8px",borderTop:"1px solid var(--cia-border)"},children:t.jsxs("button",{type:"button",onClick:s,style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"8px 10px",borderRadius:"var(--cia-r)",background:"var(--cia-bg-tint)",border:"1px solid color-mix(in oklab, var(--cia-brand-500) 20%, transparent)",color:"var(--cia-brand-500)",fontFamily:"inherit",fontSize:13,fontWeight:500,cursor:"pointer",letterSpacing:"var(--cia-tracking-tight)",transition:"background-color 0.15s ease, transform 0.15s ease"},onMouseEnter:U=>{const X=U.currentTarget;X.style.background="color-mix(in oklab, var(--cia-brand-500) 14%, transparent)",X.style.transform="translateY(-1px)"},onMouseLeave:U=>{const X=U.currentTarget;X.style.background="var(--cia-bg-tint)",X.style.transform=""},children:[t.jsx(Fe,{size:14,"aria-hidden":"true"}),N]})})]})}function d_({item:e,isActive:a,tabIndex:n,onSelect:s,setRowRef:i,tr:r}){const o=i_[e.tone??"neutral"];return t.jsxs("button",{ref:i(e.id),"data-thread-id":e.id,type:"button",role:"option","aria-selected":a,tabIndex:n,onClick:()=>s(e.id),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"8px 8px",borderRadius:"var(--cia-r-sm)",background:a?"color-mix(in oklab, var(--cia-brand-500) 10%, transparent)":"transparent",border:"1px solid",borderColor:a?"color-mix(in oklab, var(--cia-brand-500) 22%, transparent)":"transparent",curs
920or:"pointer",textAlign:"left",transition:"background-color 0.12s ease, border-color 0.12s ease",color:a?"var(--cia-text)":"var(--cia-text-2)"},onMouseEnter:l=>{a||(l.currentTarget.style.background="var(--cia-bg-tint)",l.currentTarget.style.borderColor="var(--cia-border)")},onMouseLeave:l=>{a||(l.currentTarget.style.background="transparent",l.currentTarget.style.borderColor="transparent")},children:[e.avatarInitial?t.jsx("span",{"aria-hidden":"true",style:{width:22,height:22,borderRadius:"50%",flex:"none",display:"grid",placeItems:"center",fontSize:10.5,fontWeight:600,color:"#fff",background:`color-mix(in oklab, ${o} 85%, black)`},children:e.avatarInitial.charAt(0).toUpperCase()}):t.jsx(sn,{size:13,style:{flex:"none",color:a?"var(--cia-brand-500)":o},"aria-hidden":"true"}),t.jsxs("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:1},children:[t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,fontWeight:a?500:400},children:e.title||r("conversations.untitled")}),e.subtitle&&t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,color:"var(--cia-text-3)"}
920,children:e.subtitle}),e.extra?t.jsx("span",{style:{display:"flex",gap:4,alignItems:"center",overflow:"hidden",marginTop:3},children:e.extra}):null]}),e.badge!=null&&e.badge>0&&t.jsx("span",{style:{flex:"none",minWidth:18,height:18,padding:"0 5px",borderRadius:999,display:"grid",placeItems:"center",fontSize:10.5,fontWeight:600,fontFamily:"var(--cia-font-mono)",background:"var(--cia-brand-500)",color:"#fff"},children:e.badge>99?"99+":e.badge}),t.jsx("span",{style:{fontSize:"var(--cia-fs-2xs)",color:"var(--cia-text-3)",fontFamily:"var(--cia-font-mono)",flex:"none",letterSpacing:"var(--cia-tracking-mono)"},children:o_(e.at,r)}),a&&t.jsx(ca,{size:12,style:{flex:"none",color:"var(--cia-brand-500)"},"aria-hidden":"true"})]})}function u_({item:e,isActive:a,tabIndex:n,onSelect:s,setRowRef:i,tr:r,staggerIndex:o,selectable:l,selected:c,onToggleSelect:d,disabledPorTope:u}){const p=l&&c,f=!!(l&&u),x=()=>{f||(l&&d?d(e.id):s(e.id))};return t.jsxs("button",{ref:i(e.id),"data-thread-id":e.id,"data-active":!l&&a||void 0,type:"button",role:"option","aria-selected":l?p:a,"aria-disabled":f||void 0,tabIndex:n,onClick:x,className:o!=null?"cia-stagger-item cia-threadrow":"cia-threadrow",style:{width:"100%",display:"flex",alignItems:"flex-start",gap:10,padding:"10px",textAlign:"left",cursor:f?"not-allowed":"pointer",opacity:f?.55:1,fontFamily:"inherit","--cia-row-bg":!l&&a||p?"var(--cia-row-active-bg)":"transparent",...o!=null?{"--i":o}:{}},children:[l&&t.jsx("span",{onClick:h=>h.stopPropagation(),style:{display:"flex",paddingTop:2},children:t.jsx(mn,{checked:!!c,disabled:f,onChange:()=>d?.(e.id),ariaLabel:r("conversations.selectAria",{title:e.title||r("conversations.untitled")})})}),e.avatar,t.jsxs("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsxs("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13.5,fontWeight:e.unread?700:500,color:"var(--cia-text)",display:"flex",alignItems:"center",gap:6},children:[e.unread&&t.jsx("span",{"aria-hidden":"true",style:{width:7,height:7,borderRadius:"50%",background:"var(--cia-brand-500)",flex:"none"}}),t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:e.title||r("conversations.untitled")})]}),e.marks?t.jsx("span",{className:"cia-threadrow-marcas",style:{flex:"none",display:"inline-flex",alignItems:"center",gap:"var(--cia-space-xs)"},children:e.marks}):null,t.jsx("span",{className:"cia-mono",style:{flex:"none",fontSize:10.5,color:"var(--cia-text-2)",fontVariantNumeric:"tabular-nums"},children:cv(e.at)})]}),e.subtitle&&t.jsx("span",{className:"cia-threadrow-preview",style:{fontSize:12,color:"var(--cia-text-2)",lineHeight:1.4,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"}
920,children:e.subtitle}),e.extra?t.jsx("span",{style:{display:"flex",gap:4,alignItems:"center",flexWrap:"wrap",overflow:"hidden",marginTop:2},children:e.extra}):null]})]})}function p_({side:e,children:a,runStart:n,runEnd:s,timeLabel:i,timeTitle:r,status:o,senderLabel:l,badge:c,avatar:d,provisional:u,accent:p,accentInk:f="#fff",metaPosition:x="abajo",actions:h,enterIndex:b,id:g,highlighted:v}){const y=e==="out",k=18,w=4,j=n?y?`${k}px ${w}px ${k}px ${k}px`:`${w}px ${k}px ${k}px ${k}px`:`${k}px`,C=p!=null,N=C?p:y?"var(--cia-bubble-own-bg)":"var(--cia-bubble-in-bg)",S=C?f:y?"var(--cia-bubble-own-ink)":"var(--cia-bubble-in-ink)",_=y?"var(--cia-bubble-own-meta)":"var(--cia-bubble-in-meta)",R=!y||C?void 0:"1px solid var(--cia-bubble-own-border)",A=y?void 0:"1px solid var(--cia-bubble-in-border)",E=x==="arriba"&&n&&(l||i);return t.jsxs("div",{id:g,className:"cia-bubble-row",style:{display:"flex",justifyContent:y?"flex-end":"flex-start",alignItems:"flex-end",gap:6,marginTop:n?8:0,paddingLeft:y||s?0:30,paddingRight:y&&!s?30:0,"--i":b??0},children:[!y&&s&&d,y&&h&&t.jsx("span",{className:"cia-bubble-actions",children:h}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:y?"flex-end":"flex-start",gap:2,minWidth:0,maxWidth:y?"78%":"85%"},children:[E?t.jsxs("span",{style:{display:"flex",alignItems:"baseline",gap:6,padding:"0 4px",width:"100%",minWidth:0},children:[l&&t.jsx("span",{style:{fontSize:12,fontWeight:700,color:"var(--cia-text-2)",minWidth:0,flex:"1 1 auto",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),i&&t.jsx("span",{className:"cia-mono",title:r,style:{fontSize:"var(--cia-fs-2xs)",color:"var(--cia-text-3)",whiteSpace:"nowrap",flex:"none"},children:i})]}):n&&l&&t.jsx("span",{className:"cia-mono",style:{fontSize:9.5,letterSpacing:"0.06em",padding:"0 4px",color:y?"var(--cia-brand-500)":C?p:"var(--cia-text-3)"},children:l}),t.jsx("div",{className:v?`cia-bubble-enter-${y?"own":"in"} cia-bubble-highlight`:`cia-bubble-enter-${y?"own":"in"}`,"aria-busy":u||void 0,style:{maxWidth:"100%",padding:"9px 12px",fontSize:13.5,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",opacity:u?.75:1,borderRadius:j,background:N,color:S,border:y?R:A,boxShadow:y&&C?"var(--cia-shadow-sm)":void 0},children:a}),c&&t.jsx("span",{style:{padding:"0 4px"},children:c}),o&&t.jsx("span",{style:{padding:"0 4px"},children:o}),x==="abajo"&&s&&!u&&i&&t.jsx("span",{className:"cia-mono",title:r,style:{fontSize:9.5,color:_,padding:"0 4px",whiteSpace:"nowrap"},children:i})]}),!y&&h&&t.jsx("span",{className:"cia-bubble-actions",children:h}),y&&s&&d]})}function h_({label:e,ariaLabel:a,className:n,style:s}){return t.jsxs("div",{role:"separator","aria-label":a??e,className:n,style:{display:"flex",alignItems:"center",gap:10,margin:"10px 6px 4px",...s},children:[t.jsx("span",{style:{flex:1,height:1,background:"var(--cia-border)"},"aria-hidden":"true"}),t.jsx("span",{className:"cia-mono","aria-hidden":"true",style:{flex:"none",padding:"3px 10px",borderRadius:"var(--cia-r-pill)",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",fontSize:10.5,letterSpacing:"0.06em",textTransform:"uppercase",color:"var(--cia-text-3)"},children:e}),t.jsx("span",{style:{flex:1,height:1,background:"var(--cia-border)"},"aria-hidden":"true"})]})}const m_=80,f_=60;function x_({items:e,renderItem:a,dayKeyOf:n,dayLabelOf:s,keyOf:i,onLoadOlder:r,loadingOlder:o,noMoreOlder:l,emptyText:c,className:d,newMessagesLabel:u}){const p=m.useRef(null),[f,x]=m.useState(!0),[h,b]=m.useState(!1),[g,v]=m.useState(0),y=m.useRef(null),k=m.useRef(e.length),w=m.useCallback(()=>{const N=p.current;N&&(N.scrollTop=N.scrollHeight,x(!0),b(!1),v(0))},[]),j=m.useCallback(()=>{const N=p.current;if(!N)return;const S=N.scrollHeight-N.scrollTop-N.clientHeight<=m_;x(S),S&&(b(!1),v(0)),N.scrollTop<=f_&&r&&!o&&!l&&(y.current=N.scrollHeight,r())},[r,o,l]);m.useLayoutEffect(()=>{const N=p.current;if(!N)return;const S=e.length>k.current,_=e.length-k.current,R=y.current;R!==null&&S?(N.scrollTop+=N.scrollHeight-R,y.current=null):S&&(f?N.scrollTop=N.scrollHeight:(b(!0),v(A=>A+_))),k.current=e.length},[e.length,f]),m.useEffect(()=>{const N=p.current;N&&(N.scrollTop=N.scrollHeight)},[]);let C=null;return t.jsxs("div",{style:{position:"relative",flex:1,minHeight:0,display:"flex"},children:[t.jsxs("div",{ref:p,onScroll:j,className:d??"cia-scroll",role:"log","aria-live":"polite",style:{flex:1,minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column",gap:3,padding:"4px 2px"},children:[r&&!l&&t.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"6px 0",fontSize:"var(--cia-fs-2xs)",color:"var(--cia-text-3)",minHeight:24},children:o?he.t("ds:chatThread.loadingOlder"):""}
920),e.length===0&&c,e.map((N,S)=>{const _=n(N),R=_!==C;return C=_,t.jsxs("div",{style:{display:"contents"},children:[R&&t.jsx(h_,{label:s(_)}),a(N,S)]},i?i(N,S):S)})]}),h&&t.jsxs("button",{type:"button",onClick:w,style:{position:"absolute",bottom:10,left:"50%",transform:"translateX(-50%)",display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:999,background:"var(--cia-brand-500)",border:0,color:"#fff",fontFamily:"inherit",fontSize:12,fontWeight:500,cursor:"pointer",boxShadow:"var(--cia-shadow-sm)",minHeight:32},children:[t.jsx(Vb,{size:13,"aria-hidden":"true"}),u??(g>0?he.t("ds:chatThread.newMessagesCount",{count:g}):he.t("ds:chatThread.newMessages"))]})]})}const Fa=(e,a)=>String(he.t(`ds:suggestion.${e}`,a)),Dn={bad:{bg:"color-mix(in oklab, var(--cia-bad-500) 9%, transparent)",border:"color-mix(in oklab, var(--cia-bad-500) 28%, transparent)",text:"var(--cia-bad-500)"},ok:{bg:"color-mix(in oklab, var(--cia-ok-500) 9%, transparent)",border:"color-mix(in oklab, var(--cia-ok-500) 28%, transparent)",text:"var(--cia-ok-500)"}};function Uo({onClick:e,icon:a,label:n,tone:s}){const i=s==="ok"?"var(--cia-ok-500)":s==="bad"?"var(--cia-bad-500)":"var(--cia-text-2)";return t.jsxs("button",{type:"button",onClick:e,title:n,"aria-label":n,className:"inline-flex items-center gap-1 rounded-lg transition-colors",style:{color:i,background:"var(--cia-bg-elev)",border:`1px solid color-mix(in oklab, ${i} 30%, transparent)`,padding:"5px 9px",minHeight:32,fontSize:11.5,fontWeight:600,cursor:"pointer",whiteSpace:"nowrap"},onMouseEnter:r=>{r.currentTarget.style.background=`color-mix(in oklab, ${i} 12%, var(--cia-bg-elev))`},onMouseLeave:r=>{r.currentTarget.style.background="var(--cia-bg-elev)"},children:[a,t.jsx("span",{children:n})]})}function Nf({before:e,after:a,note:n,location:s,state:i="pending",staleReason:r,onAccept:o,onReject:l,highlighted:c=!1,position:d,style:u,anchorRef:p}){const[f,x]=m.useState(!1),[h,b]=m.useState(a),g=m.useRef(null);m.useEffect(()=>{b(a),x(!1)},[a]),m.useEffect(()=>{if(!f)return;const k=g.current;k&&(k.focus(),k.setSelectionRange(k.value.length,k.value.length),k.style.height="auto",k.style.height=`${Math.min(400,k.scrollHeight)}px`)},[f]);const v=i==="pending",y=c?"var(--cia-cta-500)":i==="stale"?"color-mix(in oklab, var(--cia-warn-500) 40%, transparent)":"var(--cia-border)";return t.jsxs("div",{ref:p,style:{border:`1px solid ${y}`,borderRadius:"var(--cia-r)",background:"var(--cia-bg-elev)",boxShadow:c?"0 0 0 3px color-mix(in oklab, var(--cia-cta-500) 22%, transparent)":"none",overflow:"hidden",transition:"box-shadow .18s ease, border-color .18s ease",opacity:i==="accepted"||i==="rejected"?.6:1,...u},children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{padding:"7px 10px",borderBottom:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)"},children:[d&&t.jsx("span",{className:"cia-mono",style:{fontSize:10,fontWeight:700,color:"var(--cia-cta-500)",background:"color-mix(in oklab, var(--cia-cta-500) 12%, transparent)",borderRadius:999,padding:"2px 7px"},children:Fa("position",{index:d.index,total:d.total})}),s&&t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-2)",fontWeight:600},children:s}),t.jsx("span",{style:{flex:1}}),i==="accepted"&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-ok-500)",fontWeight:600},children:Fa("accepted")}),i==="rejected"&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-text-3)",fontWeight:600},children:Fa("rejected")}),i==="stale"&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-warn-ink)",fontWeight:600},children:Fa("stale")})]}),n&&t.jsx("p",{style:{margin:0,padding:"8px 10px 0",fontSize:12,color:"var(--cia-text-2)",lineHeight:1.5},children:n}),i==="stale"&&r&&t.jsx("p",{style:{margin:0,padding:"6px 10px 0",fontSize:11.5,color:"var(--cia-warn-ink)",lineHeight:1.5},children:r}),e!==""&&t.jsxs("div",{className:"cia-mono",style:{margin:"8px 10px 0",padding:"8px 10px",background:Dn.bad.bg,border:`1px solid ${Dn.bad.border}`,borderRadius:8,fontSize:12,lineHeight:1.65,whiteSpace:"pre-wrap",wordBreak:"break-word",color:"var(--cia-text)"},children:[t.jsx("span",{"aria-hidden":!0,style:{color:Dn.bad.text,fontWeight:700,marginRight:6},children:"−"}),t.jsx("span",{style:{textDecoration:"line-through",textDecorationColor:Dn.bad.text},children:e})]}),(a!==""||f)&&(f?t.jsxs("div",{style:{margin:"8px 10px 0"},children:[t.jsx("textarea",{ref:g,className:"cia-mono",value:h,onChange:k=>{b(k.target.value),k.currentTarget.style.height="auto",k.currentTarget.style.height=`${Math.min(400,k.currentTarget.scrollHeight)}px`},onKeyDown:k=>
920{k.key==="Enter"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),o?.(h)),k.key==="Escape"&&(k.preventDefault(),b(a),x(!1))},"aria-label":Fa("editAria"),style:{width:"100%",padding:"8px 10px",background:Dn.ok.bg,border:"1px solid var(--cia-cta-500)",borderRadius:8,fontSize:12,lineHeight:1.65,color:"var(--cia-text)",resize:"vertical",outline:"none"}}),t.jsx("p",{style:{margin:"4px 0 0",fontSize:10.5,color:"var(--cia-text-3)"},children:Fa("editHint")})]}):t.jsxs("div",{className:"cia-mono",style:{margin:"8px 10px 0",padding:"8px 10px",background:Dn.ok.bg,border:`1px solid ${Dn.ok.border}`,borderRadius:8,fontSize:12,lineHeight:1.65,whiteSpace:"pre-wrap",wordBreak:"break-word",color:"var(--cia-text)"},children:[t.jsx("span",{"aria-hidden":!0,style:{color:Dn.ok.text,fontWeight:700,marginRight:6},children:"+"}),h]})),a===""&&!f&&t.jsx("p",{style:{margin:0,padding:"8px 10px 0",fontSize:11.5,color:"var(--cia-text-3)"},children:Fa("deletesFragment")}),v&&t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{padding:"10px"},children:[t.jsx(Uo,{onClick:()=>o?.(f?h:a),icon:f?t.jsx(AS,{className:"size-3"}):t.jsx(ct,{className:"size-3"}),label:Fa(f?"acceptEdited":"accept"),tone:"ok"}),t.jsx(Uo,{onClick:()=>l?.(),icon:t.jsx(nt,{className:"size-3"}),label:Fa("reject"),tone:"bad"}),!f&&t.jsx(Uo,{onClick:()=>x(!0),icon:t.jsx(qt,{className:"size-3"}),label:Fa("edit"),tone:"neutral"}),f&&t.jsx(Uo,{onClick:()=>{b(a),x(!1)},icon:t.jsx(nt,{className:"size-3"}),label:Fa("cancelEdit"),tone:"neutral"})]})]})}function Gl({actions:e,onPick:a,disabled:n=!1}){const{t:s}=M("ds");return t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},role:"group","aria-label":s("quickActions.aria"),children:e.map(i=>t.jsx("button",{type:"button",disabled:n,onClick:()=>a(i.instruction),title:i.instruction,style:{display:"inline-flex",alignItems:"center",gap:6,height:32,minHeight:44,padding:"0 14px",borderRadius:"var(--cia-r-pill)",border:"1px solid var(--cia-border-2)",background:"var(--cia-bg-elev)",color:n?"var(--cia-text-4)":"var(--cia-text-2)",fontFamily:"var(--cia-font-sans)",fontSize:12.5,fontWeight:500,letterSpacing:"var(--cia-tracking-tight)",cursor:n?"not-allowed":"pointer",opacity:n?.55:1,transition:"border-color var(--cia-dur-fast) ease, background var(--cia-dur-fast) ease, color var(--cia-dur-fast) ease, box-shadow var(--cia-dur-fast) ease",outline:"none",whiteSpace:"nowrap"},onMouseEnter:r=>{if(n)return;const o=r.currentTarget;o.style.borderColor="var(--cia-brand-300)",o.style.background="color-mix(in oklab, var(--cia-brand-500) 6%, var(--cia-bg-elev))",o.style.color="var(--cia-brand-500)"},onMouseLeave:r=>{if(n)return;const o=r.currentTarget;o.style.borderColor="var(--cia-border-2)",o.style.background="var(--cia-bg-elev)",o.style.color="var(--cia-text-2)"},onFocus:r=>{n||(r.currentTarget.style.boxShadow="0 0 0 3px var(--cia-ring)")},onBlur:r=>{r.currentTarget.style.boxShadow="none"},children:i.label},i.instruction))})}function g_({value:e,onChange:a,onComment:n}){const{t:s}=M("ds"),[i,r]=m.useState(""),[o,l]=m.useState(!1);function c(f){a(f),f==="down"&&n&&l(!0)}function d(){n&&i.trim()&&n(i.trim()),l(!1),r("")}function u(f){f.key==="Enter"&&(f.preventDefault(),d()),f.key==="Escape"&&(l(!1),r(""))}const p=(f,x)=>({display:"inline-flex",alignItems:"center",justifyContent:"center",width:32,height:32,minWidth:44,minHeight:44,borderRadius:"var(--cia-r)",border:"1px solid",borderColor:f?x==="up"?"var(--cia-ok-500)":"var(--cia-bad-500)":"var(--cia-border-2)",background:f?x==="up"?"color-mix(in oklab, var(--cia-ok-500) 12%, transparent)":"color-mix(in oklab, var(--cia-bad-500) 12%, transparent)":"transparent",color:f?x==="up"?"var(--cia-ok-500)":"var(--cia-bad-500)":"var(--cia-text-3)",cursor:"pointer",transition:"border-color var(--cia-dur-fast) ease, background var(--cia-dur-fast) ease, color var(--cia-dur-fast) ease",outline:"none"});return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",fontFamily:"var(--cia-font-sans)",letterSpacing:"var(--cia-tracking-tight)"},children:s("feedback.question")}),t.jsx("button",{type:"button","aria-label":s("feedback.up"),"aria-pressed":e==="up",onClick:()=>c("up"),style:p(e==="up","up"),onFocus:f=>{f.currentTarget.style.boxShadow="0 0 0 3px var(--cia-ring)"},onBlur:f=>{f.currentTarget.style.boxShadow="none"},children:t.jsx(p2,{size:14,"aria-hidden":"true"})}),t.jsx("button",{type:"button","aria-label":s("feedback.down"),"aria-pressed":e==="down",onClick:()=>c("down"),style:p(e==="down","down"),onFocus:f=>{f.currentTarget.style.boxShadow="0 0 0 3px var(--cia-ring)"},onBlur:f=>{f.currentTarget.style.boxShadow="none"},children:t.jsx(u2,{size:14,"aria-hidden":"true"})})]}),o&&n&&t.jsxs("div",{style:{display:"flex",gap:6}
920,children:[t.jsx("input",{autoFocus:!0,type:"text",value:i,onChange:f=>r(f.target.value),onKeyDown:u,placeholder:s("feedback.commentPlaceholder"),"aria-label":s("feedback.commentAria"),style:{flex:1,height:34,padding:"0 10px",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r)",background:"var(--cia-bg-elev)",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)",fontSize:12.5,letterSpacing:"var(--cia-tracking-tight)",outline:"none",transition:"border-color var(--cia-dur-fast) ease, box-shadow var(--cia-dur-fast) ease"},onFocus:f=>{f.currentTarget.style.borderColor="var(--cia-brand-500)",f.currentTarget.style.boxShadow="0 0 0 3px var(--cia-ring)"},onBlur:f=>{f.currentTarget.style.borderColor="var(--cia-border-2)",f.currentTarget.style.boxShadow="none"}}),t.jsx("button",{type:"button",onClick:d,style:{height:34,padding:"0 12px",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-brand-500)",background:"var(--cia-brand-500)",color:"#fff",fontFamily:"var(--cia-font-sans)",fontSize:12.5,fontWeight:500,cursor:"pointer",transition:"background var(--cia-dur-fast) ease"},children:s("feedback.send")})]})]})}function b_({onReload:e}){const{t:a}=M("ds"),n=()=>{e?e():window.location.reload()};return t.jsxs("div",{className:"cia",role:"alert","aria-live":"assertive",style:{minHeight:"100dvh",display:"flex",alignItems:"center",justifyContent:"center",padding:"32px 24px",background:"var(--cia-bg)",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)"},children:[t.jsx("span",{"aria-hidden":"true",style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:0,background:["radial-gradient(60% 60% at 20% 30%, color-mix(in oklab, var(--cia-brand-500) 10%, transparent), transparent 70%)","radial-gradient(50% 50% at 80% 75%, color-mix(in oklab, var(--cia-cta-500) 8%, transparent), transparent 70%)"].join(", ")}}),t.jsxs("div",{style:{position:"relative",zIndex:1,width:"100%",maxWidth:440,background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r-xl)",boxShadow:"var(--cia-shadow-lg)",padding:"40px 36px 36px",display:"flex",flexDirection:"column",alignItems:"center",gap:24,textAlign:"center"},children:[t.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center"},children:[t.jsx("span",{"aria-hidden":"true",style:{position:"absolute",inset:-18,borderRadius:"50%",border:"1px solid var(--cia-border)",opacity:.6}}),t.jsx("span",{"aria-hidden":"true",style:{position:"absolute",inset:-36,borderRadius:"50%",border:"1px solid var(--cia-border)",opacity:.3}}),t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:64,height:64,borderRadius:20,background:"color-mix(in oklab, var(--cia-brand-500) 10%, var(--cia-bg-elev))",border:"1px solid color-mix(in oklab, var(--cia-brand-500) 20%, transparent)"},children:t.jsxs("svg",{width:"34",height:"22",viewBox:"0 0 34 22",fill:"none","aria-hidden":"true",focusable:"false",children:[t.jsx("path",{d:"M2 18 C6 8, 14 4, 22 7 C28 9, 30 14, 32 12",stroke:"var(--cia-cta-500)",strokeWidth:"2.5",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M2 12 C7 3, 16 1, 23 5 C28 8, 30 11, 32 8",stroke:"var(--cia-ok-500)",strokeWidth:"2.5",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M2 6 C8 -1, 17 -1, 24 3 C29 6, 31 8, 32 5",stroke:"var(--cia-sky-500)",strokeWidth:"2.5",strokeLinecap:"round",fill:"none"})]})})]}),t.jsxs("div",{"aria-label":"Enlassa AI",style:{display:"flex",alignItems:"baseline",gap:6,marginTop:-8},children:[t.jsx("span",{style:{fontFamily:"var(--cia-font-sans)",fontSize:13,fontWeight:700,letterSpacing:"0.12em",textTransform:"uppercase",color:"var(--cia-text-3)"},children:"Enlassa"}),t.jsx("span",{style:{fontFamily:"var(--cia-font-mono)",fontSize:12,fontWeight:600,letterSpacing:"0.04em",color:"var(--cia-cta-500)"},children:"AI"})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,maxWidth:340},children:[t.jsx("h1",{style:{margin:0,fontSize:20,fontWeight:650,lineHeight:1.3,letterSpacing:"var(--cia-tracking-tight)",color:"var(--cia-text)"},children:a("error.title")}),t.jsx("p",{style:{margin:0,fontSize:13.5,lineHeight:1.6,color:"var(--cia-text-3)"},children:a("error.body")})]}),t.jsxs("button",{type:"button",onClick:n,autoFocus:!0,"aria-label":a("error.reloadAria"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:7,minHeight:44,padding:"0 22px",fontFamily:"var(--cia-font-sans)",fontSize:14,fontWeight:600,letterSpacing:"var(--cia-tracking-tight)",color:"white",background:"var(--cia-brand-500)",border:"1px solid var(--cia-brand-600)",borderRadius:"var(--cia-r-sm)",cursor:"pointer",transition:"background-color var(--cia-dur-fast) var(--cia-ease-smooth), transform var(--cia-dur-fast) var(--cia-ease-smooth)",WebkitTapHighlightColor:"transparent"},onMouseEnter:s=>{s.currentTarget.style.backgroundColor="var(--cia-brand-600)",s.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:s=>{s.currentTarget.style.backgroundColor="var(--cia-brand-500)",s.currentTarget.style.transform="translateY(0)"},onMouseDown:s=>{s.currentTarget.style.transform="translateY(0)"},children:[t.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[t.jsx("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),t.jsx("path",{d:"M21 3v5h-5"})]}),a("error.reload")]}),t.jsx("div",{"aria-hidden":"true",style:{width:"100%",height:1,background:"var(--cia-border)"}}
920),t.jsx("p",{style:{margin:0,fontSize:11.5,color:"var(--cia-text-4)",letterSpacing:"0.01em"},children:a("error.support")})]})]})}function y_(){return t.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18","aria-hidden":"true",children:[t.jsx("path",{fill:"#4285F4",d:"M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.49h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92A8.78 8.78 0 0 0 17.64 9.2z"}),t.jsx("path",{fill:"#34A853",d:"M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.81.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.33A9 9 0 0 0 9 18z"}),t.jsx("path",{fill:"#FBBC05",d:"M3.97 10.72a5.4 5.4 0 0 1 0-3.44V4.95H.96a9 9 0 0 0 0 8.1l3.01-2.33z"}),t.jsx("path",{fill:"#EA4335",d:"M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58A9 9 0 0 0 .96 4.95l3.01 2.33C4.68 5.16 6.66 3.58 9 3.58z"})]})}function v_(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 23 23","aria-hidden":"true",children:[t.jsx("rect",{x:"1",y:"1",width:"10",height:"10",fill:"#F25022"}),t.jsx("rect",{x:"12",y:"1",width:"10",height:"10",fill:"#7FBA00"}),t.jsx("rect",{x:"1",y:"12",width:"10",height:"10",fill:"#00A4EF"}),t.jsx("rect",{x:"12",y:"12",width:"10",height:"10",fill:"#FFB900"})]})}function Zl({provider:e,href:a,onClick:n,label:s,disabled:i=!1,fullWidth:r=!0}){const{t:o}=M("ds"),l="cia-btn cia-btn-outline cia-btn-lg",c={width:r?"100%":void 0,justifyContent:"center",gap:10},d=t.jsxs(t.Fragment,{children:[e==="google"?t.jsx(y_,{}):t.jsx(v_,{}),t.jsx("span",{children:s??o(e==="google"?"social.google":"social.microsoft")})]});return a&&!i?t.jsx("a",{className:l,href:a,style:c,children:d}):t.jsx("button",{type:"button",className:l,onClick:n,disabled:i,style:c,children:d})}function dv({title:e,description:a,icon:n,selected:s,motivo:i,motivoId:r}){return t.jsxs(t.Fragment,{children:[n?t.jsx("span",{className:"cia-choice-card-icon","aria-hidden":"true",children:n}):null,t.jsxs("span",{className:"cia-choice-card-text",children:[t.jsxs("span",{className:"cia-choice-card-head",children:[t.jsx("span",{className:"cia-choice-card-title",children:e}),s?t.jsx("span",{className:"cia-choice-card-check","aria-hidden":"true",children:t.jsx(ct,{})}):null]}),a?t.jsx("span",{className:"cia-choice-card-desc",children:a}):null,i?t.jsx("span",{id:r,className:"cia-choice-card-reason",children:i}):null]})]})}function Bu({title:e,description:a,icon:n,selected:s=!1,onClick:i,disabled:r=!1,disabledReason:o}){const l=m.useId(),c=r?o:void 0;return t.jsx("button",{type:"button",className:"cia-choice-card","data-selected":s?"":void 0,onClick:i,disabled:r,"aria-pressed":s,"aria-describedby":c?l:void 0,children:t.jsx(dv,{title:e,description:a,icon:n,selected:s,motivo:c,motivoId:l})})}function uv({value:e,onChange:a,options:n,ariaLabel:s,ariaLabelledBy:i,className:r}){const o=m.useId(),l=m.useRef([]),c=n.map((x,h)=>x.disabled?-1:h).filter(x=>x>=0),d=n.findIndex(x=>x.value===e&&!x.disabled),u=d>=0?d:c[0]??-1,p=(x,h)=>{if(c.length===0)return;let b;if(h==="inicio")b=c[0];else if(h==="fin")b=c[c.length-1];else{const g=c.indexOf(x),v=g<0?0:(g+h+c.length)%c.length;b=c[v]}a(n[b].value),l.current[b]?.focus()},f=(x,h)=>{switch(x.key){case"ArrowRight":case"ArrowDown":x.preventDefault(),p(h,1);return;case"ArrowLeft":case"ArrowUp":x.preventDefault(),p(h,-1);return;case"Home":x.preventDefault(),p(h,"inicio");return;case"End":x.preventDefault(),p(h,"fin");return;default:return}};return t.jsx("div",{role:"radiogroup","aria-label":i?void 0:s,"aria-labelledby":i,className:r?`cia-choice-group ${r}`:"cia-choice-group",children:n.map((x,h)=>{const b=x.value===e&&!x.disabled,g=x.disabled?x.disabledReason:void 0,v=`${o}-motivo-${h}`;return t.jsx("button",{ref:y=>{l.current[h]=y},type:"button",role:"radio","aria-checked":b,"aria-disabled":x.disabled?!0:void 0,"aria-describedby":g?v:void 0,tabIndex:h===u?0:-1,className:"cia-choice-card","data-selected":b?"":void 0,"data-disabled":x.disabled?"":void 0,onClick:()=>{x.disabled||a(x.value)},onKeyDown:y=>
920f(y,h),children:t.jsx(dv,{title:x.title,description:x.description,icon:x.icon,selected:b,motivo:g,motivoId:v})},x.value)})})}const Sf={bad:0,warn:1,info:2},j_={bad:cs,warn:Tt,info:Mi};function w_(e){return e.map((a,n)=>({it:a,i:n})).sort((a,n)=>Sf[a.it.tone]-Sf[n.it.tone]||a.i-n.i).map(({it:a})=>a)}function k_({title:e,items:a,headingLevel:n=3,className:s,style:i}){const r=m.useId();if(a.length===0)return null;const o=w_(a),l=o[0].tone,c=n===4?"h4":"h3";return t.jsxs("section",{className:s?`cia-attention ${s}`:"cia-attention","data-tone":l,"aria-labelledby":`${r}-titulo`,style:i,children:[t.jsx(c,{id:`${r}-titulo`,className:"cia-attention-title",children:e}),t.jsx("ul",{className:"cia-attention-items",children:o.map(d=>{const u=d.icon??j_[d.tone],p=d.action?.icon;return t.jsxs("li",{className:"cia-attention-item","data-tone":d.tone,children:[t.jsx("span",{className:"cia-attention-mark","aria-hidden":"true",children:t.jsx(u,{})}),t.jsxs("div",{className:"cia-attention-text",children:[t.jsx("span",{className:"cia-attention-main",children:d.text}),d.detail?t.jsx("span",{className:"cia-attention-detail",children:d.detail}):null]}),d.action?t.jsx(Ie,{size:"sm",variant:"outline",className:"cia-attention-action",icon:p?t.jsx(p,{}):void 0,loading:d.action.loading,onClick:d.action.onClick,children:d.action.label}):null]},d.id)})})]})}const Cf=["var(--cia-brand-500)","var(--cia-cta-500)","var(--cia-brand-300)","var(--cia-cta-400)"];function N_({count:e=80,duration:a=1700}){const n=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,[s,i]=m.useState(!n);if(m.useEffect(()=>{if(n)return;const o=setTimeout(()=>i(!1),a);return()=>clearTimeout(o)},[a,n]),n||!s)return null;const r=Array.from({length:e},(o,l)=>({i:l,left:Math.random()*100,dx:(Math.random()-.5)*260,delay:Math.random()*220,dur:900+Math.random()*800,rot:Math.random()*720-360,size:6+Math.random()*6,color:Cf[l%Cf.length]}));return t.jsxs("div",{"aria-hidden":!0,style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none",zIndex:50},children:[t.jsx("style",{children:`@keyframes cia-confetti-fall {
921        0% { transform: translate3d(0, -10%, 0) rotate(0deg); opacity: 1; }
922        100% { transform: translate3d(var(--cdx), 110vh, 0) rotate(var(--crot)); opacity: 0; }
923      }`}),r.map(o=>t.jsx("span",{style:{position:"absolute",top:0,left:`${o.left}%`,width:o.size,height:o.size*.6,background:o.color,borderRadius:1,"--cdx":`${o.dx}px`,"--crot":`${o.rot}deg`,animation:`cia-confetti-fall ${o.dur}ms cubic-bezier(0.22,1,0.36,1) ${o.delay}ms forwards`}},o.i))]})}function S_({remainingMinutes:e,totalMinutes:a,label:n,note:s}){const{t:i}=M("ds"),r=n??i("meter.trial"),o=Math.max(0,a),l=Math.max(0,o>0?Math.min(e,o):e),c=o>0?l/o:0,d=c<=.05?"var(--cia-bad-500)":c<=.2?"var(--cia-warn-500)":"var(--cia-ok-500)";return t.jsxs("div",{style:{width:"100%"},children:[t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",marginBottom:4},children:[t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5,letterSpacing:"0.04em"},children:r}),t.jsxs("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-2)"},children:[Math.round(l)," / ",Math.round(o)," min"]})]}),t.jsx("div",{style:{height:5,borderRadius:999,background:"var(--cia-bg-soft)",overflow:"hidden"},role:"progressbar","aria-valuenow":Math.round(l),"aria-valuemin":0,"aria-valuemax":Math.round(o),children:t.jsx("div",{style:{height:"100%",width:`${Math.round(c*100)}%`,background:d,borderRadius:999,transition:"width var(--cia-dur) var(--cia-ease-smooth)"}})}),s&&t.jsx("div",{className:"cia-text-3",style:{fontSize:10,lineHeight:1.45,marginTop:4},children:s})]})}const Xr=[{code:"CO",dial:"+57",flag:"🇨🇴",label:"Colombia"},{code:"MX",dial:"+52",flag:"🇲🇽",label:"México"},{code:"US",dial:"+1",flag:"🇺🇸",label:"Estados Unidos"},{code:"PE",dial:"+51",flag:"🇵🇪",label:"Perú"},{code:"CL",dial:"+56",flag:"🇨🇱",label:"Chile"},{code:"AR",dial:"+54",flag:"🇦🇷",label:"Argentina"}],_f=/^\+[1-9]\d{6,14}$/;function C_(e){return e?Xr.find(a=>a.code===e.toUpperCase())?.dial??null:null}function __(e){return e?[...Xr].sort((n,s)=>s.dial.length-n.dial.length).find(n=>e.startsWith(n.dial))?.dial??null:null}function E_(e){const a=Xr.find(n=>e.startsWith(n.dial));return a?{dial:a.dial,national:e.slice(a.dial.length)}:{dial:Xr[0].dial,national:e.replace(/^\+/,"").replace(/\D/g,"")}}
923function A_({value:e,onChange:a,error:n,id:s,placeholder:i="300 123 4567",disabled:r,allowedCountries:o,...l}){const{t:c}=M("ds"),d=m.useId(),u=s??`cia-phone-${d}`,p=`${u}-error`,[f,x]=m.useState(!1),{dial:h,national:b}=E_(e||"");function g(y){a(`${y}${b}`)}function v(y){a(`${h}${y.replace(/\D/g,"")}`)}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"stretch",width:"100%",borderRadius:"var(--cia-r)",border:`1.5px solid ${n?"var(--cia-bad-500)":f?"var(--cia-brand-500)":"var(--cia-border-2)"}`,background:r?"var(--cia-bg-soft)":"var(--cia-bg)",boxShadow:f&&!n?"0 0 0 3px var(--cia-ring)":"none",opacity:r?.6:1,overflow:"hidden",transition:"border-color var(--cia-dur-fast) ease, box-shadow var(--cia-dur-fast) ease"},children:[t.jsx("select",{"aria-label":c("phone.countryAria"),value:h,disabled:r,onChange:y=>g(y.target.value),onFocus:()=>x(!0),onBlur:()=>x(!1),style:{flex:"none",minWidth:92,minHeight:44,padding:"0 6px 0 10px",border:"none",borderRight:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)",fontSize:13.5,cursor:r?"not-allowed":"pointer",outline:"none",appearance:"none",WebkitAppearance:"none"},children:Xr.filter(y=>!o||o.includes(y.code)||y.dial===h).map(y=>t.jsxs("option",{value:y.dial,children:[y.flag," ",y.dial]},y.code))}),t.jsx("input",{...l,id:u,type:"tel",inputMode:"tel",autoComplete:"tel",value:b,disabled:r,placeholder:i,"aria-invalid":!!n,"aria-describedby":n?p:void 0,onChange:y=>v(y.target.value),onFocus:()=>x(!0),onBlur:()=>x(!1),style:{flex:1,minWidth:0,minHeight:44,padding:"0 12px",border:"none",outline:"none",background:"transparent",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)",fontSize:14}})]}),n&&t.jsx("span",{id:p,role:"alert",style:{fontSize:12,color:"var(--cia-bad-500)",fontFamily:"var(--cia-font-sans)",lineHeight:1.4},children:n})]})}function mh({title:e,icon:a,summary:n,badge:s,defaultOpen:i=!1,open:r,onToggle:o,children:l}){const c=m.useId(),[d,u]=m.useState(i),p=r??d,f=typeof window<"u"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;function x(){const h=!p;r===void 0&&u(h),o?.(h)}return t.jsxs("section",{style:{border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r-lg)",background:"var(--cia-bg-elev)",overflow:"hidden"},children:[t.jsxs("button",{type:"button",className:"cia-collapsible-head",onClick:x,"aria-expanded":p,"aria-controls":c,style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"13px 16px",border:0,background:"transparent",cursor:"pointer",textAlign:"left",font:"inherit",color:"var(--cia-text)",transition:"background var(--cia-dur-fast) ease"},children:[a&&t.jsx("span",{"aria-hidden":!0,style:{flex:"none",width:28,height:28,borderRadius:"var(--cia-r-sm)",display:"inline-flex",alignItems:"center",justifyContent:"center",background:"var(--cia-bg-tint)",color:"var(--cia-brand-500)"},children:t.jsx(a,{size:15})}),t.jsx("span",{style:{fontSize:14,fontWeight:600,flex:"none"},children:e}),s&&t.jsx("span",{style:{flex:"none",display:"inline-flex"},children:s}),t.jsx("span",{style:{flex:1}}),n&&t.jsx("span",{"aria-hidden":p,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,color:"var(--cia-text-3)",opacity:p?0:1,transition:f?"none":"opacity var(--cia-dur) var(--cia-ease-smooth)"},children:n}),t.jsx(Ut,{size:16,"aria-hidden":!0,style:{flex:"none",color:"var(--cia-text-3)",transform:p?"rotate(180deg)":"none",transition:f?"none":"transform var(--cia-dur) var(--cia-ease-smooth)"}})]}),t.jsx("div",{style:{display:"grid",gridTemplateRows:p?"1fr":"0fr",transition:f?"none":"grid-template-rows var(--cia-dur) var(--cia-ease-smooth)"},children:t.jsx("div",{id:c,style:{overflow:"hidden",minHeight:0,visibility:p?"visible":"hidden",transition:f?"none":"visibility var(--cia-dur)"},children:t.jsx("div",{style:{padding:"14px 16px",borderTop:"1px solid var(--cia-border)"},children:l})})}),t.jsx("style",{children:`
924        .cia-collapsible-head:hover { background: var(--cia-bg-soft) !important; }
925      `})]})}function pv({open:e,children:a,id:n}){const[s,i]=m.useState(!1);m.useEffect(()=>{const c=window.matchMedia("(prefers-reduced-motion: reduce)");
925i(c.matches);const d=()=>i(c.matches);return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[]);const[r,o]=m.useState(!1),l=m.useRef(!0);return m.useEffect(()=>{if(l.current){l.current=!1;return}s||o(!0)},[e,s]),t.jsx("div",{style:{display:"grid",gridTemplateRows:e?"1fr":"0fr",transition:s?"none":"grid-template-rows var(--cia-dur) var(--cia-ease-smooth)"},onTransitionEnd:c=>{c.propertyName==="grid-template-rows"&&o(!1)},children:t.jsx("div",{id:n,style:{overflow:r?"hidden":"visible",minHeight:0,visibility:e?"visible":"hidden",transition:s?"none":"visibility var(--cia-dur)"},children:a})})}const R_={ok:"var(--cia-ok-500)",bad:"var(--cia-bad-500)",warn:"var(--cia-warn-500)",info:"var(--cia-sky-500)",neutral:"var(--cia-text-4)"};function T_({stages:e,total:a,pctMode:n="ofTotal",valueFormat:s,empty:i}){const{t:r}=M("ds"),o=a??e[0]?.value??0,l=s??(c=>c.toLocaleString());return o<=0?i!==void 0?t.jsx(t.Fragment,{children:i}):t.jsx("div",{className:"cia-text-3",style:{fontSize:12,textAlign:"center",padding:"8px 0"},children:r("funnel.empty")}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.map((c,d)=>{const u=Math.max(0,Math.min(1,o>0?c.value/o:0)),p=Math.round(u*100),f=d>0?e[d-1].value:0,x=n==="ofPrevious"&&d>0&&f>0?Math.round((c.value/f-1)*100):null;return t.jsxs("div",{children:[t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",gap:8,marginBottom:3},children:[t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-2)",minWidth:0},children:c.label}),t.jsxs("span",{className:"cia-mono",style:{fontSize:11.5,color:"var(--cia-text-3)",flex:"none"},children:[l(c.value)," · ",p,"%",x!=null&&t.jsx("span",{style:{marginLeft:6},children:x<0?`−${Math.abs(x)}%`:x>0?`+${x}%`:"±0%"})]})]}),t.jsx("div",{role:"img","aria-label":`${c.label}: ${l(c.value)} (${p}%)${c.hint?` — ${c.hint}`:""}`,style:{height:8,borderRadius:"var(--cia-r-pill)",background:"var(--cia-bg-soft)",overflow:"hidden"},children:t.jsx("div",{className:"cia-funnel-relleno",style:{height:"100%",width:"100%",background:c.tone&&R_[c.tone]||"var(--cia-magnitud)",clipPath:`inset(0 ${100-u*100}% 0 0 round var(--cia-r-pill))`}})}),c.hint&&t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:4,lineHeight:1.45},children:c.hint})]},c.key)})})}const Ef=6,Vo=8,M_=600;function P_(e,a){let n=[];if(a&&a.length>0)n=a.map(r=>({...r,items:[...r.items]}));else{let r={key:"g0",items:[]};(e??[]).forEach((o,l)=>{o.separatorAbove&&r.items.length>0&&(n.push(r),r={key:`g${l}`,items:[]}),r.items.push(o)}),r.items.length>0&&n.push(r)}const s=[],i=n.map(r=>({...r,items:r.items.filter(o=>(o.danger&&s.push(o),!o.danger))})).filter(r=>r.items.length>0);return s.length>0&&i.push({key:"__destructivas",items:s}),i}function Af(e){return e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLocaleLowerCase()}function vn({trigger:e,iconTrigger:a,triggerClassName:n,triggerAriaLabel:s,items:i,groups:r,align:o="end",disabled:l,"aria-label":c,minWidth:d,onOpenChange:u}){const{t:p}=M("ds"),f=kj(),[x,h]=m.useState(!1),[b,g]=m.useState(null),v=m.useRef(null),y=m.useRef(null),k=m.useRef("first"),w=m.useRef({texto:"",hasta:0}),j=m.useId(),C=m.useMemo(()=>P_(i,r),[i,r]),N=C.some(D=>D.items.some(F=>F.icon)),S=D=>{h(D),u?.(D)},_=D=>{S(!1),g(null),D&&v.current?.focus()},R=D=>{k.current=D,S(!0)},A=()=>Array.from(y.current?.querySelectorAll('[role^="menuitem"]')??[]),E=(D,F)=>{const G=A();if(G.length===0)return;let te;if(D==="first")te=0;else if(D==="last")te=G.length-1;else{const B=G.indexOf(document.activeElement);te=B<0?D===1?0:G.length-1:(B+D+G.length)%G.length}G[te]?.focus(F)},I=D=>{const F=Date.now(),G=w.current;G.texto=F<G.hasta?G.texto+D:D,G.hasta=F+M_;const te=Af(G.texto),B=A(),ne=B.indexOf(document.activeElement),me=G.texto.length===1?ne+1:Math.max(ne,0);for(let Ee=0;Ee<B.length;Ee++){const L=B[(me+Ee)%B.length];if(L&&Af(L.dataset.label??"").startsWith(te)){L.focus();return}}};m.useLayoutEffect(()=>{if(!x)return;const D=v.current,F=y.current;if(!D||!F)return;const G=D.getBoundingClientRect(),te=F.getBoundingClientRect();let B=G.bottom+Ef,ne="bottom";B+te.height>window.innerHeight-Vo&&(B=Math.max(Vo,G.top-te.height-Ef),ne="top");let me=o==="end"?G.right-te.width:G.left;me=Math.max(Vo,Math.min(me,window.innerWidth-te.width-Vo)),g({top:B,left:me,side:ne})},[x,o,C]),m.useLayoutEffect(()=>{!x||!b||E(k.current,{preventScroll:!0})},[x,b===null]),m.useEffect(()=>{if(!x)return;const D=F=>{F.key!=="Escape"||F.defaultPrevented||(F.preventDefault(),F.stopPropagation(),_(!0))};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[x]),m.useEffect(()=>{if(!x)return;const D=F=>{const G=F.target;y.current?.contains(G)||v.current?.contains(G)||(S(!1),g(null))};return document.addEventListener("pointerdown",D,!0),()=>document.removeEventListener("pointerdown",D,!0)},[x]),m.useEffect(()=>{if(!x)return;const D=F=>{F.type==="scroll"&&F.target instanceof Node&&y.current?.contains(F.target)||(S(!1),g(null))};return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[x]);const P=D=>{if(!D.disabled){if(D.keepOpen){D.onSelect();return}_(!0),D.onSelect()}},O=D=>{D.key==="ArrowDown"?(D.preventDefault(),x?E("first"):R("first")):D.key==="ArrowUp"&&(D.preventDefault(),x?E("last"):R("last"))},K=D=>{switch(D.key){case"ArrowDown":D.preventDefault(),E(1);break;case"ArrowUp":D.preventDefault(),E(-1);break;case"Home":D.preventDefault(),E("first");break;case"End":D.preventDefault(),E("last");break;case"Tab":_(!0);break;default:D.key.length===1&&D.key!==" "&&!D.ctrlKey&&!D.metaKey&&!D.altKey&&I(D.key)}},W=typeof document<"u"?document.querySelector(".cia[data-theme]")?.getAttribute("data-theme")??void 0:void 0,V=o==="end"?"left":"right",U=D=>{const F=D.icon,G=D.type==="checkbox"||D.type==="radio",te=D.type==="checkbox"?"menuitemcheckbox":D.type==="radio"?"menuitemradio":"menuitem",B=t.jsxs("button",{type:"button",role:te,tabIndex:-1,
925className:"cia-ddm-item","data-label":D.label,"data-danger":D.danger?"":void 0,"aria-checked":G?!!D.checked:void 0,"aria-disabled":D.disabled||void 0,onClick:()=>P(D),onPointerMove:ne=>{ne.pointerType!=="touch"&&document.activeElement!==ne.currentTarget&&ne.currentTarget.focus({preventScroll:!0})},children:[N?t.jsx("span",{className:"cia-ddm-icon","aria-hidden":"true",children:F?t.jsx(F,{}):null}):null,t.jsxs("span",{className:"cia-ddm-text",children:[t.jsx("span",{className:"cia-ddm-label",children:D.label}),D.description?t.jsx("span",{className:"cia-ddm-desc",children:D.description}):null]}),D.trailing||G?t.jsxs("span",{className:"cia-ddm-trailing",children:[D.trailing,G?t.jsx("span",{className:"cia-ddm-check","aria-hidden":"true",children:D.checked?t.jsx(ct,{}):null}):null]}):null]});return t.jsx(m.Fragment,{children:D.disabled&&D.disabledReason?t.jsx(Ra,{label:D.disabledReason,position:V,children:B}):B},D.key)},X=x?t.jsx("div",{ref:y,className:"cia cia-ddm","data-theme":W,"data-open":b?"":void 0,role:"menu",id:j,"aria-label":c,onKeyDown:K,style:{position:"fixed",top:b?.top??0,left:b?.left??0,opacity:b?void 0:0,pointerEvents:b?void 0:"none",zIndex:"var(--cia-z-menu, 9100)",minWidth:d,transformOrigin:`${b?.side==="top"?"bottom":"top"} ${o==="end"?"right":"left"}`},children:C.map((D,F)=>t.jsxs(m.Fragment,{children:[F>0?t.jsx("div",{role:"separator",className:"cia-ddm-sep"}):null,t.jsxs("div",{role:"group",className:"cia-ddm-group","aria-labelledby":D.title?`${j}-${D.key}`:void 0,children:[D.title?t.jsx("div",{id:`${j}-${D.key}`,className:"cia-ddm-group-title","aria-hidden":"true",children:D.title}):null,D.items.map(U)]})]},D.key))}):null,ie=a?.size??f??"md",de=a?Nj(a.badge)!=null?p("iconButton.withBadge",{label:a.label,count:a.badge}):a.label:void 0,$={ref:v,type:"button",disabled:l,"aria-haspopup":"menu","aria-expanded":x,"aria-controls":x?j:void 0,onClick:()=>x?_(!1):R("first"),onKeyDown:O},z=a?t.jsx("button",{...$,...Cj({variant:a.variant,size:ie,shape:a.shape,className:n}),"aria-label":s??de,children:t.jsx(Sj,{icon:a.icon,badge:a.badge,badgeTone:a.badgeTone,size:ie,shape:a.shape})}):t.jsx("button",{...$,className:n,"aria-label":s??c,style:n?{position:"relative"}:{background:"none",border:0,padding:0,margin:0,font:"inherit",color:"inherit",display:"inline-flex",alignItems:"center",cursor:l?"default":"pointer",opacity:l?.6:1},children:e});return t.jsxs(t.Fragment,{children:[a?t.jsx(Ra,{label:a.label,children:z}):z,X&&typeof document<"u"?Ti.createPortal(X,document.body):X]})}function z_({src:e,resolveSrc:a,playLabel:n,errorLabel:s,className:i}){const[r,o]=m.useState(e??null),[l,c]=m.useState(e&&!a?"ready":"idle"),d=m.useRef(null),u=m.useCallback(async()=>{if(a){c("loading");try{const p=await a();o(p),c("ready"),requestAnimationFrame(()=>{d.current?.play().catch(()=>{})})}catch{c("error")}}},[a]);return l==="ready"&&r?t.jsx("audio",{ref:d,controls:!0,preload:"none",src:r,className:i,style:{width:"100%",height:36}}):l==="error"?t.jsxs("div",{className:i,style:{display:"flex",alignItems:"center",gap:6,fontSize:12,color:"var(--cia-bad-500)",fontFamily:"var(--cia-font-sans)"},role:"alert",children:[t.jsx(Tt,{size:13,"aria-hidden":"true"})," ",s]}):t.jsxs("button",{type:"button",onClick:u,disabled:l==="loading",className:i,style:{display:"inline-flex",alignItems:"center",gap:6,height:32,padding:"0 12px",borderRadius:"var(--cia-r-pill)",border:"1px solid var(--cia-border-2)",background:"var(--cia-bg-soft)",color:"var(--cia-text-2)",fontFamily:"var(--cia-font-sans)",fontSize:12.5,fontWeight:500,cursor:l==="loading"?"wait":"pointer"},children:[l==="loading"?t.jsx(je,{size:13,style:{animation:"spin 1s linear infinite"},"aria-hidden":"true"}):t.jsx(rn,{size:13,"aria-hidden":"true"}),n]})}const Rf=Object.freeze({"👍":"ok bien pulgar like dale bueno thumbs up good","👎":"mal no pulgar dislike thumbs down bad","🙏":"gracias favor porfa please thanks pray","👏":"aplauso bravo felicitaciones clap","🙌":"genial celebrar manos hands celebrate","🤝":"trato acuerdo mano handshake deal","👋":"hola chau saludo hi bye wave","✋":"esperá alto stop wait hand","💪":"fuerza animo strong muscle","🤙":"llamame dale call me","😀":"feliz sonrisa happy smile","😊":"contento amable gracias happy blush","😅":"ups nervios uf sweat","😂":"risa jaja lol laugh","🥰":"cariño amor love","😍":"encanta amor love heart eyes","🤔":"pensando duda hmm think","😐":"neutral serio neutral","😔":"triste pena sad","😢":"llorar triste cry","😡":"enojo bronca angry","😴":"sueño dormir sleep","🤯":"increible sorpresa mind blown","🙈":"verguenza ups oops monkey","✅":"listo hecho ok check done","❌":"no error mal cross wrong","⚠️":"atencion cuidado warning","❗":"importante urgente important","❓":"duda pregunta question","⏰":"hora tiempo reloj alarma time clock","📅":"fecha calendario cita calendar date","📍":"ubicacion lugar direccion location pin","📞":"llamar telefono call phone","📱":"celular movil mobile phone","✉️":"correo email mail","📎":"adjunto archivo attach clip","📄":"documento archivo document file","💳":"pago tarjeta payment card","💰":"plata dinero pago money","🧾":"factura recibo receipt invoice","🏠":"casa domicilio home house","🏥":"clinica hospital salud health","🚗":"auto carro coche car","🎉":"fiesta felicitaciones party congrats","❤️":"corazon amor gracias heart love","🔥":"fuego genial fire hot","⭐":"estrella favorito calificacion star","💡":"idea sugerencia idea tip","🔒":"seguro privado lock secure","🔗":"enlace link"}),D_=Object.freeze([{clave:"frecuentes",emojis:["👍","🙏","✅","😊","👋","❤️","😂","🎉"]},{clave:"gente",emojis:["😀","😊","😅","😂","🥰","😍","🤔","😐","😔","😢","😡","😴","🤯","🙈"]},{clave:"gestos",emojis:["👍","👎","🙏","👏","🙌","🤝","👋","✋","💪","🤙"]},{clave:"objetos",emojis:["⏰","📅","📍","📞","📱","✉️","📎","📄","💳","💰","🧾","🏠","🏥","🚗"]},{clave:"simbolos",emojis:["✅","❌","⚠️","❗","❓","🎉","❤️","🔥","⭐","💡","🔒","🔗"]}]);function I_({onPick:e,onClose:a,labels:n,embedded:s=!1}
925){const[i,r]=m.useState(""),o=m.useRef(null),l=m.useRef(null);m.useEffect(()=>{l.current?.focus();const u=f=>{f.key==="Escape"&&(f.stopPropagation(),a())},p=f=>{o.current&&!o.current.contains(f.target)&&a()};return document.addEventListener("keydown",u),document.addEventListener("mousedown",p),()=>{document.removeEventListener("keydown",u),document.removeEventListener("mousedown",p)}},[a]);const c=m.useMemo(()=>{const u=i.trim().toLowerCase();return u?Object.keys(Rf).filter(p=>Rf[p].includes(u)):null},[i]),d=u=>t.jsx("button",{type:"button",className:"cia-emoji-item",onClick:()=>{e(u),a()},title:u,children:u},u);return t.jsxs("div",{ref:o,className:s?"cia-emoji-content":"cia-emoji-panel",role:s?void 0:"dialog","aria-label":s?void 0:n.titulo,children:[t.jsx("input",{ref:l,type:"search",className:"cia-input cia-input-sm",value:i,onChange:u=>r(u.target.value),placeholder:n.buscar,"aria-label":n.buscar}),t.jsx("div",{className:"cia-emoji-scroll",children:c?c.length?t.jsx("div",{className:"cia-emoji-grid",children:c.map(d)}):t.jsx("p",{className:"cia-emoji-vacio",children:n.sinResultados}):D_.map(u=>t.jsxs("div",{children:[t.jsx("span",{className:"cia-emoji-grupo",children:n.grupos[u.clave]}),t.jsx("div",{className:"cia-emoji-grid",children:u.emojis.map(d)})]},u.clave))})]})}function _r(e){if(!isFinite(e)||e<0)return"--:--";const a=Math.floor(e/1e3),n=Math.floor(a/60),s=a%60;return`${String(n).padStart(2,"0")}:${String(s).padStart(2,"0")}`}const L_=[1,1.5,2];function F_({resolveSrc:e,onTimeUpdate:a,seekToMs:n,disabled:s,playOnSeek:i=!0}){const r=m.useRef(null),[o,l]=m.useState("idle"),[c,d]=m.useState(!1),[u,p]=m.useState(0),[f,x]=m.useState(0),[h,b]=m.useState(1),g=m.useRef(null),v=m.useCallback(async()=>{if(o==="ready")return!0;if(o==="loading")return!1;l("loading");try{const j=await e(),C=r.current;return C&&(C.src=j),l("ready"),!0}catch{return l("error"),!1}},[e,o]),y=m.useCallback(async()=>{if(s)return;const j=await v(),C=r.current;if(!(!j||!C))if(C.paused){const N=g.current;N!=null&&(C.currentTime=N/1e3,g.current=null),C.play().catch(()=>{})}else C.pause()},[s,v]);m.useEffect(()=>{!n||s||(async()=>{const j=await v(),C=r.current;if(!j||!C){g.current=n.ms;return}C.currentTime=n.ms/1e3,p(n.ms),i&&C.play().catch(()=>{})})()},[n?.nonce,s]),m.useEffect(()=>{const j=r.current;j&&(j.playbackRate=h)},[h]);const k=m.useCallback(j=>{const C=r.current;if(!C||!f||s)return;const N=Math.max(0,Math.min(f,j*f));C.currentTime=N/1e3,p(N)},[f,s]);return{mediaRef:r,state:o,playing:c,currentMs:u,durationMs:f,rate:h,setRate:b,togglePlay:y,seekByRatio:k,mediaHandlers:{onLoadedMetadata:j=>x((j.currentTarget.duration||0)*1e3),onTimeUpdate:j=>{const C=j.currentTarget.currentTime*1e3;p(C),a?.(C)},onPlay:()=>d(!0),onPause:()=>d(!1),onEnded:()=>d(!1)},progressPct:f>0?Math.min(100,u/f*100):0}}function O_({engine:e,disabled:a,playLabel:n,pauseLabel:s,errorLabel:i,speedLabel:r,unavailableLabel:o,bare:l,className:c}){const{state:d,playing:u,currentMs:p,durationMs:f,rate:x,setRate:h,togglePlay:b,seekByRatio:g,progressPct:v}=e;return t.jsx("div",{className:c,style:{display:"flex",alignItems:"center",gap:10,padding:l?"6px 2px 0":"8px 12px",borderRadius:l?0:"var(--cia-r)",border:l?0:"1px solid var(--cia-border)",background:l?"transparent":"var(--cia-bg-elev)",opacity:a?.55:1},children:d==="error"?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12.5,color:"var(--cia-bad-500)"},children:[t.jsx(Tt,{size:14,"aria-hidden":"true"})," ",i]}):a?t.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12.5,color:"var(--cia-text-3)"},children:o}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:b,"aria-label":u?s:n,disabled:d==="loading",style:{display:"grid",placeItems:"center",width:32,height:32,flex:"none",borderRadius:"50%",border:0,background:"var(--cia-brand-500)",color:"#fff",cursor:d==="loading"?"wait":"pointer"},children:d==="loading"?t.jsx(je,{size:15,style:{animation:"spin 1s linear infinite"},"aria-hidden":"true"}):u?t.jsx(Nc,{size:15,"aria-hidden":"true"}):t.jsx(rn,{size:15,"aria-hidden":"true"})}),t.jsx("div",{role:"slider","aria-label":n,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(v),tabIndex:0,onClick:y=>{const k=y.currentTarget.getBoundingClientRect();g((y.clientX-k.left)/k.width)},onKeyDown:y=>{y.key==="ArrowRight"&&g(Math.min(1,v/100+.02)),y.key==="ArrowLeft"&&g(Math.max(0,v/100-.02))},style:{position:"relative",flex:1,height:6,borderRadius:"var(--cia-r-pill)",background:"var(--cia-border)",cursor:"pointer"},children:t.jsx("div",{style:{position:"absolute",inset:0,width:`${v}%`,borderRadius:"var(--cia-r-pill)",background:"var(--cia-brand-500)",transition:"width 0.1s linear"}})}),t.jsxs("span",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)",flex:"none",minWidth:82,textAlign:"right"},children:[_r(p)," / ",_r(f)]}),t.jsx("div",{role:"group","aria-label":r,style:{display:"flex",gap:2,flex:"none"},children:L_.map(y=>t.jsxs("button",{type:"button",onClick:()=>h(y),"aria-pressed":x===y,style:{height:22,padding:"0 6px",borderRadius:"var(--cia-r-sm)",border:0,background:x===y?"var(--cia-bg-tint)":"transparent",color:x===y?"var(--cia-brand-500)":"var(--cia-text-3)",fontSize:10.5,fontWeight:700,cursor:"pointer"},children:[y,"×"]},y))})]})})}function $_({resolveSrc:e,onTimeUpdate:a,seekToMs:n,disabled:s,playLabel:i,pauseL
925abel:r,errorLabel:o,speedLabel:l,unavailableLabel:c,className:d,variant:u="default",seed:p}){const f=F_({resolveSrc:e,onTimeUpdate:a,seekToMs:n,disabled:s});return t.jsxs(t.Fragment,{children:[t.jsx("audio",{ref:f.mediaRef,preload:"none",hidden:!0,...f.mediaHandlers}),u==="voz"?t.jsx(W_,{engine:f,disabled:s,playLabel:i,pauseLabel:r,errorLabel:o,unavailableLabel:c,className:d,seed:p??""}):t.jsx(O_,{engine:f,disabled:s,playLabel:i,pauseLabel:r,errorLabel:o,speedLabel:l,unavailableLabel:c,className:d})]})}const hv=44;function q_(e,a){let n=5381+a;for(let s=0;s<e.length;s++)n=n*33^e.charCodeAt(s);return n>>>0}function B_(e){const a=[];for(let n=0;n<hv;n++)a.push(.22+q_(`${e}:${n}`,17)%100/100/1.28);return a}function W_({engine:e,disabled:a,playLabel:n,pauseLabel:s,errorLabel:i,unavailableLabel:r,className:o,seed:l}){const{state:c,playing:d,currentMs:u,durationMs:p,togglePlay:f,seekByRatio:x,progressPct:h}=e,b=B_(l),g=v=>{v.key==="ArrowRight"&&(v.preventDefault(),x(Math.min(1,h/100+.05))),v.key==="ArrowLeft"&&(v.preventDefault(),x(Math.max(0,h/100-.05)))};return t.jsx("div",{className:o,style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px 4px 4px",borderRadius:"var(--cia-r-pill)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-elev)",opacity:a?.55:1,maxWidth:260},children:c==="error"?t.jsx("span",{style:{fontSize:12,color:"var(--cia-bad-500)",padding:"0 6px"},children:i}):a?t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-3)",padding:"0 6px"},children:r}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:f,"aria-label":d?s:n,disabled:c==="loading",style:{display:"grid",placeItems:"center",width:30,height:30,flex:"none",borderRadius:"50%",border:0,background:"var(--cia-brand-500)",color:"#fff",cursor:c==="loading"?"wait":"pointer"},children:c==="loading"?t.jsx(je,{size:14,style:{animation:"spin 1s linear infinite"},"aria-hidden":"true"}):d?t.jsx(Nc,{size:13,"aria-hidden":"true"}):t.jsx(rn,{size:13,"aria-hidden":"true"})}),t.jsx("div",{role:"slider",tabIndex:0,"aria-label":n,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(h),"aria-valuetext":`${_r(u)} / ${_r(p)}`,onKeyDown:g,onClick:v=>{const y=v.currentTarget.getBoundingClientRect();x((v.clientX-y.left)/y.width)},"data-playing":d||void 0,className:"cia-voicebar-rail",style:{display:"flex",alignItems:"center",gap:1.5,height:22,flex:1,minWidth:80,cursor:"pointer"},children:b.map((v,y)=>{const k=y/hv*100<h;return t.jsx("span",{"data-played":k||void 0,className:"cia-voicebar-bar","aria-hidden":"true",style:{width:2,height:`${Math.round(v*100)}%`,borderRadius:1,flex:"none",background:k?"var(--cia-brand-500)":"var(--cia-border-strong)","--i":y}},y)})}),t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)",flex:"none",fontVariantNumeric:"tabular-nums"},children:_r(d||u>0?u:p)})]})})}function U_(e){let a=5381;for(let n=0;n<e.length;n++)a=a*33^e.charCodeAt(n);return a>>>0}const Tf=["var(--cia-brand-500)","var(--cia-cta-500)","var(--cia-sky-500)","var(--cia-ok-500)","var(--cia-brand-700)","var(--cia-cta-600)"];function V_(e){const a=U_(e||"?")%Tf.length;return Tf[a]}const K_={neutral:"var(--cia-text-3)",info:"var(--cia-sky-500)",success:"var(--cia-ok-500)",warning:"var(--cia-warn-500)",danger:"var(--cia-bad-500)"},H_={neutral:"var(--cia-text-2)",info:"var(--cia-info-ink)",success:"var(--cia-ok-ink)",warning:"var(--cia-warn-ink)",danger:"var(--cia-bad-ink)"},Q_={neutral:th,info:Mi,success:ct,warning:Qa,danger:nt};function at({label:e,tone:a="neutral",spinning:n,icon:s,pulse:i,size:r="sm",truncate:o,className:l,style:c}){const d=K_[a],u=H_[a],p=s===!1?null:s??Q_[a],f=n?"spinner":i?"pulse":p?"glyph":"dot";return t.jsxs("span",{className:l?`cia-pill ${l}`:"cia-pill","data-size":r,"data-mark":f,"data-truncate":o?"":void 0,title:o?e:void 0,style:{color:u,background:`color-mix(in oklab, ${d} 14%, transparent)`,border:`1px solid color-mix(in oklab, ${d} 30%, transparent)`,...c},children:[f==="spinner"?t.jsx("span",{className:"cia-pill-glyph cia-pill-spin","aria-hidden":"true",children:t.jsx(je,{})}):f==="glyph"&&p?t.jsx("span",{className:"cia-pill-glyph","aria-hidden":"true",children:t.jsx(p,{})}):t.jsx("span",{className:"cia-pill-dot","data-pulse":f==="pulse"?"":void 0,"aria-hidden":"true",style:{background:d,color:d}}),o?t.jsx("span",{className:"cia-pill-label",children:e}):e]})}const G_={saved:"var(--cia-ok-ink)",saving:"var(--cia-select-ink)",dirty:"var(--cia-warn-ink)",error:"var(--cia-bad-ink)"};function Z_({state:e}){const{t:a}=M("ds"),n={saved:{icon:ct,label:a("saveIndicator.saved")},saving:{icon:je,label:a("saveIndicator.saving")},dirty:{icon:qt,label:a("saveIndicator.dirty")},error:{icon:Tt,label:a("saveIndicator.error")}}[e],s=n.icon;return t.jsxs("span",{className:"cia-row cia-gap-2 cia-mono",role:"status",style:{fontSize:"var(--cia-fs-2xs)",color:G_[e],display:"inline-flex",alignItems:"center",gap:6,whiteSpace:"nowrap",flex:"none"},children:[t.jsx(s,{size:11,"aria-hidden":"true",className:e==="saving"?"cia-giro":void 0}),n.label]})}const Y_=e=>/\p{L}/u.test(e),X_={sm:28,md:34,lg:40},J_={ok:"var(--cia-ok-500)",warn:"var(--cia-warn-500)",bad:"var(--cia-bad-500)",neutral:"var(--cia-text-4)"};function eE(e){const a=(e||"").trim();if(!a)return"?";
925const n=a.split(/\s+/).filter(Boolean);return n.length===1?n[0][0].toUpperCase():(n[0][0]+n[n.length-1][0]).toUpperCase()}function Sn({name:e,src:a,initials:n,size:s="md",shape:i="circle",tone:r,status:o,statusLabel:l,className:c,style:d}){const[u,p]=m.useState(void 0),f=a!=null&&a===u,x=X_[s],h=r??V_(e||"?"),b=!!a&&!f,g=n??eE(e),v=Y_(g);return t.jsxs("span",{className:c,title:e,style:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",width:x,height:x,flex:"none",borderRadius:i==="circle"?"50%":"var(--cia-r)",overflow:"hidden",background:`color-mix(in srgb, ${h} 18%, var(--cia-bg-elev))`,border:`1.5px solid color-mix(in srgb, ${h} 45%, var(--cia-bg-elev))`,color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)",fontWeight:700,fontSize:Math.max(9,Math.round(x*.38)),letterSpacing:"var(--cia-tracking-tight)",userSelect:"none",...d},children:[b?t.jsx("img",{src:a??void 0,alt:"","aria-hidden":"true",onError:()=>p(a??void 0),style:{width:"100%",height:"100%",objectFit:"cover"}}):v?t.jsx("span",{"aria-hidden":"true",children:g}):t.jsx(En,{"aria-hidden":"true",size:Math.max(12,Math.round(x*.52)),strokeWidth:2}),o&&t.jsx("span",{role:l?"img":void 0,"aria-label":l,"aria-hidden":l?void 0:"true",style:{position:"absolute",right:-1,bottom:-1,width:Math.max(8,Math.round(x*.3)),height:Math.max(8,Math.round(x*.3)),borderRadius:"50%",background:J_[o],border:"2px solid var(--cia-bg-elev)",boxSizing:"content-box"}})]})}function tE({active:e=!0,label:a,className:n,style:s}){const{t:i}=M("ds"),r=a??i("typing.label");return t.jsxs("span",{role:"status","aria-label":r,className:n,style:{display:"inline-flex",alignItems:"center",gap:4,height:16,color:"var(--cia-text-3)",...s},children:[[0,1,2].map(o=>t.jsx("span",{"aria-hidden":"true",className:"cia-ti-dot","data-active":e||void 0,style:{width:6,height:6,borderRadius:"50%",background:"currentColor",opacity:.4,flex:"none",animationDelay:`${o*.16}s`}},o)),t.jsx("style",{children:`
926        @keyframes cia-ti-pulse {
927          0%, 55%, 100% { opacity: 0.4; transform: translateY(0); }
928          27% { opacity: 1; transform: translateY(-3px); }
929        }
930        .cia-ti-dot[data-active] { animation: cia-ti-pulse 1.15s ease-in-out infinite; }
931        @media (prefers-reduced-motion: reduce) {
932          @keyframes cia-ti-pulse-reduced {
933            0%, 55%, 100% { opacity: 0.4; }
934            27% { opacity: 1; }
935          }
936          .cia-ti-dot[data-active] { animation-name: cia-ti-pulse-reduced; }
937        }
938      `})]})}const mv="mas",fv=e=>`p:${e}`,xv=e=>`a:${e}`;function aE(e){const a=new Map;if(!e)return a;const n=e.querySelectorAll("[data-medida]");for(let s=0;s<n.length;s++){const i=n[s],r=i?.dataset.medida;i&&r&&a.set(r,i.getBoundingClientRect().width)}return a}function nE({ids:e,value:a,disponible:n,anchos:s,gap:i}){const r=c=>s.get(c)??0,o=[0];let l=0;if(e.forEach((c,d)=>{l+=r(fv(c))+(d>0?i:0),o.push(l)}),l<=n)return e.length;for(let c=e.length-1;c>=0;c--){const d=e.slice(c).includes(a),u=r(d?xv(a):mv);if((o[c]??0)+(c>0?i:0)+u<=n)return c}return 0}const Mf=6;function Pf({item:e,active:a,onClick:n,medida:s,tabIndex:i}){const r=e.icon;return t.jsxs("button",{"data-medida":s,type:"button","aria-pressed":a,onClick:n,tabIndex:i,"data-id":e.id,className:["cia-filterrail-pill",a?"cia-filterrail-pill--active":null,e.count!=null?"cia-filterrail-pill--count":null].filter(Boolean).join(" "),children:[r&&t.jsx(r,{"aria-hidden":"true"}),e.label,t.jsx(pc,{value:e.count,active:a})]})}function Nd({activo:e,textoMas:a}){return t.jsxs(t.Fragment,{children:[e?t.jsxs(t.Fragment,{children:[e.icon?t.jsx(e.icon,{"aria-hidden":"true"}):null,e.label,t.jsx(pc,{value:e.count,active:!0})]}):a,t.jsx(Ut,{className:"cia-filterrail-more-chevron","aria-hidden":"true"})]})}function sE({items:e,value:a,onChange:n,ariaLabel:s,layout:i="menu",moreLabel:r,className:o}){const{t:l}=M("ds"),c=m.useRef(null),d=m.useRef(null),[u,p]=m.useState(e.length),[f,x]=m.useState(void 0),h=N=>r?`${r} · ${N}`:l("filterRail.moreCount",{count:N}),b=m.useCallback(()=>{const N=c.current;if(!N||i!=="menu")return;const S=aE(d.current);p(nE({ids:e.map(_=>_.id),value:a,disponible:N.clientWidth,anchos:S,gap:Mf}))},[e,i,a]);m.useLayoutEffect(()=>{b()},[b]),m.useLayoutEffect(()=>{const N=c.current;if(!N||typeof ResizeObserver>"u"||i!=="menu")return;const S=new ResizeObserver(()=>b());S.observe(N),d.current&&S.observe(d.current);let _=!0;return document.fonts?.ready.then(()=>{_&&b()}).catch(()=>{}),()=>{_=!1,S.disconnect()}},[b,i]);const g=m.useCallback(()=>{const N=c.current;if(!N||i!=="scroll")return;const S=N.scrollLeft<=1,_=N.scrollLeft+N.clientWidth>=N.scrollWidth-1;x(S&&_?void 0:S?"end":_?"start":"both")},[i]);m.useLayoutEffect(()=>{const N=c.current;if(!N||i!=="scroll")return;const S=N.querySelector(`[data-id="${CSS.escape(a)}"]`);if(S){const R=S.offsetLeft-12,A=S.offsetLeft+S.offsetWidth+12-N.clientWidth;R<N.scrollLeft?N.scrollLeft=Math.max(0,R):A>N.scrollLeft&&(N.scrollLeft=A)}if(g(),typeof ResizeObserver>"u")return;const _=new ResizeObserver(g);return _.observe(N),()=>_.disconnect()},[i,a,e,g]);const v=i==="menu",y=v?e.slice(0,u):e,k=v?e.slice(u):[],w=k.find(N=>
938N.id===a)??null,j=m.useMemo(()=>k.map(N=>({key:N.id,label:N.label,icon:N.icon,type:"radio",checked:N.id===a,trailing:t.jsx(pc,{value:N.count,active:N.id===a}),onSelect:()=>n(N.id)})),[k,n,a]),C=w?l("filterRail.moreAriaActive",{label:w.label,count:k.length}):l("filterRail.moreAria",{count:k.length});return t.jsxs("div",{ref:c,role:"group","aria-label":s,className:["cia-filterrail",o].filter(Boolean).join(" "),"data-layout":i,"data-fade":i==="scroll"?f:void 0,onScroll:i==="scroll"?g:void 0,children:[v?t.jsx("div",{"aria-hidden":"true",inert:!0,style:{position:"absolute",top:0,left:0,right:0,height:0,overflow:"hidden",visibility:"hidden"},children:t.jsxs("div",{ref:d,style:{display:"flex",gap:Mf,width:"max-content"},children:[e.map(N=>t.jsx(Pf,{item:N,active:N.id===a,onClick:()=>{},tabIndex:-1,medida:fv(N.id)},N.id)),t.jsx("span",{className:"cia-filterrail-pill","data-medida":mv,children:t.jsx(Nd,{activo:null,textoMas:h(Math.max(e.length-1,1))})}),e.map(N=>t.jsx("span",{className:"cia-filterrail-pill cia-filterrail-pill--active","data-medida":xv(N.id),children:t.jsx(Nd,{activo:N,textoMas:""})},`a:${N.id}`))]})}):null,y.map(N=>t.jsx(Pf,{item:N,active:N.id===a,onClick:()=>n(N.id)},N.id)),k.length>0&&t.jsx(vn,{align:"end","aria-label":r??l("filterRail.more"),triggerAriaLabel:C,triggerClassName:w?"cia-filterrail-pill cia-filterrail-pill--active":"cia-filterrail-pill",items:j,trigger:t.jsx(Nd,{activo:w,textoMas:h(k.length)})})]})}const zf=560;function iE({items:e,onSelect:a,collapsedWidth:n=220,disabled:s,ariaLabel:i,className:r}){const o=m.useRef(null),l=m.useRef(new Map),c=m.useRef(new Map),[,d]=m.useState(0),[u,p]=m.useState(new Set),[f,x]=m.useState(!1),[h,b]=m.useState(!1),g=m.useRef(null),v=m.useRef(0),y=typeof window<"u"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1,k=m.useCallback(()=>{for(const[S,_]of l.current)c.current.set(S,_.getBoundingClientRect().width+(_.scrollWidth-_.clientWidth)+1);d(S=>S+1)},[]);m.useEffect(()=>{k(),typeof document<"u"&&"fonts"in document&&document.fonts.ready.then(k).catch(()=>{})},[e,k]),m.useEffect(()=>{const S=o.current;if(!S||typeof ResizeObserver>"u")return;const _=new ResizeObserver(()=>k());return _.observe(S),()=>_.disconnect()},[k]);const w=m.useCallback(()=>{const S=o.current;S&&(x(S.scrollLeft>4),b(S.scrollLeft+S.clientWidth<S.scrollWidth-4))},[]);m.useEffect(()=>{w()},[e,w]);const j=S=>{const _=o.current;_&&(v.current=Date.now()+zf,_.scrollBy({left:S*240,behavior:y?"auto":"smooth"}),window.setTimeout(w,zf))},C=S=>_=>{const R=Date.now(),A=g.current,E=R<v.current&&!!A&&A.x===_.clientX&&A.y===_.clientY;g.current={x:_.clientX,y:_.clientY},!E&&p(I=>new Set(I).add(S))},N=()=>p(new Set);return t.jsxs("div",{role:"group","aria-label":i,className:r,style:{display:"flex",alignItems:"center",gap:2,minWidth:0},onMouseLeave:N,children:[t.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",onClick:()=>j(-1),style:{flex:"none",visibility:f?"visible":"hidden",display:"grid",placeItems:"center",width:22,height:22,borderRadius:"50%",border:"1px solid var(--cia-border-2)",background:"var(--cia-bg-elev)",color:"var(--cia-text-3)",cursor:"pointer"},children:t.jsx(gn,{size:13,"aria-hidden":"true"})}),t.jsx("div",{ref:o,className:"cia-scroll cia-scroll-x",onScroll:w,style:{display:"flex",gap:6,overflowX:"auto",scrollSnapType:"x proximity",minWidth:0,padding:"2px 1px"},children:e.map(S=>{const _=u.has(S.id),R=c.current.get(S.id);return t.jsx("button",{ref:A=>{A?l.current.set(S.id,A):l.current.delete(S.id)},type:"button",title:S.text,disabled:s,onMouseEnter:C(S.id),onFocus:()=>p(A=>new Set(A).add(S.id)),onClick:()=>a(S.text,S),style:{flex:"none",scrollSnapAlign:"start",maxWidth:_&&R?R:n,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",height:28,padding:"0 11px",borderRadius:"var(--cia-r-pill)",border:"1px solid var(--cia-border-2)",background:"var(--cia-bg-soft)",color:"var(--cia-text-2)",fontSize:12.5,fontFamily:"inherit",cursor:s?"default":"pointer",opacity:s?.5:_?1:.82,transition:y?"none":"max-width 220ms var(--cia-ease-out-expo), opacity 150ms ease"},children:S.text},S.id)})}),t.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",onClick:()=>j(1),style:{flex:"none",visibility:h?"visible":"hidden",display:"grid",placeItems:"center",width:22,height:22,borderRadius:"50%",border:"1px solid var(--cia-border-2)",background:"var(--cia-bg-elev)",color:"var(--cia-text-3)",cursor:"pointer"},children:t.jsx(ca,{size:13,"aria-hidden":"true"})})]})}function Df(e){return Array.from(e.querySelectorAll('a[href],button:not([disabled]),input
938:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'))}function rE({open:e,onClose:a,ariaLabel:n,children:s,toolbar:i,onPrev:r,onNext:o,prevDisabled:l,nextDisabled:c,prevLabel:d,nextLabel:u}){const{t:p}=M("ds"),f=m.useRef(null),x=m.useRef(null);if(m.useEffect(()=>{if(!e)return;x.current=document.activeElement;const y=document.body.style.overflow;document.body.style.overflow="hidden";const k=j=>{if(j.key==="Escape"){a();return}if(j.key==="ArrowLeft"&&r&&!l){r();return}if(j.key==="ArrowRight"&&o&&!c){o();return}if(j.key==="Tab"){const C=f.current;if(!C)return;const N=Df(C);if(N.length===0){j.preventDefault();return}const S=N[0],_=N[N.length-1];j.shiftKey&&document.activeElement===S?(j.preventDefault(),_.focus()):!j.shiftKey&&document.activeElement===_&&(j.preventDefault(),S.focus())}};window.addEventListener("keydown",k);const w=requestAnimationFrame(()=>{(f.current&&Df(f.current)[0])?.focus()});return()=>{window.removeEventListener("keydown",k),document.body.style.overflow=y,cancelAnimationFrame(w),x.current?.focus?.()}},[e,a,r,o,l,c]),!e)return null;const h=typeof document<"u"?document.querySelector(".cia[data-theme]")?.getAttribute("data-theme")??void 0:void 0,b=typeof window<"u"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1,g=y=>{const k=y==="prev"?l:c,w=y==="prev"?r:o;if(!w)return null;const j=y==="prev"?gn:ca,C=y==="prev"?d??p("lightbox.prev"):u??p("lightbox.next");return t.jsx("button",{type:"button",onClick:w,disabled:k,"aria-label":C,title:C,style:{position:"absolute",top:"50%",[y==="prev"?"left":"right"]:14,transform:"translateY(-50%)",width:44,height:44,borderRadius:"50%",border:"1px solid rgba(255,255,255,0.28)",background:"rgba(255,255,255,0.12)",color:"#fff",display:"grid",placeItems:"center",cursor:k?"default":"pointer",opacity:k?.35:1},children:t.jsx(j,{size:20,"aria-hidden":"true"})})},v=t.jsxs("div",{className:"cia","data-theme":h,role:"dialog","aria-modal":"true","aria-label":n,style:{position:"fixed",inset:0,zIndex:9300,display:"flex",flexDirection:"column",background:"var(--cia-lightbox-bg)",animation:b?"none":"cia-lightbox-in var(--cia-dur-fast) ease"},onClick:a,children:[i&&t.jsx("div",{style:{flex:"none",padding:"12px 68px 12px 16px",minHeight:68,display:"flex",alignItems:"center",gap:8,color:"#fff"},onClick:y=>y.stopPropagation(),children:i}),t.jsxs("div",{ref:f,style:{position:"relative",flex:1,minHeight:0,display:"flex",alignItems:"center",justifyContent:"center"},onClick:y=>y.stopPropagation(),children:[g("prev"),s,g("next")]}),t.jsx("button",{type:"button",onClick:a,"aria-label":p("lightbox.close"),title:p("lightbox.close"),style:{position:"absolute",top:14,right:14,width:40,height:40,borderRadius:"50%",border:"1px solid rgba(255,255,255,0.28)",background:"rgba(255,255,255,0.12)",color:"#fff",display:"grid",placeItems:"center",cursor:"pointer"},children:t.jsx(nt,{size:18,"aria-hidden":"true"})}),t.jsx("style",{children:`
939        @keyframes cia-lightbox-in { from { opacity: 0; } to { opacity: 1; } }
940        @media (prefers-reduced-motion: reduce) {
941          .cia [role="dialog"] { animation: none !important; }
942        }
943      `})]});return typeof document<"u"?Ti.createPortal(v,document.body):v}const Wu=new Set;let oE=0;function pa(e){return new Promise(a=>{const n={id:++oE,resolve:a,...e};Wu.forEach(s=>s(n))})}function lE(){const{t:e}=M("ds"),[a,n]=m.useState([]),[s,i]=m.useState(!1),[r,o]=m.useState(null);m.useEffect(()=>{const p=f=>n(x=>[...x,f]);return Wu.add(p),()=>{Wu.delete(p)}},[]);const l=a[0]??null,c=()=>n(p=>p.slice(1)),d=()=>{s||(l?.resolve(!1),o(null),c())},u=async()=>{if(l){if(!l.onConfirm){l.resolve(!0),o(null),c();return}i(!0),o(null);try{await l.onConfirm(),l.resolve(!0),i(!1),c()}catch(p){i(!1),o(p?.response?.data?.message||p?.message||e("confirmDialog.genericError"))}}};return l?t.jsxs(ot,{open:!0,onClose:d,title:l.title??e("confirmDialog.defaultTitle"),hideClose:!0,footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{variant:"ghost",onClick:d,disabled:s,"data-cia-autofocus":l.danger?"":void 0,children:l.cancelLabel??e("confirmDialog.cancel")}),t.jsx(Ie,{variant:l.danger?"danger":"primary",onClick:u,loading:s,children:l.confirmLabel??e("confirmDialog.confirm")})]}),children:[t.jsx("div",{style:{fontSize:13.5,color:"var(--cia-text-2)",lineHeight:1.5},children:l.message}),r&&t.jsx("div",{role:"alert",style:{marginTop:12,padding:"8px 10px",borderRadius:"var(--cia-r-sm)",background:"color-mix(in oklab, var(--cia-bad-500) 10%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-bad-500) 26%, transparent)",color:"var(--cia-bad-ink)",fontSize:12.5,lineHeight:1.4},children:r})]}):null}function Rs({title:e,icon:a,hint:n,aside:s,children:i,className:r,style:o}){const l=m.useId();return t.jsxs("section",{className:r?`cia-detail-section ${r}`:"cia-detail-section","aria-labelledby":l,style:o,children:[t.jsxs("div",{className:"cia-detail-section-head",children:[a?t.jsx(a,{size:14,"aria-hidden":"true",className:"cia-detail-section-icon"}):null,t.jsx("h3",{id:l,className:"cia-detail-section-title",children:e}),n?t.jsx(Ra,{label:n,children:t.jsx("span",{className:"cia-detail-section-hint",tabIndex:0,role:"img","aria-label":n,children:t.jsx(Mi,{size:13,"aria-hidden":"true"})})}):null,t.jsx("span",{className:"cia-detail-section-spacer"}),s?t.jsx("div",{className:"cia-detail-section-aside",children:s}):null]}),i?t.jsx("div",{className:"cia-detail-section-body",children:i}):null]})}function Zt({label:e,children:a,action:n,mono:s,inline:i}){return t.jsxs("div",{className:i?"cia-detail-row cia-detail-row--inline":"cia-detail-row",children:[t.jsxs("div",{className:"cia-detail-row-text",children:[t.jsx("div",{className:"cia-detail-row-label",children:e}),t.jsx("div",{className:s?"cia-detail-row-value cia-mono":"cia-detail-row-value",children:a})]}),n?t.jsx("div",{className:"cia-detail-row-action",children:n}):null]})}
943function Ws({title:e,subtitle:a,meta:n,leading:s,icon:i,tone:r,trailing:o,variant:l="plain",size:c="md",subtitleMono:d,tooltip:u,className:p,style:f}){const x=["cia-entity-row",`cia-entity-row--${l}`,`cia-entity-row--${c}`,p].filter(Boolean).join(" "),h=s??(i?t.jsx("span",{className:"cia-entity-row-tile","aria-hidden":"true",style:{"--cia-entity-tone":r??"var(--cia-brand-500)"},children:t.jsx(i,{size:c==="lg"?18:c==="sm"?13:15})}):null);return t.jsxs("div",{className:x,style:f,title:u,children:[h?t.jsx("div",{className:"cia-entity-row-leading",children:h}):null,t.jsxs("div",{className:"cia-entity-row-text",children:[t.jsx("div",{className:"cia-entity-row-title",children:e}),a?t.jsx("div",{className:d?"cia-entity-row-subtitle cia-mono":"cia-entity-row-subtitle",children:a}):null,n?t.jsx("div",{className:"cia-entity-row-meta",children:n}):null]}),o?t.jsx("div",{className:"cia-entity-row-trailing",children:o}):null]})}function kl({value:e,label:a,copiedLabel:n,size:s="sm"}){const[i,r]=m.useState(!1),o=m.useRef(null);m.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const l=n??he.t("ds:copyField.copied");async function c(){try{await navigator.clipboard.writeText(e),r(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>r(!1),1600)}catch{}}return t.jsxs(t.Fragment,{children:[t.jsx(Lt,{icon:i?t.jsx(ct,{size:14}):t.jsx(bn,{size:14}),label:i?l:a,size:s,variant:"ghost",tone:i?"ok":"default",onClick:()=>void c()}),t.jsx("span",{role:"status",style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},children:i?l:""})]})}function cE({filters:e,onClearAll:a,clearAllLabel:n,focusAfterClearRef:s,"aria-label":i,className:r}){const{t:o}=M("ds"),l=m.useRef(null),c=m.useRef(null);return m.useEffect(()=>{const d=c.current;if(d==null)return;c.current=null;const u=l.current?.querySelectorAll(".cia-filter-chip-remove");!u||u.length===0||u[Math.min(d,u.length-1)]?.focus()},[e]),e.length===0?null:t.jsxs("ul",{ref:l,className:["cia-activefilters",r].filter(Boolean).join(" "),"aria-label":i??o("activeFilters.aria"),children:[e.map((d,u)=>{const p=d.label?`${d.label}: ${d.value}`:d.value;return t.jsx("li",{children:t.jsxs("span",{className:"cia-filter-chip",title:p,children:[d.tone!==void 0&&d.tone!==null?t.jsx("span",{className:"cia-filter-chip-dot","aria-hidden":"true",style:{background:Zy(d.tone)}}):null,d.label?t.jsxs("span",{className:"cia-filter-chip-label",children:[d.label,":"]}):null,t.jsx("span",{className:"cia-filter-chip-value",children:d.value}),t.jsx("button",{type:"button",className:"cia-filter-chip-remove","aria-label":o("activeFilters.remove",{label:p}),onClick:()=>{e.length===1?s?.current?.focus():c.current=u,d.onRemove()},children:t.jsx(nt,{"aria-hidden":"true"})})]})},d.key)}),a?t.jsx("li",{children:t.jsx(Ie,{size:"sm",variant:"ghost",onClick:()=>{s?.current?.focus(),a()},children:n??o("activeFilters.clearAll")})}):null]})}function Nl({title:e,description:a,icon:n,status:s,control:i,disabled:r=!1,disabledReason:o,foot:l,dependent:c=!1,className:d,style:u}){const p=m.useId(),f=`${p}-titulo`,x=`${p}-desc`,h=`${p}-pie`,b=`${p}-motivo`,g=`${p}-control`,v=r&&!!o,y=m.useRef(null);m.useEffect(()=>{});const k=[a?x:null,l?h:null,v?b:null].filter(Boolean).join(" ")||void 0,w=m.useMemo(()=>({labelId:f,describedBy:k,controlId:g,disabled:r,disabledReason:v?o:void 0}),[f,k,g,r,v,o]),j=typeof i=="function"?i({labelId:f,descId:k,controlId:g,disabled:r}):i,C=t.jsx("span",{className:"cia-setting-row-control","data-disabled":r?"":void 0,children:j});return t.jsxs("div",{ref:y,className:d?`cia-setting-row ${d}`:"cia-setting-row","data-icon":n&&!c?"":void 0,"data-dependent":c?"":void 0,"data-disabled":r?"":void 0,style:u,children:[t.jsxs("div",{className:"cia-setting-row-main",children:[n&&!c?t.jsx("span",{className:"cia-setting-row-icon","aria-hidden":"true",children:t.jsx(n,{})}):null,t.jsxs("div",{className:"cia-setting-row-text",children:[t.jsxs("div",{className:"cia-setting-row-head",children:[t.jsx("label",{id:f,htmlFor:g,className:"cia-setting-row-title",children:e}),s?t.jsx("span",{className:"cia-setting-row-status",children:s}):null]}),a?t.jsx("p",{id:x,className:"cia-setting-row-desc",children:a}):null]}),t.jsx(_j.Provider,{value:w,children:v?t.jsx(Ra,{label:o,children:C}):C}),l?t.jsx("div",{id:h,className:"cia-setting-row-foot",children:l}):null]}),v?t.jsx("span",{id:b,className:"cia-sr-only",children:o}):null]})}function as({title:e,description:a,icon:n,aside:s,children:i,footer:r,headingLevel:o=2,className:l,style:c}
943){const d=m.useId(),u=o===3?"h3":"h2";return t.jsxs("section",{className:l?`cia-settings-section ${l}`:"cia-settings-section","aria-labelledby":`${d}-titulo`,style:c,children:[t.jsxs("div",{className:"cia-settings-section-head",children:[t.jsxs("div",{className:"cia-settings-section-titles",children:[t.jsxs(u,{id:`${d}-titulo`,className:"cia-settings-section-title",children:[n?t.jsx(n,{"aria-hidden":"true"}):null,t.jsx("span",{children:e})]}),a?t.jsx("p",{className:"cia-settings-section-desc",children:a}):null]}),s?t.jsx("div",{className:"cia-settings-section-aside",children:s}):null]}),t.jsx("div",{className:"cia-settings-section-panel",children:i}),r?t.jsx("div",{className:"cia-settings-section-foot",children:r}):null]})}const dE=600;function uE({visible:e,state:a,message:n,onSave:s,onDiscard:i,saveLabel:r,discardLabel:o,saveVariant:l="primary",extraActions:c,ariaLabel:d,focusAfterHideRef:u}){const{t:p}=M("ds"),[f,x]=m.useState(e?"abierta":"oculta"),h=m.useRef(f);h.current=f;const b=m.useRef(null),g=m.useRef(null),v=m.useRef(!1),y=m.useRef(null),k=()=>{const S=u?.current;if(S?.isConnected)return S;const _=y.current;return _?.isConnected?_:null},w=()=>v.current&&(document.activeElement===null||document.activeElement===document.body);if(m.useLayoutEffect(()=>{if(e){x("abierta");return}if(h.current!=="abierta")return;const S=b.current;S&&(S.contains(document.activeElement)||w())&&(k()?.focus({preventScroll:!0}),v.current=S.contains(document.activeElement)),x("cerrando")},[e]),m.useLayoutEffect(()=>{a!=="saved"||!w()||((k()??g.current)?.focus({preventScroll:!0}),v.current=!!b.current?.contains(document.activeElement))},[a]),m.useEffect(()=>{if(f!=="cerrando")return;const S=window.setTimeout(()=>x("oculta"),dE);return()=>window.clearTimeout(S)},[f]),f==="oculta")return null;const j=a,C=a==="saving",N=a==="saved";return t.jsx("div",{className:"cia-savebar",role:"region","aria-label":d??p("saveBar.region"),children:t.jsxs("div",{ref:b,className:"cia-savebar-inner","data-state":f==="cerrando"?"closing":"open",inert:f==="cerrando"||void 0,onAnimationEnd:S=>{S.target===S.currentTarget&&f==="cerrando"&&x("oculta")},onFocus:S=>
943{if(!v.current){const _=S.relatedTarget;y.current=_ instanceof HTMLElement&&!S.currentTarget.contains(_)?_:null}v.current=!0},onBlur:S=>{if(!S.target.isConnected)return;const _=S.relatedTarget;v.current=_ instanceof Node&&S.currentTarget.contains(_)},children:[t.jsxs("div",{ref:g,className:"cia-savebar-status",tabIndex:-1,children:[t.jsx(Z_,{state:j}),n?t.jsx("span",{className:"cia-savebar-message","data-tone":a==="error"?"bad":void 0,children:n}):null]}),N?null:t.jsxs("div",{className:"cia-savebar-actions",children:[i?t.jsx(Ie,{variant:"ghost",onClick:i,disabled:C,disabledReason:C?p("saveBar.savingReason"):void 0,children:o??p("saveBar.discard")}):null,c,t.jsx(Ie,{variant:l,loading:C,onClick:()=>s(),children:r??p("saveBar.save")})]})]})})}const pE=.9;function hE(e,a){return!a||a<=0?"ok":e>=a?"bad":e/a>=pE?"warn":"ok"}function KB(e,a){const n=a-1;return n<=0?-1:e>0?Math.min(e-1,n-1):0}function HB(e,a,n){return!n&&e<a}function mE(e){return e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey}function fE({title:e,items:a,collapsedWhenDone:n=!0,doneLabel:s,className:i,style:r}){const{t:o}=M("ds"),l=m.useId(),[c,d]=m.useState(!1),u=a.filter(v=>!v.optional),p=u.length,f=u.filter(v=>v.done).length,x=p>0&&f===p,h=x&&n&&!c,b=["cia-setup",x?"cia-setup--done":null,i].filter(Boolean).join(" ");if(a.length===0)return null;const g=t.jsx("ol",{id:`${l}-pasos`,className:"cia-setup-items",children:a.map(v=>t.jsxs("li",{className:"cia-setup-item","data-done":v.done?"":void 0,"data-optional":v.optional?"":void 0,children:[t.jsx("span",{className:"cia-setup-mark","aria-hidden":"true",children:v.done?t.jsx(Nt,{}):v.optional?t.jsx(kS,{}):t.jsx(CS,{})}),t.jsxs("div",{className:"cia-setup-text",children:[t.jsxs("span",{className:"cia-setup-label",children:[t.jsxs("span",{className:"cia-sr-only",children:[v.done?o("setupChecklist.itemDone"):v.optional?o("setupChecklist.itemOptional"):o("setupChecklist.itemPending"),":"," "]}),v.label,v.optional&&!v.done?t.jsx("span",{className:"cia-setup-optional","aria-hidden":"true",children:o("setupChecklist.optional")}):null]}),v.description?t.jsx("span",{className:"cia-setup-desc",children:v.description}):null]}),!v.done&&v.action?v.action.href!==void 0?t.jsx(xE,{accion:v.action,avisoExterno:o("setupChecklist.opensNewTab")}):t.jsx(Ie,{size:"sm",variant:"outline",className:"cia-setup-action",onClick:v.action.onClick,children:v.action.label}):null]},v.id))});return x&&n?t.jsxs("section",{className:b,"aria-labelledby":`${l}-titulo`,style:r,children:[t.jsxs("div",{className:"cia-setup-summary",children:[t.jsx("span",{className:"cia-setup-summary-mark","aria-hidden":"true",children:t.jsx(Nt,{})}),t.jsxs("h3",{id:`${l}-titulo`,className:"cia-setup-summary-text",children:[s??o("setupChecklist.done"),t.jsxs("span",{className:"cia-setup-summary-count",children:[" · ",f,"/",p]}),t.jsxs("span",{className:"cia-sr-only",children:[" — ",e]})]}),t.jsxs(Ie,{variant:"ghost",size:"sm",className:"cia-setup-toggle","aria-expanded":!h,"aria-controls":`${l}-pasos`,onClick:()=>d(v=>!v),children:[o(h?"setupChecklist.showSteps":"setupChecklist.hideSteps"),t.jsx("span",{className:"cia-setup-chevron","data-open":h?void 0:"","aria-hidden":"true",children:t.jsx(Ut,{})})]})]}),h?null:g]}):t.jsxs("section",{className:b,"aria-labelledby":`${l}-titulo`,style:r,children:[t.jsxs("div",{className:"cia-setup-head",children:[t.jsx("span",{className:"cia-setup-ring","aria-hidden":"true",children:t.jsx(F5,{value:p?f/p:0,size:44,thickness:4,tone:x?"ok":"brand",centerTop:t.jsxs("span",{className:"cia-setup-ring-num",children:[f,"/",p]})})}),t.jsxs("div",{className:"cia-setup-titles",children:[t.jsx("h3",{id:`${l}-titulo`,className:"cia-setup-title",children:e}),t.jsx("span",{className:"cia-setup-progress",children:o("setupChecklist.progress",{done:f,total:p})})]})]}),g]})}function xE({accion:e,avisoExterno:a}){const{href:n,label:s,onClick:i,external:r}=e;return t.jsxs("a",{className:"cia-btn cia-button cia-btn-outline cia-btn-sm cia-setup-action","data-size":"sm",href:n,target:r?"_blank":void 0,rel:r?"noopener noreferrer":void 0,onClick:o=>{!r&&!mE(o)||i?.(o)},children:[s,r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"cia-btn-glyph","aria-hidden":"true",children:t.jsx(Ja,{})}),t.jsxs("span",{className:"cia-sr-only",children:[" (",a,")"]})]}):null]})}
943function gv({id:e,label:a,required:n,description:s,error:i,valueLength:r,maxLength:o,counter:l,disabled:c,className:d,style:u,children:p}){const{t:f}=M("ds"),x=hE(r,o);return t.jsxs("div",{className:d?`cia-field ${d}`:"cia-field","data-invalid":i?"":void 0,"data-disabled":c?"":void 0,style:u,children:[a?t.jsxs("label",{className:"cia-field-label",htmlFor:e,children:[a,n?t.jsx("span",{className:"cia-field-required","aria-hidden":"true",children:" *"}):null]}):null,p,s||i||l?t.jsxs("div",{className:"cia-field-foot",children:[t.jsxs("div",{className:"cia-field-notes",children:[s?t.jsx("p",{id:`${e}-ayuda`,className:"cia-field-desc",children:s}):null,i?t.jsxs("p",{id:`${e}-error`,className:"cia-field-error",children:[t.jsx(Qg,{"aria-hidden":"true"}),t.jsx("span",{children:i})]}):null]}),l?t.jsx("span",{className:"cia-field-counter","data-nivel":x==="ok"?void 0:x,"aria-hidden":"true",children:o?`${r} / ${o}`:r}):null]}):null,o?t.jsxs(t.Fragment,{children:[t.jsx("span",{id:`${e}-tope`,className:"cia-sr-only",children:f("field.maxChars",{max:o})}),t.jsxs("span",{className:"cia-sr-only","aria-live":"polite",children:[l&&x==="warn"?f("field.nearLimit",{max:o}):null,l&&x==="bad"?f("field.atLimit",{max:o}):null]})]}):null]})}function bv(e,a){return[a.description?`${e}-ayuda`:null,a.error?`${e}-error`:null,a.maxLength?`${e}-tope`:null].filter(Boolean).join(" ")||void 0}function Lc({value:e,onChange:a,label:n,description:s,error:i,maxLength:r,counter:o,placeholder:l,mono:c,disabled:d,required:u,id:p,ariaLabel:f,autoFocus:x,onBlur:h,onKeyDown:b,inputRef:g,type:v="text",autoComplete:y,name:k,size:w="lg",className:j,style:C}){const N=m.useId(),S=p??N;return t.jsx(gv,{id:S,label:n,required:u,description:s,error:i,valueLength:e.length,maxLength:r,counter:o,disabled:d,className:j,style:C,children:t.jsx("input",{ref:g,id:S,type:v,name:k,className:"cia-input cia-field-input","data-size":w,"data-mono":c?"":void 0,value:e,onChange:_=>a(_.target.value),onBlur:h,onKeyDown:b,placeholder:l,maxLength:r,disabled:d,required:u,"aria-required":u||void 0,"aria-invalid":i?!0:void 0,"aria-label":n?void 0:f,"aria-describedby":bv(S,{description:s,error:i,maxLength:r}),autoFocus:x,autoComplete:y,spellCheck:c?!1:void 0})})}function yv({value:e,onChange:a,label:n,description:s,error:i,maxLength:r,counter:o,placeholder:l,mono:c,disabled:d,required:u,id:p,ariaLabel:f,autoFocus:x,onBlur:h,onKeyDown:b,inputRef:g,rows:v=3,autoGrow:y,name:k,size:w="lg",className:j,style:C}){const N=m.useId(),S=p??N,_=m.useRef(null);m.useLayoutEffect(()=>{const A=_.current;!y||!A||If(A)},[e,y]),m.useEffect(()=>{const A=_.current;if(!y||!A||typeof ResizeObserver>"u")return;let E=A.clientWidth;const I=new ResizeObserver(()=>{A.clientWidth!==E&&(E=A.clientWidth,If(A))});return I.observe(A),()=>I.disconnect()},[y]);const R=A=>{_.current=A,typeof g=="function"?g(A):g&&typeof g=="object"&&(g.current=A)};return t.jsx(gv,{id:S,label:n,required:u,description:s,error:i,valueLength:e.length,maxLength:r,counter:o,disabled:d,className:j,style:C,children:t.jsx("textarea",{ref:R,id:S,name:k,className:"cia-input cia-field-input cia-field-textarea","data-size":w,"data-mono":c?"":void 0,"data-autogrow":y?"":void 0,rows:v,value:e,onChange:A=>a(A.target.value),onBlur:h,onKeyDown:b,placeholder:l,maxLength:r,disabled:d,required:u,"aria-required":u||void 0,"aria-invalid":i?!0:void 0,"aria-label":n?void 0:f,"aria-describedby":bv(S,{description:s,error:i,maxLength:r}),autoFocus:x,spellCheck:c?!1:void 0})})}function If(e){e.style.overflowY="hidden",e.style.height="auto",e.style.height=`${e.scrollHeight+(e.offsetHeight-e.clientHeight)}px`,e.style.overflowY=e.scrollHeight-e.clientHeight>1?"":"hidden"}function Lf({collapsed:e}){const{t:a}=M("nav");return t.jsx("span",{className:"cia-dot cia-dot-pulse","aria-label":a("labels.liveDot"),style:{width:6,height:6,color:"var(--cia-ok-500)",position:e?"absolute":"static",top:e?6:"auto",right:e?6:"auto"}})}function gE(){const{t:e}=M("nav"),{can:a}=tt(),n=a("billing.manage"),{data:s,isLoading:i}=se({queryKey:["plan-usage"],queryFn:async()=>(await T.get("/organizations/me/plan-usage")).data,staleTime:6e4}),{data:r}=se({queryKey:C2,queryFn:async()=>(await T.get("/organizations/me/channels")).data,staleTime:15e3,refetchInterval:2e4});if(!i&&!s?.plan)return null;const o=s?.usage?.cycleStart?new Date(s.usage.cycleStart).toLocaleDateString("es-CO",{month:"long"}):new Date().toLocaleDateString("es-CO",{month:"long"});if(i)return t.jsxs("div",{className:"cia-usage-card",style:{marginTop:0},children:[t.jsx("div",{className:"cia-skeleton",style:{height:10,width:"60%",marginBottom:8}}),t.jsx("div",{className:"cia-skeleton",style:{height:10,width:"45%",marginBottom:8}}),t.jsx("div",{className:"cia-progress-track",children:t.jsx("div",{className:"cia-skeleton",style:{height:"100%",width:"100%",borderRadius:"inherit"}})}),t.jsx("div",{className:"cia-skeleton",style:{height:30,marginTop:9,borderRadius:6}})]});const l=s.usage,c=l.includedMinutes>0?l.usedMinutes/l.includedMinutes:0,d=Math.min(1.5,c),u=l.overageMinutes>0,p=!u&&c>=.8,f=u?"cia-progress-fill cia-progress-fill-over":p?"cia-progress-fill cia-progress-fill-warn":"cia-progress-fill",x=g=>g>=1e3?`${(g/1e3).toFixed(g%1e3===0?0:1)}k`:String(g),h=!!r&&r.total>0,b=h&&r.total>0?Math.min(1,r.inUse/r.total):0;return t.jsxs("div",{className:"cia-usage-card",children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:6},children:[t.jsx("span",{className:"cia-eyebrow",style:{marginBottom:0},children:e("usage.minutes",{month:o})}),t.jsxs("span",{className:"cia-mono cia-text-2",style:{fontSize:11},children:[x(l.usedMinutes)," / ",x(l.includedMinutes)]})]}),s.usageByProduct&&s.usageByProduct.meetingPlanMinutes>0&&t.jsx("div",{className:"cia-mono cia-text-3",style:{fontSize:10,marginBottom:6},children:e("usage.byProduct",{voice:x(Math.round(s.usageByProduct.voiceMinutes)),meetings:x(Math.round(s.usageByProduct.meetingPlanMinutes))})}),t.jsx("div",{className:"cia-progress-track",children:t.jsx("div",{className:f,style:{width:`${Math.min(100,d*100)}%`}})}),h&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{height:1,background:"var(--cia-border)",margin:"11px 0 8px"}}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6},children:[t.jsxs("span",{className:"cia-eyebrow",style:{marginBottom:0,display:"inline-flex",alignItems:"center",gap:5},children:[t.jsx(vi,{size:11})," ",e("usage.channels")]}),t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx("span",{className:"cia-mono cia-text-2",style:{fontSize:11},children:e("usage.channelsInUse",{used:r.inUse,total:r.total})}),n&&t.jsx(et,{to:"/settings",search:{s:"billing"},title:e("usage.manageChannels"),"aria-label":e("usage.manageChannels"),style:{display:"grid",placeItems:"center",width:18,height:18,flex:"none",borderRadius:"var(--cia-r-sm)",border:"1px solid var(--cia-border-2)",background:"transparent",color:"var(--cia-text-2)",cursor:"pointer",padding:0},children:t.jsx(Fe,{size:12})})]})]}),t.jsx("div",{className:"cia-progress-track",style:{height:5},children:t.jsx("div",{className:"cia-progress-fill",style:{width:`${b*100}%`}})})]})]})}
943function bE(e){const a=e.trim().split(/\s+/).filter(Boolean);return a.length===0?"·":a.length===1?a[0].slice(0,2).toUpperCase():(a[0][0]+a[1][0]).toUpperCase()}function yE(){const{t:e}=M("nav"),{sidebarCollapsed:a,toggleSidebar:n,mobileOpen:s,setMobileOpen:i}=xy();S2();const r=Pe(y=>y.user),o=rt(y=>y.user),l=rt(y=>y.orgName),c=rt(y=>y.isActive()),{location:d}=bu();m.useEffect(()=>{s&&i(!1)},[d.pathname]);const u=!c&&r?.role==="superadmin",p=c?o:r,f=(u?Vy:Uy).map(y=>({...y,items:y.items.filter(k=>Ky(p,k))})).filter(y=>y.items.length>0),x=b5(d.pathname,f.flatMap(y=>y.items.map(k=>k.to))),h=xt(y=>y.resolved),b=u?e("workspace.platform"):c?l||e("workspace.organization"):"Enlassa AI",g=u?"superadmin":c?e("workspace.view360"):void 0,v=bE(b);return t.jsxs(t.Fragment,{children:[s&&t.jsx("div",{className:"cia cia-sidebar-backdrop","data-theme":h,onClick:()=>i(!1),"aria-hidden":"true"}),t.jsxs("aside",{className:"cia cia-sidebar","data-theme":h,"data-mobile-open":s?"true":"false",style:{width:a?64:232,flex:"none",background:"var(--cia-bg-soft)",borderRight:"1px solid var(--cia-border)",display:"flex",flexDirection:"column",transition:"width .2s var(--cia-ease-smooth), transform .25s var(--cia-ease-snappy)",height:"100%",overflow:"hidden",minWidth:a?64:232,maxWidth:a?64:232},role:"navigation","aria-label":e("labels.mainMenu"),children:[t.jsxs("div",{style:{height:56,flex:"none",display:"flex",alignItems:"center",justifyContent:a?"center":"space-between",padding:a?"0":"0 14px 0 16px",borderBottom:"1px solid var(--cia-border)"},children:[t.jsx(Dc,{iconOnly:a,height:26}),!a&&t.jsx("button",{onClick:n,className:"cia-btn cia-btn-ghost cia-btn-icon","aria-label":e("labels.collapseMenu"),style:{width:28,height:28},children:t.jsx(gn,{size:14,strokeWidth:2,style:{color:"var(--cia-text-3)"}})})]}),!a&&t.jsxs("div",{className:c?"cia-workspace-card cia-workspace-card-imp":"cia-workspace-card",children:[t.jsx("div",{className:u?"cia-workspace-badge cia-workspace-badge-platform":c?"cia-workspace-badge cia-workspace-badge-imp":"cia-workspace-badge","aria-hidden":"true",children:u?"★":v}),t.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:1},children:[t.jsx("span",{className:"cia-truncate",style:{fontFamily:"var(--cia-font-sans)",fontSize:13,fontWeight:500,letterSpacing:"var(--cia-tracking-tight)",color:"var(--cia-text)"},children:b}),g?t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:g}):t.jsx(vE,{})]})]}),t.jsx("nav",{className:"cia-sidebar-scroll",style:{flex:1,padding:"0 8px",paddingBottom:8},children:f.map(y=>t.jsxs("div",{style:{marginBottom:14},children:[!a&&t.jsx("div",{className:"cia-eyebrow",style:{padding:"8px 10px 4px"},children:e(y.sectionKey)}),t.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:2},children:y.items.map(k=>{const w=k.icon,j=e(k.labelKey),C=x===k.to;return t.jsx("li",{children:t.jsx(Ra,{label:a?j:void 0,position:"right",children:t.jsxs(et,{to:k.to,className:["cia-sidebar-link",C?"cia-sidebar-link-active":"",a?"cia-sidebar-link-collapsed":""].filter(Boolean).join(" "),"aria-label":a?j:void 0,"aria-current":C?"page":void 0,style:{position:"relative"},children:[t.jsx(w,{size:16,strokeWidth:C?2:1.75,"aria-hidden":"true",style:{flex:"none"}}),!a&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{flex:1},children:j}),k.live&&t.jsx(Lf,{collapsed:!1}),k.soon&&t.jsx("span",{className:"cia-soon-tag",children:e("labels.soon")}),k.beta&&t.jsx("span",{className:"cia-beta-tag",children:e("labels.beta")})]}),a&&k.live&&t.jsx(Lf,{collapsed:!0})]})})},k.to)})})]},y.sectionKey))}),!u&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{padding:"8px 8px 4px",borderTop:"1px solid var(--cia-border)"},children:t.jsx(Ra,{label:a?e("labels.settings"):void 0,position:"right",children:t.jsxs(et,{to:"/settings",search:{s:void 0},className:["cia-sidebar-link",d.pathname.startsWith("/settings")?"cia-sidebar-link-active":"",a?"cia-sidebar-link-collapsed":""].filter(Boolean).join(" "),"aria-label":a?e("labels.settings"):void 0,"aria-current":d.pathname.startsWith("/settings")?"page":void 0,children:[t.jsx(uy,{size:16,strokeWidth:d.pathname.startsWith("/settings")?2:1.75,"aria-hidden":"true",style:{flex:"none"}}),!a&&t.jsx("span",{style:{flex:1},children:e("labels.settings")})]})})}),!a&&t.jsx(gE,{})]}),a&&t.jsx("div",{style:{padding:"8px 0 12px",display:"flex",justifyContent:"center",borderTop:"1px solid var(--cia-border)"},children:t.jsx("button",{onClick:n,className:"cia-btn cia-btn-ghost cia-btn-icon","aria-label":e("labels.expandMenu"),style:{width:28,height:28},children:t.jsx(ca,{size:14,strokeWidth:2,style:{color:"var(--cia-text-3)"}})})})]})]})}function vE(){const{t:e}=M("nav"),{data:a,isLoading:n}=se({queryKey:["plan-usage"],queryFn:async()=>(await T.get("/organizations/me/plan-usage")).data,staleTime:6e4});if(n)return t.jsx("span",{className:"cia-skeleton",style:{display:"block",height:10,width:80,borderRadius:4}});const s=a?.trial;if(s&&s.status!=="converted")return s.status==="exhausted"||s.remainingMinutes<=0?t.jsx(et,{to:"/plan",className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-cta-500)",textDecoration:"none",fontWeight:600},children:e("trial.exhausted")}):t.jsx(S_,{label:e("trial.freeTrial"),remainingMinutes:s.remainingMinutes,totalMinutes:Math.round(s.totalSeconds/60),note:e("trial.meterNote")});if(!a?.plan)return t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:e("plan.noActivePlan")});const i=a.plan,r=i.includedMinutes>=1e3?`${i.includedMinutes/1e3}k min`:`${i.includedMinutes} min`;return t.jsxs("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:[i.name," · ",r]})}function jE(){const{t:e}=M("layout"),a=rt(p=>p.orgName),n=rt(p=>p.expiresAt),s=rt(p=>p.stop),[i,r]=m.useState(()=>Date.now());m.useEffect(()=>{const p=setInterval(()=>r(Date.now()),1e3);return()=>clearInterval(p)},[]);const o=Math.max(0,(n??0)-i);m.useEffect(()=>{n&&o<=0&&(s(),window.location.href="/admin/tenants?vista360=expirada")},[o,n,s]);const l=Math.floor(o/6e4),c=Math.floor(o%6e4/1e3),d=o<5*6e4;async function u(){await KN(),window.location.href="/admin/tenants"}return t.jsxs("div",{className:"h-10 shrink-0 bg-amber-100 border-b border-amber-300 flex items-center gap-3 px-4 text-amber-900",children:[t.jsx(qs,{className:"size-4 shrink-0"}),t.jsx("div",{className:"text-[13px] truncate",children:t.jsx(wa,{t:e,i18nKey:"imp.viewing",values:{org:a||e("imp.orgFallback")},components:{b0:t.jsx("span",{className:"font-semibold"}),b1:t.jsx("span",{className:"font-semibold"})}})}),t.jsxs("div",{className:`ml-auto font-mono text-[12px] tabular-nums ${d?"text-rose-600 font-semibold":"text-amber-600"}`,title:e("imp.timeLeftTitle"),children:[l,":",String(c).padStart(2,"0")]}),t.jsxs("button",{onClick:u,className:"inline-flex items-center gap-1.5 text-[12px] font-medium rounded-lg border border-amber-400 bg-amber-50 hover:bg-white px-2.5 py-1 transition-colors",children:[t.jsx(eh,{className:"size-3.5"}),e("imp.exit")]})]})}function wE(){const{t:e}=M("layout"),n=Up()?.role!=="superadmin",{data:s}=se({queryKey:["plan-usage"],queryFn:async()=>(await T.get("/organizations/me/plan-usage")).data,staleTime:6e4,enabled:n}),i=s?.trial;if(!n||!i||i.status==="converted")return null;const r=i.status==="exhausted"||i.remainingMinutes<=0,o=!r&&i.totalSeconds>0&&i.remainingSeconds/i.totalSeconds<=.2;return!r&&!o?null:t.jsx(le,{tone:r?"bad":"warn",children:t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[t.jsx("span",{style:{flex:1,minWidth:200},children:r?e("trial.exhausted",{total:Math.round(i.totalSeconds/60)}):e("trial.remaining",{min:Math.round(i.remainingMinutes)})}),t.jsx(et,{to:"/plan",className:"cia-btn cia-btn-cta cia-btn-sm",style:{flex:"none"},children:e("trial.choosePlan")})]})})}const fn=Object.create(null);fn.open="0";fn.close="1";fn.ping="2";fn.pong="3";fn.message="4";fn.upgrade="5";fn.noop="6";
vendor: 6,080 bytes, line 943
943const Sl=Object.create(null);Object.keys(fn).forEach(e=>{Sl[fn[e]]=e});const Uu={type:"error",data:"parser error"},vv=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",jv=typeof ArrayBuffer=="function",wv=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,fh=({type:e,data:a},n,s)=>vv&&a instanceof Blob?n?s(a):Ff(a,s):jv&&(a instanceof ArrayBuffer||wv(a))?n?s(a):Ff(new Blob([a]),s):s(fn[e]+(a||"")),Ff=(e,a)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];a("b"+(s||""))},n.readAsDataURL(e)};function Of(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Sd;function kE(e,a){if(vv&&e.data instanceof Blob)return e.data.arrayBuffer().then(Of).then(a);if(jv&&(e.data instanceof ArrayBuffer||wv(e.data)))return a(Of(e.data));fh(e,!1,n=>{Sd||(Sd=new TextEncoder),a(Sd.encode(n))})}const $f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gr=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<$f.length;e++)gr[$f.charCodeAt(e)]=e;const NE=e=>{let a=e.length*.75,n=e.length,s,i=0,r,o,l,c;e[e.length-1]==="="&&(a--,e[e.length-2]==="="&&a--);const d=new ArrayBuffer(a),u=new Uint8Array(d);for(s=0;s<n;s+=4)r=gr[e.charCodeAt(s)],o=gr[e.charCodeAt(s+1)],l=gr[e.charCodeAt(s+2)],c=gr[e.charCodeAt(s+3)],u[i++]=r<<2|o>>4,u[i++]=(o&15)<<4|l>>2,u[i++]=(l&3)<<6|c&63;return d},SE=typeof ArrayBuffer=="function",xh=(e,a)=>{if(typeof e!="string")return{type:"message",data:kv(e,a)};const n=e.charAt(0);return n==="b"?{type:"message",data:CE(e.substring(1),a)}:Sl[n]?e.length>1?{type:Sl[n],data:e.substring(1)}:{type:Sl[n]}:Uu},CE=(e,a)=>{if(SE){const n=NE(e);return kv(n,a)}else return{base64:!0,data:e}},kv=(e,a)=>{switch(a){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Nv="�",_E=(e,a)=>{const n=e.length,s=new Array(n);let i=0;e.forEach((r,o)=>{fh(r,!1,l=>{s[o]=l,++i===n&&a(s.join(Nv))})})},EE=(e,a)=>{const n=e.split(Nv),s=[];for(let i=0;i<n.length;i++){const r=xh(n[i],a);if(s.push(r),r.type==="error")break}return s};function AE(){return new TransformStream({transform(e,a){kE(e,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}e.data&&typeof e.data!="string"&&(i[0]|=128),a.enqueue(i),a.enqueue(n)})}})}let Cd;function Ko(e){return e.reduce((a,n)=>a+n.length,0)}function Ho(e,a){if(e[0].length===a)return e.shift();const n=new Uint8Array(a);let s=0;for(let i=0;i<a;i++)n[i]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),n}function RE(e,a){Cd||(Cd=new TextDecoder);const n=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,l){for(n.push(o);;){if(s===0){if(Ko(n)<1)break;const c=Ho(n,1);r=(c[0]&128)===128,i=c[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(Ko(n)<2)break;const c=Ho(n,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(Ko(n)<8)break;const c=Ho(n,8),d=new DataView(c.buffer,c.byteOffset,c.length),u=d.getUint32(0);if(u>Math.pow(2,21)-1){l.enqueue(Uu);break}i=u*Math.pow(2,32)+d.getUint32(4),s=3}else{if(Ko(n)<i)break;const c=Ho(n,i);l.enqueue(xh(r?c:Cd.decode(c),a)),s=0}if(i===0||i>e){l.enqueue(Uu);break}}}})}const Sv=4;function Bt(e){if(e)return TE(e)}function TE(e){for(var a in Bt.prototype)e[a]=Bt.prototype[a];return e}Bt.prototype.on=Bt.prototype.addEventListener=function(e,a){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(a),this};Bt.prototype.once=function(e,a){function n(){this.off(e,n),a.apply(this,arguments)}return n.fn=a,this.on(e,n),this};Bt.prototype.off=Bt.prototype.removeListener=Bt.prototype.removeAllListeners=Bt.prototype.removeEventListener=function(e,a){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var s,i=0;i<n.length;i++)if(s=n[i],s===a||s.fn===a){n.splice(i,1);break}return n.length===0&&delete this._callbacks["$"+e],this};Bt.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var a=new Array(arguments.length-1),n=this._callbacks["$"+e],s=1;s<arguments.length;s++)a[s-1]=arguments[s];if(n){n=n.slice(0);for(var s=0,i=n.length;s<i;++s)n[s].apply(this,a)}return this};Bt.prototype.emitReserved=Bt.prototype.emit;Bt.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};Bt.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Fc=typeof Promise=="function"&&typeof Promise.resolve=="function"?a=>Promise.resolve().then(a):(a,n)=>n(a,0),$a=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ME="arraybuffer";function Cv(e,...a){return a.reduce((n,s)=>(e.hasOwnProperty(s)&&(n[s]=e[s]),n),{})}const PE=$a.setTimeout,zE=$a.clearTimeout;function Oc(e,a){a.useNativeTimers?(e.setTimeoutFn=PE.bind($a),e.clearTimeoutFn=zE.bind($a)):(e.setTimeoutFn=$a.setTimeout.bind($a),e.clearTimeoutFn=$a.clearTimeout.bind($a))}const DE=1.33;function IE(e){return typeof e=="string"?LE(e):Math.ceil((e.byteLength||e.size)*DE)}function LE(e){let a=0,n=0;for(let s=0,i=e.length;s<i;s++)a=e.charCodeAt(s),a<128?n+=1:a<2048?n+=2:a<55296||a>=57344?n+=3:(s++,n+=4);return n}function _v(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function FE(e){let a="";for(let n in e)e.hasOwnProperty(n)&&(a.length&&(a+="&"),a+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return a}function OE(e){let a={},n=e.split("&");for(let s=0,i=n.length;s<i;s++){let r=n[s].split("=");a[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return a}
vendor: 4,501 bytes, line 943
943class $E extends Error{constructor(a,n,s){super(a),this.description=n,this.context=s,this.type="TransportError"}}class gh extends Bt{constructor(a){super(),this.writable=!1,Oc(this,a),this.opts=a,this.query=a.query,this.socket=a.socket,this.supportsBinary=!a.forceBase64}onError(a,n,s){return super.emitReserved("error",new $E(a,n,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(a){this.readyState==="open"&&this.write(a)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(a){const n=xh(a,this.socket.binaryType);this.onPacket(n)}onPacket(a){super.emitReserved("packet",a)}onClose(a){this.readyState="closed",super.emitReserved("close",a)}pause(a){}createUri(a,n={}){return a+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const a=this.opts.hostname;return a.indexOf(":")===-1?a:"["+a+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(a){const n=FE(a);return n.length?"?"+n:""}}class qE extends gh{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(a){this.readyState="pausing";const n=()=>{this.readyState="paused",a()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||n()})),this.writable||(s++,this.once("drain",function(){--s||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(a){const n=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};EE(a,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const a=()=>{this.write([{type:"close"}])};this.readyState==="open"?a():this.once("open",a)}write(a){this.writable=!1,_E(a,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const a=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=_v()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(a,n)}}let Ev=!1;try{Ev=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const BE=Ev;function WE(){}class UE extends qE{constructor(a){if(super(a),typeof location<"u"){const n=location.protocol==="https:";let s=location.port;s||(s=n?"443":"80"),this.xd=typeof location<"u"&&a.hostname!==location.hostname||s!==a.port}}doWrite(a,n){const s=this.request({method:"POST",data:a});s.on("success",n),s.on("error",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const a=this.request();a.on("data",this.onData.bind(this)),a.on("error",(n,s)=>{this.onError("xhr poll error",n,s)}),this.pollXhr=a}}class un extends Bt{constructor(a,n,s){super(),this.createRequest=a,Oc(this,s),this._opts=s,this._method=s.method||"GET",this._uri=n,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var a;const n=Cv(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(n);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(a=this._opts.cookieJar)===null||a===void 0||a.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=un.requestsCount++,un.requests[this._index]=this)}_onError(a){this.emitReserved("error",a,this._xhr),this._cleanup(!0)}
vendor: 16,365 bytes, line 943
943_cleanup(a){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=WE,a)try{this._xhr.abort()}catch{}typeof document<"u"&&delete un.requests[this._index],this._xhr=null}}_onLoad(){const a=this._xhr.responseText;a!==null&&(this.emitReserved("data",a),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}un.requestsCount=0;un.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",qf);else if(typeof addEventListener=="function"){const e="onpagehide"in $a?"pagehide":"unload";addEventListener(e,qf,!1)}}function qf(){for(let e in un.requests)un.requests.hasOwnProperty(e)&&un.requests[e].abort()}const VE=(function(){const e=Av({xdomain:!1});return e&&e.responseType!==null})();class KE extends UE{constructor(a){super(a);const n=a&&a.forceBase64;this.supportsBinary=VE&&!n}request(a={}){return Object.assign(a,{xd:this.xd},this.opts),new un(Av,this.uri(),a)}}function Av(e){const a=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!a||BE))return new XMLHttpRequest}catch{}if(!a)try{return new $a[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Rv=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class HE extends gh{get name(){return"websocket"}doOpen(){const a=this.uri(),n=this.opts.protocols,s=Rv?{}:Cv(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(a,n,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=a=>this.onClose({description:"websocket connection closed",context:a}),this.ws.onmessage=a=>this.onData(a.data),this.ws.onerror=a=>this.onError("websocket error",a)}write(a){this.writable=!1;for(let n=0;n<a.length;n++){const s=a[n],i=n===a.length-1;fh(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&Fc(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const a=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=_v()),this.supportsBinary||(n.b64=1),this.createUri(a,n)}}const _d=$a.WebSocket||$a.MozWebSocket;class QE extends HE{createSocket(a,n,s){return Rv?new _d(a,n,s):n?new _d(a,n):new _d(a)}doWrite(a,n){this.ws.send(n)}}class GE extends gh{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(a){return this.emitReserved("error",a)}this._transport.closed.then(()=>{this.onClose()}).catch(a=>{this.onError("webtransport error",a)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(a=>{const n=RE(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=a.readable.pipeThrough(n).getReader(),i=AE();i.readable.pipeTo(a.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:l,value:c})=>{l||(this.onPacket(c),r())}).catch(l=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(a){this.writable=!1;for(let n=0;n<a.length;n++){const s=a[n],i=n===a.length-1;this._writer.write(s).then(()=>{i&&Fc(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var a;(a=this._transport)===null||a===void 0||a.close()}}const ZE={websocket:QE,webtransport:GE,polling:KE},YE=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,XE=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Vu(e){if(e.length>8e3)throw"URI too long";const a=e,n=e.indexOf("["),s=e.indexOf("]");n!=-1&&s!=-1&&(e=e.substring(0,n)+e.substring(n,s).replace(/:/g,";")+e.substring(s,e.length));let i=YE.exec(e||""),r={},o=14;for(;o--;)r[XE[o]]=i[o]||"";return n!=-1&&s!=-1&&(r.source=a,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=JE(r,r.path),r.queryKey=eA(r,r.query),r}function JE(e,a){const n=/\/{2,9}/g,s=a.replace(n,"/").split("/");return(a.slice(0,1)=="/"||a.length===0)&&s.splice(0,1),a.slice(-1)=="/"&&s.splice(s.length-1,1),s}function eA(e,a){const n={};return a.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(n[i]=r)}),n}const Ku=typeof addEventListener=="function"&&typeof removeEventListener=="function",Cl=[];Ku&&addEventListener("offline",()=>{Cl.forEach(e=>e())},!1);class Xn extends Bt{constructor(a,n){if(super(),this.binaryType=ME,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,a&&typeof a=="object"&&(n=a,a=null),a){const s=Vu(a);n.hostname=s.host,n.secure=s.protocol==="https"||s.protocol==="wss",n.port=s.port,s.query&&(n.query=s.query)}else n.host&&(n.hostname=Vu(n.host).host);Oc(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=OE(this.opts.query)),Ku&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Cl.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(a){const n=Object.assign({},this.opts.query);n.EIO=Sv,n.transport=a,this.id&&(n.sid=this.id);const s=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[a]);return new this._transportsByName[a](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const a=this.opts.rememberUpgrade&&Xn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(a);n.open(),this.setTransport(n)}setTransport(a){this.transport&&this.transport.removeAllListeners(),this.transport=a,a.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",Xn.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(a){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",a),this.emitReserved("heartbeat"),a.type){case"open":this.onHandshake(JSON.parse(a.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=a.data,this._onError(n);break;case"message":this.emitReserved("data",a.data),this.emitReserved("message",a.data);break}}onHandshake(a){this.emitReserved("handshake",a),this.id=a.sid,this.transport.query.sid=a.sid,this._pingInterval=a.pingInterval,this._pingTimeout=a.pingTimeout,this._maxPayload=a.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const a=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+a,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},a),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const a=this._getWritablePackets();this.transport.send(a),this._prevBufferLen=a.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(n+=IE(i)),s>0&&n>this._maxPayload)return this.writeBuffer.slice(0,s);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const a=Date.now()>this._pingTimeoutTime;return a&&(this._pingTimeoutTime=0,Fc(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),a}write(a,n,s){return this._sendPacket("message",a,n,s),this}send(a,n,s){return this._sendPacket("message",a,n,s),this}_sendPacket(a,n,s,i){if(typeof n=="function"&&(i=n,n=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:a,data:n,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const a=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),a()},s=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():a()}):this.upgrading?s():a()),this}_onError(a){if(Xn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",a),this._onClose("transport error",a)}_onClose(a,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Ku&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Cl.indexOf(this._offlineEventListener);s!==-1&&Cl.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",a,n),this.writeBuffer=[],this._prevBufferLen=0}}}Xn.protocol=Sv;class tA extends Xn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let a=0;a<this._upgrades.length;a++)this._probe(this._upgrades[a])}_probe(a){let n=this.createTransport(a),s=!1;Xn.priorWebsocketSuccess=!1;const i=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!s)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;Xn.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(u(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const f=new Error("probe error");f.transport=n.name,this.emitReserved("upgradeError",f)}}))};function r(){s||(s=!0,u(),n.close(),n=null)}const o=p=>{const f=new Error("probe error: "+p);f.transport=n.name,r(),this.emitReserved("upgradeError",f)};function l(){o("transport closed")}function c(){o("socket closed")}function d(p){n&&p.name!==n.name&&r()}const u=()=>{n.removeListener("open",i),n.removeListener("error",o),n.removeListener("close",l),this.off("close",c),this.off("upgrading",d)};n.once("open",i),n.once("error",o),n.once("close",l),this.once("close",c),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&a!=="webtransport"?this.setTimeoutFn(()=>{s||n.open()},200):n.open()}onHandshake(a){this._upgrades=this._filterUpgrades(a.upgrades),super.onHandshake(a)}_filterUpgrades(a){const n=[];for(let s=0;s<a.length;s++)~this.transports.indexOf(a[s])&&n.push(a[s]);return n}}let aA=class extends tA{constructor(a,n={}){const s=typeof a=="object"?a:n;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>ZE[i]).filter(i=>!!i)),super(a,s)}};function nA(e,a="",n){let s=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),s=Vu(e)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+a,s.href=s.protocol+"://"+r+(n&&n.port===s.port?"":":"+s.port),s}const sA=typeof ArrayBuffer=="function",iA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Tv=Object.prototype.toString,rA=typeof Blob=="function"||typeof Blob<"u"&&Tv.call(Blob)==="[object BlobConstructor]",oA=typeof File=="function"||typeof File<"u"&&Tv.call(File)==="[object FileConstructor]";function bh(e){return sA&&(e instanceof ArrayBuffer||iA(e))||rA&&e instanceof Blob||oA&&e instanceof File}function _l(e,a){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,s=e.length;n<s;n++)if(_l(e[n]))return!0;return!1}if(bh(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return _l(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&_l(e[n]))return!0;return!1}function lA(e){const a=[],n=e.data,s=e;return s.data=Hu(n,a),s.attachments=a.length,{packet:s,buffers:a}}function Hu(e,a){if(!e)return e;if(bh(e)){const n={_placeholder:!0,num:a.length};return a.push(e),n}else if(Array.isArray(e)){const n=new Array(e.length);for(let s=0;s<e.length;s++)n[s]=Hu(e[s],a);return n}else if(typeof e=="object"&&!(e instanceof Date)){const n={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=Hu(e[s],a));return n}return e}function cA(e,a){return e.data=Qu(e.data,a),delete e.attachments,e}function Qu(e,a){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<a.length)return a[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Qu(e[n],a);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Qu(e[n],a));return e}const dA=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var it;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(it||(it={}));class uA{constructor(a){this.replacer=a}encode(a){return(a.type===it.EVENT||a.type===it.ACK)&&_l(a)?this.encodeAsBinary({type:a.type===it.EVENT?it.BINARY_EVENT:it.BINARY_ACK,nsp:a.nsp,data:a.data,id:a.id}):[this.encodeAsString(a)]}encodeAsString(a){let n=""+a.type;return(a.type===it.BINARY_EVENT||a.type===it.BINARY_ACK)&&(n+=a.attachments+"-"),a.nsp&&a.nsp!=="/"&&(n+=a.nsp+","),a.id!=null&&(n+=a.id),a.data!=null&&(n+=JSON.stringify(a.data,this.replacer)),n}encodeAsBinary(a){const n=lA(a),s=this.encodeAsString(n.packet),i=n.buffers;return i.unshift(s),i}}
vendor: 6,140 bytes, line 943
943class yh extends Bt{constructor(a){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof a=="function"?{reviver:a}:a)}add(a){let n;if(typeof a=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(a);const s=n.type===it.BINARY_EVENT;s||n.type===it.BINARY_ACK?(n.type=s?it.EVENT:it.ACK,this.reconstructor=new pA(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(bh(a)||a.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(a),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+a)}decodeString(a){let n=0;const s={type:Number(a.charAt(0))};if(it[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===it.BINARY_EVENT||s.type===it.BINARY_ACK){const r=n+1;for(;a.charAt(++n)!=="-"&&n!=a.length;);const o=a.substring(r,n);if(o!=Number(o)||a.charAt(n)!=="-")throw new Error("Illegal attachments");const l=Number(o);if(!hA(l)||l<0)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=l}if(a.charAt(n+1)==="/"){const r=n+1;for(;++n&&!(a.charAt(n)===","||n===a.length););s.nsp=a.substring(r,n)}else s.nsp="/";const i=a.charAt(n+1);if(i!==""&&Number(i)==i){const r=n+1;for(;++n;){const o=a.charAt(n);if(o==null||Number(o)!=o){--n;break}if(n===a.length)break}s.id=Number(a.substring(r,n+1))}if(a.charAt(++n)){const r=this.tryParse(a.substr(n));if(yh.isPayloadValid(s.type,r))s.data=r;else throw new Error("invalid payload")}return s}tryParse(a){try{return JSON.parse(a,this.opts.reviver)}catch{return!1}}static isPayloadValid(a,n){switch(a){case it.CONNECT:return Bf(n);case it.DISCONNECT:return n===void 0;case it.CONNECT_ERROR:return typeof n=="string"||Bf(n);case it.EVENT:case it.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&dA.indexOf(n[0])===-1);case it.ACK:case it.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class pA{constructor(a){this.packet=a,this.buffers=[],this.reconPack=a}takeBinaryData(a){if(this.buffers.push(a),this.buffers.length===this.reconPack.attachments){const n=cA(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const hA=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Bf(e){return Object.prototype.toString.call(e)==="[object Object]"}const mA=Object.freeze(Object.defineProperty({__proto__:null,Decoder:yh,Encoder:uA,get PacketType(){return it}},Symbol.toStringTag,{value:"Module"}));function Ya(e,a,n){return e.on(a,n),function(){e.off(a,n)}}const fA=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Mv extends Bt{constructor(a,n,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=a,this.nsp=n,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const a=this.io;this.subs=[Ya(a,"open",this.onopen.bind(this)),Ya(a,"packet",this.onpacket.bind(this)),Ya(a,"error",this.onerror.bind(this)),Ya(a,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...a){return a.unshift("message"),this.emit.apply(this,a),this}emit(a,...n){var s,i,r;if(fA.hasOwnProperty(a))throw new Error('"'+a.toString()+'" is a reserved event name');if(n.unshift(a),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const o={type:it.EVENT,data:n};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const u=this.ids++,p=n.pop();this._registerAckCallback(u,p),o.id=u}const l=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,c=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!l||(c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(a,n){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[a]=n;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[a];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===a&&this.sendBuffer.splice(l,1);n.call(this,new Error("operation has timed out"))},i),o=(...l)=>{this.io.clearTimeoutFn(r),n.apply(this,l)};o.withError=!0,this.acks[a]=o}emitWithAck(a,...n){return new Promise((s,i)=>{const r=(o,l)=>o?i(o):s(l);r.withError=!0,n.push(r),this.emit(a,...n)})}_addToQueue(a){let n;typeof a[a.length-1]=="function"&&(n=a.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:a,flags:Object.assign({fromQueue:!0},this.flags)};a.push((i,...r)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(i)):(this._queue.shift(),n&&n(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(a=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!a||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(a){a.nsp=this.nsp,this.io._packet(a)}onopen(){typeof this.auth=="function"?this.auth(a=>{this._sendConnectPacket(a)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(a){this.packet({type:it.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},a):a})}onerror(a){this.connected||this.emitReserved("connect_error",a)}onclose(a,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",a,n),this._clearAcks()}
vendor: 7,087 bytes, line 943
943_clearAcks(){Object.keys(this.acks).forEach(a=>{if(!this.sendBuffer.some(s=>String(s.id)===a)){const s=this.acks[a];delete this.acks[a],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(a){if(a.nsp===this.nsp)switch(a.type){case it.CONNECT:a.data&&a.data.sid?this.onconnect(a.data.sid,a.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case it.EVENT:case it.BINARY_EVENT:this.onevent(a);break;case it.ACK:case it.BINARY_ACK:this.onack(a);break;case it.DISCONNECT:this.ondisconnect();break;case it.CONNECT_ERROR:this.destroy();const s=new Error(a.data.message);s.data=a.data.data,this.emitReserved("connect_error",s);break}}onevent(a){const n=a.data||[];a.id!=null&&n.push(this.ack(a.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(a){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const s of n)s.apply(this,a)}super.emit.apply(this,a),this._pid&&a.length&&typeof a[a.length-1]=="string"&&(this._lastOffset=a[a.length-1])}ack(a){const n=this;let s=!1;return function(...i){s||(s=!0,n.packet({type:it.ACK,id:a,data:i}))}}onack(a){const n=this.acks[a.id];typeof n=="function"&&(delete this.acks[a.id],n.withError&&a.data.unshift(null),n.apply(this,a.data))}onconnect(a,n){this.id=a,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(a=>this.emitEvent(a)),this.receiveBuffer=[],this.sendBuffer.forEach(a=>{this.notifyOutgoingListeners(a),this.packet(a)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(a=>a()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:it.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(a){return this.flags.compress=a,this}get volatile(){return this.flags.volatile=!0,this}timeout(a){return this.flags.timeout=a,this}onAny(a){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(a),this}prependAny(a){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(a),this}offAny(a){if(!this._anyListeners)return this;if(a){const n=this._anyListeners;for(let s=0;s<n.length;s++)if(a===n[s])return n.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(a){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(a),this}prependAnyOutgoing(a){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(a),this}offAnyOutgoing(a){if(!this._anyOutgoingListeners)return this;if(a){const n=this._anyOutgoingListeners;for(let s=0;s<n.length;s++)if(a===n[s])return n.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(a){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const s of n)s.apply(this,a.data)}}}function Oi(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Oi.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var a=Math.random(),n=Math.floor(a*this.jitter*e);e=(Math.floor(a*10)&1)==0?e-n:e+n}return Math.min(e,this.max)|0};Oi.prototype.reset=function(){this.attempts=0};Oi.prototype.setMin=function(e){this.ms=e};Oi.prototype.setMax=function(e){this.max=e};Oi.prototype.setJitter=function(e){this.jitter=e};class Gu extends Bt{constructor(a,n){var s;super(),this.nsps={},this.subs=[],a&&typeof a=="object"&&(n=a,a=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,Oc(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((s=n.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new Oi({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=a;const i=n.parser||mA;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(a){return arguments.length?(this._reconnection=!!a,a||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(a){return a===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=a,this)}reconnectionDelay(a){var n;return a===void 0?this._reconnectionDelay:(this._reconnectionDelay=a,(n=this.backoff)===null||n===void 0||n.setMin(a),this)}randomizationFactor(a){var n;return a===void 0?this._randomizationFactor:(this._randomizationFactor=a,(n=this.backoff)===null||n===void 0||n.setJitter(a),this)}reconnectionDelayMax(a){var n;return a===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=a,(n=this.backoff)===null||n===void 0||n.setMax(a),this)}timeout(a){return arguments.length?(this._timeout=a,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(a){if(~this._readyState.indexOf("open"))return this;this.engine=new aA(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=Ya(n,"open",function(){s.onopen(),a&&a()}),r=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),a?a(l):this.maybeReconnectOnOpen()},o=Ya(n,"error",r);if(this._timeout!==!1){const l=this._timeout,c=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),n.close()},l);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(i),this.subs.push(o),this}connect(a){return this.open(a)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const a=this.engine;this.subs.push(Ya(a,"ping",this.onping.bind(this)),Ya(a,"data",this.ondata.bind(this)),Ya(a,"error",this.onerror.bind(this)),Ya(a,"close",this.onclose.bind(this)),Ya(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(a){try{this.decoder.add(a)}catch(n){this.onclose("parse error",n)}}ondecoded(a){Fc(()=>{this.emitReserved("packet",a)},this.setTimeoutFn)}onerror(a){this.emitReserved("error",a)}socket(a,n){let s=this.nsps[a];return s?this._autoConnect&&!s.active&&s.connect():(s=new Mv(this,a,n),this.nsps[a]=s),s}_destroy(a){const n=Object.keys(this.nsps);for(const s of n)if(this.nsps[s].active)return;this._close()}_packet(a){const n=this.encoder.encode(a);for(let s=0;s<n.length;s++)this.engine.write(n[s],a.options)}
943cleanup(){this.subs.forEach(a=>a()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(a,n){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",a,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const a=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{a.skipReconnect||(this.emitReserved("reconnect_attempt",a.backoff.attempts),!a.skipReconnect&&a.open(i=>{i?(a._reconnecting=!1,a.reconnect(),this.emitReserved("reconnect_error",i)):a.onreconnect()}))},n);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const a=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",a)}}const er={};function Er(e,a){typeof e=="object"&&(a=e,e=void 0),a=a||{};const n=nA(e,a.path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=er[i]&&r in er[i].nsps,l=a.forceNew||a["force new connection"]||a.multiplex===!1||o;let c;return l?c=new Gu(s,a):(er[i]||(er[i]=new Gu(s,a)),c=er[i]),n.query&&!a.query&&(a.query=n.queryKey),c.socket(n.path,a)}Object.assign(Er,{Manager:Gu,Socket:Mv,io:Er,connect:Er});let ia=null,Zu=null;function ns(){const e=rt.getState(),a=e.isActive()?e.accessToken:Pe.getState().accessToken;if(!a)throw new Error("No auth token");if(ia&&Zu===a)return ia;ia&&(ia.disconnect(),ia=null);const n="https://api.enlassa.ai";return Zu=a,ia=Er(`${n}/calls`,{auth:{token:a},transports:["websocket","polling"],autoConnect:!0}),ia.on("connect",()=>{console.log("[ws] connected",ia?.id),El()}),ia.on("disconnect",s=>{console.log("[ws] disconnected",s),El()}),ia.on("connect_error",s=>{console.warn("[ws] connect_error",s.message),El()}),ia}function xA(){ia?.disconnect(),ia=null,Zu=null,El()}const Yu=new Set;function El(){const e=!!ia?.connected;for(const a of Yu)a(e)}function Xu(){return!!ia?.connected}function Pv(e){return Yu.add(e),()=>{Yu.delete(e)}}const zv=Object.freeze(Object.defineProperty({__proto__:null,disconnectSocket:xA,getSocket:ns,isSocketConnected:Xu,onSocketStatus:Pv},Symbol.toStringTag,{value:"Module"}));let gA=0;const Al=ds(e=>({alerts:[],add:a=>e(n=>{const s=Date.now();return n.alerts.find(o=>o.callId===a.callId&&o.sentimentLabel===a.sentimentLabel&&s-o.receivedAt<6e4)?n:{alerts:[{...a,id:`al_${s}_${gA++}`,receivedAt:s,read:!1},...n.alerts].slice(0,50)}}),markAllRead:()=>e(a=>({alerts:a.alerts.map(n=>({...n,read:!0}))})),clear:()=>e({alerts:[]})}));let tr=null;function bA(){if(typeof window>"u")return null;try{const e=window.AudioContext||window.webkitAudioContext;return e?(tr||(tr=new e),tr.state==="suspended"&&tr.resume(),tr):null}catch{return null}}function ar(e,a=.12,n=.05,s="sine"){const i=bA();if(!i)return;let r=i.currentTime;for(const o of e){const l=i.createOscillator(),c=i.createGain();l.type=s,l.frequency.value=o,c.gain.setValueAtTime(1e-4,r),c.gain.linearRampToValueAtTime(.16,r+.012),c.gain.exponentialRampToValueAtTime(1e-4,r+a),l.connect(c).connect(i.destination),l.start(r),l.stop(r+a+.02),r+=a+n}}const Dv=[{id:"chime",label:"Campanita (ascendente)",play:()=>ar([660,880],.14,.03)},{id:"ding",label:"Ding",play:()=>ar([880],.18)},{id:"bell",label:"Campana",play:()=>ar([784,988],.18,.02,"triangle")},{id:"blip",label:"Blip",play:()=>ar([520],.08)},{id:"alert",label:"Alerta (grave)",play:()=>ar([330,247],.16,.04,"square")},{id:"none",label:"Sin sonido",play:()=>{}}],yA=new Map(Dv.map(e=>[e.id,e]));function Iv(e){!e||e==="none"||yA.get(e)?.play()}function vA(){const{t:e}=M("calls"),{can:a}=tt(),n=a("calls.view"),s=Al(d=>d.add),{data:i}=se({queryKey:["org","alert-cfg"],queryFn:async()=>(await T.get("/organizations/me")).data,enabled:n,staleTime:5*6e4}),r=i?.branding?.liveAlerts??{},o=r.enabled!==!1,l=r.positive??"chime",c=r.negative??"alert";return m.useEffect(()=>{if(!n)return;const d=ns(),u=p=>{if(!p||p.alert!==!0)return;const f=p.sentimentLabel==="positive",x=p.sentimentLabel==="negative";s({callId:p.callId,agentName:p.agentName,direction:p.direction,number:p.number,sentimentLabel:p.sentimentLabel,sentiment:p.sentiment??null,intent:p.intent??null,at:p.at}),J({title:f?e("alert.posTitle",{name:p.agentName}):e("alert.negTitle",{name:p.agentName}),desc:p.intent||e(f?"alert.posDesc":"alert.negDesc"),tone:f?"ok":"bad"}),o&&Iv(f?l:x?c:null)};return d.on("live_signal",u),()=>{d.off("live_signal",u)}},[n,s,o,l,c]),null}let $t=null,Ar=null,Ju=null,fi=null,Rr=2e3;const jA=6e4;function Yl(){const e=rt.getState();return e.isActive()?e.accessToken:Pe.getState().accessToken}function Wf(){const e=rt.getState();if(e.isActive())return`imp:${e.user?.id??""}:${e.user?.organizationId??""}`;const a=Pe.getState().user;return`real:${a?.id??""}:${a?.organizationId??""}`}function vh(){const e=Yl();if(!e)throw new Error("No auth token");if($t&&Ar===e)return $t;if($t&&Ju===Wf())return Ar=e,!$t.connected&&!$t.active&&$t.connect(),$t;$t&&Lv();const a="https://api.enlassa.ai";return Ar=e,Ju=Wf(),$t=Er(`${a}/messaging`,{auth:n=>
943n({token:Yl()}),transports:["websocket","polling"],autoConnect:!0}),$t.on("connect",()=>{Rr=2e3,Rl()}),$t.on("disconnect",n=>{Rl(),n==="io server disconnect"&&wA()}),$t.on("connect_error",()=>Rl()),$t}function wA(){if(fi)return;const e=Rr;Rr=Math.min(Rr*2,jA),fi=setTimeout(()=>{fi=null,!(!$t||!Yl())&&(Ar=Yl(),$t.connect())},e)}function Lv(){fi&&clearTimeout(fi),fi=null,$t?.removeAllListeners(),$t?.disconnect(),$t=null,Ar=null,Ju=null}function kA(){Lv(),Rr=2e3,Rl()}const ep=new Set;function Rl(){const e=!!$t?.connected;for(const a of ep)a(e)}function tp(){return!!$t?.connected}function Xl(e){return ep.add(e),()=>{ep.delete(e)}}const Fv=Object.freeze(Object.defineProperty({__proto__:null,disconnectSocketMessaging:kA,getSocketMessaging:vh,isMessagingConnected:tp,onMessagingStatus:Xl},Symbol.toStringTag,{value:"Module"}));function NA(e){return e.state==="closed"}function Tl(e,a){return NA(e)?null:SA(e.ventana,a)}function SA(e,a){if(e.expiraEnMs===null)return e;const n=e.expiraEnMs-a;return n<=0?{abierta:!1,motivo:"vencida",expiraEnMs:e.expiraEnMs,segundosRestantes:0}:{abierta:!0,motivo:"abierta",expiraEnMs:e.expiraEnMs,segundosRestantes:Math.floor(n/1e3)}}function CA(e,a){return e.some(n=>Tl(n,a)?.abierta===!0)}function br(e){if(e===null||e<=0)return null;const a=Math.floor(e/3600),n=Math.floor(e%3600/60),s=e%60;return a>0?`${a}:${String(n).padStart(2,"0")}`:`${n}:${String(s).padStart(2,"0")}`}function $c(e,a){return e.estado!=="esperando"||e.venceEnMs-a>0?e:{estado:"contestando"}}function _A(e,a){return e.some(n=>$c(n.turno,a).estado==="esperando")}function Uf(e,a){const n=$c(e,a);return n.estado!=="esperando"?null:Math.max(1,Math.ceil((n.venceEnMs-a)/1e3))}function EA(e,a){const n=$c(e,a);return n.estado==="esperando"&&n.regla?n.regla:null}function Vf(e,a){if(e.mode!=="agent")return null;const n=$c(e.turno,a);return n.estado==="ninguno"?null:n.estado}function Si(e){return e.direction==="inbound"?"in":"out"}function AA(e,a){const n=Ed(e[a]),s=a>0?Ed(e[a-1]):null,i=a<e.length-1?Ed(e[a+1]):null;return{runStart:s!==n,runEnd:i!==n}}function Ed(e){return qc(e)?"sistema":Si(e)}function RA(e){return qc(e)||e.direction!=="outbound"||e.origin==="device"||e.status===null||e.status===void 0?null:e.status==="unknown"?"confirmando":e.status==="accepted"?"pending":["pending","sent","delivered","read","played","failed"].includes(e.status)?e.status:null}function ga(e){const a=(e.contactName??"").trim();if(a)return a;const n=(e.contactUsername??"").trim();return n?`@${n}`:e.contactExternalId}function Ov(e){return/^\+?[0-9]{7,15}$/.test(e.trim())}function TA(e){const a=(e.contactUsername??"").trim();return Ov(e.contactExternalId)?a?`${e.contactExternalId} · @${a}`:e.contactExternalId:a?`@${a}`:e.contactExternalId}function MA(e){const a=new Date(e);return Number.isNaN(a.getTime())?"sin-fecha":`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`}function Qo(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`t-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function jh(e){return qc(e)||e.direction!=="outbound"?null:e.origin==="device"?"celular_del_dueno":e.role==="agent"?"agente":e.role==="human"?"equipo":null}function PA(e){const a=new Set(e.map(r=>r.id)),n=new Map,s=[];for(const r of e){const o=r.type==="reaction"?r.replyTo?.id??null:null;if(r.type!=="reaction"||!o||!a.has(o)){s.push(r);continue}const l=Si(r)==="out";n.set(`${o}\0${l?"out":"in"}`,{emoji:(r.text??"").trim(),propia:l})}const i={};for(const[r,o]of n){if(!o.emoji)continue;const l=r.split("\0")[0],c=i[l]??=[],d=c.find(u=>u.emoji===o.emoji);d?(d.cuantas+=1,d.propia=d.propia||o.propia):c.push({emoji:o.emoji,cuantas:1,propia:o.propia})}return{visibles:s,reaccionesPor:i}}const Kf=90;function zA(e){const a=(e.text??"").trim()||(e.transcript??"").trim();return a?a.length>Kf?`${a.slice(0,Kf)}…`:a:""}const DA="call";function qc(e){return e.type===DA}function IA(e){if(!qc(e))return null;const a=e.llamada??null,n=a?.direccion??(e.direction==="outbound"?"outbound":"inbound"),s=typeof a?.durationSeconds=="number"&&Number.isFinite(a.durationSeconds)&&a.durationSeconds>=0?Math.floor(a.durationSeconds):null,i=a?.resultado?.trim()?a.resultado.trim():null;return{callId:a?.callId?.trim()?a.callId.trim():null,quienInicio:n==="outbound"?"negocio":"persona",durationSeconds:s,resultado:i,conecto:s!==null&&s>0,enCurso:a!==null&&a.fin===null&&i===null}}const LA="cia-wa-borrador:",ap=new Map;function np(e){return`${LA}${e}`}function Ml(e){if(!e)return"";const a=ap.get(e);if(a!==void 0)return a;try{return sessionStorage.getItem(np(e))??""}catch{return""}}function Ad(e,a){if(e){if(!a){ap.delete(e);try{sessionStorage.removeItem(np(e))}catch{}return}ap.set(e,a);try{sessionStorage.setItem(np(e),a)}catch{}}}function FA(e,a,n){return(e===a?n:Ml(e)).trim().length>0}const wh=50;function OA(e,a){return e.has(a)||e.size<wh}function $A(e){const a=new Set,n=[];for(const s of e)a.has(s.id)||(a.add(s.id),n.push(s));return n}function qA(e,a){const n=e?.conversationId;if(!a.activa||!n)return"no";if(n===a.activa)return"si";const s=i=>!!i&&(i===a.activa||(a.hilosDelHistorial?.has(i)??!1));return s(n)||s(e?.reopenedFromId)?"si":a.conocidas.has(n)?"no":"quizas"}function BA(e,a){return e==="si"||a==="si"?"si":e==="quizas"||a==="quizas"?"quizas":"no"}function WA(e){const a=new Set;for(const n of e){const s=n;
943if(!s||typeof s!="object")continue;typeof s.id=="string"&&a.add(s.id);const i=Array.isArray(s.pages)?s.pages:[s];for(const r of i){const o=r?.items;if(Array.isArray(o))for(const l of o){const c=l?.id;typeof c=="string"&&a.add(c)}}}return a}const $v=["todas","equipo","mias"],li=Object.freeze({sonido:!0,escritorio:!1,alcance:"equipo"}),qv="cia.whatsapp.avisos.v1.";function Bv(e){return`${qv}${e}`}function Wv(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function UA(e){if(!e)return{...li};let a;try{a=JSON.parse(e)}catch{return{...li}}const n=a&&typeof a=="object"?a:{};return{sonido:typeof n.sonido=="boolean"?n.sonido:li.sonido,escritorio:typeof n.escritorio=="boolean"?n.escritorio:li.escritorio,alcance:$v.includes(n.alcance)?n.alcance:li.alcance}}function Uv(e,a){if(!a)return null;try{return a.getItem(Bv(e))}catch{return null}}const sp=new Map,VA=Object.freeze({...li});function Rd(e){if(!e)return VA;const a=Uv(e,Wv()),n=sp.get(e);if(n&&n.crudo===a)return n.prefs;const s=Object.freeze(UA(a));return sp.set(e,{crudo:a,prefs:s}),s}const ip=new Set;function KA(e,a,n=Wv()){let s=!1;if(n)try{n.setItem(Bv(e),JSON.stringify(a)),s=!0}catch{s=!1}s||sp.set(e,{crudo:Uv(e,n),prefs:Object.freeze({...a})});for(const i of ip)try{i()}catch{}return s}function HA(e){ip.add(e);const a=n=>{(n.key===null||n.key.startsWith(qv))&&e()};try{window.addEventListener("storage",a)}catch{}return()=>{ip.delete(e);try{window.removeEventListener("storage",a)}catch{}}}function Vv(e,a){const n=new Set;for(const s of e??[]){if(!s||typeof s.conversationId!="string"||!s.conversationId)continue;if(s.hasta==null){n.add(s.conversationId);continue}const i=Date.parse(s.hasta);(Number.isNaN(i)||i>a)&&n.add(s.conversationId)}return n}function QA(e,a){let n=null;for(const s of e??[]){if(!s?.hasta)continue;const i=Date.parse(s.hasta);!Number.isNaN(i)&&i>a&&(n===null||i<n)&&(n=i)}return n}function GA(e){if(e.isError){const a=e.error?.response?.status;return a===501||a===404?"apagado":"desconocido"}return e.isPending?"cargando":"encendido"}function ZA(e,a,n){const s=!!n&&a.assigneeUserId===n;return e==="todas"?!0:e==="mias"?s:a.mode==="human"&&(s||a.assigneeUserId==null)}function YA(e){const a=e.aviso;if(!a||a.entrante!==!0)return{avisar:!1,motivo:"no_es_entrante"};const n=typeof a.conversationId=="string"?a.conversationId:"";return n?e.silenciadas.has(n)?{avisar:!1,motivo:"silenciada"}:e.conversacion?.silenciada===!0?{avisar:!1,motivo:"silenciada"}:e.pestañaVisible&&e.hiloAbierto===n?{avisar:!1,motivo:"hilo_a_la_vista"}:e.conversacion?ZA(e.prefs.alcance,e.conversacion,e.yoId)?{avisar:!0,motivo:"avisar"}:{avisar:!1,motivo:"fuera_del_alcance"}:e.prefs.alcance==="todas"?{avisar:!0,motivo:"avisar"}:{avisar:!1,motivo:"sin_datos_de_la_conversacion"}:{avisar:!1,motivo:"sin_conversacion"}}function Hf(e){const a=e.prefs.sonido||e.prefs.escritorio;return{sonido:e.prefs.sonido,escritorio:e.prefs.escritorio&&e.permiso==="granted"&&!e.mirando,enPantalla:a&&e.pestañaAlFrente&&!e.enBandeja}}function XA(e){return e.sonido||e.escritorio||e.enPantalla}function JA(e){return e.mirando?0:e.pestañaAlFrente?150:450}function Qf(e,a=8e3){const n=globalThis.navigator?.locks;return!n||typeof n.request!="function"?Promise.resolve(!0):new Promise(s=>{try{n.request(`cia-wa-aviso:${e}`,{ifAvailable:!0},i=>{if(!i){s(!1);return}return s(!0),new Promise(r=>setTimeout(r,a))}).catch(()=>s(!0))}catch{s(!0)}})}const eR=[784,1047],Td=.08,tR=.02,aR=.09,nR=2e3,Kv="cia.whatsapp.avisos.ultimoSonido";let qn=null,Gf=0;function Hv(){try{return typeof window>"u"?null:window.AudioContext||window.webkitAudioContext||null}catch{return null}}function Qv(){return Hv()!==null}function sR(){if(typeof window>"u"||!Qv())return()=>{};const e=["pointerdown","keydown"],a=()=>{kh(),qn&&qn.state==="running"&&n()},n=()=>{for(const s of e)window.removeEventListener(s,a,!0)};for(const s of e)window.addEventListener(s,a,{capture:!0,passive:!0});return n}function kh(){const e=Hv();if(!e)return null;try{return qn||(qn=new e),qn.state==="suspended"&&qn.resume().catch(()=>{}),qn}catch{return null}}function iR(){try{const e=Number(window.localStorage.getItem(Kv));return Number.isFinite(e)?e:0}catch{return 0}}function rR(e,a){return e-a>=nR}function Gv(e={}){const a=Date.now();if(!e.forzar&&!rR(a,Math.max(Gf,iR())))return!1;const n=e.forzar?kh():qn;if(!n)return!1;try{if(n.state==="suspended"&&n.resume().catch(()=>{}),n.state!=="running"&&!e.forzar)return!1;let s=n.currentTime+.01;for(const i of eR){const r=n.createOscillator(),o=n.createGain();r.type="sine",r.frequency.value=i,o.gain.setValueAtTime(1e-4,s),o.gain.linearRampToValueAtTime(aR,s+.
943008),o.gain.exponentialRampToValueAtTime(1e-4,s+Td),r.connect(o).connect(n.destination),r.start(s),r.stop(s+Td+.02),s+=Td+tR}Gf=a;try{window.localStorage.setItem(Kv,String(a))}catch{}return!0}catch{return!1}}function Nh(){try{return typeof window<"u"&&"Notification"in window?window.Notification:null}catch{return null}}function Is(){const e=Nh();if(!e)return"no_soportado";try{const a=e.permission;return a==="granted"||a==="denied"?a:"default"}catch{return"no_soportado"}}async function oR(){const e=Nh();if(!e)return"no_soportado";try{const a=await new Promise(n=>{const s=e.requestPermission(i=>n(i));s&&typeof s.then=="function"&&s.then(n,()=>n(e.permission))});return a==="granted"||a==="denied"?a:"default"}catch{return Is()}}const Tr=new Map;function lR(e){const a=Nh();if(!a||Is()!=="granted")return!1;try{const n={body:e.cuerpo,tag:e.conversationId,renotify:!0,silent:!0,icon:e.icono},s=new a(e.titulo,n);return Tr.set(e.conversationId,s),s.onclick=()=>{try{window.focus()}catch{}try{e.alClic()}finally{s.close()}},s.onclose=()=>{Tr.get(e.conversationId)===s&&Tr.delete(e.conversationId)},!0}catch{return!1}}function cR(e){const a=Tr.get(e);if(a){Tr.delete(e);try{a.close()}catch{}}}const Mt="whatsapp.inbox.menu",dR=`${Mt}.motivo.enCurso`,uR=`${Mt}.motivo.hayMasReciente`,pR="flows.bandeja.menu.motivo.consultando",hR="flows.bandeja.menu.motivo.sinDato";function mR(e){if(!e.puedeVer)return[];const a=e.estado==="closed",n=p=>!!e.enCurso?.[p],s=p=>n(p)?{disabled:!0,motivo:dR}:{},i=[],r=[];a&&e.puedeOperar&&r.push({key:"reabrir",icono:"RotateCcw",rotulo:`${Mt}.reabrir`,tipo:"action",...e.hayMasReciente?{disabled:!0,motivo:uR}:s("reabrir")}),a&&e.hayMasReciente&&r.push({key:"irAReciente",icono:"ArrowUpRight",rotulo:`${Mt}.irAReciente`,tipo:"action"}),!a&&e.puedeOperar&&r.push({key:"cerrar",icono:"CircleCheck",rotulo:`${Mt}.cerrar`,tipo:"action"});const o=e.pospuestaHasta?Date.parse(e.pospuestaHasta):Number.NaN,l=e.estado==="snoozed"&&Number.isFinite(o)&&o>(e.ahoraMs??Date.now());!a&&e.puedeOperar&&l?r.push({key:"despertar",icono:"Sunrise",rotulo:`${Mt}.despertar`,tipo:"action",descripcion:{clave:`${Mt}.despertarDesc`,hastaIso:e.pospuestaHasta},...s("despertar")}):!a&&e.puedeOperar&&r.push({key:"posponer",icono:"Clock",rotulo:`${Mt}.posponer`,tipo:"action"}),e.puedeOperar&&r.push({key:"plantilla",icono:"FileText",rotulo:`${Mt}.plantilla`,tipo:"action"}),!a&&e.puedeOperar&&(r.push({key:"transferir",icono:"ArrowRightLeft",rotulo:`${Mt}.transferir`,tipo:"action"}),r.push({key:"asignar",icono:"UserPlus",rotulo:`${Mt}.asignar`,tipo:"action"})),e.puedeOperar&&r.push({key:"tipificar",icono:"Tag",rotulo:`${Mt}.tipificar`,tipo:"action"}),r.length&&i.push({key:"conversacion",items:r});const c=e.flujo;if(c?.disponible&&c.puedeOperar){const p=[];c.corrida?p.push({key:"sacarDelFlujo",icono:"CircleStop",rotulo:"flows.bandeja.menu.sacar",tipo:"action",descripcion:c.corrida.flowName.trim()?{clave:"flows.bandeja.menu.sacarDesc",params:{nombre:c.corrida.flowName.trim()}}:{clave:"flows.bandeja.menu.sacarDescSinNombre"},...s("sacarDelFlujo")}):p.push({key:"lanzarFlujo",icono:"Workflow",rotulo:"flows.bandeja.menu.lanzar",tipo:"action",...c.corrida===void 0?{disabled:!0,motivo:c.falloLaConsulta?hR:pR}:{}}),i.push({key:"flujo",items:p})}const d=[];e.puedeOperar&&d.push({key:"importante",icono:"Star",rotulo:`${Mt}.importante`,tipo:"checkbox",checked:e.importante,descripcion:{clave:`${Mt}.importanteDesc`},mantenerAbierto:!0,...s("importante")}),d.push({key:"silenciar",icono:"BellOff",rotulo:`${Mt}.silenciar`,tipo:"checkbox",checked:e.silenciada,descripcion:fR(e.silenciada,e.silencioHasta),mantenerAbierto:e.silenciada,...s("silenciar")}),i.push({key:"marcas",items:d});const u=[];return e.puedeOperar&&u.push({key:"exportar",icono:"Download",rotulo:`${Mt}.exportar`,tipo:"action",...s("exportar")}),u.push({key:"copiar",icono:"Copy",rotulo:`${Mt}.copiar`,tipo:"action"}),i.push({key:"salida",items:u}),e.esAdminReal&&e.puedeManejar&&i.push({key:"peligro",items:[{key:"eliminar",icono:"Trash2",rotulo:`${Mt}.eliminar`,tipo:"action",danger:!0,...s("eliminar")}]}),i}function fR(e,a){return e?a===void 0?{clave:`${Mt}.silenciadaDesc`}:a===null?{clave:`${Mt}.silenciadaSiempre`}:{clave:`${Mt}.silenciadaHasta`,hastaIso:a}:{clave:`${Mt}.silenciarDesc`}}const Zv=3,Pl=1e3;function xR(e){const a=e.trim().length;return a<Zv?{largo:a,valida:!1,problema:"corta"}:a>Pl?{largo:a,valida:!1,problema:"larga"}:{largo:a,valida:!0,problema:null}}const Jl=[{clave:"unaHora",horas:1},{clave:"tresHoras",horas:3},{clave:"manana",horas:24}];function rp(e,a){const n=Jl.find(s=>
943s.clave===e)??Jl[0];return new Date(a+n.horas*36e5).toISOString()}const Yv=[{clave:"unaHora",horas:1},{clave:"ochoHoras",horas:8},{clave:"unDia",horas:24},{clave:"siempre",horas:null}];function gR(e,a){const n=Yv.find(s=>s.clave===e);return!n||n.horas===null?null:new Date(a+n.horas*36e5).toISOString()}function Sh(e){const a=e?.response?.data;return a&&typeof a=="object"?a:null}function ec(e){const a=e?.response?.status;return typeof a=="number"?a:null}function _a(e){const a=Sh(e)?.message;if(typeof a=="string"&&a.trim())return a;if(Array.isArray(a)){const n=a.filter(s=>typeof s=="string"&&s.trim().length>0);if(n.length)return n.join(" · ")}return null}async function bR(e){const a=e?.response?.data;if(!a||typeof a.text!="function")return _a(e);try{const n=JSON.parse(await a.text());return _a({response:{data:n}})}catch{return null}}function yR(e){if(ec(e)!==409)return null;const a=Sh(e);if(a?.code!=="hilo_mas_reciente")return null;const n=a.conversationId;return typeof n=="string"&&n.length>0?n:null}const vR=["clave_de_api_no_borra","impersonacion_no_borra","solo_administradores"];function jR(e){if(ec(e)!==403)return null;const a=Sh(e)?.code;return typeof a=="string"&&vR.includes(a)?`whatsapp.inbox.eliminar.rechazo.${a}`:null}function wR(e,a){return["nombre","telefono","usuario","linea","estado","enlace"].filter(s=>typeof e[s]=="string"&&e[s].trim().length>0).map(s=>`${a[s]}: ${e[s]}`).join(`
944`)}function kR(e,a){return`${e.replace(/\/+$/,"")}/whatsapp/bandeja?c=${encodeURIComponent(a)}`}function NR(e){const a=e.trim();return a.startsWith("+")?a:`+${a}`}function Xv(e,a){const n=(e??"").trim(),s=(a??"").trim();return n&&s?`${n} · ${s}`:n||s||null}function SR(e,a,n){if(!e?.pages)return e;let s=!1;const i=e.pages.map(r=>!r||!r.items.some(o=>o.id===a)?r:(s=!0,{...r,items:r.items.map(o=>o.id===a?{...o,...n}:o)}));return s?{...e,pages:i}:e}function Ch(e,a){const n=[...e];return a?n.sort((s,i)=>{const r=a[s.id]??0,o=a[i.id]??0;return r!==o?r-o:(s.name??"").localeCompare(i.name??"")}):n}function Jr(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}const CR=3e4,_R=5e3,ER=8e3,AR=250,jo=["wa-conversations-conteos"],Jv=["wa-presencia"];function _h(){return se({queryKey:Jv,queryFn:async()=>(await T.get("/whatsapp/conversations/presencia")).data,refetchInterval:6e4,refetchIntervalInBackground:!0,placeholderData:e=>e})}function RR(e){return se({queryKey:jo,queryFn:async()=>(await T.get("/whatsapp/conversations/conteos")).data,enabled:e.habilitado,refetchInterval:e.intervalo,refetchIntervalInBackground:!0,placeholderData:a=>a})}function TR({activa:e,historialALaVista:a,onMensajeEnHiloAbierto:n,onReabierta:s}){const i=xe(),r=m.useRef(e);r.current=e;const o=m.useRef(a);o.current=a;const l=m.useRef(n);l.current=n;const c=m.useRef(s);c.current=s;const[d,u]=m.useState(()=>tp()),[p,f]=m.useState(!1);return m.useEffect(()=>{let h=!0,b=null,g=null,v=!1,y="no";const k=P=>{const O=r.current,K=O?i.getQueryData(["wa-historial",O]):void 0;return qA(P,{activa:O,hilosDelHistorial:K?.hilos?new Set(K.hilos.map(W=>W.id)):null,conocidas:WA(i.getQueriesData({queryKey:["wa-conversations"]}).map(([,W])=>W))})},w=(P,O="no")=>{v=v||P,y=BA(y,O),!g&&(g=setTimeout(()=>{g=null,i.invalidateQueries({queryKey:["wa-conversations"]}),i.invalidateQueries({queryKey:jo});const K=r.current;if(v&&K&&i.invalidateQueries({queryKey:["wa-messages",K]}),K&&y!=="no"){const W=y==="si"||o.current?.()===!0;i.invalidateQueries({queryKey:["wa-historial",K],...W?{}:{refetchType:"none"}})}v=!1,y="no"},AR))},j=P=>!!P?.conversationId&&P.conversationId===r.current,C=P=>{const O=j(P);if(w(O,k(P)),O&&P.conversationId)try{l.current?.(P.conversationId)}catch{}},N=P=>w(j(P)),S=P=>{const O=!!P?.reopenedFromId&&P.reopenedFromId===r.current;if(w(j(P)||O,k(P)),O&&P.conversationId)try{c.current?.(P.conversationId)}catch{}},_=P=>w(j(P)),R=()=>{i.invalidateQueries({queryKey:Jv})},A=()=>{b?.off("wa:message",C),b?.off("wa:status",N),b?.off("wa:conversation",S),b?.off("wa:turn",_),b?.off("wa:presence",R)},E=()=>{let P;try{P=vh()}catch{return}P===b&&P.listeners("wa:message").includes(C)||(A(),b=P,P.on("wa:message",C),P.on("wa:status",N),P.on("wa:conversation",S),P.on("wa:turn",_),P.on("wa:presence",R))};E();const I=Xl(P=>{!P||!h||b&&b.listeners("wa:message").includes(C)||E()});return()=>{h=!1,I(),g&&clearTimeout(g),A(),b=null}},[i]),m.useEffect(()=>{const h=Xl(u);u(tp());const b=setTimeout(()=>f(!0),ER);return()=>{h(),clearTimeout(b)}}
944,[]),{conectado:d,intervaloDeRespaldo:!d?_R:CR,caido:p&&!d}}function e0(e){const[a,n]=m.useState(()=>typeof window<"u"&&window.matchMedia(e).matches);return m.useEffect(()=>{const s=window.matchMedia(e),i=()=>n(s.matches);return i(),s.addEventListener("change",i),()=>s.removeEventListener("change",i)},[e]),a}function Bc(){return se({queryKey:["equipo-para-asignar"],queryFn:async()=>(await T.get("/users")).data.filter(e=>e.active!==!1),staleTime:5*6e4})}function MR({conversationId:e,mode:a,assigneeUserId:n,puedeOperar:s,yo:i,onCambio:r}){const{t:o}=M("misc"),l=xe(),[c,d]=m.useState(null),u=Bc(),p=se({queryKey:["wa-carga-equipo"],queryFn:async()=>(await T.get("/whatsapp/conversations/carga-del-equipo")).data,staleTime:3e4}),f=_h(),x=g=>f.data?.online?.includes(g)??!1,h=oe({mutationFn:async g=>(await T.patch(`/whatsapp/conversations/${e}/asignar`,g)).data,onSuccess:()=>{d(null),r(),l.invalidateQueries({queryKey:["wa-carga-equipo"]})},onError:g=>d(g?.response?.data?.message??o("whatsapp.inbox.asignar.falloGenerico"))}),b=n?n===i?o("whatsapp.inbox.asignar.yo"):u.data?.find(g=>g.id===n)?.name??n:o(a==="agent"?"whatsapp.inbox.asignar.ia":"whatsapp.inbox.asignar.nadie");return t.jsxs("span",{style:{display:"inline-flex",flexDirection:"column",gap:4},children:[t.jsx(vn,{disabled:!s||h.isPending,"aria-label":o("whatsapp.inbox.asignar.titulo"),triggerClassName:"cia-btn cia-btn-sm cia-btn-ghost cia-inbox-atiende-btn",triggerAriaLabel:o("whatsapp.inbox.asignar.disparador",{quien:b}),trigger:t.jsxs(t.Fragment,{children:[a==="agent"&&!n?t.jsx(Ft,{"aria-hidden":!0}):t.jsx(En,{"aria-hidden":!0}),t.jsx("span",{className:"cia-inbox-atiende-quien",children:b}),t.jsx(Ut,{"aria-hidden":!0})]}),items:[{key:"ia",label:o("whatsapp.inbox.asignar.ia"),icon:Ft,onSelect:()=>h.mutate({tipo:"ia"})},...Ch(u.data??[],p.data?.porUsuario).map(g=>({key:g.id,label:g.id===i?o("whatsapp.inbox.asignar.yo"):g.name,description:eo(o,Jr(p.data?.porUsuario?.[g.id])),icon:En,trailing:x(g.id)?t.jsxs("span",{className:"cia-inbox-presencia-punto",children:[t.jsx("span",{"aria-hidden":"true",className:"cia-inbox-presencia-dot"}),o("whatsapp.inbox.presencia.conectado")]}):void 0,onSelect:()=>h.mutate({tipo:"persona",userId:g.id})})),{key:"nadie",label:o("whatsapp.inbox.asignar.nadie"),description:eo(o,Jr(p.data?.sinAsignar)),separatorAbove:!0,onSelect:()=>h.mutate({tipo:"nadie"})}]}),c?t.jsx(le,{tone:"bad",children:c}):null]})}function eo(e,a){return a===null?void 0:e("whatsapp.inbox.carga.abiertas",{count:a})}function PR({conversationId:e,state:a,snoozedUntil:n,puedeOperar:s,onCambio:i}){const{t:r}=M("misc"),o=xe(),[l,c]=m.useState(""),[d,u]=m.useState(!1),[p,f]=m.useState(null),x=se({queryKey:["wa-notas",e],queryFn:async()=>(await T.get(`/whatsapp/conversations/${e}/notas`)).data}),h=oe({mutationFn:async j=>(await T.patch(`/whatsapp/conversations/${e}/posponer`,{hasta:j})).data,onSuccess:()=>{f(null),i()},onError:j=>f(j?.response?.data?.message??r("whatsapp.inbox.asignar.falloGenerico"))}),b=oe({mutationFn:async j=>(await T.post(`/whatsapp/conversations/${e}/notas`,{texto:j})).data,onSuccess:()=>{c(""),f(null),o.invalidateQueries({queryKey:["wa-notas",e]})},onError:j=>f(j?.response?.data?.message??r("whatsapp.inbox.asignar.falloGenerico"))}),g=a==="snoozed"&&n&&new Date(n).getTime()>Date.now(),y=e0("(max-height: 740px)")?0:1,k=[...x.data??[]].reverse(),w=d?k:k.slice(0,y);return t.jsxs(t.Fragment,{children:[t.jsxs(Rs,{title:r("whatsapp.inbox.posponer.titulo"),icon:Qa,hint:r("whatsapp.inbox.posponer.explicacion"),aside:g?t.jsx(Ie,{size:"sm",variant:"outline",disabled:!s,disabledReason:r("whatsapp.inbox.noPermission"),loading:h.isPending,onClick:()=>h.mutate(null),children:r("whatsapp.inbox.posponer.despertar")}):t.jsx("span",{className:"cia-inbox-posponer-opciones",role:"group","aria-label":r("whatsapp.inbox.posponer.accion"),children:Jl.map(j=>t.jsx(Ie,{size:"sm",variant:"outline","aria-label":r(`whatsapp.inbox.posponer.${j.clave}`),disabled:!s||h.isPending,disabledReason:s?void 0:r("whatsapp.inbox.noPermission"),onClick:()=>h.mutate(rp(j.clave,Date.now())),children:r(`whatsapp.inbox.posponer.corto.${j.clave}`)},j.clave))}),children:[g?t.jsx("span",{className:"cia-inbox-posponer-estado",children:r("whatsapp.inbox.posponer.hasta",{cuando:Be(n)})}):null,p?t.jsx(le,{tone:"bad",children:p}):null]}),t.jsxs(Rs,{title:r("whatsapp.inbox.notas.titulo"),icon:hy,hint:r("whatsapp.inbox.notas.aviso"),aside:k.length>y?t.jsx("button",{type:"button",className:"cia-inbox-ver-todas",onClick:()=>u(j=>!j),children:d?r("whatsapp.inbox.notas.verMenos"):r("whatsapp.inbox.notas.verTodas",{n:k.length})}):k.length===1?t.jsx("span",{className:"cia-inbox-sub",children:"1"}):void 0,children:[s?t.jsxs("div",{className:"cia-inbox-notas-nueva",children:[t.jsx("textarea",{value:l,onCh
944ange:j=>c(j.target.value),placeholder:r("whatsapp.inbox.notas.placeholder"),"aria-label":r("whatsapp.inbox.notas.placeholder"),rows:1,maxLength:4e3}),t.jsx(Ie,{size:"sm",variant:"outline",disabled:!l.trim(),disabledReason:r("whatsapp.inbox.notas.motivoVacia"),loading:b.isPending,onClick:()=>b.mutate(l.trim()),children:r("whatsapp.inbox.notas.agregarCorto")})]}):null,w.length?t.jsx("ul",{className:"cia-inbox-notas-lista",children:w.map(j=>t.jsxs("li",{children:[t.jsx(Sn,{name:j.authorName??r("whatsapp.inbox.notas.alguien"),size:"sm"}),t.jsxs("div",{className:"cia-inbox-notas-cuerpo",children:[t.jsxs("span",{className:"cia-inbox-notas-quien",children:[t.jsx("strong",{children:j.authorName??r("whatsapp.inbox.notas.alguien")})," · ",Be(j.createdAt)]}),t.jsx("span",{className:"cia-inbox-notas-texto",children:j.texto})]})]},j.id))}):k.length===0?t.jsx("span",{className:"cia-inbox-sub",children:r("whatsapp.inbox.notas.vacio")}):null]})]})}function tn(e,a){const n=[e.invalidateQueries({queryKey:["wa-conversations"]}),e.invalidateQueries({queryKey:jo})];return a&&n.push(e.invalidateQueries({queryKey:["wa-messages",a]}),e.invalidateQueries({queryKey:["wa-ficha",a]}),e.invalidateQueries({queryKey:["wa-notas",a]})),Promise.all(n)}async function op(e,a,n){await e.cancelQueries({queryKey:["wa-conversations"]});const s=e.getQueriesData({queryKey:["wa-conversations"]});return e.setQueriesData({queryKey:["wa-conversations"]},i=>SR(i,a,n)),()=>{for(const[i,r]of s)e.setQueryData(i,r)}}function t0({conversationId:e,onNavegar:a,onReabierta:n}){const{t:s}=M("misc"),i=xe(),r=oe({mutationFn:async o=>(await T.post(`/whatsapp/conversations/${o}/reopen`)).data,onSuccess:(o,l)=>{const c=o?.conversationId??l;tn(i,l),J({tone:"ok",title:s("whatsapp.inbox.reabrir.listo")}),c!==l&&a(c),n?.(c)},onError:(o,l)=>{const c=yR(o);if(c){tn(i,l),J({tone:"info",title:s("whatsapp.inbox.reabrir.masReciente"),desc:s("whatsapp.inbox.reabrir.masRecienteDesc")}),a(c);return}J({tone:"bad",title:s("whatsapp.inbox.reabrir.fallo"),desc:_a(o)??s("whatsapp.inbox.reabrir.falloDesc")})}});return{reabrir:()=>{r.isPending||r.mutate(e)},enCurso:r.isPending}}function wo({legend:e,opciones:a,value:n,onChange:s,disabled:i}){const r=m.useId();return t.jsxs("fieldset",{className:"cia-waop-lista",disabled:i,children:[t.jsx("legend",{className:"cia-sr-only",children:e}),a.map(o=>{const l=n===o.value;return t.jsxs("label",{className:"cia-waop-opcion","data-checked":l?"":void 0,children:[t.jsx("input",{type:"radio",className:"cia-waop-radio",name:r,value:o.value,checked:l,"data-cia-autofocus":l?"":void 0,onChange:()=>s(o.value)}),o.icon?t.jsx("span",{className:"cia-waop-opcion-icono","aria-hidden":"true",children:o.icon}):null,t.jsxs("span",{className:"cia-waop-opcion-texto",children:[t.jsx("span",{className:"cia-waop-opcion-rotulo",children:o.label}),o.description?t.jsx("span",{className:"cia-waop-opcion-desc",children:o.description}):null]}),o.trailing?t.jsx("span",{className:"cia-waop-opcion-fin",children:o.trailing}):null]},o.value)})]})}function a0({etiqueta:e}){return t.jsx("div",{className:"cia-waop-lista","aria-busy":"true","aria-label":e,children:[0,1,2].map(a=>t.jsx(ge,{h:44,r:8},a))})}function n0({texto:e}){return t.jsx("span",{className:"cia-waop-presencia",children:e})}const Eh=["wa-carga-equipo"];function s0(){return se({queryKey:Eh,queryFn:async()=>(await T.get("/whatsapp/conversations/carga-del-equipo")).data,staleTime:3e4})}function zR({open:e,onClose:a,conversationId:n,nombreDelContacto:s,assigneeUserId:i,agenteActualId:r,yo:o,onTransferida:l}){const{t:c}=M("misc"),d=xe(),u=m.useId(),p=`${u}-ayuda`,f=`${u}-meta`,x=`${u}-panel`,[h,b]=m.useState("persona"),[g,v]=m.useState({persona:null,agente:null}),[y,k]=m.useState(""),[w,j]=m.useState(!1),C=Bc(),N=s0(),S=_h(),_=se({queryKey:["agents"],enabled:e&&h==="agente",queryFn:async()=>{const z=(await T.get("/agents")).data;return Array.isArray(z)?z:[]},staleTime:6e4}),R=Ch((C.data??[]).filter(z=>z.id!==i),N.data?.porUsuario),A=(_.data??[]).filter(z=>z.status!=="archived"&&z.id!==(r??void 0)),E=R.map(z=>({value:z.id,label:z.id===o?c("whatsapp.inbox.asignar.yo"):z.name,description:eo(c,Jr(N.data?.porUsuario?.[z.id])),icon:t.jsx(En,{}),trailing:S.data?.online?.includes(z.id)?t.jsx(n0,{texto:c("whatsapp.inbox.presencia.conectado")}):void 0})),I=A.map(z=>({value:z.id,label:z.name,description:z.status==="draft"?c("whatsapp.inbox.transferir.borrador"):void 0,icon:t.jsx(Ft,{})})),P=g[h],O=h==="persona"?R.find(z=>z.id===P)?.name??"":A.find(z=>z.id===P)?.name??"",K=xR(y),W=!!P&&K.valida,V=oe({mutationFn:async z=>(await T.post(`/whatsapp/conversations/${z.id}/transferir`,{destino:z.destino,nota:z.nota})).data,onSuccess:(z,D)=>{tn(d,D.id),d.invalidateQueries({queryKey:Eh});const F=D.destino.tipo==="persona"&&!!o&&D.destino.userId===o;J({tone:"ok",title:F?c("whatsapp.inbox.transferir.listoAMi"):c("whatsapp.inbox.transferir.listo",{nombre:O}),desc:c("whatsapp.inbox.transferir.listoDesc")}),l?.(),a()}}),U=()=>{j(!0),!(!W||!P||V.isPending)&&V.mutate({id:n,destino:h==="agente"?{tipo:"agente",agentId:P}:{tipo:"persona",userId:P},nota:y.trim()})},X=P?K.problema==="corta"?c("whatsapp.inbox.transferir.notaCorta",{min:Zv}):K.problema==="larga"?c("whatsapp.inbox.transferir.notaLarga",{max:Pl}):null:c("whatsapp.inbox.transferir.faltaDestino"),ie=h==="persona"?C:_,de=h==="persona"?E:I;let $;return ie.isPending?$=t.jsx(a0,{etiqueta:c("whatsapp.inbox.transferir.cargando")}):ie.isError?$=t.jsx(le,{tone:"bad",title:c(h==="persona"?"whatsapp.inbox.transferir.errorPersonas":"whatsapp.inbox.transferir.errorAgentes"),action:{label:c("whatsapp.inbox.transferir.reintentar"),onClick:()=>void ie.refetch()},actionPlacement:"end",children:_a(ie.error)??c("whatsapp.inbox.transferir.errorDesc")}):de.length===0?$=t.jsx(st,{mini:!0,icon:h==="persona"?En:Ft,title:c(h==="persona"?"whatsapp.inbox.transferir.sinPersonas":"whatsapp.inbox.transferir.sinAgentes"),desc:c(h==="persona"?"whatsapp.inbox.transferir.sinPersonasDesc":"whatsapp.inbox.transferir.sinAgentesDesc")}):$=t.jsx(wo,{legend:c(h==="persona"?"whatsapp.inbox.transferir.personasAria":"whatsapp.inbox.transferir.agentesAria"),opciones:de,value:P,onChange:z=>v(D=>({...D,[h]:z})),disabled:V.isPending}),t.jsx(ot,{open:e,onClose:a,maxWidth:520,title:c("whatsapp.inbox.transferir.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{onClick:a,children:c("whatsapp.inbox.transferir.cancelar")}
944),t.jsx(Ie,{variant:"cta",disabled:!W,loading:V.isPending,onClick:U,children:c("whatsapp.inbox.transferir.confirmar")})]}),children:t.jsxs("div",{className:"cia-waop-cuerpo",children:[t.jsx("p",{className:"cia-waop-desc",children:c("whatsapp.inbox.transferir.desc",{nombre:s})}),t.jsx(Fi,{items:[{id:"persona",label:c("whatsapp.inbox.transferir.aPersona"),panelId:x},{id:"agente",label:c("whatsapp.inbox.transferir.aAgente"),panelId:x}],active:h,onChange:z=>b(z==="agente"?"agente":"persona")}),t.jsx("div",{id:x,role:"tabpanel",className:"cia-waop-panel","aria-label":c(h==="persona"?"whatsapp.inbox.transferir.aPersona":"whatsapp.inbox.transferir.aAgente"),children:$}),t.jsxs("div",{className:"cia-waop-campo",children:[t.jsx("label",{className:"cia-waop-rotulo-campo",htmlFor:u,children:c("whatsapp.inbox.transferir.notaLabel")}),t.jsx("textarea",{id:u,className:"input cia-waop-nota",value:y,maxLength:Pl,rows:3,placeholder:c("whatsapp.inbox.transferir.notaPlaceholder"),"aria-describedby":`${p} ${f}`,"aria-invalid":w&&K.problema==="corta"?!0:void 0,"aria-required":"true",disabled:V.isPending,onChange:z=>k(z.target.value),onBlur:()=>j(!0),onKeyDown:z=>{z.key==="Enter"&&(z.ctrlKey||z.metaKey)&&(z.preventDefault(),U())}}),t.jsx("span",{id:p,className:"cia-waop-ayuda",children:c("whatsapp.inbox.transferir.notaAyuda")}),t.jsxs("div",{id:f,className:"cia-waop-meta",children:[t.jsx("span",{"aria-live":"polite",children:X}),t.jsx("span",{className:"cia-waop-contador",children:c("whatsapp.inbox.transferir.contador",{n:y.length,max:Pl})})]})]}),V.isError?t.jsx(le,{tone:"bad",title:c("whatsapp.inbox.transferir.fallo"),children:_a(V.error)??c("whatsapp.inbox.transferir.falloDesc")}):null]})})}const Wc=["wa-silenciadas"];function Ah(e=!0){return se({queryKey:Wc,queryFn:async()=>{const a=(await T.get("/whatsapp/conversations/silenciadas")).data;return{items:Array.isArray(a?.items)?a.items:[]}},enabled:e,staleTime:6e4})}function Ci(e,a=new Date){const n=new Date(e);return Number.isNaN(n.getTime())?Be(e):n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()?n.toLocaleTimeString(Te(),{hour:"2-digit",minute:"2-digit"}):Be(e)}function DR({open:e,onClose:a,conversationId:n}){const{t:s}=M("misc"),i=xe(),[r,o]=m.useState("unaHora"),l=oe({mutationFn:async u=>(await T.put(`/whatsapp/conversations/${u.id}/silencio`,{hasta:gR(u.clave,Date.now())})).data,onSuccess:async(u,p)=>{await op(i,p.id,{silenciada:!0}),i.invalidateQueries({queryKey:Wc}),tn(i,p.id),J({tone:"ok",title:s("whatsapp.inbox.silenciar.listo"),desc:u.hasta?s("whatsapp.inbox.silenciar.listoHasta",{cuando:Ci(u.hasta)}):s("whatsapp.inbox.silenciar.listoSiempre")}),a()}}),c=new Date,d=Yv.map(u=>({value:u.clave,label:s(`whatsapp.inbox.silenciar.${u.clave}`),description:u.horas===null?s("whatsapp.inbox.silenciar.siempreDesc"):s("whatsapp.inbox.silenciar.hastaAprox",{cuando:Ci(new Date(c.getTime()+u.horas*36e5).toISOString(),c)})}));return t.jsx(ot,{open:e,onClose:a,maxWidth:380,title:s("whatsapp.inbox.silenciar.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{onClick:a,children:s("whatsapp.inbox.silenciar.cancelar")}
944),t.jsx(Ie,{variant:"cta",loading:l.isPending,onClick:()=>{l.isPending||l.mutate({id:n,clave:r})},children:s("whatsapp.inbox.silenciar.confirmar")})]}),children:t.jsxs("div",{className:"cia-waop-cuerpo",children:[t.jsx("p",{className:"cia-waop-desc",children:s("whatsapp.inbox.silenciar.desc")}),t.jsx(wo,{legend:s("whatsapp.inbox.silenciar.aria"),opciones:d,value:r,onChange:u=>o(u),disabled:l.isPending}),l.isError?t.jsx(le,{tone:"bad",title:s("whatsapp.inbox.silenciar.fallo"),children:_a(l.error)??s("whatsapp.inbox.silenciar.falloDesc")}):null]})})}function IR(e=!0){const{data:a}=Ah(e),n=a?.items,[s,i]=m.useState(0);return m.useEffect(()=>{const r=QA(n,Date.now());if(r===null)return;const o=Math.min(Math.max(r-Date.now()+50,0),2**31-1),l=setTimeout(()=>i(c=>c+1),o);return()=>clearTimeout(l)},[n,s]),m.useMemo(()=>Vv(n,Date.now()),[n,s])}function i0(e){const a=m.useSyncExternalStore(HA,()=>Rd(e),()=>Rd(null)),n=m.useCallback(s=>{e&&KA(e,{...Rd(e),...s})},[e]);return[a,n]}function LR(){const[e,a]=m.useState(()=>Is()),n=m.useCallback(()=>a(Is()),[]);return m.useEffect(()=>(window.addEventListener("focus",n),document.addEventListener("visibilitychange",n),()=>{window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",n)}),[n]),[e,a,n]}function FR({size:e,variant:a="soft"}){const{t:n}=M("misc"),s=Pe(S=>S.user?.id??null),i=rt(S=>S.isActive()),[r,o]=i0(s),[l,c,d]=LR(),[u,p]=m.useState(!1),f=m.useId(),x=m.useId(),h=Qv(),b=r.escritorio&&l==="granted",g=r.sonido||b,v=!i&&l!=="denied"&&l!=="no_soportado",y="whatsapp.inbox.avisos",k=S=>{S&&kh(),o({sonido:S})},w=async S=>{if(!S){o({escritorio:!1});return}let _=Is();_==="default"&&(_=await oR()),c(_),o({escritorio:_==="granted"})},j=()=>{p(!Gv({forzar:!0}))};let C;l==="no_soportado"?C=n(`${y}.escritorioNoSoportado`):l==="default"?C=n(`${y}.escritorioAyudaPedir`):C=n(`${y}.escritorioAyudaActiva`);const N=$v.map(S=>({value:S,label:n(`${y}.alcance.${S}`),description:n(`${y}.alcance.${S}Desc`)}));return t.jsx(Or,{iconTrigger:{icon:g?t.jsx(Qb,{}):t.jsx(Qp,{}),label:n(g?`${y}.trigger`:`${y}.triggerApagados`),variant:a,size:e},placement:"bottom-end",width:300,ariaLabel:n(`${y}.titulo`),onOpenChange:S=>{S&&d()},children:t.jsxs("div",{className:"cia-waav-panel",children:[t.jsxs("div",{className:"cia-waav-cabeza",children:[t.jsx("span",{className:"cia-waav-titulo",children:n(`${y}.titulo`)}),t.jsx("span",{className:"cia-waav-sub",children:n(`${y}.subtitulo`)})]}),i?t.jsx(le,{tone:"neutral",children:n(`${y}.soporte`)}):null,t.jsxs("div",{className:"cia-waav-grupo",children:[t.jsxs("div",{className:"cia-waav-fila",children:[t.jsx("label",{className:"cia-waav-rotulo",htmlFor:f,children:n(`${y}.sonido`)}),t.jsx(vt,{id:f,checked:r.sonido,onChange:k,disabled:i})]}),t.jsxs("div",{className:"cia-waav-fila",children:[t.jsx("label",{className:"cia-waav-rotulo",htmlFor:x,children:n(`${y}.escritorio`)}),t.jsx(vt,{id:x,checked:b,onChange:w,disabled:!v})]}),i?null:l==="denied"?t.jsx(le,{tone:"warn",title:n(`${y}.bloqueadoTitulo`),children:n(`${y}.bloqueadoCuerpo`)}):t.jsx("p",{className:"cia-waav-ayuda",children:C})]}),!g&&!i?t.jsx("p",{className:"cia-waav-ayuda",children:n(`${y}.apagadoTodo`)}):null,t.jsxs("div",{className:"cia-waav-grupo cia-waav-grupo--alcance",children:[t.jsx("span",{className:"cia-waav-seccion","aria-hidden":"true",children:n(`${y}.alcanceTitulo`)}),t.jsx(wo,{legend:n(`${y}.alcanceTitulo`),opciones:N,value:r.alcance,onChange:S=>o({alcance:S}),disabled:i})]}),t.jsxs("div",{className:"cia-waav-pie",children:[t.jsx(Ie,{size:"sm",icon:t.jsx(w2,{}),onClick:j,disabled:!h,children:n(`${y}.probarSonido`)}),!h||u?t.jsx("p",{className:"cia-waav-ayuda",children:n(`${y}.sinAudio`)}):null,t.jsx("p",{className:"cia-waav-ayuda",children:n(`${y}.silenciarPista`)})]})]})})}const Mr="/whatsapp/bandeja",OR="/favicon.svg?v=2",$R=15e3,qR=100,BR=300,WR=2e4;function Md(e,a){const n=e===Mr||e.startsWith(`${Mr}/`);let s=!0,i=!0;try{s=document.visibilityState==="visible",i=document.hasFocus()}catch{}return{enBandeja:n,hiloAbierto:n?a:null,pestañaAlFrente:s,mirando:s&&i}}function UR(e){return new Promise(a=>setTimeout(a,e))}function VR(){const{t:e}=M("misc"),a=dt(),n=Pe(x=>x.user),s=rt(x=>x.isActive()),i=!!n&&n.role!=="superadmin"&&!!n.organizationId&&!s&&lt(n,"whatsapp.view"),r=Ah(i),o=IR(i),[l]=i0(i&&n?n.id:null),c=i?GA(r):"apagado",d=c==="encendido"||c==="desconocido",u=bu({select:x=>x.location.pathname}),p=bu({select:x=>{const h=x.location.search?.c;return typeof h=="string"&&h?h:null}}),f=m.useRef({prefs:l,silenciadas:o,silenciosConocidos:r.isSuccess,silenciosEl:r.dataUpdatedAt,refrescarSilencios:r.refetch,yoId:n?.id??null,pathname:u,hiloEnLaUrl:p,t:e,nav:a});return f.current={prefs:l,silenciadas:o,silenciosConocidos:r.isSuccess,silenciosEl:r.dataUpdatedAt,refrescarSilencios:r.refetch,yoId:n?.id??null,pathname:u,hiloEnLaUrl:p,t:e,nav:a},m.useEffect(()=>{if(i)return sR()},[i]),m.useEffect(()=>{p&&(u===Mr||u.startsWith(`${Mr}/`))&&cR(p)},[p,u]),m.useEffect(()=>{if(!d)return;let x=!0,h=null;const b=new Set,g=new Map,v=new Map,y=_=>{if(b.add(_),b.size>BR){const R=b.values().next().value;R!==void 0&&b.delete(R)}},k=(_,R)=>{const A=g.get(_);if(A&&A.vence>Date.now()&&A.pedidaEl>=R)return Promise.resolve(A.lectura);const E=v.get(_);if(E)return E;const I=Date.now(),P=T.get(`/whatsapp/conversations/${encodeURIComponent(_)}`).then(O=>({estado:"ok",datos:O.data}
944)).catch(O=>{const K=O?.response?.status;return K===401||K===403||K===404?{estado:"sin_acceso"}:{estado:"error"}}).then(O=>{if(v.delete(_),O.estado!=="error"&&(g.set(_,{lectura:O,vence:Date.now()+$R,pedidaEl:I}),g.size>qR)){const K=g.keys().next().value;K!==void 0&&g.delete(K)}return O});return v.set(_,P),P},w=async _=>{if(!_||_.entrante!==!0||typeof _.conversationId!="string"||!_.conversationId)return;const R=_.conversationId,A=_.messageId?`m:${_.messageId}`:`c:${R}:${_.at??""}`;if(b.has(A))return;y(A);const E=Md(f.current.pathname,f.current.hiloEnLaUrl);if(E.mirando&&E.hiloAbierto===R){Qf(A);return}const I=JA(E);if(I>0&&await UR(I),!x||!await Qf(A)||!x)return;let P=f.current,O=P.silenciadas,K=P.silenciosEl;if(O.has(R))return;const W=Md(P.pathname,P.hiloEnLaUrl),V=Is();if(!XA(Hf({prefs:P.prefs,permiso:V,...W})))return;if(P.silenciosConocidos&&Date.now()-P.silenciosEl>WR){try{const te=await P.refrescarSilencios({cancelRefetch:!1});te.data&&(O=Vv(te.data.items,Date.now()),K=Math.max(K,te.dataUpdatedAt||Date.now()))}catch{}if(!x)return}const U=await k(R,K);if(!x||U.estado==="sin_acceso")return;const X=U.estado==="ok"?U.datos:null;P=f.current;const ie=Md(P.pathname,P.hiloEnLaUrl);if(!YA({aviso:_,conversacion:X,prefs:P.prefs,silenciadas:O,yoId:P.yoId,hiloAbierto:ie.hiloAbierto,pestañaVisible:ie.mirando}).avisar)return;const $=Hf({prefs:P.prefs,permiso:Is(),...ie}),z=X?ga(X):P.t("whatsapp.inbox.avisos.tituloGenerico"),D=P.t("whatsapp.inbox.avisos.cuerpo"),F=P.nav,G=()=>{F({to:Mr,search:{c:R}})};$.sonido&&Gv(),$.escritorio&&lR({conversationId:R,titulo:z,cuerpo:D,icono:OR,alClic:G}),$.enPantalla&&J({title:z,desc:D,tone:"info",icon:Ba,action:{label:P.t("whatsapp.inbox.avisos.ver"),onClick:G}})},j=_=>{w(_).catch(()=>{})},C=_=>{_?.conversationId&&g.delete(_.conversationId),_?.reopenedFromId&&g.delete(_.reopenedFromId)},N=()=>{let _;try{_=vh()}catch{return}_===h&&_.listeners("wa:message").includes(j)||(h?.off("wa:message",j),h?.off("wa:conversation",C),h=_,_.on("wa:message",j),_.on("wa:conversation",C))};N();const S=Xl(_=>{!_||!x||h&&h.listeners("wa:message").includes(j)||N()});return()=>{x=!1,S(),h?.off("wa:message",j),h?.off("wa:conversation",C),h=null}},[d]),null}function KR(){const{can:e}=tt(),{t:a}=M("settings"),n=dt(),s=wl(c=>c.open),i=wl(c=>c.reason),r=wl(c=>c.close);if(!s||!i)return null;const o={title:a(`paywall.reasons.${i}.title`,{defaultValue:a("paywall.reasons.trial_exhausted.title")}),body:a(`paywall.reasons.${i}.body`,{defaultValue:a("paywall.reasons.trial_exhausted.body")})},l=i==="payment_suspended";return t.jsx(ot,{open:s,onClose:r,eyebrow:a("paywall.eyebrow"),title:o.title,footer:t.jsxs("div",{className:"cia-row cia-gap-2",style:{justifyContent:"flex-end"},children:[t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost",onClick:r,children:a("paywall.notNow")}),e("billing.manage")&&t.jsxs("button",{type:"button",className:"cia-btn cia-btn-cta",onClick:()=>{r(),n(l?{to:"/settings",search:{s:"billing"}}:{to:"/plan"})},children:[a(l?"paywall.updatePayment":"paywall.choosePlan")," ",t.jsx(oa,{size:14})]})]}),children:t.jsxs("div",{className:"cia-row cia-gap-3",style:{alignItems:"flex-start"},children:[t.jsx("span",{style:{flex:"none",width:40,height:40,borderRadius:10,display:"grid",placeItems:"center",background:"var(--cia-bg-tint)",color:"var(--cia-cta-500)"},children:t.jsx(_t,{size:20})}),t.jsx("p",{className:"cia-text-2",style:{margin:0,fontSize:14,lineHeight:1.6},children:o.body})]})})}function HR({children:e}){const a=rt(i=>i.isActive()),n=xt(i=>i.resolved),s=dt();return m.useEffect(()=>{if(rt.getState().isActive())return;const i=Pe.getState().user;!i||i.role==="superadmin"||i.onboardingState===void 0&&T.get("/auth/me").then(({data:r})=>{const o=Pe.getState().user;if(o&&o.id===r?.id){const l={...o,...r};Pe.getState().setUser(l),gc(l)&&s({to:"/onboarding",search:{preview:void 0}})}}).catch(()=>{})},[]),m.useEffect(()=>{rt.getState().isActive()||Ua.getState().mode==="auto"&&T.get("/organizations/me").then(({data:i})=>Ua.getState().applyTenantDefault(i?.businessProfile?.language)).catch(()=>{})},[]),t.jsxs("div",{className:"cia cia-shell-root flex flex-col","data-theme":n,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:[a&&t.jsx(jE,{}),t.jsx(wE,{}),t.jsxs("div",{className:"flex flex-1 min-h-0",children:[t.jsx(yE,{}),t.jsx("div",{className:"flex-1 flex flex-col overflow-hidden min-h-0 min-w-0",children:e})]}),t.jsx(Hy,{}),t.jsx(lE,{}),t.jsx(KR,{}),t.jsx(vA,{}),t.jsx(VR,{})]})}
944class QR extends m.Component{constructor(a){super(a),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(a,n){try{T.post("/client-errors",{message:a.message,stack:a.stack,componentStack:n.componentStack??void 0,url:typeof window<"u"?window.location.href:void 0}).catch(()=>{})}catch{}}handleReload=()=>{window.location.reload()};render(){return this.state.hasError?this.props.fallback!==void 0?this.props.fallback:t.jsx(b_,{onReload:this.handleReload}):this.props.children}}const GR="https://api.enlassa.ai/api/v1".replace(/\/+$/,"");function tc(e){return`${GR}/auth/oauth/${e}/start`}function r0(){const[e,a]=m.useState({email:!0,google:!1,microsoft:!1,turnstile:{enabled:!1,siteKey:null},trialMinutes:null});return m.useEffect(()=>{let n=!0;return T.get("/auth/providers").then(({data:s})=>{if(n){const i=s?.turnstile;a({email:s?.email!==!1,google:!!s?.google,microsoft:!!s?.microsoft,turnstile:i?.enabled&&i?.siteKey?{enabled:!0,siteKey:i.siteKey}:{enabled:!1,siteKey:null},trialMinutes:Number.isFinite(Number(s?.trialMinutes))&&Number(s?.trialMinutes)>0?Math.round(Number(s.trialMinutes)):null})}}).catch(()=>{}),()=>{n=!1}},[]),e}function Rh({children:e,size:a=16,stroke:n=1.75,style:s,className:i}){return t.jsx("svg",{width:a,height:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:s,className:i,children:e})}const ZR=e=>t.jsxs(Rh,{...e,children:[t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),t.jsx("polyline",{points:"12 5 19 12 12 19"})]}),YR=e=>t.jsxs(Rh,{...e,children:[t.jsx("circle",{cx:"12",cy:"12",r:"4"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"4"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"6.34",y2:"6.34"}),t.jsx("line",{x1:"17.66",y1:"17.66",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"4",y2:"12"}),t.jsx("line",{x1:"20",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"6.34",y2:"17.66"}),t.jsx("line",{x1:"17.66",y1:"6.34",x2:"19.78",y2:"4.22"})]}),XR=e=>t.jsx(Rh,{...e,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"})});function JR(){const a=Array.from({length:64},(n,s)=>{const i=s/63,r=Math.sin(i*Math.PI),o=Math.sin(s*12.9898+78.233)*43758.5453,l=o-Math.floor(o);return 8+r*28+l*14});return t.jsx("div",{className:"cia-row",style:{gap:3,height:64,alignItems:"center"},children:a.map((n,s)=>t.jsx("span",{style:{flex:1,height:n+"px",background:s<64*.62?"linear-gradient(180deg, var(--cia-cta-500) 0%, var(--cia-cta-500) 70%, var(--cia-brand-300) 100%)":"var(--hero-wave-idle)",borderRadius:1.5,animation:s<64*.62?`cia-barlive ${.6+s%7*.07}s ease-in-out infinite alternate`:"none",animationDelay:s*18+"ms",transformOrigin:"center"}},s))})}function Pd({who:e,text:a,delay:n=0,typing:s=!1}){const{t:i}=M("auth");return t.jsxs("div",{className:`cia-row cia-gap-3 cia-fade-up${s?" cia-caret":""}`,style:{alignItems:"flex-start",animationDelay:n+"s"},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:10,color:e==="agent"?"var(--cia-cta-500)":"var(--cia-sky-500)",letterSpacing:"0.06em",marginTop:2,width:44,flexShrink:0},children:e==="agent"?"AURA":i("hero.transcriptUser")}),t.jsx("span",{style:{flex:1,color:e==="agent"?"var(--hero-ink)":"var(--hero-soft)"},children:a})]})}function Go({label:e}){return t.jsx("div",{className:"cia-mono",style:{fontSize:11,color:"var(--hero-strong)",letterSpacing:"0.06em",textTransform:"uppercase"},children:e})}function eT(){const{t:e}=M("auth");return t.jsxs("div",{className:"cia-col cia-gap-6",children:[t.jsxs("div",{className:"cia-row cia-gap-2",children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{color:"var(--cia-ok-500)",width:6,height:6}}),t.jsx("span",{className:"cia-mono",style:{fontSize:11,color:"var(--hero-mut)",letterSpacing:"0.08em",textTransform:"uppercase"},children:e("hero.activeCalls")})]}),t.jsxs("h1",{className:"cia-hero-headline",style:{margin:0,fontSize:"clamp(40px, 4.6vw, 64px)",fontWeight:600,letterSpacing:"-0.032em",lineHeight:1.02,color:"var(--hero-ink)"},children:[e("hero.headlinePrefix")," ",t.jsx("span",{style:{background:"linear-gradient(100deg, var(--cia-brand-300), var(--cia-cta-400))",WebkitBackgroun
944dClip:"text",backgroundClip:"text",WebkitTextFillColor:"transparent",color:"transparent"},children:e("hero.headlineHighlight")}),",",t.jsx("br",{}),e("hero.headlineLine2"),t.jsx("br",{}),e("hero.headlineLine3")]}),t.jsx("p",{style:{margin:0,maxWidth:480,fontSize:16.5,lineHeight:1.55,color:"var(--hero-soft)"},children:e("hero.subtitle")}),t.jsxs("div",{className:"cia-glass-card",style:{maxWidth:540,marginTop:12},children:[t.jsxs("div",{className:"cia-row cia-gap-3",style:{marginBottom:14},children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{color:"var(--cia-ok-500)",width:8,height:8}}),t.jsx("span",{className:"cia-mono cia-truncate",style:{fontSize:11,color:"var(--hero-mut)",letterSpacing:"0.06em",textTransform:"uppercase",minWidth:0},children:e("hero.liveTag")}),t.jsx("span",{style:{flex:1}}),t.jsx("span",{className:"cia-mono",style:{fontSize:11,color:"var(--hero-faint)"},children:"0:47"})]}),t.jsx(JR,{}),t.jsxs("div",{style:{marginTop:14,display:"flex",flexDirection:"column",gap:8,fontSize:13.5},children:[t.jsx(Pd,{who:"agent",text:e("hero.transcript1"),delay:0}),t.jsx(Pd,{who:"user",text:e("hero.transcript2"),delay:1.2}),t.jsx(Pd,{who:"agent",text:e("hero.transcript3"),delay:2.4,typing:!0})]})]}),t.jsxs("div",{className:"cia-row cia-gap-6 cia-trust-row",style:{marginTop:16,opacity:.5},children:[t.jsx(Go,{label:e("hero.trustBanco")}),t.jsx(Go,{label:e("hero.trustDavivienda")}),t.jsx(Go,{label:e("hero.trustFalabella")}),t.jsx(Go,{label:e("hero.trustRappi")})]})]})}function o0(){const{t:e}=M("auth");return t.jsxs("section",{className:"cia-hero-section",style:{position:"relative",background:"var(--hero-bg)",color:"var(--hero-ink)",overflow:"hidden",padding:"40px 56px",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{style:{position:"absolute",inset:0,overflow:"hidden"},children:[t.jsx("div",{style:{position:"absolute",bottom:"-30%",left:"-18%",width:"70%",height:"85%",background:"radial-gradient(circle at 40% 60%, color-mix(in oklab, var(--cia-brand-500) 55%, transparent), transparent 62%)",filter:"blur(70px)",opacity:"var(--hero-glow)"}}),t.jsx("div",{style:{position:"absolute",top:"-25%",right:"-12%",width:"48%",height:"60%",background:"radial-gradient(circle, color-mix(in oklab, var(--cia-cta-500) 45%, transparent), transparent 65%)",filter:"blur(80px)",opacity:"var(--hero-glow-2)"}}),t.jsx("div",{style:{position:"absolute",inset:0,background:"var(--hero-vignette)"}})]}),t.jsx("div",{className:"cia-bg-grid",style:{position:"absolute",inset:0,opacity:.35,"--cia-grid-line":"var(--hero-grid)"}}),t.jsx("div",{className:"cia-grain",style:{position:"absolute",inset:0,pointerEvents:"none"}}),t.jsx("div",{className:"cia-row",style:{position:"relative",justifyContent:"space-between"},children:t.jsx(Dc,{height:30})}),t.jsx("div",{style:{position:"relative",flex:1,display:"flex",flexDirection:"column",justifyContent:"center",marginTop:24,marginBottom:24},children:t.jsx(eT,{})}),t.jsxs("div",{className:"cia-row",style:{position:"relative",justifyContent:"space-between",color:"var(--hero-faint)"},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:11},children:e("hero.versionTag",{version:"1.0"})}),t.jsxs("div",{className:"cia-row cia-gap-4 cia-mono",style:{fontSize:11},children:[t.jsx("span",{children:e("hero.complianceSoc2")}),t.jsx("span",{children:"·"}),t.jsx("span",{children:e("hero.complianceGdpr")}),t.jsx("span",{children:"·"}),t.jsx("span",{children:e("hero.compliancePci")})]})]})]})}function tT(){const{t:e}=M("auth"),a=dt(),n=Pe(w=>w.setSession),[s,i]=m.useState(""),[r,o]=m.useState(""),[l,c]=m.useState(!1),[d,u]=m.useState(null),[p,f]=m.useState(!1),x=r0(),h=x.google||x.microsoft;async function b(w){w.preventDefault(),u(null),f(!0);try{const{data:j}=await T.post("/auth/login",{email:s,password:r});n(j),a({to:lo(j.user)})}catch(j){u(j?.response?.data?.message||e("login.errorInvalid"))}finally{f(!1)}}const[g,v]=m.useState(()=>{try{return localStorage.getItem("conectaia.theme")==="dark"?"dark":"light"}catch{return"light"}}),y=m.useRef(null),k=m.useCallback(()=>{const w=y.current;w&&(w.setAttribute("data-theme-switching",""),requestAnimationFrame(()=>{const j=g==="light"?"dark":"light";v(j);try{localStorage.setItem("conectaia.theme",j)}catch{}requestAnimationFrame(()=>{w.removeAttribute("data-theme-switching")})}))},[g]);return m.useEffect(()=>{const w=y.current;w&&w.setAttribute("data-theme",g)},[g]),t.jsxs("div",{ref:y,className:"cia cia-login-grid","data-theme":g,children:[t.jsx(o0,{}),t.jsxs("section",{className:"cia-form-section",style:{display:"flex",flexDirection:"column",padding:"32px 48px",position:"relative",background:"var(--cia-bg)"},children:[t.jsx("div",{className:"cia-row",style:{justifyContent:"flex-end",gap:6},children:t.jsx("button",{className:"cia-btn cia-btn-icon cia-btn-ghost",onClick:k,"aria-label":e("common.themeToggleAria"),type:"button",children:g==="dark"?t.jsx(YR,{size:16}):t.jsx(XR,{size:16})})}),t.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsxs("div",{style:{width:"100%",maxWidth:360},className:"cia-fade-up",children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:12},children:e("login.eyebrow")}),t.jsx("h2",{style:{fontSize:28,fontWeight:600,margin:"0 0 8px",letterSpacing:"-0.028em",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)"},children:e("login.title")}),t.jsx("p",{className:"cia-text-2",style:{margin:0,fontSize:14,lineHeight:1.55},children:e("login.subtitle")}),h&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"cia-col cia-gap-3",style:{marginTop:24},children:[x.google&&t.jsx(Zl,{provider:"google",href:tc("google")}),x.microsoft&&t.jsx(Zl,{provider:"microsoft",href:tc("microsoft")})]}),t.jsxs("div",{className:"cia-row cia-gap-3",style:{alignItems:"center",margin:"18px 0 4px"},children:[t.jsx("span",{style:{flex:1,height:1,background:"var(--cia-border)"}}
944),t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-4)",letterSpacing:"0.08em",textTransform:"uppercase"},children:e("common.orWithEmail")}),t.jsx("span",{style:{flex:1,height:1,background:"var(--cia-border)"}})]})]}),t.jsxs("form",{onSubmit:b,style:{marginTop:28,display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsx("label",{className:"cia-label",htmlFor:"cia-email",children:e("common.emailLabel")}),t.jsx("input",{id:"cia-email",className:"cia-input",type:"email",required:!0,autoFocus:!0,autoComplete:"email",value:s,onChange:w=>i(w.target.value),placeholder:e("common.emailPlaceholder")})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",marginBottom:6},children:[t.jsx("label",{className:"cia-label",htmlFor:"cia-pwd",style:{margin:0},children:e("common.passwordLabel")}),t.jsx("a",{href:"#",className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-brand-500)",textDecoration:"none",letterSpacing:"0.06em"},onClick:w=>w.preventDefault(),"aria-label":e("login.forgotPasswordAria"),children:e("login.forgotPassword")})]}),t.jsxs("div",{style:{position:"relative"},children:[t.jsx("input",{id:"cia-pwd",className:"cia-input cia-input-pwd",type:l?"text":"password",required:!0,autoComplete:"current-password",value:r,onChange:w=>o(w.target.value),placeholder:"••••••••"}),t.jsx("button",{type:"button",className:"cia-input-eye-toggle",onClick:()=>c(w=>!w),"aria-label":e(l?"common.hidePassword":"common.showPassword"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",width:44,height:44,display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",cursor:"pointer",color:"var(--cia-text-3)",borderRadius:"var(--cia-r-sm)",padding:0},children:l?t.jsx(zS,{className:"size-4"}):t.jsx(qs,{className:"size-4"})})]})]}),d&&t.jsx("div",{className:"cia-badge-danger",role:"alert",children:d}),t.jsx("button",{type:"submit",disabled:p,className:"cia-btn cia-btn-cta cia-btn-lg",style:{marginTop:6,justifyContent:"center"},children:p?t.jsxs(t.Fragment,{children:[t.jsx(je,{style:{width:14,height:14,animation:"spin 1s linear infinite"}}),e("login.connecting")]}):t.jsxs(t.Fragment,{children:[e("login.submit"),t.jsx(ZR,{size:14})]})})]}),t.jsxs("p",{className:"cia-text-3",style:{marginTop:22,fontSize:12.5,lineHeight:1.55},children:[e("login.noAccount")," ",t.jsx(et,{to:"/register",style:{color:"var(--cia-brand-500)",fontWeight:500,textDecoration:"none"},children:e("login.createAccountLink")})]})]})}),t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",color:"var(--cia-text-4)",fontSize:11.5},children:[t.jsx("span",{children:"© 2026 Enlassa AI"}),t.jsxs("div",{className:"cia-row cia-gap-3",children:[t.jsx("a",{href:"#",style:{color:"inherit",textDecoration:"none"},onClick:w=>w.preventDefault(),children:e("common.privacy")}),t.jsx("a",{href:"#",style:{color:"inherit",textDecoration:"none"},onClick:w=>w.preventDefault(),children:e("common.status")}),t.jsx("a",{href:"#",style:{color:"inherit",textDecoration:"none"},onClick:w=>w.preventDefault(),children:e("common.support")})]})]})]}),t.jsx("style",{children:"@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }"})]})}function aT(){const{t:e}=M("auth"),a=dt(),n=Pe(V=>V.setSession),[s,i]=m.useState("form"),[r,o]=m.useState(""),[l,c]=m.useState(""),[d,u]=m.useState(""),[p,f]=m.useState(""),[x,h]=m.useState(""),[b,g]=m.useState(null),[v,y]=m.useState(null),[k,w]=m.useState(!1),j=r0(),C=j.google||j.microsoft,N=j.turnstile.enabled&&!!j.turnstile.siteKey,[S,_]=m.useState(null),R=m.useRef(null);async function A(V){V.preventDefault(),g(null),w(!0);try{await T.post("/auth/signup",{name:r,email:l,password:d,lang:Ua.getState().resolved,...p.trim()?{orgName:p.trim()}:{},...S?{turnstileToken:S}:{}}),y(e("register.codeSent",{email:l})),i("verify")}catch(U){g(U?.response?.data?.message||e("register.errorCreate")),N&&R.current?.reset()}finally{w(!1)}}async function E(V){V.preventDefault(),g(null),w(!0);try{const{data:U}=await T.post("/auth/signup/verify",{email:l,code:x});n(U),a({to:lo(U.user)})}catch(U){g(U?.response?.data?.message||e("register.errorCode"))}finally{w(!1)}}async function I(){g(null),y(null);try{await T.post("/auth/signup/resend",{email:l,lang:Ua.getState().resolved}),y(e("register.codeResent"))}catch(V){g(V?.response?.data?.message||e("register.errorResend"))}}const[P,O]=m.useState(()=>{try{return localStorage.getItem("conectaia.theme")==="dark"?"dark":"light"}catch{return"light"}}),K=m.useRef(null),W=m.useCallback(()=>{const V=K.current;V&&(V.setAttribute("data-theme-switching",""),requestAnimationFrame(()=>{const U=P==="light"?"dark":"light";O(U);try{localStorage.setItem("conectaia.theme",U)}catch{}requestAnimationFrame(()=>V.removeAttribute("data-theme-switching"))}))},[P]);return m.useEffect(()=>{K.current?.setAttribute("data-theme",P)},[P]),t.jsxs("div",{ref:K,className:"cia cia-login-grid","data-theme":P,children:[t.jsx(o0,{}),t.jsxs("section",{className:"cia-form-section",style:{display:"flex",flexDirection:"column",padding:"32px 48px",position:"relative",background:"var(--cia-bg)"},children:[t.jsx("div",{className:"cia-row",style:{justifyContent:"flex-end",gap:6},children:t.jsx("button",{className:"cia-btn cia-btn-icon cia-btn-ghost",onClick:W,"aria-label":e("common.themeToggleAria"),type:"button",children:P==="dark"?t.jsx(Zr,{size:16}):t.jsx(Hr,{size:16})})}),t.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsxs("div",{style:{width:"100%",maxWidth:380},className:"cia-fade-up",children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:12},children:j.trialMinutes?e("register.eyebrowMin",{min:j.trialMinutes}):e("register.eyebrow")}),s==="form"?t.jsxs(t.Fragment,{children:[t.jsx("h2",{style:{fontSize:28,fontWeight:600,margin:"0 0 8px",letterSpacing:"-0.028em",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)"},children:e("register.title")}),t.jsx("p",{className:"cia-text-2",style:{margin:0,fontSize:14,lineHeight:1.55},children:j.trialMinutes?e("register.subtitleMin",{min:j.trialMinutes}):e("register.subtitle")}),C&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"cia-col cia-gap-3",style:{marginTop:24},children:[j.google&&t.jsx(Zl,{provider:"google",href:tc("google")}),j.microsoft&&t.jsx(Zl,{provider:"microsoft",href:tc("microsoft")})]}),t.jsxs("div",{className:"cia-row cia-gap-3",style:{alignItems:"center",margin:"18px 0 4px"},children:[t.jsx("span",{style:{flex:1,height:1,background:"var(--cia-border)"}}
944),t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-4)",letterSpacing:"0.08em",textTransform:"uppercase"},children:e("common.orWithEmail")}),t.jsx("span",{style:{flex:1,height:1,background:"var(--cia-border)"}})]})]}),t.jsxs("form",{onSubmit:A,style:{marginTop:8,display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsx("label",{className:"cia-label",htmlFor:"reg-name",children:e("register.nameLabel")}),t.jsx("input",{id:"reg-name",className:"cia-input",required:!0,autoFocus:!0,autoComplete:"name",value:r,onChange:V=>o(V.target.value),placeholder:e("register.namePlaceholder")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-label",htmlFor:"reg-email",children:e("common.emailLabel")}),t.jsx("input",{id:"reg-email",className:"cia-input",type:"email",required:!0,autoComplete:"email",value:l,onChange:V=>c(V.target.value),placeholder:e("common.emailPlaceholder")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-label",htmlFor:"reg-pwd",children:e("common.passwordLabel")}),t.jsx("input",{id:"reg-pwd",className:"cia-input",type:"password",required:!0,minLength:12,autoComplete:"new-password",value:d,onChange:V=>u(V.target.value),placeholder:e("register.passwordPlaceholder")})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"cia-label",htmlFor:"reg-org",children:[e("register.companyLabel")," ",t.jsx("span",{style:{color:"var(--cia-text-4)"},children:e("register.optional")})]}),t.jsx("input",{id:"reg-org",className:"cia-input",autoComplete:"organization",value:p,onChange:V=>f(V.target.value),placeholder:e("register.companyPlaceholder")})]}),N&&t.jsx(Ej,{ref:R,siteKey:j.turnstile.siteKey,theme:P,onToken:_}),b&&t.jsx("div",{className:"cia-badge-danger",role:"alert",children:b}),t.jsx("button",{type:"submit",disabled:k||N&&!S,className:"cia-btn cia-btn-cta cia-btn-lg",style:{marginTop:6,justifyContent:"center"},children:k?t.jsxs(t.Fragment,{children:[t.jsx(je,{style:{width:14,height:14,animation:"spin 1s linear infinite"}})," ",e("register.creating")]}):t.jsxs(t.Fragment,{children:[e("register.submit")," ",t.jsx(oa,{size:14})]})})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("h2",{style:{fontSize:26,fontWeight:600,margin:"0 0 8px",letterSpacing:"-0.028em",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)",display:"flex",alignItems:"center",gap:10},children:[t.jsx(HS,{size:22,style:{color:"var(--cia-cta-500)"}})," ",e("register.verifyTitle")]}),t.jsx("p",{className:"cia-text-2",style:{margin:0,fontSize:14,lineHeight:1.55},children:v??e("register.codeSent",{email:l})}),t.jsxs("form",{onSubmit:E,style:{marginTop:24,display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{children:[t.jsx("label",{className:"cia-label",htmlFor:"reg-code",children:e("register.codeLabel")}),t.jsx("input",{id:"reg-code",className:"cia-input cia-mono",inputMode:"numeric",pattern:"\\d{6}",maxLength:6,required:!0,autoFocus:!0,value:x,onChange:V=>h(V.target.value.replace(/\D/g,"").slice(0,6)),placeholder:"● ● ● ● ● ●",style:{letterSpacing:"0.4em",fontSize:20,textAlign:"center"}})]}),b&&t.jsx("div",{className:"cia-badge-danger",role:"alert",children:b}),t.jsx("button",{type:"submit",disabled:k||x.length!==6,className:"cia-btn cia-btn-cta cia-btn-lg",style:{marginTop:6,justifyContent:"center"},children:k?t.jsxs(t.Fragment,{children:[t.jsx(je,{style:{width:14,height:14,animation:"spin 1s linear infinite"}})," ",e("register.verifying")]}):t.jsxs(t.Fragment,{children:[e("register.verifySubmit")," ",t.jsx(oa,{size:14})]})})]}),t.jsxs("p",{className:"cia-text-3",style:{marginTop:18,fontSize:12.5},children:[e("register.notReceived")," ",t.jsx("button",{type:"button",onClick:I,style:{background:"none",border:"none",padding:0,cursor:"pointer",color:"var(--cia-brand-500)",fontWeight:500},children:e("register.resend")})," · ",t.jsx("button",{type:"button",onClick:()=>{i("form"),g(null),y(null)},style:{background:"none",border:"none",padding:0,cursor:"pointer",color:"var(--cia-text-3)"},children:e("register.changeEmail")})]})]}),t.jsxs("p",{className:"cia-text-3",style:{marginTop:22,fontSize:12.5,lineHeight:1.55},children:[e("register.hasAccount")," ",t.jsx(et,{to:"/login",style:{color:"var(--cia-brand-500)",fontWeight:500,textDecoration:"none"},children:e("register.signInLink")})]})]})}),t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",color:"var(--cia-text-4)",fontSize:11.5},children:[t.jsx("span",{children:"© 2026 Enlassa AI"}),t.jsx("span",{className:"cia-mono",style:{fontSize:11},children:e("register.footerNote")})]})]}),t.jsx("style",{children:"@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }"})]})}function nT(){const{t:e}=M("auth"),a=dt(),n=Pe(o=>o.setTokens),s=Pe(o=>o.setUser),[i,r]=m.useState(null);return m.useEffect(()=>{(async()=>{const l=new URLSearchParams(window.location.search).get("error");
944if(l==="account_exists"){r(e("callback.errorAccountExists"));return}if(l){r(e("callback.errorGeneric"));return}const c=new URLSearchParams(window.location.hash.replace(/^#/,"")),d=c.get("access_token"),u=c.get("refresh_token");if(!d||!u){r(e("callback.errorNoSession"));return}try{window.history.replaceState(null,"",window.location.pathname)}catch{}n(d,u);try{const{data:p}=await T.get("/auth/me");s(p),a({to:lo(p)})}catch{r(e("callback.errorLoadAccount"))}})()},[]),t.jsx("div",{className:"cia","data-theme":"dark",style:{minHeight:"100vh",display:"grid",placeItems:"center",background:"var(--cia-bg)"},children:t.jsxs("div",{className:"cia-col cia-gap-4 cia-fade-up",style:{alignItems:"center",textAlign:"center",maxWidth:360,padding:24},children:[t.jsx(Dc,{height:34}),i?t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"cia-text-2",style:{fontSize:14,lineHeight:1.55},children:i}),t.jsx(et,{to:"/login",className:"cia-btn cia-btn-cta",children:e("callback.backToLogin")})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{color:"var(--cia-cta-500)",width:10,height:10}}),t.jsx("p",{className:"cia-text-2 cia-caret",style:{fontSize:14},children:e("callback.connecting")})]})]})})}const Zo=["Hablás por teléfono, en español neutro de Colombia, con tono cálido y profesional.","Respondé en máximo 2 frases por turno; una sola idea por turno.","Nunca leas listas largas ni te extiendas: el cliente te escucha, no te lee.","Si no entendés algo, pedí que lo repitan con naturalidad.","Confirmá los datos importantes (montos, fechas, números) repitiéndolos."].join(" "),Pr={cobranza:{id:"cobranza",name:"Cobranza temprana",preset:{greeting:"Hola, le saluda el asistente de cobranzas. ¿Hablo con la persona titular de la cuenta?",systemPrompt:["Sos un agente de cobranza temprana (mora de 1 a 30 días).",Zo,"Objetivo: recordar la obligación con respeto, entender por qué no se ha pagado y ofrecer una solución (fecha de pago o enlace).","Sé empático, nunca agresivo ni amenazante. No te comprometas a condonar montos ni a cambiar condiciones sin autorización.","Si la persona pide hablar con un humano o se molesta, ofrecé transferir."].join(" "),analytics:{summaryEnabled:!0,sentimentEnabled:!0,successEvaluation:{enabled:!0,prompt:"La llamada es exitosa si el cliente se compromete a una fecha de pago o acepta el enlace de pago."}}}},leads:{id:"leads",name:"Calificación de leads",preset:{greeting:"Hola, gracias por su interés. Le hago un par de preguntas rápidas para conectarlo con la persona indicada, ¿le parece?",systemPrompt:["Sos un agente de calificación de leads.",Zo,"Objetivo: calificar el interés del prospecto con pocas preguntas (necesidad, urgencia, presupuesto) y, si califica, transferir a un asesor humano.","Sé ágil y cordial; no interrogues, conversá. No prometas precios ni condiciones."].join(" "),analytics:{summaryEnabled:!0,sentimentEnabled:!0,successEvaluation:{enabled:!0,prompt:"Exitosa si el prospecto califica (tiene necesidad y disposición) y acepta el siguiente paso."}}}},recepcionista:{id:"recepcionista",name:"Recepcionista",preset:{greeting:"Hola, bienvenido. ¿En qué le puedo ayudar hoy?",systemPrompt:["Sos un recepcionista virtual para llamadas entrantes.",Zo,"Objetivo: responder preguntas frecuentes, tomar datos para agendar y dirigir la llamada al área correcta.","Sé servicial y claro. Si la consulta excede lo que sabés, ofrecé transferir o tomar un mensaje."].join(" "),analytics:{summaryEnabled:!0,sentimentEnabled:!0}}},nps:{id:"nps",name:"Encuesta NPS",preset:{greeting:"Hola, le llamo de parte del equipo de calidad. ¿Tiene un minuto para una pregunta corta sobre su experiencia?",systemPrompt:["Sos un agente que hace una encuesta de satisfacción (NPS) post-venta, breve.",Zo,"Objetivo: preguntar del 0 al 10 qué tan probable es que recomiende el servicio, y pedir un comentario corto del porqué.","Sé breve y agradecido; respetá si la persona no quiere participar. No discutas la calificación."].join(" "),analytics:{summaryEnabled:!0,sentimentEnabled:!0,dataPoints:[{id:"nps_score",name:"Puntaje NPS",description:"Número del 0 al 10 que dio el cliente.",type:"integer",required:!1},{id:"nps_motivo",name:"Motivo",description:"Razón breve que dio el cliente por su puntaje.",type:"string",required:!1}]}}}},Zf=["brand","cta","ok","sky"],l0=["brand","cta","ok","sky","warn","bad"],Th=e=>`var(--cia-${e}-500)`;function sT(e){let a=0;for(let n=0;n<e.length;n++)a=a*31+e.charCodeAt(n)>>>0;return Zf[a%Zf.length]}function c0(e,a){return e&&l0.includes(e)?e:sT(a)}function to(e){return e?e==="es"?"es-CO":e:"—"}function ss({id:e,size:a=32,accent:n}){const s=Th(c0(n,e));return t.jsx("div",{style:{width:a,height:a,borderRadius:8,flex:"none",background:`linear-gradient(135deg, ${s}, color-mix(in oklab, ${s} 70%, black))`,color:"white",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"inset 0 1px 0 rgba(255,255,255,0.18)"},children:t.jsx(Ft,{size:Math.round(a*.5),strokeWidth:1.6})})}function iT({id:e,value:a,onChange:n,size:s=40}){const{t:i}=M("agents"),[r,o]=m.useState(!1),l=m.useRef(null);m.useEffect(()=>{if(!r)return;const d=u=>{l.current?.contains(u.target)||o(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]);const c=c0(a,e);return t.jsxs("div",{ref:l,style:{position:"relative",flex:"none"},children:[t.jsx("button",{type:"button",onClick:()=>o(d=>!d),"aria-label":i("visuals.colorPickerAria"),title:i("visuals.colorPickerTitle"),style:{border:0,background:"transparent",padding:0,cursor:"pointer",borderRadius:8,display:"block",lineHeight:0},children:t.jsx(ss,{id:e,accent:a,size:s})}),r&&t.jsx("div",{className:"cia-card",style:{position:"absolute",top:s+8,left:0,zIndex:50,padding:10,display:"flex",gap:8,width:"max-content",boxShadow:"var(--cia-sha
944dow-lg)"},children:l0.map(d=>{const u=c===d;return t.jsx("button",{type:"button",onClick:()=>{n(d),o(!1)},"aria-label":i("visuals.colorNamed",{name:d}),"aria-pressed":u,title:d,style:{border:u?"2px solid var(--cia-text)":"2px solid transparent",background:"transparent",padding:0,borderRadius:10,cursor:"pointer",lineHeight:0},children:t.jsx(ss,{id:e,accent:d,size:32})},d)})})]})}const rT=String.raw`\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}`,oT=new Set(["agent_id","organization_id","call_id","call_direction","caller_number","session_type","call_type","mode"]),lT=["current_","system__","sip","lk"];function cT(e){const a=e.toLowerCase();return oT.has(a)?!0:lT.some(n=>a.startsWith(n))}function d0(...e){const a=new Set,n=[];for(const s of e){if(!s||s.indexOf("{{")===-1)continue;const i=new RegExp(rT,"g");let r;for(;(r=i.exec(s))!==null;){const o=r[1];a.has(o)||cT(o)||(a.add(o),n.push(o))}}return n}function dT(e,a){const n=d0(...e);if(n.length===0)return[];const s=new Map,i=new Map;for(const r of Array.isArray(a)?a:[])r&&typeof r.name=="string"&&(s.set(r.name,r),i.has(r.name.toLowerCase())||i.set(r.name.toLowerCase(),r));return n.map(r=>{const o=s.get(r)??i.get(r.toLowerCase());return{name:r,...o?.defaultValue!==void 0&&o.defaultValue!==null?{defaultValue:String(o.defaultValue)}:{},...o?.description?{description:o.description}:{}}})}function u0(e){if(!e)return{all:[],required:[]};const a=dT([e.systemPrompt,e.greeting],e.dynamicVariables);return{all:a,required:a.filter(n=>n.defaultValue===void 0)}}let uT=0;const zd=()=>`m${++uT}`,pT=e=>`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`;function p0({agent:e,isNew:a,dirty:n,onboarding:s,preview:i,onEnded:r,onLive:o,endedSlot:l}){const{t:c}=M("agentsBuilder"),d=!a&&!!e.id,[u,p]=m.useState("voice"),[f,x]=m.useState("idle"),[h,b]=m.useState(null),[g,v]=m.useState(!1),[y,k]=m.useState(!1),[w,j]=m.useState(!1),[C,N]=m.useState(null),[S,_]=m.useState([]),[R,A]=m.useState(""),[E,I]=m.useState(0),{all:P,required:O}=u0(e),[K,W]=m.useState({}),[V,U]=m.useState(!1),X=O.every(ce=>(K[ce.name]??"").trim()!==""),ie=P.length>0&&!V&&f==="idle",de=m.useRef(null),$=m.useRef(null),z=m.useRef(null),D=m.useRef(null),F=m.useRef(new Map),G=m.useRef(null),te=m.useRef(!1),B=m.useRef(null),ne=m.useRef(null),me=m.useRef(null),Ee=m.useRef(null),L=m.useRef([]),re=m.useRef(!1),ke=m.useRef(null),H=m.useRef(0),fe=m.useRef([]),Z=m.useRef(!1),ae=m.useRef(!1);m.useEffect(()=>{fe.current=S},[S]);const pe=m.useCallback(()=>{!r||Z.current||(Z.current=!0,r({sessionId:ke.current,elapsed:H.current,hadMessages:fe.current.length>0}))},[r]),ye=m.useCallback(()=>{!o||ae.current||(ae.current=!0,o())},[o]),qe=m.useCallback(()=>{const ce=de.current;if(de.current=null,Ee.current=null,L.current=[],D.current=null,$.current?.stop(),$.current=null,z.current&&(z.current.innerHTML=""),j(!1),N(null),F.current.clear(),B.current&&(clearInterval(B.current),B.current=null),ne.current&&(clearTimeout(ne.current),ne.current=null),me.current?.(),me.current=null,ce)try{ce.disconnect()}catch{}},[]);m.useEffect(()=>()=>qe(),[qe]),m.useEffect(()=>{G.current?.scrollIntoView({behavior:"smooth"})},[S,y]),m.useEffect(()=>{qe(),x("idle"),_([]),I(0),U(!1),ke.current=null,H.current=0,Z.current=!1},[e.id]);function ut(ce,Se){_(De=>{const ue=F.current.get(ce);if(ue)return De.map(ze=>ze.id===ue?{...ze,text:Se}:ze);const Ze=zd();return F.current.set(ce,Ze),[...De,{id:Ze,role:"agent",text:Se}]})}function bt(ce,Se){_(De=>{const ue=F.current.get(ce);if(ue)return De.map(ze=>ze.id===ue?{...ze,text:Se}:ze);const Ze=zd();return F.current.set(ce,Ze),[...De,{id:Ze,role:"user",text:Se}]})}async function Ge(ce){if(i)throw new Error(c("test.previewError"));const Se=Object.fromEntries(Object.entries(K).filter(([,ue])=>ue.trim()!=="")),{data:De}=await T.post("/web-agent/session",{agentId:e.id,mode:ce,...s?{onboarding:!0}:{},...Object.keys(Se).length>0?{variables:Se}:{}});return De}async function yt(){const ce=de.current;if(ce)try{await ce.startAudio(),j(!ce.canPlaybackAudio)}catch{}}const ve=m.useCallback(async(ce,Se)=>{if(de.current)return de.current;if(te.current)return null;te.current=!0,b(null),N(null),p(ce),x("connecting"),Z.current=!1;try{const De=await Ge(ce);ke.current=De.sessionId;const ue=new Aj;if(de.current=ue,ue.on(fr.AudioPlaybackStatusChanged,()=>{j(!ue.canPlaybackAudio)}),ue.on(fr.TrackSubscribed,ze=>{if(ze.kind===hm.Kind.Audio&&(D.current=ze,ce==="voice"&&z.current)){const Ot=ze.attach();Ot.autoplay=!0,Ot.setAttribute("playsinline",""),z.current.appendChild(Ot)}}),ue.on(fr.ActiveSpeakersChanged,ze=>k(ze.some(Ot=>!Ot.isLocal))),ue.on(fr.Disconnected,()=>{x(ze=>ze==="live"||ze==="connecting"?"ended":ze),qe(),pe()}),me.current=Gg(ue,{ignoreLocal:ce!=="voice",onSegment:ze=>{(ze.role==="user"?bt:ut)(ze.id,ze.text)}}),await ue.connect(De.url,De.token),ce==="chat"&&(Ee.current=Rj(ue)),ce==="voice"){try{const ze=await(Se??ad());if(de.current!==ue)return ze.stop(),null;$.current=ze,await ue.localParticipant.publishTrack(ze),v(!1)}catch(ze){N(ze?.name==="NotAllowedError"?c("test.micPermission"):ze?.message||c("test.micFailed"))}try{await ue.startAudio()}catch{}ue.canPlaybackAudio||j(!0)}I(0),H.current=0,B.current=setInterval(()=>{I(ze=>{const Ot=ze+1;return H.current=Ot,Ot})},1e3);const Ze=De.maxSessionSeconds??0;return Ze>0&&(ne.current=setTimeout(()=>{qe(),x("ended"),pe()},Ze*1e3)),x("live"),ye(),ue}catch(De){return Se?.then(ue=>ue.stop()).catch(()=>{}),b(De?.response?.data?.message??(De?.name==="NotAllowedError"?c("test.micPermission"):De?.message)??c("test.connectFailed")),x("error"),qe(),null}finally{te.current=!1}},[qe,pe,K,e.id,c]);function Ke(){const ce=R.trim();ce&&(A(""),_(Se=>[...Se,{id:zd(),role:"user",text:ce}
944]),L.current.push(ce),He())}async function He(){if(!re.current){re.current=!0;try{const ce=await ve("chat");if(!ce){L.current=[];return}for(Ee.current&&await Ee.current;L.current.length>0&&de.current===ce;){const Se=L.current.shift();try{await ce.localParticipant.sendText(Se,{topic:"lk.chat"})}catch(De){de.current&&b(De?.message??c("test.sendFailed"))}}}finally{re.current=!1,L.current.length>0&&de.current!==null&&!re.current&&He()}}}function Xe(){if(de.current||te.current)return;const ce=i?void 0:ad();ce?.catch(()=>{}),ve("voice",ce)}function Et(){const ce=de.current;if(!ce)return;const Se=ad();Se.catch(()=>{}),N(null),(async()=>{try{const De=await Se;if(de.current!==ce){De.stop();return}const ue=ce.localParticipant.getTrackPublication(hm.Source.Microphone);ue?.track&&await ce.localParticipant.unpublishTrack(ue.track,!0),$.current?.stop(),$.current=De,await ce.localParticipant.publishTrack(De),v(!1),ce.startAudio().catch(()=>{})}catch(De){N(De?.name==="NotAllowedError"?c("test.micPermission"):De?.message||c("test.micFailed"))}})()}function Yt(){const ce=de.current;if(!ce)return;const Se=!g;v(Se),ce.localParticipant.setMicrophoneEnabled(!Se)}function It(){qe(),x("ended"),pe()}function Pn(){_([]),I(0),x("idle"),N(null)}const St=f==="live",sa=f==="connecting",ma=S[S.length-1],$e=St&&!y&&ma?.role==="user";return d?t.jsxs(Yf,{children:[t.jsx("div",{ref:z,className:"hidden","aria-hidden":!0}),w&&t.jsx("button",{type:"button",onClick:yt,"aria-label":c("test.enableAudioAria"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,width:"100%",marginBottom:10,padding:"11px 14px",borderRadius:12,cursor:"pointer",border:"none",background:"var(--cia-cta-500)",color:"#fff",fontWeight:600,fontSize:14},children:c("test.enableAudioCta")}),St&&u==="voice"&&C&&t.jsxs("div",{className:"cia-badge cia-badge-bad",role:"alert",style:{height:"auto",padding:"8px 10px",fontSize:12,marginBottom:10,whiteSpace:"normal",textAlign:"left",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{flex:1},children:C}),t.jsxs("button",{type:"button",onClick:Et,className:"cia-btn cia-btn-sm",style:{flex:"none"},children:[t.jsx(Ta,{size:13})," ",c("test.micRetry")]})]}),t.jsx("div",{className:"cia-row",style:{justifyContent:"center",paddingBottom:12},children:t.jsx("div",{className:"cia-toggle",children:["voice","chat"].map(ce=>t.jsxs("button",{type:"button",onClick:()=>St||sa?null:p(ce),disabled:St||sa,className:`cia-toggle-btn ${u===ce?"cia-toggle-btn-active":""}`,style:{display:"flex",alignItems:"center",gap:6,opacity:(St||sa)&&u!==ce?.5:1},children:[ce==="voice"?t.jsx(Il,{size:13}):t.jsx(sn,{size:13}),c(ce==="voice"?"test.modeVoice":"test.modeChat")]},ce))})}),t.jsx(Xf,{agent:e,phase:f,elapsed:E,mode:u}),u==="voice"&&t.jsx("div",{style:{padding:"14px 4px 4px"},children:t.jsx(Qy,{active:St,speaking:y})}),ie?t.jsxs("div",{className:"cia-col",style:{gap:10,padding:"8px 2px",flex:1,minHeight:0,overflowY:"auto"},children:[t.jsx("span",{className:"cia-eyebrow",children:c("test.varsTitle")}),P.map(ce=>{const Se=ce.defaultValue===void 0,De=K[ce.name]??"";return t.jsxs("div",{children:[t.jsxs("div",{className:"cia-row cia-gap-2",style:{marginBottom:4},children:[t.jsx("code",{className:"cia-mono",style:{fontSize:12,color:"var(--cia-brand-500)"},children:`{{${ce.name}}}`}),t.jsx("span",{className:"cia-text-4",style:{fontSize:10.5},children:c(Se?"test.varRequired":"test.varOptional")})]}),t.jsx("input",{className:"input",value:De,onChange:ue=>W(Ze=>({...Ze,[ce.name]:ue.target.value})),placeholder:ce.defaultValue!==void 0?c("test.varDefaultPlaceholder",{value:ce.defaultValue}):ce.description||c("test.varPlaceholderFallback")})]},ce.name)}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta",style:{width:"100%"},disabled:!X,onClick:()=>U(!0),children:c("test.continue")})]}):f==="idle"?t.jsxs(Jf,{children:[t.jsx(ex,{}),t.jsxs("div",{className:"cia-col",style:{gap:4},children:[t.jsx("span",{style:{fontSize:13.5,fontWeight:500,color:"var(--cia-text)"},children:c("test.idleTitle")}),t.jsx("span",{className:"cia-text-3",style:{fontSize:12,maxWidth:280}
944,children:c(u==="voice"?"test.idleDescVoice":"test.idleDescChat")})]})]}):t.jsxs("div",{className:"cia-col",style:{flex:1,minHeight:0,gap:0},children:[t.jsxs("div",{className:"cia-row",style:{marginBottom:10},children:[t.jsx("span",{className:"cia-eyebrow",children:c("test.liveTranscript")}),t.jsx("span",{style:{flex:1}}),t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:c("test.messagesCount",{count:S.length})})]}),t.jsxs("div",{className:"cia-scroll",style:{flex:1,minHeight:0,overflowY:"auto",paddingRight:4},children:[t.jsx(vo,{messages:S,agentName:e.name||c("test.agentFallback"),userLabel:c("test.userLabel"),typing:$e,typingLabel:c("test.typingLabel",{name:e.name||c("test.theAgent")}),showTimestamps:!1,emptyText:c(sa?"test.connecting":"test.transcriptEmpty")}),t.jsx("div",{ref:G})]}),t.jsxs("div",{className:"cia-row cia-gap-2",style:{marginTop:10,padding:"7px 10px",borderRadius:"var(--cia-r-sm)",background:"var(--cia-bg-soft)",border:"1px dashed var(--cia-border-2)",color:"var(--cia-text-4)",fontSize:10.5},children:[t.jsx(Mi,{size:12,style:{flex:"none"}}),t.jsx("span",{className:"cia-mono",children:c("test.toolsNote")})]})]}),f==="error"&&h&&t.jsx("div",{className:"cia-badge cia-badge-bad",role:"alert",style:{height:"auto",padding:"8px 12px",fontSize:12.5,marginTop:10},children:h}),t.jsxs("div",{style:{marginTop:12,paddingTop:12,borderTop:"1px solid var(--cia-border)"},children:[u==="voice"&&f==="idle"&&!ie&&t.jsxs("button",{type:"button",onClick:Xe,className:"cia-btn cia-btn-cta cia-btn-lg",style:{width:"100%",justifyContent:"center"},children:[t.jsx(rn,{size:15})," ",c("test.startTest")]}),u==="voice"&&sa&&t.jsxs("button",{type:"button",disabled:!0,className:"cia-btn cia-btn-cta cia-btn-lg",style:{width:"100%",justifyContent:"center"},children:[t.jsx(je,{size:15,style:{animation:"spin 1s linear infinite"}})," ",c("test.connecting")]}),u==="voice"&&St&&t.jsxs("div",{className:"cia-row cia-gap-2",style:{justifyContent:"center"},children:[t.jsxs("button",{type:"button",onClick:It,className:"cia-btn cia-btn-lg",style:{flex:1,background:"var(--cia-bad-500)",color:"#fff",borderColor:"var(--cia-bad-500)",justifyContent:"center"},children:[t.jsx(Ts,{size:15})," ",c("test.hangup")]}),t.jsx("button",{type:"button",onClick:Yt,disabled:!!C,className:"cia-btn cia-btn-outline cia-btn-lg cia-btn-icon",style:{width:42},title:c(g?"test.micActivate":"test.micMute"),children:g?t.jsx(Ap,{size:15}):t.jsx(Ta,{size:15})})]}),u==="chat"&&f!=="ended"&&!ie&&t.jsxs("div",{className:"cia-col cia-gap-2",children:[St&&t.jsxs("button",{type:"button",onClick:It,className:"cia-btn cia-btn-outline cia-btn-sm",style:{width:"100%",justifyContent:"center",color:"var(--cia-bad-500)",borderColor:"var(--cia-border-2)"},children:[t.jsx(nt,{size:14})," ",c("test.endChat")]}),t.jsxs("div",{className:"cia-row cia-gap-2",children:[t.jsx("input",{className:"input",style:{flex:1},placeholder:c("test.chatPlaceholder"),value:R,onChange:ce=>A(ce.target.value),onKeyDown:ce=>ce.key==="Enter"&&!ce.shiftKey&&(ce.preventDefault(),Ke())}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta cia-btn-icon",style:{width:42,he
944ight:42},onClick:Ke,disabled:!R.trim()||sa,"aria-label":c("test.sendAria"),children:sa?t.jsx(je,{size:15,style:{animation:"spin 1s linear infinite"}}):t.jsx(Gr,{size:15})})]})]}),f==="ended"&&(l??t.jsx("button",{type:"button",className:"cia-btn cia-btn-outline",style:{width:"100%"},onClick:Pn,children:c("test.restart")})),t.jsx(tx,{})]})]}):t.jsxs(Yf,{children:[t.jsx(Xf,{agent:e,phase:"idle",elapsed:0,mode:u}),t.jsxs(Jf,{children:[t.jsx(ex,{}),t.jsxs("div",{className:"cia-col",style:{gap:4},children:[t.jsx("span",{style:{fontSize:13.5,fontWeight:500,color:"var(--cia-text)"},children:c("test.notTestableTitle")}),t.jsx("span",{className:"cia-text-3",style:{fontSize:12,maxWidth:280},children:c("test.notTestableDesc")})]})]}),t.jsx(tx,{})]})}function Yf({children:e}){const{t:a}=M("agentsBuilder");return t.jsxs("div",{style:{display:"flex",flexDirection:"column",minHeight:"100%",padding:18,gap:0},children:[t.jsxs("div",{className:"cia-row cia-gap-3",style:{paddingBottom:14,marginBottom:4},children:[t.jsx("div",{style:{width:30,height:30,borderRadius:8,flex:"none",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--cia-bg-tint)",color:"var(--cia-cta-500)"},children:t.jsx(rn,{size:14})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("h3",{style:{margin:0,fontSize:14,fontWeight:600,color:"var(--cia-text)"},children:a("test.shellTitle")}),t.jsx("div",{className:"cia-mono cia-text-3",style:{fontSize:10.5,marginTop:1},children:a("test.shellSubtitle")})]})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",flex:1,minHeight:0},children:e})]})}function Xf({agent:e,phase:a,elapsed:n,mode:s}){const{t:i}=M("agentsBuilder"),r=a==="live",o=a==="connecting";return t.jsx("div",{style:{background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",borderRadius:12,padding:14},children:t.jsxs("div",{className:"cia-row cia-gap-3",children:[t.jsx(ss,{id:e.id||"nuevo",accent:e.accent,size:42}),t.jsxs("div",{className:"cia-col",style:{gap:2,minWidth:0,flex:1},children:[t.jsx("span",{style:{fontSize:14,fontWeight:600,color:"var(--cia-text)"},className:"cia-truncate",children:e.name||i("test.agentNameFallback")}),t.jsxs("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:[e.id||"ag_…"," · ",i("test.cardTestSuffix")]})]}),t.jsxs("div",{className:"cia-col",style:{alignItems:"flex-end",gap:4,flex:"none"},children:[r?t.jsxs("span",{className:"cia-badge cia-badge-success",children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{width:5,height:5,color:"var(--cia-ok-500)"}}),i(s==="voice"?"test.statusInCall":"test.statusInChat")]}):o?t.jsxs("span",{className:"cia-badge",children:[t.jsx(je,{size:11,style:{animation:"spin 1s linear infinite"}})," ",i("test.statusConnecting")]}):a==="ended"?t.jsx("span",{className:"cia-badge",children:i("test.statusEnded")}):t.jsx("span",{className:"cia-badge",children:i("test.statusInactive")}),(r||a==="ended")&&t.jsx("span",{className:"cia-mono",style:{fontSize:12,color:"var(--cia-text-2)"},children:pT(n)})]})]})})}function Jf({children:e}){return t.jsx("div",{className:"cia-col",style:{flex:1,minHeight:180,marginTop:14,background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",borderRadius:12,alignItems:"center",justifyContent:"center",gap:14,textAlign:"center",padding:16},children:e})}function ex(){return t.jsx("div",{style:{width:48,height:48,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--cia-bg-tint)",color:"var(--cia-brand-500)"},children:t.jsx(Ta,{size:20})})}function tx(){const{t:e}=M("agentsBuilder");return t.jsx("div",{className:"cia-text-4",style:{fontSize:10.5,textAlign:"center",marginTop:12},children:e("test.footerNote")})}const Mh="agentsBuilder";function h0(e,a){return he.t(`${Mh}:diff.field.${e.replace(/\./g,"_")}`,{defaultValue:a})}const hT={configurado:"diff.value.configured","(sin criterio)":"diff.value.noCriteria",desactivado:"diff.value.disabled"};function Yo(e){if(typeof e!="string")return e;const a=hT[e];return a?he.t(`${Mh}:${a}`):e}const mT={creación:"versions.reason.created","edición de prompt":"versions.reason.edited","edición de prompt por copiloto":"versions.reason.copilotEdited"};function ax(e){if(!e)return e;const a=mT[e];return a?he.t(`${Mh}:${a}`):e}function fT(e){return se({queryKey:["agent",e,"copilot-versions"],queryFn:async()=>{const{data:a}=await T.get(`/agents/${e}/copilot/versions`);return a},enabled:!!e,staleTime:3e4})}function xT(e){return oe({mutationFn:async a=>{await T.post(`/agents/${e}/copilot/feedback`,a)}})}const Qs=(e,a)=>String(he.t(`copilot:stream.error.${e}`,a));function gT(){const e=rt.getState();return e.isActive()&&e.accessToken?e.accessToken:Pe.getState().accessToken}function bT(e){const a=e.split(`
945`).filter(i=>i.trim().length>0);let n="message",s="";for(const i of a)i.startsWith("event:")?n=i.slice(6).trim():i.startsWith("data:")&&(s=i.slice(5).trim());return s?{event:n,data:s}:null}function m0(e,a){const n=m.useRef(null),s=m.useCallback(()=>{n.current?.abort(),n.current=null},[]);return{send:m.useCallback(async(r,o,l)=>{if(!e){o.onError(Qs("noAgentId"),!1);return}const c=gT();if(!c){o.onError(Qs("noSession"),!1);return}n.current?.abort();const d=new AbortController;n.current=d;const p=`https://api.enlassa.ai/api/v1/agents/${e}/copilot/build/stream`,f={};let x="",h=!1,b="";try{const g=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`,Accept:"text/event-stream","Cache-Control":"no-cache"},body:JSON.stringify({message:r,...a?{threadId:a}:{},...l?.mode?{mode:l.mode}:{},...l?.improveMode?{improveMode:l.improveMode}:{}}),signal:d.signal});if(!g.ok){let k=Qs("httpError",{status:g.status});try{const w=await g.json();w?.message&&(k=w.message)}catch{}o.onError(k,!1);return}if(!g.body){o.onError(Qs("noStream"),!1);return}const v=g.body.getReader(),y=new TextDecoder("utf-8");for(;;){const{done:k,value:w}=await v.read();if(k){h||o.onError(Qs("emptyStream"),!1);break}b+=y.decode(w,{stream:!0});const j=b.split(`
946
947`);b=j.pop()??"";for(const C of j){const N=bT(C);if(!N)continue;let S;try{S=JSON.parse(N.data)}catch{continue}switch(N.event){case"block_start":{const _=S.id;_&&(f[_]="");break}case"text_delta":{const _=S.id,R=S.delta??"";_!==void 0?f[_]=(f[_]??"")+R:x+=R,x=Object.values(f).join(""),h=x.length>0,o.onToken(x);break}case"block_end":break;case"tool_call":{const _=S.name??"herramienta";o.onToolCall(_);break}case"draft_patch":{const _={toolName:S.toolName??"",patch:S.patch??{},diff:S.diff??[],rationale:S.rationale??"",previewText:S.previewText??"",i18n:S.i18n??null,sensitive:S.sensitive??!1,promptEdits:S.promptEdits??null};o.onDraftPatch(_);break}case"clarify":{const _=S.question??"";if(_){const R=Array.isArray(S.options)?S.options.filter(A=>typeof A=="string"):void 0;o.onClarify?.({question:_,options:R,messageId:S.messageId??void 0})}break}case"action":{const _=S.action;_?.id&&o.onAction&&o.onAction(_);break}case"card":{const _=S.kind??"";_&&o.onCard&&o.onCard({kind:_,data:S.data??{},messageId:S.messageId??""});break}case"usage":break;case"done":{const _=S.messageId??"",R=S.threadId??a??"";o.onDone(_,R);return}case"error":{const _=S.message??"Error desconocido en el stream.";o.onError(_,h);return}default:break}}}}catch(g){if(g.name==="AbortError")return;const v=g instanceof Error?g.message:Qs("connection");o.onError(v,h)}finally{n.current===d&&(n.current=null)}},[e,a]),abort:s}}
947const f0=m.createContext(null),ko=()=>m.useContext(f0);function Ha({icon:e,title:a,subtitle:n,right:s,children:i}){return t.jsxs("div",{style:{maxWidth:560,width:"100%",border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r)",background:"var(--cia-bg-elev)",overflow:"hidden",marginBottom:8},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",borderBottom:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)"},children:[t.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,borderRadius:8,flex:"none",background:"color-mix(in oklab, var(--cia-brand-500) 12%, transparent)",color:"var(--cia-brand-500)"},"aria-hidden":"true",children:e}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"var(--cia-text)",letterSpacing:"var(--cia-tracking-tight)"},children:a}),n&&t.jsx("div",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-4)"},children:n})]}),s]}),t.jsx("div",{style:{padding:14},children:i})]})}function Kt({label:e,value:a}){return a==null||a===""?null:t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline",minWidth:0},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-4)",flex:"none"},children:e}),t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-2)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]})}function Pa({tone:e,label:a}){const n=e==="ok"?"var(--cia-ok-500)":e==="warn"?"var(--cia-warn-500)":e==="bad"?"var(--cia-bad-500)":"var(--cia-text-4)",s=e==="ok"?"var(--cia-ok-ink)":e==="warn"?"var(--cia-warn-ink)":e==="bad"?"var(--cia-bad-ink)":"var(--cia-text-2)";return t.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 8px",borderRadius:"var(--cia-r-pill)",fontSize:10.5,fontWeight:600,fontFamily:"var(--cia-font-mono)",color:s,background:`color-mix(in oklab, ${n} 12%, transparent)`,border:`1px solid color-mix(in oklab, ${n} 30%, transparent)`},children:a})}function Jn({onClick:e,variant:a="ghost",disabled:n,children:s}){const i={display:"inline-flex",alignItems:"center",gap:5,height:28,padding:"0 10px",borderRadius:"var(--cia-r-sm)",fontFamily:"var(--cia-font-sans)",fontSize:12,fontWeight:600,letterSpacing:"var(--cia-tracking-tight)",cursor:n?"not-allowed":"pointer",opacity:n?.55:1,transition:"background var(--cia-dur-fast) ease, transform var(--cia-dur-fast) ease"},r={primary:{...i,background:"var(--cia-cta-500)",color:"#fff",border:"1px solid var(--cia-cta-600)"},ghost:{...i,background:"transparent",color:"var(--cia-text-2)",border:"1px solid var(--cia-border-2)"},danger:{...i,background:"var(--cia-bad-500)",color:"#fff",border:"1px solid var(--cia-bad-500)"}};return t.jsx("button",{type:"button",onClick:e,disabled:n,style:r[a],onMouseDown:o=>{n||(o.currentTarget.style.transform="scale(0.97)")},onMouseUp:o=>{o.currentTarget.style.transform="none"},onMouseLeave:o=>{o.currentTarget.style.transform="none"},children:s})}function Uc(e){const a=Number(e??0);return`${Math.floor(a/60)}:${String(Math.round(a%60)).padStart(2,"0")}`}function yT({data:e}){const{t:a}=M("copilot"),n=dt(),s=ko(),i=Pe(l=>l.user),r=e.agents??[],o=Number(e.total??r.length);return t.jsx(Ha,{icon:t.jsx(Ft,{size:14}),title:a("cards.agentList.title"),subtitle:a("cards.agentList.subtitle",{shown:r.length,total:o}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[r.map((l,c)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",padding:"8px 0",borderTop:c===0?"none":"1px solid var(--cia-border)"},children:[t.jsxs("div",{style:{flex:1,minWidth:140},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600,color:"var(--cia-text)"},children:l.name})," ",t.jsx(Pa,{tone:l.status==="published"?"ok":"muted",label:l.status==="published"?a("cards.agentList.published"):a("cards.agentList.draft")})]}),t.jsxs("div",{style:{display:"flex",gap:6,flex:"none"},children:[s&&t.jsxs(Jn,{onClick:()=>s(a("cards.agentList.askDetail",{name:l.name,id:l.id})),children:[t.jsx(qs,{size:12})," ",a("cards.agentList.detail")]}),s&&lt(i,"playground.use")&&t.jsxs(Jn,{onClick:()=>s(a("cards.agentList.askTest",{name:l.name,id:l.id})),children:[t.jsx(Ta,{size:12})," ",a("cards.agentList.test")]}),lt(i,"agents.manage")&&t.jsxs(Jn,{onClick:()=>n({to:`/agents/${l.id}`}),children:[t.jsx(qt,{size:12})," ",a("cards.agentList.edit")]})]})]},l.id)),r.length===0&&t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-4)"},children:a("cards.agentList.empty")})]})})}function vT({direction:e}){return e==="inbound"?t.jsx(yn,{size:12,"aria-hidden":"true"}):e==="outbound"?t.jsx(ka,{size:12,"aria-hidden":"true"}):t.jsx(Va,{size:12,"aria-hidden":"true"})}function x0(e){if(!e)return"";
947try{return new Date(String(e)).toLocaleString(Te(),{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return""}}function jT({data:e}){const{t:a}=M("copilot"),n=ko(),s=e.calls??[],i=Number(e.total??s.length);return t.jsx(Ha,{icon:t.jsx(Ma,{size:14}),title:a("cards.recentCalls.title"),subtitle:a("cards.recentCalls.subtitle",{shown:s.length,total:i}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.map((r,o)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",padding:"8px 0",borderTop:o===0?"none":"1px solid var(--cia-border)"},children:[t.jsx("span",{style:{color:"var(--cia-text-3)",flex:"none"},children:t.jsx(vT,{direction:r.direction})}),t.jsxs("div",{style:{flex:1,minWidth:150},children:[t.jsxs("div",{style:{fontSize:12.5,fontWeight:600,color:"var(--cia-text)"},children:[r.agentName||a("cards.recentCalls.noAgent")," ",t.jsx(Pa,{tone:r.status==="completed"?"ok":r.status==="failed"?"bad":"muted",label:String(r.status??"")})]}),t.jsx("div",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-4)"},children:[r.to||r.from,Uc(r.durationSeconds),x0(r.createdAt)].filter(Boolean).join(" · ")})]}),n&&r.id&&t.jsxs(Jn,{onClick:()=>n(a("cards.recentCalls.askDetail",{id:r.id})),children:[t.jsx(qs,{size:12})," ",a("cards.recentCalls.detail")]})]},r.id??o)),s.length===0&&t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-4)"},children:a("cards.recentCalls.empty")})]})})}function wT({data:e}){const{t:a}=M("copilot"),n=ko(),{can:s}=tt(),[i,r]=m.useState(!1),o=e.transcript??[],l=e.id??null,c=e.sentiment,d=e.success,u=e.extractedFields??null;return t.jsx(Ha,{icon:t.jsx(Ma,{size:14}),title:a("cards.callDetail.title"),subtitle:l??void 0,right:t.jsxs("div",{style:{display:"flex",gap:5,flex:"none"},children:[c&&t.jsx(Pa,{tone:c==="positive"?"ok":c==="negative"?"bad":"muted",label:a(`cards.callDetail.sentiment.${c}`,{defaultValue:c})}),t.jsx(Pa,{tone:d==="success"?"ok":d==="failure"?"bad":"muted",label:a(`cards.callDetail.success.${d||"unknown"}`,{defaultValue:String(d??"")})})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:6},children:[t.jsx(Kt,{label:a("cards.callDetail.agent"),value:e.agentName}),t.jsx(Kt,{label:a("cards.callDetail.direction"),value:e.direction}),t.jsx(Kt,{label:a("cards.callDetail.from"),value:e.from}),t.jsx(Kt,{label:a("cards.callDetail.to"),value:e.to}),t.jsx(Kt,{label:a("cards.callDetail.duration"),value:Uc(e.durationSeconds)}),t.jsx(Kt,{label:a("cards.callDetail.date"),value:x0(e.createdAt)}),t.jsx(Kt,{label:a("cards.callDetail.endReason"),value:e.endReason})]}),typeof e.summary=="string"&&e.summary!==""&&t.jsx("p",{style:{margin:"4px 0 0",fontSize:12.5,color:"var(--cia-text-2)",lineHeight:1.55},children:e.summary}),u&&Object.keys(u).length>0&&t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:4,marginTop:2},children:Object.entries(u).slice(0,8).map(([p,f])=>t.jsx(Kt,{label:p,value:String(f??"")},p))}),e.hasRecording===!0&&l&&t.jsx("div",{style:{marginTop:4},children:t.jsx(z_,{resolveSrc:async()=>{const{data:p}=await T.get(`/calls/${l}/recording`);if(p?.status!=="ready"||!p.url)throw new Error("sin url");return p.url},playLabel:a("cards.callDetail.playRecording"),errorLabel:a("cards.callDetail.recordingError")})}),l&&s("agents.manage")&&n&&t.jsx("div",{style:{marginTop:4},children:t.jsxs(Jn,{onClick:()=>n(a("cards.callDetail.askCreateTest",{id:l})),children:[t.jsx(Yp,{size:12})," ",a("cards.callDetail.createTest")]})}),o.length>0&&t.jsxs("div",{style:{marginTop:4},children:[t.jsxs("button",{type:"button",onClick:()=>r(p=>!p),style:{display:"inline-flex",alignItems:"center",gap:4,background:"none",border:"none",padding:0,fontSize:12,fontWeight:600,color:"var(--cia-brand-500)",cursor:"pointer"},"aria-expanded":i,children:[i?t.jsx(Rn,{size:13}):t.jsx(Ut,{size:13}),a("cards.callDetail.transcript",{count:o.length})]}),i&&t.jsx("div",{style:{marginTop:6,maxHeight:260,overflowY:"auto",display:"flex",flexDirection:"column",gap:6,padding:8,borderRadius:"var(--cia-r-sm)",background:"var(--cia-bg-soft)"},children:o.map((p,f)=>t.jsx("div",{style:{alignSelf:p.role==="user"?"flex-end":"flex-start",maxWidth:"86%",padding:"6px 10px",borderRadius:10,fontSize:12,lineHeight:1.5,background:p.role==="user"?"color-mix(in oklab, var(--cia-brand-500) 12%, transparent)":"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",color:"var(--cia-text-2)"},children:p.text},f))})]})]})})}function Bn({label:e,value:a,tone:n}){return t.jsxs("div",{style:{flex:"1 1 90px",minWidth:90,padding:"8px 10px",borderRadius:"var(--cia-r-sm)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)"},children:[t.jsx("div",{className:"cia-mono",style:{fontSize:9.5,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--cia-text-4)"},children:e}),t.jsx("div",{style:{fontSize:18,fontWeight:700,letterSpacing:"-0.02em",color:n==="ok"?"var(--cia-ok-500)":n==="bad"?"var(--cia-bad-500)":"var(--cia-text)",fontVariantNumeric:"tabular-nums"},children:a})]})}function kT({data:e}){const{t:a}=M("copilot"),n=e.funnel??{},s=e.sentiment??{},i=e.success??{},r=e.duration??{},o=[{key:"targets",label:a("cards.campaign.targets"),value:n.targets??0},{key:"dialed",label:a("cards.campaign.dialed"),value:n.dialed??0},{key:"connected",label:a("cards.campaign.connected"),value:n.connected??0},{key:"human",label:a("cards.campaign.human"),value:n.human??0},{key:"goalMet",label:a("cards.campaign.goalMet"),value:n.goalMet??0}],l=Number(i.rate??0);return t.jsx(Ha,{icon:t.jsx(kc,{size:14}),title:String(e.name??a("cards.campaign.title")),subtitle:String(e.campaignId??""),right:e.status?t.jsx(Pa,{tone:e.status==="running"?"ok":"muted",label:String(e.status)}):void 0,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsx(Bn,{label:a("cards.campaign.kpiGoal"),value:`${Math.round(l*100)}
947%`,tone:l>=.5?"ok":void 0}),t.jsx(Bn,{label:a("cards.campaign.kpiSentiment"),value:`${s.positive??0}/${s.negative??0}`,tone:(s.positive??0)>=(s.negative??0)?"ok":"bad"}),t.jsx(Bn,{label:a("cards.campaign.kpiAvg"),value:Uc(r.avgSeconds)})]}),t.jsx(T_,{stages:o})]})})}function NT({data:e}){const{t:a}=M("copilot"),n=e.sentiment??{},s=e.success??{},i=e.byDirection??{},r=e.telephony??null,o=Number(e.totalCalls??0),l=Number(e.analyzedCalls??0),c=Number(s.success??0),d=Number(s.failure??0),u=c+d,p=u>0?c/u:null,f=[{label:a("cards.analytics.sent.positive"),value:n.positive??0,tone:"ok"},{label:a("cards.analytics.sent.neutral"),value:n.neutral??0,tone:"neutral"},{label:a("cards.analytics.sent.negative"),value:n.negative??0,tone:"bad"},{label:a("cards.analytics.sent.unknown"),value:n.unknown??0,tone:"muted"}].filter(w=>w.value>0),x=r?[{label:a("cards.analytics.tel.answered"),value:Number(r.answered??0),tone:"ok"},{label:a("cards.analytics.tel.noAnswer"),value:Number(r.noAnswer??0),tone:"bad"},{label:a("cards.analytics.tel.voicemail"),value:Number(r.voicemail??0),tone:"warn"},{label:a("cards.analytics.tel.busy"),value:Number(r.busy??0),tone:"warn"},{label:a("cards.analytics.tel.rejected"),value:Number(r.rejected??0),tone:"bad"},{label:a("cards.analytics.tel.failed"),value:Number(r.failed??0),tone:"bad"},{label:a("cards.analytics.tel.unknown"),value:Number(r.unknown??0),tone:"muted"}].filter(w=>w.value>0):[],h=r?.answerRate!=null?Number(r.answerRate):null,b=w=>w.length>22?`${w.slice(0,21)}…`:w,g=(w,j)=>(Array.isArray(w)?w:[]).slice(0,5).map(C=>{const N=j?a(`format:endReason.${C.key}`,{defaultValue:String(C.key)}):String(C.key),S=b(N);return{label:S,value:Number(C.count)||0,...N!==S?{hint:N}:{}}}).filter(C=>C.value>0),v=g(r?.byCloseReason,!1),y=g(r?.byEndReason,!0),k=[{label:a("cards.analytics.goal.met"),value:c,tone:"ok"},{label:a("cards.analytics.goal.notMet"),value:d,tone:"bad"},{label:a("cards.analytics.goal.unknown"),value:s.unknown??0,tone:"muted"}].filter(w=>w.value>0);return t.jsx(Ha,{icon:t.jsx(us,{size:14}),title:a("cards.analytics.title"),subtitle:e.agentName?String(e.agentName):a("cards.analytics.allAgents"),right:t.jsx(Pa,{tone:"muted",label:a("cards.analytics.window",{days:Number(e.windowDays??7)})}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsx(Bn,{label:a("cards.analytics.kpiTotal"),value:String(o)}),t.jsx(Bn,{label:a("cards.analytics.kpiAnalyzed"),value:String(l)}),t.jsx(Bn,{label:a("cards.analytics.kpiGoal"),value:p==null?"—":`${Math.round(p*100)}%`,tone:p==null?void 0:p>=.5?"ok":"bad"}),h!=null&&t.jsx(Bn,{label:a("cards.analytics.kpiAnswerRate"),value:`${Math.round(h*100)}%`,tone:h>=.5?"ok":"bad"}),t.jsx(Bn,{label:a("cards.analytics.kpiAvg"),value:Uc(Number(e.avgDurationSeconds??0))})]}),x.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"cia-mono",style:{fontSize:10,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--cia-text-4)",marginBottom:4},children:a("cards.analytics.telTitle")}),t.jsx(Io,{data:x}),t.jsx("div",{style:{fontSize:11,lineHeight:1.45,color:"var(--cia-text-3)",marginTop:4},children:a("cards.analytics.telCaption")})]}),(f.length>0||k.length>0)&&t.jsxs("div",{style:{display:"flex",gap:16,flexWrap:"wrap",alignItems:"flex-start"},children:[f.length>0&&t.jsxs("div",{style:{flex:"1 1 220px",minWidth:200},children:[t.jsx("div",{className:"cia-mono",style:{fontSize:10,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--cia-text-4)",marginBottom:4},children:a("cards.analytics.sentTitle")}),t.jsx(Qj,{data:f,height:200,outerRadius:68,innerRadius:44})]}),k.length>0&&t.jsxs("div",{style:{flex:"1 1 240px",minWidth:220},children:[t.jsx("div",{className:"cia-mono",style:{fontSize:10,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--cia-text-4)",marginBottom:4},children:a("cards.analytics.goalTitle")}),t.jsx(Io,{data:k})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(120px, 1fr))",gap:6}
947,children:[t.jsx(Kt,{label:a("cards.analytics.dir.inbound"),value:String(i.inbound??0)}),t.jsx(Kt,{label:a("cards.analytics.dir.outbound"),value:String(i.outbound??0)}),t.jsx(Kt,{label:a("cards.analytics.dir.web"),value:String(i.web??0)}),o>l&&t.jsx(Kt,{label:a("cards.analytics.notAnalyzed"),value:String(o-l)})]}),(v.length>0||y.length>0)&&t.jsxs("div",{style:{display:"flex",gap:16,flexWrap:"wrap"},children:[v.length>0&&t.jsxs("div",{style:{flex:"1 1 220px",minWidth:200},children:[t.jsx("div",{className:"cia-mono",style:{fontSize:10,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--cia-text-4)",marginBottom:4},children:a("cards.analytics.closeTitle")}),t.jsx(Io,{data:v})]}),y.length>0&&t.jsxs("div",{style:{flex:"1 1 220px",minWidth:200},children:[t.jsx("div",{className:"cia-mono",style:{fontSize:10,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--cia-text-4)",marginBottom:4},children:a("cards.analytics.endTitle")}),t.jsx(Io,{data:y})]})]}),t.jsx("div",{style:{fontSize:11,lineHeight:1.45,color:"var(--cia-text-3)",padding:"6px 10px",borderRadius:"var(--cia-r-sm)",background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)"},children:a("cards.analytics.caption",{analyzed:l})})]})})}function ST({data:e}){const{t:a}=M("copilot"),n=e.plan??null,s=e.usage??{},i=e.trial,r=e.insightCode,o=Number(s.usedMinutes??0),l=Number(s.includedMinutes??0),c=l>0?Math.min(1,o/l):0,d=Te();return t.jsx(Ha,{icon:t.jsx(_c,{size:14}),title:a("cards.billing.title"),subtitle:n?String(n.name??""):void 0,right:r?t.jsx(Pa,{tone:r==="quota_exceeded"?"bad":"warn",label:a(`cards.billing.insight.${r}`,{defaultValue:r})}):void 0,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,color:"var(--cia-text-3)",marginBottom:4},children:[t.jsx("span",{children:a("cards.billing.minutes")}),t.jsxs("span",{className:"cia-mono",style:{fontVariantNumeric:"tabular-nums"},children:[o.toLocaleString(d)," / ",l.toLocaleString(d)]})]}),t.jsx("div",{style:{height:8,borderRadius:999,background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",overflow:"hidden"},children:t.jsx("div",{style:{width:`${Math.round(c*100)}%`,height:"100%",background:c>=1?"var(--cia-bad-500)":c>=.85?"var(--cia-warn-500)":"var(--cia-ok-500)",transition:"width 300ms ease"}})})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:6},children:[t.jsx(Kt,{label:a("cards.billing.cycle"),value:s.cycleEnd?new Date(String(s.cycleEnd)).toLocaleDateString(d,{day:"2-digit",month:"short"}):null}),t.jsx(Kt,{label:a("cards.billing.channels"),value:String(e.purchasedChannels??0)}),t.jsx(Kt,{label:a("cards.billing.nextBill"),value:e.nextBillUsd!=null?`US$ ${Number(e.nextBillUsd).toLocaleString(d)}`:null}),i&&i.status==="active"&&t.jsx(Kt,{label:a("cards.billing.trial"),value:`${i.remainingMinutes??0} min`})]})]})})}function ac(e,a){const n=e.headers?.["content-disposition"],s=n?.match(/filename\*=UTF-8''([^;]+)/i);if(s?.[1])try{return decodeURIComponent(s[1])}catch{}return n?.match(/filename="?([^";]+)"?/)?.[1]??a}function ao(e,a){const n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=a,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(n)}function CT(e){const a=document.createElement("a");a.href=e,a.rel="noopener",document.body.appendChild(a),a.click(),a.remove()}const _T={list:e=>T.get("/campaigns",{params:e}).then(a=>a.data),get:e=>T.get(`/campaigns/${e}`).then(a=>a.data),create:e=>T.post("/campaigns",e).then(a=>a.data),update:(e,a)=>T.patch(`/campaigns/${e}`,a).then(n=>n.data),remove:(e,a)=>T.delete(`/campaigns/${e}`,{data:{confirmName:a}}).then(n=>n.data),deletePreview:e=>T.get(`/campaigns/${e}/delete-preview`).then(a=>a.data),undelivered:e=>T.get(`/campaigns/${e}/undelivered`).then(a=>a.data),retryUndelivered:e=>T.post(`/campaigns/${e}/retry-undelivered`).then(a=>a.data),clone:e=>T.post(`/campaigns/${e}/clone`).then(a=>a.data),uploadBatch:(e,a)=>{const n=new FormData;return n.append("file",a),T.post(`/campaigns/${e}/batches`,n,{headers:{"Content-Type":"multipart/form-data"}}).then(s=>s.data)},batches:e=>T.get(`/campaigns/${e}/batches`).then(a=>a.data),renameBatch:(e,a,n)=>T.patch(`/campaigns/${e}/batches/${a}`,{label:n}).then(s=>s.data),deleteBatch:(e,a)=>T.delete(`/campaigns/${e}/batches/${a}`).then(n=>n.data),targets:(e,a)=>T.get(`/campaigns/${e}/targets`,{params:a}).then(n=>n.data),targetAttempts:(e,a)=>T.get(`/campaigns/${e}/targets/${a}/attempts`).then(n=>n.data),addContacts:(e,a)=>T.post(`/campaigns/${e}/contacts`,{contacts:a}).then(n=>n.data),launch:e=>T.post(`/campaigns/${e}/launch`).then(a=>a.data),pause:e=>T.post(`/campaigns/${e}/pause`).then(a=>a.data),resume:e=>T.post(`/campaigns/${e}/resume`).then(a=>a.data),stop:e=>T.post(`/campaigns/${e}/stop`).then(a=>a.data),report:e=>T.get(`/campaigns/${e}/report`).then(a=>a.data),insights:e=>T.get(`/campaigns/${e}/report/insights`).then(a=>a.data),activity:(e,a)=>T.get(`/campaigns/${e}/report/activity`,{params:{range:a}}).then(n=>n.data),ley2300:()=>T.get("/campaigns/ley2300").then(e=>e.data),retryPreview:e=>T.post("/campaigns/retry-preview",e).then(a=>a.data),holidays:e=>T.get("/campaigns/holidays",{params:{year:e}}).then(a=>a.data),listSuppressions:e=>T.get("/campaigns/suppressions",{params:e}).then(a=>a.data),addSuppression:(e,a)=>T.post("/campaigns/suppressions",{phoneE164:e,reason:a}).then(n=>n.data),removeSuppression:e=>T.delete(`/campaigns/suppressions/${encodeURIComponent(e)}`).then(a=>a.data),downloadTemplate:async(e,a)=>{const n=await T.get("/campaigns/template",{params:{agentId:e,numberId:a},responseType:"blob"});ao(n.data,ac(n,"plantilla.csv"))},downloadExport:async(e,a={})=>{const n=a.format??"csv",s=await T.get(`/campaigns/${e}/report/export`,{params:{format:n,...a.batchId?{batchId:a.batchId}:{}},responseType:"blob"});ao(s.data,ac(s,`campana_${e}.${n}`))}};function GB(e){const a=m.useRef(e);a.current=e,m.useEffect(()=>{let n;try{n=ns()}catch{return}const i=["progress","started","completed","paused"].map(r=>{const o=l=>a.current(r,l);return n.on(`campaign:${r}`,o),[r,o]});return()=>{for(const[r,o]of i)n.off(`campaign:${r}`,o)}},[])}function ET(e,a){return{id:e.id,phone:e.destinationNumber,name:e.displayName??null,status:e.status,outcome:e.outcome??null,attempts:e.attempts??0,lastError:e.lastError?String(e.lastError).slice(0,120):null,
947sentiment:e.sentiment??null,vars:Object.fromEntries(a.map(n=>[n,String((e.variables??{})[n]??"").slice(0,80)]))}}function AT(e,a){return e==="done"?a==="answered"?"ok":a==="voicemail"?"warn":a?"bad":"muted":e==="dialing"?"warn":"muted"}function RT({value:e}){if(!e||e==="unknown")return t.jsx("span",{style:{color:"var(--cia-text-4)"},children:"—"});const a=e==="positive"?"var(--cia-ok-500)":e==="negative"?"var(--cia-bad-500)":"var(--cia-text-4)";return t.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:a},"aria-label":e})}const Gs={padding:"5px 8px",fontSize:9.5,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--cia-text-4)",fontFamily:"var(--cia-font-mono)",textAlign:"left",whiteSpace:"nowrap",borderBottom:"1px solid var(--cia-border)"},ms={padding:"6px 8px",fontSize:12,color:"var(--cia-text-2)",whiteSpace:"nowrap",borderBottom:"1px solid var(--cia-border)",maxWidth:180,overflow:"hidden",textOverflow:"ellipsis"};function TT({data:e}){const{t:a}=M("copilot"),n=String(e.campaignId??""),s=Array.isArray(e.varKeys)?e.varKeys:[],i=Number(e.pageSize??10),r=e.statusFilter?String(e.statusFilter):void 0,o=e.q?String(e.q):void 0,l=Array.isArray(e.leads)?e.leads:[],[c,d]=m.useState(l),[u,p]=m.useState(Number(e.page??0)),[f,x]=m.useState(Number(e.total??l.length)),[h,b]=m.useState(!1),[g,v]=m.useState(!1),y=Math.max(1,Math.ceil(f/Math.max(1,i))),k=c.some(j=>j.name),w=async j=>{if(!(j<0||j>=y||h||!n)){b(!0),v(!1);try{const C=await _T.targets(n,{page:j,limit:i,status:r,q:o});d(C.items.map(N=>ET(N,s))),x(C.total),p(j)}catch{v(!0)}finally{b(!1)}}};return t.jsx(Ha,{icon:t.jsx(Bs,{size:14}),title:String(e.name??a("cards.leads.title")),subtitle:a("cards.leads.subtitle",{total:f}),right:r?t.jsx(Pa,{tone:"muted",label:String(r)}):void 0,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx("div",{className:"cia-scroll-x",style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:t.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",minWidth:420},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:Gs,children:a("cards.leads.phone")}),k&&t.jsx("th",{style:Gs,children:a("cards.leads.name")}),t.jsx("th",{style:Gs,children:a("cards.leads.status")}),t.jsx("th",{style:Gs,children:a("cards.leads.attempts")}),t.jsx("th",{style:Gs,children:a("cards.leads.sentiment")}),s.map(j=>t.jsx("th",{style:Gs,children:j.replace(/_/g," ")},j))]})}),t.jsxs("tbody",{style:{opacity:h?.5:1,transition:"opacity 120ms"},children:[c.map(j=>t.jsxs("tr",{children:[t.jsx("td",{style:{...ms,fontFamily:"var(--cia-font-mono)",fontVariantNumeric:"tabular-nums"},children:j.phone}),k&&t.jsx("td",{style:ms,children:j.name??"—"}),t.jsx("td",{style:ms,children:t.jsx(Pa,{tone:AT(j.status,j.outcome),label:a(`cards.leads.outcomes.${j.outcome??j.status}`,{defaultValue:j.outcome??j.status})})}),t.jsx("td",{style:{...ms,fontVariantNumeric:"tabular-nums",textAlign:"center"},children:j.attempts}),t.jsx("td",{style:{...ms,textAlign:"center"},children:t.jsx(RT,{value:j.sentiment})}),s.map(C=>t.jsx("td",{style:ms,title:j.vars?.[C]??"",children:j.vars?.[C]||"—"},C))]},j.id)),c.length===0&&t.jsx("tr",{children:t.jsx("td",{style:{...ms,textAlign:"center",color:"var(--cia-text-4)"},colSpan:5+s.length+(k?1:0),children:a("cards.leads.empty")})})]})]})}),(y>1||g)&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8},children:[g&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-bad-500)"},children:a("cards.leads.pageError")}),t.jsx("button",{type:"button",onClick:()=>w(u-1),disabled:u<=0||h,"aria-label":a("cards.leads.prev"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"var(--cia-r-sm)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)",color:"var(--cia-text-2)",cursor:u<=0||h?"default":"pointer",opacity:u<=0?.4:1},children:t.jsx(gn,{size:14})}),t.jsxs("span",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)",fontVariantNumeric:"tabular-nums"},children:[u+1," / ",y]}),t.jsx("button",{type:"button",onClick:()=>w(u+1),disabled:u>=y-1||h,"aria-label":a("cards.leads.next"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"var(--cia-r-sm)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)",color:"var(--cia-text-2)",cursor:u>=y-1||h?"default":"pointer",opacity:u>=y-1?.4:1},children:t.jsx(ca,{size:14})})]})]})})}const MT=3e3,PT=80;function zT(e){return e==="passed"?"ok":e==="failed"||e==="error"?"bad":"warn"}function DT({data:e}){const{t:a}=M("copilot"),[n,s]=m.useState(e),[i,r]=m.useState(!1),o=m.useRef(0),l=n.status==="queued"||n.status==="running";m.useEffect(()=>{if(!l||!n.runId||!n.agentId)return;let u=!0;const p=setInterval(async()=>
947{if(u){if(o.current>=PT){clearInterval(p);return}o.current+=1;try{const{data:f}=await T.get(`/agents/${n.agentId}/sim-runs/${n.runId}`);if(!u||!f)return;s(x=>({...x,status:f.status??x.status,endReason:f.endReason??x.endReason,turns:f.turns??x.turns,verdict:f.verdict??x.verdict,error:f.error??x.error,transcript:Array.isArray(f.transcript)?f.transcript:x.transcript,finishedAt:f.finishedAt??x.finishedAt})),f.status&&f.status!=="queued"&&f.status!=="running"&&clearInterval(p)}catch{}}},MT);return()=>{u=!1,clearInterval(p)}},[l,n.runId,n.agentId]);const c=n.verdict?.criteria??[],d=c.filter(u=>u.passed).length;return t.jsx(Ha,{icon:t.jsx(Yp,{size:14}),title:n.testName||a("cards.sim.title"),subtitle:a("cards.sim.subtitle"),right:t.jsx(Pa,{tone:zT(n.status),label:a(`cards.sim.status.${n.status}`,{defaultValue:n.status})}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[l&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12.5,color:"var(--cia-text-3)"},"aria-live":"polite",children:[t.jsx(je,{size:13,style:{animation:"spin 1s linear infinite"},"aria-hidden":!0}),a("cards.sim.running")]}),n.status==="error"&&t.jsx("div",{style:{fontSize:12.5,color:"var(--cia-bad-500)"},children:n.error||a("cards.sim.errorGeneric")}),!l&&n.verdict&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(120px, 1fr))",gap:6},children:[t.jsx(Kt,{label:a("cards.sim.criteriaMet"),value:`${d}/${c.length}`}),t.jsx(Kt,{label:a("cards.sim.turns"),value:String(n.turns??0)}),t.jsx(Kt,{label:a("cards.sim.endReason"),value:a(`cards.sim.end.${n.endReason??"unknown"}`,{defaultValue:n.endReason??"—"})})]}),t.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:6},children:c.map(u=>t.jsxs("li",{style:{display:"flex",gap:8,alignItems:"flex-start"},children:[t.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,borderRadius:6,flex:"none",marginTop:1,background:u.passed?"color-mix(in oklab, var(--cia-ok-500) 16%, transparent)":"color-mix(in oklab, var(--cia-bad-500) 14%, transparent)",color:u.passed?"var(--cia-ok-600)":"var(--cia-bad-500)"},"aria-hidden":!0,children:u.passed?t.jsx(ct,{size:12}):t.jsx(nt,{size:12})}),t.jsx("span",{style:{fontSize:12.5,lineHeight:1.5,color:"var(--cia-text-2)"},children:u.rationale})]},u.id))}),n.verdict.summary&&t.jsx("div",{style:{fontSize:12,lineHeight:1.5,color:"var(--cia-text-3)",padding:"6px 10px",borderRadius:"var(--cia-r-sm)",background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)"},children:n.verdict.summary})]}),n.transcript?.length>0&&t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>r(u=>!u),"aria-expanded":i,style:{display:"inline-flex",alignItems:"center",gap:5,padding:"4px 8px",minHeight:28,borderRadius:"var(--cia-r-sm)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)",color:"var(--cia-text-3)",fontSize:11.5,cursor:"pointer"},children:[i?t.jsx(Rn,{size:12}):t.jsx(Ut,{size:12}),a("cards.sim.transcript",{n:n.transcript.length})]}),i&&t.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6,maxHeight:260,overflowY:"auto"},className:"cia-scroll",children:n.transcript.map((u,p)=>t.jsxs("div",{style:{fontSize:12,lineHeight:1.5},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:9.5,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--cia-text-4)",marginRight:6},children:u.role==="tool"?`${a("cards.sim.roleTool")}${u.toolName?` · ${u.toolName}`:""}`:a(`cards.sim.role.${u.role}`,{defaultValue:u.role})}),t.jsx("span",{style:{color:u.role==="tool"?"var(--cia-text-4)":"var(--cia-text-2)"},children:u.text})]},p))})]})]})})}function IT({uiConfig:e,connect:a,embedded:n=!1}){const s=e.languages??[],[i,r]=m.useState(s[0]?.code||"es"),o=e.accentColor||"var(--cia-cta-500)",l=Tj(o),c=e.voiceEnabled,d=e.chatEnabled,u=c&&d,[p,f]=m.useState(c?"voice":"chat"),[x,h]=m.useState(""),b=(e.variables??[]).filter(re=>re.required!==!1),[g,v]=m.useState({}),[y,k]=m.useState(!1),w=b.every(re=>(g[re.name]??"").trim()!==""),j=b.length>0&&!y,C=m.useCallback(()=>Object.fromEntries(Object.entries(g).filter(([,re])=>re.trim()!=="")),[g]),{phase:N,mode:S,error:_,muted:R,audioBlocked:A,micError:E,elapsed:I,agentSpeaking:P,segments:O,audioContainerRef:K,startVoice:W,sendChat:V,toggleMute:U,hangup:X,restart:ie,retryMic:de,enableAudio:$}=Mj({connect:a,lang:i,getVariables:C}),z=m.useMemo(()=>O.map(re=>({id:re.id,role:re.role,text:re.text})),[O]),D=m.useRef(null);m.useEffect(()=>{D.current?.scrollIntoView({behavior:"smooth"})},[O]);function F(){const re=x.trim();re&&(h(""),V(re))}const G=N==="connecting",te=N==="live",B=S==="none",ne=B?p:S==="chat"?"chat":"voice",me=ne==="voice",Ee=ne==="chat",L=Ee&&z.length>0&&z[z.length-1].role==="user"&&(te||G);return t.jsxs("div",{className:"cia-col",style:{height:n?"100%":void 0,minHeight:n?void 0:420,gap:0},children:[t.jsx("div",{ref:K,className:"hidden","aria-hidden":!0}),A&&t.jsxs("button",{type:"button",onClick:$,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,width:"100%",marginBottom:10,padding:"11px 14px",borderRadius:12,cursor:"pointer",border:"none",background:o,color:l,fontWeight:600,fontSize:14},children:[t.jsx(Il,{size:16,"aria-hidden":!0})," ",wt(i,"enableSound")]}),te&&me&&E&&t.jsxs("div",{className:"cia-badge cia-badge-bad",role:"alert",style:{height:"auto",padding:"8px 10px",fontSize:12,marginBottom:8,whiteSpace:"normal",textAlign:"left",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{flex:1},children:E}),t.jsxs("button",{type:"button",onClick:de,className:"cia-btn cia-btn-sm",style:{flex:"none"},children:[t.jsx(Ta,{size:13})," ",wt(i,"micRetry")]})]}),t.jsxs("div",{className:"cia-row",style:{alignItems:"center",gap:8,paddingBottom:12,minHeight:30},children:[u&&t.jsx("div",{className:"cia-toggle",children:["voice","chat"].map(re=>t.jsxs("button",{type:"button",onClick:()=>te||G?null:f(re),disabled:te||G,className:`cia-toggle-btn ${ne===re?"cia-toggle-btn-active":""}`,style:{display:"flex",alignItems:"center",gap:6,opacity:(te||G)&&ne!==re?.5:1},children:[re==="voice"?t.jsx(Il,{size:13}):t.jsx(sn,{size:13}),re==="voice"?wt(i,"voice"):wt(i,"chat")]},re))}),t.jsx("span",{style:{flex:1}}),te?t.jsxs("span",{className:"cia-badge cia-badge-success",children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{width:5,height:5,color:"var(--cia-ok-500)"}}),wt(i,"live"),t.jsx("span",{className:"cia-mono",style:{marginLeft:6,color:"var(--cia-text-2)"},children:Pj(I)})]}):G?t.jsxs("span",{className:"cia-badge",children:[t.jsx(je,{size:11,style:{animation:"spin 1s linear infinite"}})," ",wt(i,"connecting")]}):N==="ended"?t.jsx("span",{className:"cia-badge",children:wt(i,"ended")}):null]}),s.length>1&&t.jsx("div",{className:"cia-row",style:{justifyContent:"center",paddingBottom:10},children:t.jsxs("div",{style:{position:"relative"},children:[t.jsx("select",{className:"input cia-mono",style:{appearance:"none",fontSize:12,height:30,paddingLeft:12,paddingRight:28,borderRadius:999,cursor:"pointer"},value:i,onChange:re=>r(re.target.value),disabled:!B,children:s.map(re=>t.jsx("option",{value:re.code,children:re.label||re.code.toUpperCase()},re.code))}),t.jsx(Ut,{size:14,style:{position:"absolute",right:9,top:"50%",transform:"translateY(-50%)",pointerEvents:"none",color:"var(--cia-text-3)"}})]})}),t.jsx("div",{className:"cia-col",style:{flex:1,minHeight:0,alignItems:"center",justifyContent:"center",gap:16,overflowY:"auto"},children:B&&j?t.jsxs("div",{className:"cia-col",style:{width:"100%",maxWidth:280,gap:12,padding:"8px 2px"},children:[t.jsx("span",{className:"cia-eyebrow",style:{textAlign:"center"},children:wt(i,"beforeStart")}),b.map(re=>t.jsxs("div",{children:[t.jsx("label",{className:"cia-text-3",style:{fontSize:12,display:"block",marginBottom:4},children:re.description||re.name}),t.jsx("input",{className:"input",style:{width:"100%"},value:g[re.name]??"",onChange:ke=>v(H=>({...H,[re.name]:ke.target.value})),onKeyDown:ke=>ke.key==="Enter"&&w&&(ke.preventDefault(),k(!0)),placeholder:re.description||re.name})]},re.name)),t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta",style:{width:"100%",justifyContent:"center",background:o,borderColor:o,color:l},disabled:!w,onClick:()=>k(!0),children:wt(i,"start")})]}):Ee?t.jsxs("div",{style:{width:"100%",alignSelf:"stretch"},children:[t.jsx(vo,{messages:z,agentName:e.agentName||"Agente",userLabel:wt(i,"you"),typing:L,typingLabel:`${e.agentName||""} ${wt(i,"thinking")}`.trim(),showTimestamps:!1,dense:!0,emptyText:G?wt(i,"connecting"):""}),t.jsx("div",{ref:D})]}):t.jsxs(t.Fragment,{children:[t.jsx(Qy,{active:te,speaking:P,color:o}),t.jsx("p",{className:"cia-text-3",style:{fontSize:13,textAlign:"center",minHeight:20,margin:0},children:te?P?wt(i,"speaking"):wt(i,"listening"):G?wt(i,"connecting"):N==="ended"?wt(i,"ended"):me?wt
947(i,"talk"):e.agentName||""})]})}),t.jsxs("div",{style:{paddingTop:12,marginTop:4,borderTop:"1px solid var(--cia-border)"},children:[N==="error"&&_&&t.jsx("div",{className:"cia-badge cia-badge-bad",role:"alert",style:{height:"auto",padding:"8px 10px",fontSize:12,marginBottom:8,whiteSpace:"normal",textAlign:"left"},children:zj(i,_)}),me&&B&&!j&&N!=="ended"&&t.jsxs("button",{type:"button",onClick:W,disabled:G,className:"cia-btn cia-btn-cta cia-btn-lg",style:{width:"100%",justifyContent:"center",background:o,borderColor:o,color:l},children:[t.jsx(rn,{size:15})," ",wt(i,"talk")]}),me&&G&&t.jsxs("button",{type:"button",disabled:!0,className:"cia-btn cia-btn-cta cia-btn-lg",style:{width:"100%",justifyContent:"center"},children:[t.jsx(je,{size:15,style:{animation:"spin 1s linear infinite"}})," ",wt(i,"connecting")]}),me&&te&&t.jsxs("div",{className:"cia-row cia-gap-2",style:{justifyContent:"center"},children:[t.jsxs("button",{type:"button",onClick:X,className:"cia-btn cia-btn-lg",style:{flex:1,background:"var(--cia-bad-500)",color:"#fff",borderColor:"var(--cia-bad-500)",justifyContent:"center"},children:[t.jsx(Ts,{size:15})," ",wt(i,"end")]}),t.jsx("button",{type:"button",onClick:U,disabled:!!E,className:"cia-btn cia-btn-outline cia-btn-lg cia-btn-icon",style:{width:42},title:R?wt(i,"unmute"):wt(i,"mute"),children:R?t.jsx(Ap,{size:15}):t.jsx(Ta,{size:15})})]}),Ee&&N!=="ended"&&!j&&t.jsxs("div",{className:"cia-col cia-gap-2",children:[te&&t.jsxs("button",{type:"button",onClick:X,className:"cia-btn cia-btn-outline cia-btn-sm",style:{width:"100%",justifyContent:"center",color:"var(--cia-bad-500)",borderColor:"var(--cia-border-2)"},children:[t.jsx(Ts,{size:14})," ",wt(i,"end")]}),t.jsxs("div",{className:"cia-row cia-gap-2",children:[t.jsx("input",{className:"input",style:{flex:1},placeholder:wt(i,"placeholder"),value:x,onChange:re=>h(re.target.value),onKeyDown:re=>re.key==="Enter"&&!re.shiftKey&&(re.preventDefault(),F())}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta cia-btn-icon",style:{width:42,he
947ight:42,background:o,borderColor:o,color:l},onClick:F,disabled:!x.trim()||G,"aria-label":wt(i,"chat"),children:G?t.jsx(je,{size:15,style:{animation:"spin 1s linear infinite"}}):t.jsx(Gr,{size:15})})]})]}),N==="ended"&&t.jsx("button",{type:"button",className:"cia-btn cia-btn-outline",style:{width:"100%",justifyContent:"center"},onClick:ie,children:wt(i,"restart")})]})]})}function LT({variables:e,values:a,onChange:n}){return e.length===0?null:t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:8},children:e.map(s=>t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-4)"},children:`{{${s.name}}}`}),t.jsx("input",{className:"input",value:a[s.name]??"",placeholder:s.description??s.defaultValue??"",onChange:i=>n(s.name,i.target.value),style:{height:32,fontSize:12.5}})]},s.name))})}function FT({data:e}){const{t:a}=M("copilot"),n=e.variables??[],[s,i]=m.useState(e.phoneNumber??""),[r,o]=m.useState(()=>Object.fromEntries(n.map(b=>[b.name,b.defaultValue??""]))),[l,c]=m.useState("idle"),[d,u]=m.useState(""),p=/^\+[1-9]\d{6,15}$/.test(s.trim()),f=n.find(b=>!b.defaultValue&&!(r[b.name]??"").trim()),x=p?f?a("cards.outbound.needVars"):null:a("cards.outbound.needPhone");async function h(){if(!(x||l==="calling")){c("calling"),u("");try{const b=Object.fromEntries(Object.entries(r).filter(([,g])=>String(g??"").trim()!==""));await T.post("/calls/originate",{agentId:e.agentId,destinationNumber:s.trim(),...Object.keys(b).length>0?{variables:b}:{}}),c("done")}catch(b){u(b?.response?.data?.message??a("cards.outbound.error")),c("error")}}}return t.jsx(Ha,{icon:t.jsx(ka,{size:14}),title:a("cards.outbound.title"),subtitle:String(e.agentName??""),children:l==="done"?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"var(--cia-ok-500)",fontSize:13,fontWeight:600},children:[t.jsx(Nt,{size:16,"aria-hidden":"true"})," ",a("cards.outbound.calling",{phone:s})]}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,maxWidth:260},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-4)"},children:a("cards.outbound.phoneLabel")}),t.jsx("input",{className:"input",type:"tel",value:s,placeholder:"+573001234567",onChange:b=>i(b.target.value),style:{height:34,fontSize:13}})]}),t.jsx(LT,{variables:n,values:r,onChange:(b,g)=>o(v=>({...v,[b]:g}))}),l==="error"&&t.jsx("span",{style:{fontSize:12,color:"var(--cia-bad-500)"},role:"alert",children:d}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsxs(Jn,{variant:"primary",disabled:!!x||l==="calling",onClick:h,children:[t.jsx(ka,{size:12}),l==="calling"?a("cards.outbound.starting"):x??a("cards.outbound.call")]}),t.jsx("span",{style:{fontSize:11,color:"var(--cia-text-4)"},children:a("cards.outbound.hint")})]})]})})}function OT({data:e}){const{t:a,i18n:n}=M("copilot"),s=String(e.agentId??""),i=e.variables??[],r=m.useMemo(()=>({agentName:String(e.agentName??""),voiceEnabled:!0,chatEnabled:!1,languages:[{code:n.language?.startsWith("en")?"en":"es"}],variables:i.map(l=>({name:l.name,required:!l.defaultValue,description:l.description??void 0}))}),[e.agentName,i,n.language]);async function o(l,c){const{data:d}=await T.post("/web-agent/session",{agentId:s,mode:"voice",...c&&Object.keys(c).length>0?{variables:c}:{}});return{token:d.token,url:d.url,sessionId:d.sessionId,maxSessionSeconds:d.maxSessionSeconds}}return t.jsx(Ha,{icon:t.jsx(Ta,{size:14}),title:a("cards.webTest.title"),subtitle:String(e.agentName??""),right:t.jsx(Pa,{tone:"muted",label:a("cards.webTest.inChat")}),children:t.jsx("div",{style:{minHeight:120},children:t.jsx(IT,{uiConfig:r,connect:o,embedded:!0})})})}function $T(e){return e==="confirmed"?"ok":e==="pending"||e==="unknown"?"warn":e==="failed"?"bad":"muted"}function qT({data:e}){const{t:a}=M("copilot"),n=dt(),s=ko();if(e.disponible===!1)return t.jsx(Ha,{icon:t.jsx(Zn,{size:14}),title:a("cards.appointments.title"),children:t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:String(e.motivo??a("cards.appointments.unavailable"))})});const i=e.citas??[],r=Number(e.total??i.length),o=l=>{if(!l.cuando)return a("cards.appointments.noDate");
947try{return new Date(l.cuando).toLocaleString(Te(),{dateStyle:"medium",timeStyle:"short",...l.zona?{timeZone:l.zona}:{}})}catch{return new Date(l.cuando).toLocaleString(Te())}};return t.jsxs(Ha,{icon:t.jsx(Zn,{size:14}),title:a("cards.appointments.title"),subtitle:a("cards.appointments.subtitle",{shown:i.length,total:r}),children:[i.length===0?t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:a("cards.appointments.empty")}):t.jsx("div",{style:{display:"flex",flexDirection:"column"},children:i.map((l,c)=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",padding:"8px 0",borderTop:c===0?"none":"1px solid var(--cia-border)"},children:[t.jsxs("div",{style:{flex:1,minWidth:180},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600,color:"var(--cia-text)"},children:o(l)}),t.jsx(Pa,{tone:$T(l.estado),label:a(`cards.appointments.status.${l.estado}`,{defaultValue:l.estado})}),!!l.vecesMovida&&t.jsx(Pa,{tone:"muted",label:a("cards.appointments.moved",{count:l.vecesMovida})})]}),t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:2},children:[l.conQuien,l.telefono,l.sinCorreoReal?a("cards.appointments.noEmail"):l.correo,l.calendario,l.duracionMinutos?a("cards.appointments.minutes",{count:l.duracionMinutos}):null].filter(Boolean).join(" · ")})]}),t.jsxs("div",{style:{display:"flex",gap:6,flex:"none"},children:[l.deLaLlamada&&t.jsxs(Jn,{onClick:()=>n({to:`/history/${l.deLaLlamada}`}),children:[t.jsx(qs,{size:12})," ",a("cards.appointments.call")]}),s&&l.deLaLlamada&&t.jsx(Jn,{onClick:()=>s(a("cards.appointments.askCall",{id:l.deLaLlamada})),children:a("cards.appointments.whatHappened")})]})]},l.id))}),e.hayMas===!0&&t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:6},children:a("cards.appointments.more")})]})}function BT({card:e}){switch(e.kind){case"agent_list":return t.jsx(yT,{data:e.data});case"recent_calls":return t.jsx(jT,{data:e.data});case"call_detail":return t.jsx(wT,{data:e.data});case"campaign_insights":return t.jsx(kT,{data:e.data});case"billing_status":return t.jsx(ST,{data:e.data});case"analytics_report":return t.jsx(NT,{data:e.data});case"campaign_leads":return t.jsx(TT,{data:e.data});case"sim_run":return t.jsx(DT,{data:e.data});case"outbound_call":return t.jsx(FT,{data:e.data});case"web_test":return t.jsx(OT,{data:e.data});case"appointment_list":return t.jsx(qT,{data:e.data});default:return null}}function g0(e){if(e.status!=="executed"||e.toolName!=="create_knowledge_base_from_site")return null;const a=e.resultRef;if(!a||typeof a!="object")return null;const n=a.kbId;return typeof n=="string"&&n?n:null}const ZB=[{id:"listAgents",icon:"bot",permission:"agents.view",category:"agentes"},{id:"analyticsReport",icon:"chart",permission:"reports.view",category:"analitica"},{id:"webTest",icon:"mic",permission:"playground.use",category:"agentes"},{id:"realCall",icon:"phone",permission:"calls.operate",category:"agentes"},{id:"recentCalls",icon:"history",permission:"calls.view",category:"analitica"},{id:"campaigns",icon:"megaphone",permission:"campaigns.view",category:"campanas"},{id:"campaignLeads",icon:"users",permission:"campaigns.view",category:"campanas"},{id:"createCampaign",icon:"plus",permission:"campaigns.manage",category:"campanas"},{id:"auditAgent",icon:"shield",permission:"agents.view",category:"agentes"},{id:"simTests",icon:"flask",permission:"agents.view",category:"agentes"},{id:"billing",icon:"wallet",permission:"billing.view",category:"cuenta"}],WT=[{id:"audit",icon:"shield",permission:"agents.view",category:"agentes"},{id:"improve",icon:"wand",permission:"agents.manage",category:"agentes"},{id:"webTest",icon:"mic",permission:"playground.use",category:"agentes"},{id:"lastCall",icon:"history",permission:"calls.view",category:"analitica"},{id:"simTests",icon:"flask",permission:"agents.view",category:"agentes"}];function UT(e,a,n=6){return e.filter(s=>lt(a,s.permission)).slice(0,n)}function VT(e,a,n=6){return e.filter(s=>lt(a,s.permission)).slice(n)}const KT={bot:Ft,shield:ho,mic:Ta,phone:ka,history:wc,megaphone:kc,wallet:_c,wand:zs,chart:us,users:Bs,plus:Fe,flask:Yp};function HT({actions:e,i18nPrefix:a="welcome",compact:n=!1}){const{t:s}=M("copilot"),i=ko(),r=Pe(f=>f.user),o=(r?.name??"").trim().split(/\s+/)[0]||"",l=n?4:6,c=UT(e,r,l),d=n?[]:VT(e,r,l),[u,p]=m.useState(!1);return t.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:n?14:20,padding:n?"20px 16px":"40px 24px",textAlign:"center",overflowY:"auto"},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:n?44:60,height:n?44:60,borderRadius:n?14:18,background:"linear-gradient(135deg, color-mix(in oklab, var(--cia-brand-500) 16%, transparent), color-mix(in oklab, var(--cia-cta-500) 14%, transparent))",color:"var(--cia-brand-500)",boxShadow:"0 2px 12px color-mix(in oklab, var(--cia-brand-500) 18%, transparent)"},"aria-hidden":"true",children:t.jsx(_t,{size:n?20:28,strokeWidth:1.5})}),t.jsxs("div",{children:[t.jsx("h2",{style:{margin:"0 0 6px",fontSize:n?16:"clamp(18px, 2.4vw, 24px)",fontWeight:700,letterSpacing:"-0.02em",color:"var(--cia-text)"},children:o?s(`${a}.titleNamed`,{name:o}):s(`${a}.title`)}),t.jsx("p",{style:{margin:0,fontSize:n?12.5:13.5,color:"var(--cia-text-3)",lineHeight:1.6,maxWidth:420},children:s(`${a}.subtitle`)})]}),c.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"cia-mono",style:{fontSize:10,textTransform:"uppercase",letterSpacing:"0.1em",color:"var(--cia-text-4)"},children:s(`${a}.eyebrow`)}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:n?"repeat(auto-fit, minmax(170px, 1fr))":"repeat(auto-fit, minmax(210px, 1fr))",gap:10,width:"100%",maxWidth:n?420:560},children:c.map(f=>t.jsx(nx,{action:f,compact:n,i18nPrefix:a,onAsk:i},f.id))}),d.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:()=>p(f=>!f),"aria-expanded":u,style:{display:"inline-flex",alignItems:"center",gap:5,padding:"6px 12px",minHeight:32,borderRadius:999,border:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)",color:"var(--cia-text-3)",fontSize:11.5,cursor:"pointer"},children:[u?t.jsx(Rn,{size:13}):t.jsx(Ut,{size:13}),u?s("welcome.lessActions"):s("welcome.moreActions",{count:d.length})]}),u&&t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:10,width:"100%",maxWidth:560},children:d.map(f=>t.jsx(nx,{action:f,compact:n,i18nPrefix:a,onAsk:i},f.id))})]}),t.jsx("p",{style:{margin:0,fontSize:11.5,color:"var(--cia-text-4)"},children:s(`${a}.hint`)})]})]})}function nx({action:e,compact:a,i18nPrefix:n,onAsk:s}){const{t:i}=M("copilot"),r=KT[e.icon];return t.jsxs("button",{type:"button",onClick:()=>s?.(i(`${n}.actions.${e.id}.prompt`)),style:{display:"flex",flexDirection:"column",alignItems:"flex-start",ga
947p:6,padding:a?"10px 12px":"14px 14px",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-elev)",cursor:"pointer",textAlign:"left",transition:"transform var(--cia-dur-fast) ease, box-shadow var(--cia-dur-fast) ease, border-color var(--cia-dur-fast) ease"},onMouseEnter:o=>{const l=o.currentTarget;l.style.transform="translateY(-1px)",l.style.borderColor="color-mix(in oklab, var(--cia-brand-500) 40%, transparent)",l.style.boxShadow="0 4px 14px color-mix(in oklab, var(--cia-brand-500) 12%, transparent)"},onMouseLeave:o=>{const l=o.currentTarget;l.style.transform="none",l.style.borderColor="var(--cia-border)",l.style.boxShadow="none"},children:[t.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:9,background:"color-mix(in oklab, var(--cia-cta-500) 12%, transparent)",color:"var(--cia-cta-500)"},"aria-hidden":"true",children:t.jsx(r,{size:15,strokeWidth:1.8})}),t.jsx("span",{style:{fontSize:13,fontWeight:600,color:"var(--cia-text)",letterSpacing:"var(--cia-tracking-tight)"},children:i(`${n}.actions.${e.id}.title`)}),!a&&t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.45},children:i(`${n}.actions.${e.id}.desc`)})]})}const an={threads:()=>["copilot","threads"],thread:e=>["copilot","thread",e],actions:e=>["copilot","actions",e]};function YB(){return se({queryKey:an.threads(),queryFn:async()=>{const{data:e}=await T.get("/copilot/threads");return e},staleTime:6e4})}function XB(e){return se({queryKey:an.thread(e??""),queryFn:async()=>{const{data:a}=await T.get(`/copilot/threads/${e}`);return a},enabled:!!e,staleTime:1e4})}function JB(e){return se({queryKey:an.actions(e??""),queryFn:async()=>{const{data:a}=await T.get(`/copilot/threads/${e}/actions`);return a},enabled:!!e,staleTime:5e3})}function e9(){const e=xe();return oe({mutationFn:async a=>{const{data:n}=await T.post("/copilot/threads",a??{});return n},onSuccess:()=>{e.invalidateQueries({queryKey:an.threads()})}})}function t9(e){const a=xe();return oe({mutationFn:async n=>{const{data:s}=await T.post(`/copilot/threads/${e}/messages`,{message:n},{timeout:6e4});return s},onSuccess:n=>{e&&(a.invalidateQueries({queryKey:an.thread(e)}),a.invalidateQueries({queryKey:an.actions(e)})),a.invalidateQueries({queryKey:an.threads()})}})}function QT(e){const a=xe();return oe({mutationFn:async({actionId:n,overridePayload:s})=>{const i=s?{overridePayload:s}:void 0,{data:r}=await T.post(`/copilot/actions/${n}/confirm`,i);return r},onSuccess:()=>{e&&(a.invalidateQueries({queryKey:an.actions(e)}),a.invalidateQueries({queryKey:an.thread(e)})),a.invalidateQueries({queryKey:["agents"]}),a.invalidateQueries({queryKey:["campaigns"]})}})}function GT(e){const a=xe();return oe({mutationFn:async n=>{const{data:s}=await T.post(`/copilot/actions/${n}/reject`);return s},onSuccess:()=>{e&&(a.invalidateQueries({queryKey:an.actions(e)}),a.invalidateQueries({queryKey:an.thread(e)}))}})}function ZT(e){return[{label:e("builder.quickActions.audit.label"),instruction:e("builder.quickActions.audit.instruction")},{label:e("builder.quickActions.buildFull.label"),instruction:e("builder.quickActions.buildFull.instruction")},{label:e("builder.quickActions.optimizePrompt.label"),instruction:e("builder.quickActions.optimizePrompt.instruction")},{label:e("builder.quickActions.chooseVoice.label"),instruction:e("builder.quickActions.chooseVoice.instruction")},{label:e("builder.quickActions.configureAnalytics.label"),instruction:e("builder.quickActions.configureAnalytics.instruction")}]}const YT={systemPrompt:t.jsx(zs,{size:13}),"tts.voiceId":t.jsx(Cr,{size:13}),"tts.provider":t.jsx(Cr,{size:13}),"tts.model":t.jsx(Cr,{size:13}),"llm.model":t.jsx(Sr,{size:13}),"llm.temperature":t.jsx(Sr,{size:13}),"llm.provider":t.jsx(Sr,{size:13}),analytics:t.jsx(us,{size:13})};function b0(e){return YT[e]??t.jsx(_t,{size:13})}let XT=0;const Xo=()=>`abm${++XT}`,sx=3;function y0({agentId:e,agentName:a,draft:n,onApplyPatch:s,onboardingMode:i,variant:r="drawer",open:o=!0,onClose:l=()=>{},kickoffMessage:c,autoApply:d,onPatchApplied:u,quickActions:p,auditKick:f,onPromptSuggestions:x,onFieldSuggestion:h}){const{can:b}=tt(),g=b("agents.manage"),{t:v}=M("agentsBuilder"),[y,k]=m.useState("chat"),[w,j]=m.useState(""),[C,N]=m.useState([]),[S,_]=m.useState(null),[R,A]=m.useState([]),[E,I]=m.useState(null),[P,O]=m.useState(null),[K,W]=m.useState(!1),[V,U]=m.useState(),[X,ie]=m.useState(null),[de,$]=m.useState(null),[z,D]=m.useState({}),[F,G]=m.useState(null),te=QT(S),B=GT(S),ne=dt(),{t:me}=M("copilot"),Ee=m.useRef(null),{send:L,abort:re}=m0(e,S),ke=xT(e),H=fT(e),fe=r==="wizard"?"interview":void 0;m.useEffect(()=>{y==="chat"&&Ee.current?.scrollIntoView({behavior:"smooth"})},[C,E,y]),m.useEffect(()=>{o||re()},[o,re]);const Z=R.filter($e=>!$e.applied).length,ae=m.useCallback(async($e,ce)=>{if(!$e.trim()||K)return;ce?.silent||j(""),$(null);const Se={id:Xo(),role:"user",content:$e};ce?.silent||N(ue=>[...ue,Se]),W(!0),I(""),O(null);const De=Xo();await L($e,{onToken:ue=>{I(ue)},onToolCall:ue=>{O(ue)},onCard:ue=>{N(Ze=>[...Ze,{id:ue.messageId||Xo(),role:"assistant",content:"",card:{kind:ue.kind,data:ue.data}}])},onAction:ue=>{D(Ze=>({...Ze,[ue.id]:ue})),N(Ze=>Ze.some(ze=>ze.actionId===ue.id)?Ze:[...Ze,{id:`act-${ue.id}`,role:"assistant",content:"",actionId:ue.id}])},onDraftPatch:ue=>{if(x&&ue.promptEdits?.suggestions?.length){x(ue.promptEdits);return}if(h&&!ue.promptEdits?.suggestions?.length){h(ue);return}const Ze=Xo(),ze=r==="wizard"&&!!d&&!ue.sensitive;A(Ot=>[...Ot,{id:Ze,toolName:ue.toolName,patch:ue.patch,diff:ue.diff,rationale:ue.rationale,previewText:ue.previewText,i18n:ue.i18n??null,applied:ze,sensitive:ue.sensitive??!1}]),ze?(s(ue.patch),u?.(ue.patch)):setTimeout(()=>k("changes"),400)},onClarify:ue=>{N(Ze=>Ze.some(ze=>ze.id===De)?Ze:[...Ze,{id:De,role:"assistant",content:ue.question}]),$(ue.options&&ue.options.length>0?ue.options:null)},onDone:(ue,Ze)=>{if(U(ue),Ze){_(Ze);try{e&&sessionStorage.setItem(`copilot.builder.${e}`,Ze)}catch{}}N(ze=>{if(ze.some(fa=>fa.id===De))return ze;const Ot=ut.current??"";return Ot?[...ze,{id:De,role:"assistant",content:Ot}]:ze}),I(null),O(null),W(!1)},onError:(ue,Ze)=>{Ze&&ut.current?N(ze=>[...ze,{id:De,role:"assistant",content:ut.current??""}]):(J({tone:"bad",title:v("builder.toastErrorTitle"),desc:ue}),ce?.silent||N(ze=>ze.filter(Ot=>Ot!==Se))),I(null),O(null),W(!1)}},{mode:fe})},[L,K,r,d,s,u,fe,v]),pe=m.useRef(!1);m.useEffect(()=>{r==="wizard"&&c&&!pe.current&&(pe.current=!0,ae(c,{silent:!0}))},[r,c]);const ye=m.useRef(0);m.useEffect(()=>{r==="drawer"&&o&&e&&f&&f!==ye.current&&!K&&(ye.current=f,k("chat"),ae(v("builder.auditKickoff"),{silent:!0}))},[f,o,e,r]);const qe=m.useRef(!1);m.useEffect(()=>{if(r!=="drawer"||!e||qe.current)return;qe.current=!0;let $e=null;try{$e=sessionStorage.getItem(`copilot.builder.${e}`)}catch{}$e&&(async()=>{try{const{data:ce}=await T.get(`/copilot/threads/${$e}`),Se=ce?.messages??[],De=[];for(const ue of Se)ue.role==="user"&&ue.content?De.push({id:ue.id,role:"user",content:ue.content}):ue.role==="assistant"&&ue.content?De.push({id:ue.id,role:"assistant",content:ue.content}):ue.role==="tool"&&ue.toolResult?.cardKind?De.push({id:ue.id,role:"assistant",content:"",card:{kind:String(ue.toolResult.cardKind),data:ue.toolResult.data??{}}}):ue.role==="tool"&&ue.pendingActionId&&De.push({id:ue.id,role:"assistant",content:"",actionId:String(ue.pen
947dingActionId)});if(De.length>0&&(_($e),N(ue=>ue.length===0?De:ue),De.some(ue=>ue.actionId)))try{const{data:ue}=await T.get(`/copilot/threads/${$e}/actions`),Ze={};for(const ze of ue??[])ze?.id&&(Ze[ze.id]=ze);D(ze=>({...Ze,...ze}))}catch{}}catch{try{sessionStorage.removeItem(`copilot.builder.${e}`)}catch{}}})()},[r,e]);const ut=m.useRef(null);m.useEffect(()=>{ut.current=E},[E]);function bt($e,ce){if(!g)return;const Se=R.find(ue=>ue.id===$e);if(!Se)return;const De=ce!=null&&Se.patch.systemPrompt!==void 0?{...Se.patch,systemPrompt:ce}:Se.patch;s(De),u?.(De),A(ue=>ue.map(Ze=>Ze.id===$e?{...Ze,applied:!0}:Ze)),J({tone:"ok",title:v("common.toastAppliedTitle"),desc:v("builder.toastAppliedDesc")})}function Ge(){if(!g)return;const $e=R.filter(Se=>!Se.applied);if($e.length===0)return;const ce={};for(const Se of $e)Se.patch.systemPrompt!==void 0&&(ce.systemPrompt=Se.patch.systemPrompt),Se.patch.greeting!==void 0&&(ce.greeting=Se.patch.greeting),Se.patch.tts!==void 0&&(ce.tts={...ce.tts,...Se.patch.tts}),Se.patch.llm!==void 0&&(ce.llm={...ce.llm,...Se.patch.llm}),Se.patch.analytics!==void 0&&(ce.analytics={...ce.analytics,...Se.patch.analytics}),Se.patch.advancedBehavior!==void 0&&(ce.advancedBehavior={...ce.advancedBehavior,...Se.patch.advancedBehavior}),Se.patch.dynamicVariables!==void 0&&(ce.dynamicVariables=Se.patch.dynamicVariables),Se.patch.tools!==void 0&&(ce.tools=Se.patch.tools),Se.patch.knowledge!==void 0&&(ce.knowledge=Se.patch.knowledge);s(ce),u?.(ce),A(Se=>Se.map(De=>({...De,applied:!0}))),J({tone:"ok",title:v("builder.toastApplyAllTitle",{count:$e.length}),desc:v("builder.toastAppliedDesc")})}function yt($e){A(ce=>ce.filter(Se=>Se.id!==$e))}function ve($e){if(!g){J({tone:"warn",title:me("builderActions.kbNoPermTitle"),desc:me("builderActions.kbNoPermDesc")});return}const ce=n.knowledge?.kbIds??[];if(ce.includes($e))return;const Se=[...ce,$e].slice(0,sx);if(!Se.includes($e)){J({tone:"warn",title:me("builderActions.kbFullTitle",{max:sx}),desc:me("builderActions.kbFullDesc")});return}const De={knowledge:{...n.knowledge??{},kbIds:Se}};s(De),u?.(De),J({tone:"ok",title:me("builderActions.kbAttachedTitle"),desc:me("builderActions.kbAttachedDesc")})}function Ke($e){G($e),te.mutate({actionId:$e},{onSuccess:ce=>{D(De=>({...De,[ce.id]:ce}));const Se=g0(ce);Se&&ve(Se)},onError:ce=>{J({tone:"bad",title:v("builder.toastErrorTitle"),desc:ce?.message??""})},onSettled:()=>G(null)})}function He($e){B.mutate($e,{onSuccess:ce=>D(Se=>({...Se,[ce.id]:ce})),onError:ce=>{J({tone:"bad",title:v("builder.toastErrorTitle"),desc:ce?.message??""})}})}function Xe($e){ne({to:"/knowledge",search:{kb:$e}})}function Et(){A([])}function Yt($e){g&&(s({systemPrompt:$e.systemPrompt}),J({tone:"ok",title:v("versions.toastRestoreTitle",{version:$e.version}),desc:v("versions.toastRestoreDesc")}),l())}function It($e){ie($e),ke.mutate({rating:$e,before:n.systemPrompt??"",messageId:V})}function Pn($e){ke.mutate({rating:X??"down",comment:$e,before:n.systemPrompt??"",messageId:V})}const St=!!(x||h),sa=m.useMemo(()=>St?[{id:"chat",label:v("tabs.chat")},{id:"versions",label:v("tabs.versions")}]:[{id:"chat",label:v("tabs.chat")},{id:"changes",label:Z>0?v("tabs.changesWithCount",{count:Z}):R.length>0?v("tabs.changesPending"):v("tabs.changes")},{id:"versions",label:v("tabs.versions")}],[St,Z,R.length,v]);m.useEffect(()=>{St&&y==="changes"&&k("chat")},[St,y]);const ma=t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[t.jsx("div",{style:{padding:"0 20px",borderBottom:"1px solid var(--cia-border)",flex:"none"},children:t.jsx(Fi,{items:sa,active:y,onChange:k})}),y==="chat"&&t.jsx(JT,{messages:C,streamingText:E,activeToolCall:P,isStreaming:K,input:w,onInput:j,onSend:ae,onJumpToChanges:St?void 0:()=>k("changes"),patchCount:St?0:R.length,messagesEndRef:Ee,onboardingMode:i,quickActions:p,clarifyOptions:de,onPickClarify:$e=>ae($e),actions:z,executingActionId:F,onConfirmAction:Ke,onRejectAction:He,onOpenKb:Xe}),y==="changes"&&t.jsx(r4,{patches:R,currentPrompt:n.systemPrompt??"",onApply:bt,onDiscard:yt,onJumpToChat:()=>k("chat")}),y==="versions"&&t.jsx(p4,{versions:H.data,isLoading:H.isLoading,onRestore:Yt}),y==="changes"&&R.length>0&&t.jsx("div",{style:{borderTop:"1px solid var(--cia-border)",padding:"12px 20px",display:"flex",alignItems:"center",gap:8,background:"var(--cia-bg-elev)",flex:"none"},children:t.jsx(u4,{pendingCount:Z,onApplyAll:Ge,onDiscardAll:Et,thumbValue:X,onThumbChange:It,onThumbComment:Pn})})]});return r==="wizard"?ma:t.jsx(Rp,{open:o,onClose:l,title:v("builder.title"),eyebrow:a?v("common.eyebrow",{name:a}):v("common.eyebrowGeneric"),width:560,children:ma})}function JT({messages:e,streamingText:a,activeToolCall:n,isStreaming:s,input:i,onInput:r,onSend:o,onJumpToChanges:l,patchCount:c,messagesEndRef:d,onboardingMode:u,quickActions:p,clarifyOptions:f,onPickClarify:x,actions:h,executingActionId:b,onConfirmAction:g,onRejectAction:v,onOpenKb:y}){const{t:k}=M("agentsBuilder"),w=p??ZT(k);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",flex:1,overflow:"hidden"},children:[w.length>0&&t.jsx("div",{style:{padding:"14px 20px 10px",borderBottom:"1px solid var(--cia-border)",flex:"none"},children:t.jsx(Gl,{actions:w,onPick:o,disabled:s})}),t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"16px 20px",display:"flex",flexDirection:"column",gap:10},children:[e.length===0&&!s&&t.jsx(t4,{onboardingMode:u,onAsk:o}),e.map(j=>{if(j.actionId){const C=h?.[j.actionId];return C?t.jsx(e4,{action:C,isExecuting:b===C.id,onConfirm:g,onReject:v,onOpenKb:y},j.id):null}return j.card?t.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:t.jsx(BT,{card:j.card})},j.id):t.jsx(a4,{message:j,onJumpToChanges:l},j.id)}),s&&t.jsx(n4,{text:a??"",toolCall:n}),f&&f.length>0&&t.jsx("div",{style:{paddingLeft:2},children:t.jsx(Gl,{actions:f.map(j=>({label:j,instruction:j})),onPick:j=>x?.(j),disabled:s})}),c>0&&!s&&t.jsxs("button",{type:"button",onClick:l,style:{alignSelf:"center",display:"inline-flex",alignItems:"center",gap:6,padding:"6px 14px",borderRadius:"var(--cia-r-pill)",border:"1px solid color-mix(in oklab, var(--cia-cta-500) 35%, transparent)",background:"color-mix(in oklab, var(--cia-cta-500) 8%, transparent)",color:"var(--cia-cta-500)",fontSize:12,fontWeight:500,fontFamily:"var(--cia-font-sans)",cursor:"pointer",marginTop:4},children:[t.jsx(Nt,{size:13,"aria-hidden":"true"}),k("builder.proposedBadge",{count:c}
947),t.jsx(ca,{size:12,"aria-hidden":"true"})]}),t.jsx("div",{ref:d})]}),t.jsx("div",{style:{padding:"10px 20px 14px",borderTop:"1px solid var(--cia-border)",flex:"none"},children:t.jsx(tv,{value:i,onChange:r,onSubmit:o,loading:s,placeholder:k(u?"builder.composerPlaceholderOnboarding":"builder.composerPlaceholder")})})]})}function e4({action:e,isExecuting:a,onConfirm:n,onReject:s,onOpenKb:i}){const{t:r}=M("copilot"),o=g0(e);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx(t_,{action:e,onConfirm:n,onReject:s,isExecuting:a}),o&&i&&t.jsxs("button",{type:"button",onClick:()=>i(o),style:{alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:"var(--cia-r-pill)",border:"1px solid color-mix(in oklab, var(--cia-brand-500) 35%, transparent)",background:"color-mix(in oklab, var(--cia-brand-500) 8%, transparent)",color:"var(--cia-brand-500)",fontSize:12,fontWeight:500,fontFamily:"var(--cia-font-sans)",cursor:"pointer"},children:[t.jsx(ua,{size:13,"aria-hidden":"true"}),r("builderActions.openKb"),t.jsx(ca,{size:12,"aria-hidden":"true"})]})]})}function t4({onboardingMode:e,onAsk:a}){const{t:n}=M("agentsBuilder"),s=e?"var(--cia-cta-500)":"var(--cia-brand-500)";return!e&&a?t.jsx(f0.Provider,{value:a,children:t.jsx(HT,{actions:WT,i18nPrefix:"builderWelcome",compact:!0})}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flex:1,gap:14,padding:"32px 8px",color:"var(--cia-text-3)",textAlign:"center"},children:[t.jsx("div",{style:{width:52,height:52,borderRadius:14,background:`color-mix(in oklab, ${s} 10%, transparent)`,border:`1px solid color-mix(in oklab, ${s} 20%, transparent)`,display:"flex",alignItems:"center",justifyContent:"center",color:s},children:t.jsx(_t,{size:22,"aria-hidden":"true"})}),t.jsxs("div",{children:[t.jsx("p",{style:{margin:0,fontSize:14,fontWeight:600,color:"var(--cia-text)",letterSpacing:"var(--cia-tracking-tight)"},children:n(e?"builder.empty.titleOnboarding":"builder.empty.title")}),t.jsx("p",{style:{margin:"5px 0 0",fontSize:12.5,lineHeight:1.55},children:e?t.jsxs(t.Fragment,{children:[n("builder.empty.descOnboardingLine1"),t.jsx("br",{}),n("builder.empty.descOnboardingLine2")]}):t.jsxs(t.Fragment,{children:[n("builder.empty.descLine1"),t.jsx("br",{}),n("builder.empty.descLine2")]})})]}),t.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center",marginTop:4},children:[{icon:t.jsx(zs,{size:11}),label:n("builder.empty.pillPrompt")},{icon:t.jsx(Cr,{size:11}),label:n("builder.empty.pillVoice")},{icon:t.jsx(Sr,{size:11}),label:n("builder.empty.pillModel")},{icon:t.jsx(us,{size:11}),label:n("builder.empty.pillAnalytics")}].map(({icon:i,label:r})=>t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 9px",borderRadius:"var(--cia-r-pill)",background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",fontSize:11,fontFamily:"var(--cia-font-sans)",color:"var(--cia-text-3)"},children:[i,r]},r))})]})}function a4({message:e}){const{t:a}=M("agentsBuilder"),n=e.role==="user";return t.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:n?"flex-end":"flex-start",gap:6},children:t.jsx("div",{style:{maxWidth:"85%",padding:"9px 13px",borderRadius:n?"var(--cia-r-lg) var(--cia-r-lg) var(--cia-r-sm) var(--cia-r-lg)":"var(--cia-r-lg) var(--cia-r-lg) var(--cia-r-lg) var(--cia-r-sm)",background:n?"var(--cia-brand-500)":"var(--cia-bg-soft)",border:n?"none":"1px solid var(--cia-border)",color:n?"#fff":"var(--cia-text)",fontSize:13.5,lineHeight:1.55,wordBreak:"break-word"},role:n?void 0:"article","aria-label":a(n?"common.ariaUserMessage":"common.ariaAssistantMessage"),children:n?t.jsx("span",{style:{fontFamily:"var(--cia-font-sans)",letterSpacing:"var(--cia-tracking-tight)"},children:e.content}):t.jsx(Mp,{content:e.content})})})}function n4({text:e,toolCall:a}){const{t:n}=M("agentsBuilder");return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},"aria-live":"polite","aria-label":n("builder.ariaAssistantResponding"),children:[a&&t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",borderRadius:"var(--cia-r-pill)",border:"1px solid color-mix(in oklab, var(--cia-brand-500) 25%, transparent)",background:"color-mix(in oklab, var(--cia-brand-500) 7%, transparent)",color:"var(--cia-brand-500)",fontSize:11.5,fontFamily:"var(--cia-font-mono)",letterSpacing:"var(--cia-tracking-mono)"},children:[t.jsx(je,{size:11,style:{animation:"spin 1s linear infinite"},"aria-hidden":"true"}),i4(a,n)]}),e?t.jsxs("div",{style:{maxWidth:"85%",padding:"9px 13px",borderRadius:"var(--cia-r-lg) var(--cia-r-lg) var(--cia-r-lg) var(--cia-r-sm)",background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",color:"var(--cia-text)",fontSize:13.5,lineHeight:1.55},children:[t.jsx(Mp,{content:e}),t.jsx("span",{style:{display:"inline-block",width:2,height:14,background:"var(--cia-brand-500)",borderRadius:1,marginLeft:2,verticalAlign:"text-bottom",animation:"cia-builder-blink 1s step-end infinite"},"aria-hidden":"true"})]}):!a&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",background:"var(--cia-bg-soft)",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border)"},children:[t.jsx(je,{size:14,style:{color:"var(--cia-brand-500)",animation:"spin 1s linear infinite"},"aria-hidden":"true"}),t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:n("common.thinking")})]}),t.jsx("style",{children:`
948        @keyframes spin { to { transform: rotate(360deg); } }
949        @keyframes cia-builder-blink { 50% { opacity: 0; } }
950      `})]})}const s4={list_voices:"toolCall.list_voices",get_agent:"toolCall.get_agent",list_llm_models:"toolCall.list_llm_models",get_call_stats:"toolCall.get_call_stats",suggest_prompt:"toolCall.suggest_prompt",configure_agent_tools:"toolCall.configure_agent_tools"};function i4(e,a){const n=s4[e];return n?a(n):a("toolCall.fallback",{name:e})}function r4({patches:e,currentPrompt:a,onApply:n,onDiscard:s,onJumpToChat:i}){const{t:r}=M("agentsBuilder");return e.length===0?t.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"40px 24px"},children:t.jsx(st,{title:r("changes.emptyTitle"),desc:r("changes.emptyDescBuilder"),action:{label:r("common.goToChat"),onClick:i}})}):t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"16px 20px",display:"flex",flexDirection:"column",gap:12},children:e.map(o=>t.jsx(o4,{patch:o,currentPrompt:a,onApply:n,onDiscard:s},o.id))})}function o4({patch:e,currentPrompt:a,onApply:n,onDiscard:s}){const{t:i}=M("agentsBuilder"),[r,o]=m.useState(!0),[l,c]=m.useState(e.patch.systemPrompt??null),[d,u]=m.useState(!1),p=e.patch.systemPrompt!==void 0&&e.patch.systemPrompt!==a,f=e.diff.filter(h=>h.field!=="systemPrompt"),x=f.length>0;return t.jsxs("div",{style:{borderRadius:"var(--cia-r)",border:e.applied?"1px solid color-mix(in oklab, var(--cia-ok-500) 35%, transparent)":"1px solid var(--cia-border)",background:e.applied?"color-mix(in oklab, var(--cia-ok-500) 4%, transparent)":"var(--cia-bg-soft)",overflow:"hidden",flex:"none"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",background:e.applied?"color-mix(in oklab, var(--cia-ok-500) 7%, transparent)":"var(--cia-bg-elev)",borderBottom:r?"1px solid var(--cia-border)":"none",cursor:"pointer"},role:"button",tabIndex:0,onClick:()=>o(h=>!h),onKeyDown:h=>(h.key==="Enter"||h.key===" ")&&o(b=>!b),"aria-expanded":r,children:[t.jsx("div",{style:{width:28,height:28,borderRadius:"var(--cia-r-sm)",background:e.applied?"color-mix(in oklab, var(--cia-ok-500) 15%, transparent)":"color-mix(in oklab, var(--cia-brand-500) 10%, transparent)",display:"flex",alignItems:"center",justifyContent:"center",color:e.applied?"var(--cia-ok-500)":"var(--cia-brand-500)",flex:"none"},children:e.applied?t.jsx(ct,{size:13}):t.jsx(_t,{size:13})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:600,color:"var(--cia-text)",letterSpacing:"var(--cia-tracking-tight)"},children:sv(e.i18n,e.previewText)||i("changes.cardTitleFallback")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:2,flexWrap:"wrap"},children:[e.diff.slice(0,3).map(h=>t.jsx(l4,{field:h},h.field)),e.diff.length>3&&t.jsx("span",{style:{fontSize:10.5,color:"var(--cia-text-4)",fontFamily:"var(--cia-font-mono)"},children:i("changes.moreFields",{count:e.diff.length-3})})]})]}),e.applied?t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",borderRadius:"var(--cia-r-pill)",background:"color-mix(in oklab, var(--cia-ok-500) 12%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-ok-500) 30%, transparent)",color:"var(--cia-ok-600)",fontSize:11,fontWeight:600,fontFamily:"var(--cia-font-mono)",flex:"none"},children:[t.jsx(Nt,{size:10,"aria-hidden":"true"})," ",i("changes.appliedBadge")]}):t.jsx("div",{style:{flex:"none"},children:r?t.jsx(Rn,{size:15,style:{color:"var(--cia-text-4)"}}):t.jsx(Ut,{size:15,style:{color:"var(--cia-text-4)"}})})]}),r&&t.jsxs("div",{style:{padding:"14px 14px",display:"flex",flexDirection:"column",gap:12},children:[e.rationale&&t.jsxs("div",{style:{padding:"8px 12px",background:"color-mix(in oklab, var(--cia-brand-500) 6%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-brand-500) 15%, transparent)",borderRadius:"var(--cia-r-sm)",fontSize:12,color:"var(--cia-text-2)",lineHeight:1.55},role:"note",children:[t.jsx("span",{style:{fontFamily:"var(--cia-font-mono)",fontSize:9.5,letterSpacing:"var(--cia-tracking-wide)",textTransform:"uppercase",color:"var(--cia-brand-500)",display:"block",marginBottom:3},children:i("common.rationaleLabel")}),e.rationale]}),x&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,borderRadius:"var(--cia-r-sm)",border:"1px solid var(--cia-border)",overflow:"hidden"},children:f.map((h,b)=>t.jsx(d4,{field:h,last:b===f.length-1},h.field))}),p&&t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:8},children:[t.jsx(zs,{size:12,style:{color:"var(--cia-brand-500)"}}),t.jsx("span",{style:{fontSize:11.5,fontWeight:500,color:"var(--cia-text-2)",fontFamily:"var(--cia-font-sans)"},children:i("changes.promptDiffLabel")}),(()=>{const h=c4(a,e.patch.systemPrompt??"");return h?t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,padding:"2px 7px",borderRadius:999,border:"1px solid",borderColor:h.heavy?"color-mix(in oklab, var(--cia-bad-500) 35%, transparent)":"var(--cia-border)",background:h.heavy?"color-mix(in oklab, var(--cia-bad-500) 12%, transparent)":"var(--cia-bg-soft)",color:h.heavy?"var(--cia-bad-500)":"var(--cia-text-3)",marginLeft:"auto"},title:i("changes.promptImpactTitle"),children:i("changes.promptImpact",{lines:h.lines,sections:h.sections})}):null})()]}),t.jsx(av,{before:a,after:e.patch.systemPrompt,onResultChange:c})]}),!e.applied&&e.sensitive&&e.patch.tools!==void 0&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs(le,{tone:"warn",children:[t.jsx("strong",{children:i("changes.sensitiveTitle")}),i("changes.sensitiveBody")]}),t.jsx(mn,{checked:d,onChange:u,label:i("changes.sensitiveAckLabel"),description:i("changes.sensitiveAckDesc")})]}),!e.applied&&t.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",paddingTop:4},children:[t.jsx("button",{type:"button",onClick:()=>s(e.id),style:{height:32,padding:"0 12px",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border-2)",background:"transparent",color:"var(--cia-text-3)",fontFamily:"var(--cia-font-sans)",fontSize:12.5,fontWeight:500,cursor:"pointer",letterSpacing:"var(--cia-tracking-tight)"},onMouseEnter:h=>{h.currentTarget.style.background="var(--cia-bg-elev)",h.currentTarget.style.color="var(--cia-text)"},onMouseLeave:h=>{h.currentTarget.style.background="transparent",h.currentTarget.style.color="var(--cia-text-3)"},children:i("common.discard")}),t.jsxs("button",{type:"button",disabled:e.sensitive&&e.patch.tools!==void 0&&!d,onClick:()=>{n(e.id,p?l:void 0)},style:{height:32,padding:"0 16px",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-cta-600)",background:e.sensitive&&e.patch.tools!==void 0&&!d?"color-mix(in oklab, var(--cia-cta-500) 40%, transparent)":"var(--cia-cta-500)",color:"#fff",fontFamily:"var(--cia-font-sans)",fontSize:12.5,fontWeight:600,cursor:e.sensitive&&e.patch.tools!==void 0&&!d?"not-allowed":"pointer",letterSpacing:"var(--cia-tracking-tight)",display:"inline-flex",alignItems:"center",gap:5,transition:"background var(--cia-dur-fast) ease"},onMouseEnter:h=>{const b=h.currentTarget;b.disabled||(b.style.background="var(--cia-cta-600)")},onMouseLeave:h=>{const b=h.currentTarget;b.disabled||(b.style.background="var(--cia-cta-500)")},"aria-disabled":e.sensitive&&e.patch.tools!==void 0&&!d,children:[t.jsx(Nt,{size:13,"aria-hidden":"true"}),i("changes.applyToEditor")]})]})]})]})}function l4({field:e}){return t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,padding:"1px 7px",borderRadius:"var(--cia-r-pill)",background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",fontSize:10.5,fontFamily:"var(--cia-font-mono)",color:"var(--cia-text-3)",letterSpacing:"var(--cia-tracking-mono)"}
950,children:[b0(e.field),h0(e.field,e.label)]})}function c4(e,a){if(!e||!a)return null;const n=o=>o.split(`
951`).filter(l=>/^\s{0,3}#{1,6}\s+\S/.test(l)).length,s=e.split(`
952`).length-a.split(`
953`).length,i=n(e)-n(a);if(s<=0&&i<=0)return null;const r=(e.length-a.length)/e.length;return{lines:Math.max(0,s),sections:Math.max(0,i),heavy:r>.35||i>=3}}function d4({field:e,last:a}){return t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,padding:"8px 12px",background:"var(--cia-bg-soft)",borderBottom:a?"none":"1px solid var(--cia-border)",flexWrap:"wrap",minHeight:40},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,width:110,flex:"none",minHeight:22,color:"var(--cia-text-3)"},children:[b0(e.field),t.jsx("span",{style:{fontSize:11.5,fontFamily:"var(--cia-font-sans)"},children:h0(e.field,e.label)})]}),t.jsx("div",{style:{...ix("bad",e.field),textDecoration:"line-through"},title:String(Yo(e.before)??""),children:Yo(e.before)||"—"}),t.jsx("span",{style:{color:"var(--cia-text-4)",fontSize:12,flex:"none"},children:"→"}),t.jsx("div",{style:ix("ok",e.field),title:String(Yo(e.after)??""),children:Yo(e.after)||"—"})]})}function ix(e,a){const n=e==="ok";return{flex:"1 1 120px",minWidth:90,fontSize:12,fontFamily:"var(--cia-font-mono)",letterSpacing:"var(--cia-tracking-mono)",lineHeight:1.45,padding:"3px 7px",borderRadius:"var(--cia-r-sm)",background:n?"color-mix(in oklab, var(--cia-ok-500) 8%, transparent)":"color-mix(in oklab, var(--cia-bad-500) 8%, transparent)",border:n?"1px solid color-mix(in oklab, var(--cia-ok-500) 20%, transparent)":"1px solid color-mix(in oklab, var(--cia-bad-500) 20%, transparent)",color:n?"var(--cia-ok-600)":"var(--cia-bad-500)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",...a==="greeting"?{}:{display:"-webkit-box",WebkitLineClamp:6,WebkitBoxOrient:"vertical",overflow:"hidden"}}}function u4({pendingCount:e,onApplyAll:a,onDiscardAll:n,thumbValue:s,onThumbChange:i,onThumbComment:r}){const{t:o}=M("agentsBuilder");return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,width:"100%",flexWrap:"wrap"},children:[t.jsx(g_,{value:s,onChange:i,onComment:r}),t.jsx("div",{style:{flex:1}}),e>0&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:n,style:{height:36,padding:"0 13px",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border-2)",background:"transparent",color:"var(--cia-text-2)",fontFamily:"var(--cia-font-sans)",fontSize:13,fontWeight:500,cursor:"pointer",letterSpacing:"var(--cia-tracking-tight)"},onMouseEnter:l=>{l.currentTarget.style.background="var(--cia-bg-soft)"},onMouseLeave:l=>{l.currentTarget.style.background="transparent"},children:o("changes.discardAll")}),t.jsxs("button",{type:"button",onClick:a,style:{height:36,padding:"0 18px",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-cta-600)",background:"var(--cia-cta-500)",color:"#fff",fontFamily:"var(--cia-font-sans)",fontSize:13,fontWeight:600,cursor:"pointer",letterSpacing:"var(--cia-tracking-tight)",display:"inline-flex",alignItems:"center",gap:6},onMouseEnter:l=>{l.currentTarget.style.background="var(--cia-cta-600)"},onMouseLeave:l=>{l.currentTarget.style.background="var(--cia-cta-500)"},children:[t.jsx(Nt,{size:14,"aria-hidden":"true"}),o("changes.applyN",{count:e})]})]})]})}function p4({versions:e,isLoading:a,onRestore:n}){const{t:s}=M("agentsBuilder");return a?t.jsx("div",{style:{padding:"20px 20px",display:"flex",flexDirection:"column",gap:10},children:[1,2,3].map(i=>t.jsx(ge,{style:{height:72,borderRadius:"var(--cia-r)"}},i))}):!e||e.length===0?t.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:40},children:t.jsx(st,{title:s("versions.emptyTitle"),desc:s("versions.emptyDesc")})}):t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"16px 20px",display:"flex",flexDirection:"column",gap:8},children:e.map(i=>t.jsx(h4,{version:i,onRestore:n},i.id))})}function h4({version:e,onRestore:a}){const{t:n}=M("agentsBuilder"),s=new Date(e.createdAt).toLocaleDateString(Te(),{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}),i=e.stats.successRate!=null?n("versions.successPct",{pct:Math.round(e.stats.successRate)}):null,r=e.stats.avgSentiment!=null?n("versions.sentiment",{val:e.stats.avgSentiment.toFixed(1)}):null;return t.jsxs("div",{style:{padding:"12px 14px",borderRadius:"var(--cia-r)",border:`1px solid ${e.isCurrent?"var(--cia-ok-500)":"var(--cia-border)"}`,background:e.isCurrent?"color-mix(in oklab, var(--cia-ok-500) 6%, transparent)":"var(--cia-bg-soft)",display:"flex",alignItems:"flex-start",ga
953p:12},children:[t.jsxs("div",{style:{width:36,height:36,borderRadius:"var(--cia-r)",background:e.isCurrent?"color-mix(in oklab, var(--cia-ok-500) 15%, transparent)":"var(--cia-bg-elev)",border:`1px solid ${e.isCurrent?"var(--cia-ok-500)":"var(--cia-border-2)"}`,display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"var(--cia-font-mono)",fontSize:12,fontWeight:600,color:e.isCurrent?"var(--cia-ok-500)":"var(--cia-text-2)",flex:"none"},"aria-label":n("versions.ariaVersion",{n:e.version}),children:["v",e.version]}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[e.isCurrent&&t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 7px",borderRadius:"var(--cia-r-pill)",background:"color-mix(in oklab, var(--cia-ok-500) 15%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-ok-500) 30%, transparent)",color:"var(--cia-ok-600)",fontSize:11,fontWeight:600,fontFamily:"var(--cia-font-mono)"},children:[t.jsx(Nt,{size:10,"aria-hidden":"true"})," ",n("versions.current")]}),e.reason&&t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-2)",fontWeight:500,letterSpacing:"var(--cia-tracking-tight)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},title:ax(e.reason)??void 0,children:ax(e.reason)})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:3,color:"var(--cia-text-3)",fontSize:11.5,fontFamily:"var(--cia-font-mono)",letterSpacing:"var(--cia-tracking-mono)"},children:[t.jsx(Qa,{size:11,"aria-hidden":"true"}),s]}),t.jsxs("div",{style:{display:"flex",gap:10,marginTop:5,flexWrap:"wrap"},children:[t.jsx(Dd,{icon:t.jsx(jS,{size:11}),label:e.stats.calls>0?n("versions.callsN",{count:e.stats.calls}):n("versions.noDataYet"),faded:e.stats.calls===0}),i&&t.jsx(Dd,{label:i}),r&&t.jsx(Dd,{label:r})]})]}),!e.isCurrent&&t.jsxs("button",{type:"button",onClick:()=>a(e),title:n("versions.restoreTitle",{version:e.version}),"aria-label":n("versions.restoreAria",{version:e.version}),style:{display:"inline-flex",alignItems:"center",gap:4,height:30,padding:"0 10px",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border-2)",background:"var(--cia-bg-elev)",color:"var(--cia-text-3)",fontFamily:"var(--cia-font-sans)",fontSize:12,fontWeight:500,cursor:"pointer",flex:"none",alignSelf:"center",transition:"border-color var(--cia-dur-fast) ease, color var(--cia-dur-fast) ease"},onMouseEnter:o=>{const l=o.currentTarget;l.style.borderColor="var(--cia-brand-300)",l.style.color="var(--cia-brand-500)"},onMouseLeave:o=>{const l=o.currentTarget;l.style.borderColor="var(--cia-border-2)",l.style.color="var(--cia-text-3)"},children:[t.jsx(po,{size:11,"aria-hidden":"true"}),n("versions.restore")]})]})}function Dd({icon:e,label:a,faded:n=!1}){return t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontFamily:"var(--cia-font-mono)",letterSpacing:"var(--cia-tracking-mono)",color:n?"var(--cia-text-4)":"var(--cia-text-3)",opacity:n?.7:1},children:[e,a]})}function m4(){const[e,a]=m.useState(()=>typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return m.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia("(prefers-reduced-motion: reduce)"),s=()=>a(n.matches);return n.addEventListener("change",s),()=>n.removeEventListener("change",s)},[]),e}function v0(e){const[a,n]=m.useState(!1),s=m.useRef(void 0),i=m4();return m.useEffect(()=>{const r=s.current;if(s.current=e,r===void 0||r===e||i)return;n(!0);const o=setTimeout(()=>n(!1),900);return()=>clearTimeout(o)},[e,i]),a}function f4(e,a){const n=e?.name?.trim()||a("liveCard.nameFallback"),s=e?.tts?.voiceId,i=s?[e?.tts?.provider,s].filter(Boolean).join(" · "):a("liveCard.voiceFallback"),r=e?.llm?.model||a("liveCard.modelFallback"),o=e?.analytics?.dataPoints?.length??0,l=e?.greeting?.trim()||a("liveCard.greetingFallback");return[{key:"name",icon:t.jsx(Ft,{size:13,"aria-hidden":"true"}),label:a("liveCard.labelName"),value:n},{key:"voice",icon:t.jsx(Cr,{size:13,"aria-hidden":"true"}),label:a("liveCard.labelVoice"),value:i},{key:"model",icon:t.jsx(Sr,{size:13,"aria-hidden":"true"}),label:a("liveCard.labelModel"),value:r},{key:"dataPoints",icon:t.jsx(us,{size:13,"aria-hidden":"true"}),label:a("liveCard.labelDataPoints"),value:a("liveCard.dataPointsCount",{count:o})},{key:"greeting",icon:t.jsx(Ba,{size:13,"aria-hidden":"true"}),label:a("liveCard.labelGreeting"),value:l,multiline:!0}]}function rx({agent:e,compact:a=!1}){const{t:n}=M("agentsBuilder"),s=f4(e,n);return a?t.jsx("div",{role:"status","aria-label":n("liveCard.regionAria"),style:{display:"flex",gap:8,overflowX:"auto",padding:"2px 2px 6px"},children:s.map(i=>t.jsx(g4,{field:i},i.key))}):t.jsxs("div",{role:"status","aria-label":n("liveCard.regionAria"),style:{border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r-lg)",background:"var(--cia-bg-elev)",padding:16,display:"flex",flexDirection:"column",gap:10,height:"fit-content"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(Ft,{size:16,style:{color:"var(--cia-brand-500)"},"aria-hidden":"true"}),t.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:"var(--cia-text-2)",letterSpacing:"var(--cia-tracking-tight)",fontFamily:"var(--cia-font-sans)"},children:n("liveCard.heading")})]}),s.map(i=>t.jsx(x4,{field:i},i.key))]})}function x4({field:e}){const a=v0(e.value);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:"8px 10px",borderRadius:"var(--cia-r-sm)",background:a?"color-mix(in oklab, var(--cia-ok-500) 14%, transparent)":"var(--cia-bg-soft)",border:`1px solid ${a?"color-mix(in oklab, var(--cia-ok-500) 40%, transparent)":"var(--cia-border)"}`,transition:"background var(--cia-dur-slow) var(--cia-ease-smooth), border-color var(--cia-dur-slow) var(--cia-ease-smooth)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5,color:a?"var(--cia-ok-600)":"var(--cia-text-3)"},children:[e.icon,t.jsx("span",{style:{fontSize:10,fontFamily:"var(--cia-font-mono)",letterSpacing:"var(--cia-tracking-mono)",textTransform:"uppercase"},children:e.label})]}),t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text)",fontWeight:500,lineHeight:1.45,overflow:e.multiline?"visible":"hidden",textOverflow:e.multiline?"clip":"ellipsis",whiteSpace:e.multiline?"normal":"nowrap",display:e.multiline?"-webkit-box":"block",WebkitLineClamp:e.multiline?3:void 0,WebkitBoxOrient:e.multiline?"vertical":void 0},title:e.value,children:e.value})]})}function g4({field:e}){const a=v0(e.value),n=e.value.length>20?`${e.value.slice(0,20)}…`:e.value;return t.jsxs("span",{title:`${e.label}: ${e.value}`,style:{display:"inline-flex",alignItems:"center",gap:5,padding:"5px 10px",borderRadius:"var(--cia-r-pill)",background:a?"color-mix(in oklab, var(--cia-ok-500) 16%, transparent)":"var(--cia-bg-soft)",border:`1px solid ${a?"color-mix(in oklab, var(--cia-ok-500) 45%, transparent)":"var(--cia-border)"}`,color:a?"var(--cia-ok-600)":"var(--cia-text-3)",fontSize:11,fontFamily:"var(--cia-font-sans)",fontWeight:500,whiteSpace:"nowrap",flex:"none",transition:"background var(--cia-dur-slow) var(--cia-ease-smooth), border-color var(--cia-dur-slow) var(--cia-ease-smooth), color var(--cia-dur-slow) var(--cia-ease-smooth)"},children:[e.icon,n]})}function b4(e){const a=e;return a?.response?.status===429?he.t("agentsBuilder:callMe.errorInProgress"):a?.response?.data?.message||he.t("agentsBuilder:callMe.errorGeneric")}function y4({agentId:e,contactPhone:a,onCallStarted:n,onError:s,disabled:i}){const{can:r}=tt(),{t:o}=M("agentsBuilder"),[l,c]=m.useState("idle"),[d,u]=m.useState(null),p=se({queryKey:["phone-numbers","call-me-button"],queryFn:async()=>(await T.get("/phone-numbers")).data,staleTime:6e4}),f=(()=>{const b=p.data??[],g=b.find(v=>v.shared===!0&&v.canOriginate===!0);return g?g.id:b.find(v=>v.canOriginate===!0&&!v.rotating)?.id??null})(),x=oe({mutationFn:async()=>{const{data:b}=await T.post("/calls/originate",{numberId:f,agentId:e,destinationNumber:a,onboardingDemo:!0});return b},onMutate:()=>{u(null),c("calling")},onSuccess:b=>{c("ringing"),n(b.callId)},onError:b=>{const g=b4(b);u(g),c("idle"),s?.(g)}});if(p.isLoading||!f||!r("calls.operate"))return null;if(l==="ringing")return t.jsx("div",{className:"cia-badge cia-badge-success",style:{width:"100%",justifyContent:"center",height:40,fontSize:12.5},children:o("callMe.ringing")});if(l==="calling")return t.jsxs("button",{type:"button",disabled:!0,className:"cia-btn cia-btn-outline cia-btn-lg",style:{width:"100%",justifyContent:"center"},children:[t.jsx(je,{size:15,style:{animation:"spin 1s linear infinite"}})," ",o("callMe.calling")]});if(l==="confirm")return t.jsxs("div",{className:"cia-col",style:{gap:8,width:"100%"},children:[t.jsx("div",{className:"cia-badge",style:{width:"100%",justifyContent:"center",height:"auto",padding:"8px 12px",whiteSpace:"normal",textAlign:"center",lineHeight:1.5},children:o("callMe.confirmText",{phone:a})}),t.jsxs("div",{className:"cia-row cia-gap-2",children:[t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{flex:1,justifyContent:"center",minHeight:44},onClick:()=>c("idle"),children:o("callMe.cancel")}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta cia-btn-sm",style:{flex:2,justifyContent:"center",minHeight:44},onClick:()=>x.mutate(),children:o("callMe.confirm")})]})]});const h=a?void 0:o("callMe.hint");return t.jsxs("div",{className:"cia-col",style:{gap:8,width:"100%"},children:[t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-lg",style:{width:"100%",justifyContent:"center"},disabled:i||!a,onClick:()=>c("confirm"),children:[t.jsx(ji,{size:15,style:{flex:"none"}}),t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:o("callMe.cta",{phone:a||"…"})})]}),h&&t.jsx("span",{className:"cia-text-4",style:{fontSize:11,textAlign:"center"},children:h}),d&&t.jsx(le,{tone:"bad",children:d})]})}const v4=2500,j4=3e4;function w4(e){return{durationSeconds:e.durationSeconds??0,successResult:e.analysis?.success?.result??null,successRationale:e.anal
953ysis?.success?.rationale??null,sentimentValue:e.analysis?.sentiment?.value??null,sentimentRationale:e.analysis?.sentiment?.rationale??null,summary:e.summary??null,extractedFields:e.extractedFields??null,transcript:e.transcript??[]}}function Id(e){return e?!!e.endedAt&&!!(e.summary||e.analysis||e.extractedFields):!1}function k4(e){const a=Math.max(0,Math.round(e));return`${Math.floor(a/60)}:${String(a%60).padStart(2,"0")}`}function N4(e){return e==null||e===""?"—":typeof e=="boolean"?e?he.t("agentsBuilder:report.yes"):he.t("agentsBuilder:report.no"):typeof e=="object"?JSON.stringify(e):String(e)}const S4={success:{labelKey:"report.successAchieved",cls:"cia-badge-success"},failure:{labelKey:"report.successNotAchieved",cls:"cia-badge-bad"}},C4={positive:{labelKey:"report.sentimentPositive",emoji:"🙂",cls:"cia-badge-success"},neutral:{labelKey:"report.sentimentNeutral",emoji:"😐",cls:"cia-badge"},negative:{labelKey:"report.sentimentNegative",emoji:"🙁",cls:"cia-badge-bad"}};function _4({result:e,rationale:a}){const{t:n}=M("agentsBuilder"),s=e?S4[e]:void 0;if(!s)return t.jsxs("span",{className:"cia-badge",title:n("report.successUndeterminedTitle"),children:[t.jsx(vc,{size:12})," ",n("report.successUndetermined")]});const i=e==="success"?Nt:cs;return t.jsxs("span",{className:`cia-badge ${s.cls}`,title:a??void 0,children:[t.jsx(i,{size:12})," ",n(s.labelKey)]})}function E4({value:e,rationale:a}){const{t:n}=M("agentsBuilder"),s=e?C4[e]:void 0;return s?t.jsxs("span",{className:`cia-badge ${s.cls}`,title:a??void 0,children:[s.emoji," ",n(s.labelKey)]}):t.jsxs("span",{className:"cia-badge",title:n("report.sentimentUndeterminedTitle"),children:[t.jsx(vc,{size:12})," ",n("report.sentimentUndetermined")]})}function A4({agentId:e,callId:a,sessionId:n,onRetry:s,onImprove:i,onFinish:r,mock:o}){const{t:l}=M("agentsBuilder"),c=[l("report.stageTranscribing"),l("report.stageEvaluating"),l("report.stageExtracting")],[d,u]=m.useState(0),[p,f]=m.useState(!1),[x,h]=m.useState(!1),g=se({queryKey:["post-call-report",a??n??e],enabled:!o&&(!!a||!!n),queryFn:async()=>{if(a){const{data:C}=await T.get(`/calls/${a}`);return C}const{data:w}=await T.get("/calls",{params:{agentId:e,limit:5}}),j=w.items.find(C=>C.roomName===n);return j||(w.items.find(C=>C.direction==="web")??null)},refetchInterval:w=>{if(p)return!1;const j=w.state.data;return Id(j)?!1:v4}});m.useEffect(()=>{if(o)return;const w=setTimeout(()=>f(!0),j4);return()=>clearTimeout(w)},[o]),m.useEffect(()=>{if(o)return;const w=setInterval(()=>u(j=>(j+1)%c.length),1800);return()=>clearInterval(w)},[o]);const v=g.data??null,y=!!o||Id(v)||p,k=o??(v?w4(v):null);return y?t.jsxs("div",{className:"cia-col",style:{gap:18,width:"100%"},children:[!k&&t.jsx(le,{tone:"info",children:l("report.processingBanner")}),k&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"cia-row cia-gap-2",style:{flexWrap:"wrap"},children:[t.jsx(_4,{result:k.successResult,rationale:k.successRationale}),t.jsx(E4,{value:k.sentimentValue,rationale:k.sentimentRationale}),t.jsxs("span",{className:"cia-badge",children:["⏱ ",k4(k.durationSeconds)]})]}),p&&!Id(v)&&t.jsx(le,{tone:"info",children:l("report.processingBannerTimeout")}),k.summary&&t.jsx("p",{className:"cia-text-2",style:{margin:0,fontSize:13.5,lineHeight:1.6},children:k.summary}),t.jsxs("div",{style:{border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r-lg)",background:"var(--cia-bg-elev)",padding:14,display:"flex",flexDirection:"column",gap:8},children:[t.jsx("span",{className:"cia-eyebrow",children:l("report.capturedData")}),k.extractedFields&&Object.keys(k.extractedFields).length>0?Object.entries(k.extractedFields).map(([w,j])=>t.jsx(Gy,{k:w,v:N4(j)},w)):t.jsx("span",{className:"cia-text-3",style:{fontSize:12.5},children:l("report.noDataCaptured")})]}),k.transcript&&k.transcript.length>0&&t.jsxs("div",{children:[t.jsxs("button",{type:"button",className:"cia-mono cia-text-3",onClick:()=>h(w=>!w),"aria-expanded":x,style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,cursor:"pointer",userSelect:"none",background:"none",border:"none",padding:0,color:"inherit"},children:[x?t.jsx(Ut,{size:12}):t.jsx(ca,{size:12}),l("report.viewTranscript")]}),x&&t.jsx("div",{style:{marginTop:12,maxHeight:320,overflowY:"auto"},children:t.jsx(vo,{messages:k.transcript.map((w,j)=>({id:`t${j}`,role:w.role,text:w.text,timestamp:w.timestamp})),showTimestamps:!1,dense:!0,emptyText:l("report.transcriptEmpty")})})]})]}),t.jsxs("div",{className:"cia-col cia-gap-3",style:{width:"100%",marginTop:4},children:[t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta cia-btn-lg",style:{width:"100%",justifyContent:"center"},onClick:r,children:l("report.goToPanel")}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-lg",style:{width:"100%",justifyContent:"center"},onClick:i,children:l("report.keepImproving")}),t.jsx(et,{to:"/meetings",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{width:"100%",justifyContent:"center"},children:l("report.tryMeetings")}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{width:"100%",justifyContent:"center",minHeight:44},onClick:s,children:l("report.tryAgain")})]})]}):t.jsxs("div",{className:"cia-col",style:{gap:16,alignItems:"center",textAlign:"center",padding:"28px 8px",width:"100%"},children:[t.jsx(je,{size:22,style:{color:"var(--cia-brand-500)",animation:"spin 1s linear infinite"}}),t.jsx("span",{className:"cia-caret",style:{fontSize:14.5,fontWeight:600,color:"var(--cia-text)"},children:c[d]}),t.jsxs("div",{style:{width:"100%",display:"grid",gap:8},children:[t.jsx(ge,{h:14,w:"60%",style:{margin:"0 auto"}}),t.jsx(ge,{h:54}),t.jsx(ge,{h:14,w:"40%",style:{margin:"0 auto"}})]}),t.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})}function Ph(e,a){const n={...e};return a.systemPrompt!==void 0&&(n.systemPrompt=a.systemPrompt),a.greeting!==void 0&&(n.greeting=a.greeting),a.tts!==void 0&&a.tts!==null&&(n.tts={...e.tts,...a.tts}),a.llm!==void 0&&a.llm!==null&&(n.llm={...e.llm,...a.llm}),a.analytics!==void 0&&a.analytics!==null&&(n.analytics={...e.analytics??{},...a.analytics}),a.advancedBehavior!==void 0&&a.advancedBehavior!==null&&(n.advancedBehavior={...e.advancedBehavior??{},...a.advancedBehavior}),a.dynamicVariables!==void 0&&a.dynamicVariables!==null&&(n.dynamicVariables=a.dynamicVariables),a.tools!==void 0&&a.tools!==null&&(n.tools=a.tools),a.knowledge!==void 0&&(n.knowledge=a.knowledge),n}function bs(e){return{name:e.name,language:e.language,greeting:e.greeting,systemPrompt:e.systemPrompt,textPrompt:e.textPrompt,stt:e.stt,llm:e.llm,tts:e.tts,vad:e.vad,interruptSpeechDuration:e.interruptSpeechDuration,tools:e.tools,handoff:e.handoff,analytics:e.analytics,accent:e.accent,backgroundAudio:e.backgroundAudio,advancedBehavior:e.advancedBehavior,recording:e.recording,widgetConfig:e.widgetConfig,callLimits:e.callLimits,knowledge:e.knowledge,dynamicVariables:e.dynamicVariables,channels:e.channels,status:e.status}}function ox(e){const[a,n]=m.useState(()=>typeof window<"u"&&window.matchMedia(e).matches);return m.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia(e),i=()=>n(s.matches);
953return i(),s.addEventListener("change",i),()=>s.removeEventListener("change",i)},[e]),a}const R4=[{id:"cobranza",icon:t.jsx(Ma,{size:18})},{id:"leads",icon:t.jsx(nh,{size:18})},{id:"recepcionista",icon:t.jsx(ay,{size:18})},{id:"nps",icon:t.jsx(Ii,{size:18})}],lx=["creating","greeting","converses","preparing"],T4=["Financiero","Salud","Educación","Construcción","Tecnología","Otro"],M4={Financiero:"financiero",Salud:"salud",Educación:"educacion",Construcción:"construccion",Tecnología:"tecnologia",Otro:"otro"},P4=["+57","+52","+51","+56","+54","+1"];function cx(e){for(const a of P4)if(e.startsWith(a))return e.slice(a.length).replace(/\D/g,"");return e.replace(/^\+/,"").replace(/\D/g,"")}function dx(e){return e.startsWith("+1")?"US":e.startsWith("+57")?"CO":null}const z4={finanzas:t.jsx(Ma,{size:18}),ventas:t.jsx(nh,{size:18}),soporte:t.jsx(ay,{size:18}),investigacion:t.jsx(Ii,{size:18})};function D4(e){return e&&z4[e]||t.jsx(_t,{size:18})}function Ld(e){return e?.response?.data?.message||he.t("onboarding:errors.createFailed")}function I4({forcePreview:e=!1}){const{t:a}=M("onboarding"),n=dt(),s=Pe(ee=>ee.user),i=Pe(ee=>ee.setUser),r=s?.role;function o(ee){const Oe=Pe.getState().user;Oe&&i({...Oe,onboardingState:ee})}const l=e||r==="superadmin"||typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1",[c,d]=m.useState("perfil"),[u,p]=m.useState(null),[f,x]=m.useState(null),[h,b]=m.useState(!1),[g,v]=m.useState(0),[y,k]=m.useState(null),[w,j]=m.useState(null),[C,N]=m.useState(""),[S,_]=m.useState(""),[R,A]=m.useState(null),[E,I]=m.useState("es"),[P,O]=m.useState(null),[K,W]=m.useState(!1),V=m.useRef(!1);function U(ee){if(K)return;O(ee);const Oe=ee==="US"?"+1":"+57",At=cx(C);V.current=!0,N(At?`${Oe}${At}`:Oe)}const X=se({queryKey:["organizations","me","onboarding-profile"],queryFn:async()=>(await T.get("/organizations/me")).data,enabled:!l,staleTime:6e4});m.useEffect(()=>{try{const ee=sessionStorage.getItem("cia.onboarding.profile");if(ee){const Oe=JSON.parse(ee);Oe.contactPhone&&N(Oe.contactPhone),Oe.companyName&&_(Oe.companyName),Oe.industry&&A(Oe.industry),Oe.language&&I(Oe.language),Oe.country&&O(Oe.country)}}catch{}},[]),m.useEffect(()=>{const ee=X.data;if(!ee)return;const Oe=ee.businessProfile;_(Jt=>Jt||Oe?.companyName||ee.name||""),A(Jt=>Jt??Oe?.industry??null),V.current||N(Jt=>Jt||Oe?.contactPhone||"");const At=Oe?.language;(At==="es"||At==="en")&&I(Jt=>Jt==="es"?At:Jt),(Oe?.country==="US"||Oe?.country==="CO")&&(O(Oe.country),W(!0))},[X.data]);const[ie,de]=m.useState(null),$=m.useRef(null),[z,D]=m.useState(!1),[F,G]=m.useState(!1),[te,B]=m.useState(null),ne=m.useRef(Promise.resolve()),me=ox("(min-width: 900px)"),Ee=ox("(max-height: 500px) and (orientation: landscape)");function L(ee){$.current=ee,de(ee)}function re(ee){if(l||!y?.id||!ee)return;const Oe=y.id;ne.current=ne.current.then(async()=>{G(!0),B(null);try{await T.patch(`/agents/${Oe}`,bs(ee))}catch(At){const Jt=Ld(At);B(Jt),J({tone:"bad",title:a("toasts.saveFailedTitle"),desc:Jt,action:{label:a("toasts.retry"),onClick:()=>re(ee)}})}finally{G(!1)}})}function ke(ee){const Oe=Ph($.current??y??{},ee);L(Oe)}function H(){D(!0),re($.current)}const fe=m.useMemo(()=>{const ee=S.trim()||X.data?.name||"mi empresa";return`Acabo de crear mi agente "${f||"el caso que elegí"}" para ${ee} (${R||"mi industria"}). Entrevistame con una pregunta corta por turno para personalizarlo (tono/persona, una política clave del negocio, el caso borde principal). Después de mis respuestas, proponé la configuración completa.`},[S,X.data?.name,R,f]),[Z,ae]=m.useState(null),pe=m.useRef(!1);function ye(){pe.current||l||(pe.current=!0,T.patch("/organizations/me/onboarding",{state:"demo_done"}).catch(()=>{}),o("demo_done"))}function qe(ee){ae({sessionId:ee.sessionId??void 0})}const ut=m.useRef(!1);m.useEffect(()=>{c==="prueba"&&(ut.current=!0)},[c]);const bt=m.useMemo(()=>{const ee=S.trim()||a("companyFallback");return{durationSeconds:87,successResult:"success",successRationale:a("previewReport.successRationale"),sentimentValue:"positive",sentimentRationale:a("previewReport.sentimentRationale"),summary:a("previewReport.summary",{company:ee}
953),extractedFields:{nombre_contacto:"María Pérez",fecha_agendada:"Jueves 10am"},transcript:[{role:"agent",text:a("previewReport.transcriptAgent1",{company:ee}),timestamp:new Date().toISOString()},{role:"user",text:a("previewReport.transcriptUser1"),timestamp:new Date().toISOString()},{role:"agent",text:a("previewReport.transcriptAgent2"),timestamp:new Date().toISOString()},{role:"user",text:a("previewReport.transcriptUser2"),timestamp:new Date().toISOString()}]}},[S,a]),[Ge,yt]=m.useState(()=>{try{return localStorage.getItem("conectaia.theme")==="dark"?"dark":"light"}catch{return"light"}}),ve=m.useRef(null),Ke=m.useCallback(()=>{const ee=ve.current;ee&&(ee.setAttribute("data-theme-switching",""),requestAnimationFrame(()=>{const Oe=Ge==="light"?"dark":"light";yt(Oe);try{localStorage.setItem("conectaia.theme",Oe)}catch{}requestAnimationFrame(()=>ee.removeAttribute("data-theme-switching"))}))},[Ge]);m.useEffect(()=>{ve.current?.setAttribute("data-theme",Ge)},[Ge]);const He=m.useRef(null);m.useEffect(()=>{He.current?.focus()},[c]),m.useEffect(()=>{if(!h)return;v(0);const ee=setInterval(()=>v(Oe=>Math.min(Oe+1,lx.length-1)),700);return()=>clearInterval(ee)},[h]);const Xe=cx(C),Et=!!P&&dx(C)===P,Yt=Xe.length>0&&!_f.test(C)?a("paso1.phoneInvalid"):Xe.length>0&&P&&!Et?a("paso1.phoneCountryMismatch",{country:a(P==="US"?"paso1.countryNameUS":"paso1.countryNameCO")}):void 0,It=_f.test(C)&&!!R&&!!P&&Et;function Pn(){if(It){if(!l){const ee={companyName:S.trim()||void 0,industry:R??void 0,contactPhone:C,language:E,...P&&!K?{country:P}:{}};try{sessionStorage.setItem("cia.onboarding.profile",JSON.stringify({companyName:S.trim(),industry:R,contactPhone:C,language:E,country:P}))}catch{}T.patch("/organizations/me/profile",ee).catch(()=>{}),T.patch("/organizations/me/onboarding",{state:"profile_done"}).catch(()=>{}),o("profile_done"),P&&!K&&W(!0)}d("caso")}}const St=se({queryKey:["playbook","templates"],queryFn:async()=>(await T.get("/playbook/templates")).data,enabled:!l,staleTime:5*6e4}),sa=(St.data??[]).filter(ee=>ee.language===E),ma=!l&&St.isLoading,$e=l||!ma&&sa.length===0;function ce(){D(!1),B(null)}async function Se(ee){p(ee.templateId),x(ee.name),j(null),b(!0);try{const Oe=S.trim()||X.data?.name||"la empresa",{data:At}=await T.post("/agents/from-template",{templateId:ee.templateId,name:`${ee.name} · ${Oe}`});k(At),L(At),ce(),T.patch("/organizations/me/onboarding",{state:"agent_created"}).catch(()=>{}),o("agent_created"),d("construccion")}catch(Oe){j(Ld(Oe))}finally{b(!1)}}async function De(ee){p(ee),x(Pr[ee].name),j(null),b(!0);const Oe=Pr[ee];try{if(l){await new Promise(Jt=>setTimeout(Jt,1800));const At={id:"ag_preview",name:Oe.name,...Oe.preset};k(At),L(At)}else{const{data:At}=await T.post("/agents",{name:Oe.name,status:"draft",...Oe.preset});k(At),L(At),T.patch("/organizations/me/onboarding",{state:"agent_created"}).catch(()=>{}),o("agent_created")}ce(),d("construccion")}catch(At){j(Ld(At))}finally{b(!1)}}function ue(){try{sessionStorage.removeItem("cia.onboarding.profile")}catch{}}function Ze(){l||(T.patch("/organizations/me/onboarding",{state:"completed"}).catch(()=>{}),o("completed"),ue()),n({to:l?"/admin/dashboard":"/dashboard"})}function ze(){d("construccion")}function Ot(){UN(),n({to:"/dashboard"})}function fa(){ae(null),d("prueba")}const Ui=c==="perfil"?0:c==="caso"?1:c==="construccion"?2:3,Vi=m.useMemo(()=>[{id:"perfil",label:a("stepper.perfil")},{id:"caso",label:a("stepper.caso")},{id:"construccion",label:a("stepper.construccion")},{id:"prueba",label:a("stepper.prueba")}],[a]);return t.jsxs("div",{ref:ve,className:"cia","data-theme":Ge,style:{minHeight:"100vh",position:"relative",overflow:"hidden",background:"var(--cia-bg)",display:"flex",flexDirection:"column"},children:[t.jsx(Hy,{}),t.jsxs("div",{"aria-hidden":!0,style:{position:"absolute",inset:0,overflow:"hidden",pointerEvents:"none"},children:[t.jsx("div",{style:{position:"absolute",top:"-20%",left:"-10%",width:"50%",height:"60%",background:"radial-gradient(circle, color-mix(in oklab, var(--cia-brand-500) 40%, transparent), transparent 65%)",filter:"blur(80px)"}}),t.jsx("div",{style:{position:"absolute",bottom:"-20%",right:"-10%",width:"45%",height:"55%",background:"radial-gradient(circle, color-mix(in oklab, var(--cia-cta-500) 35%, transparent), transparent 65%)",filter:"blur(80px)"}})]}),t.jsxs("header",{className:"cia-row",style:{position:"relative",justifyContent:"space-between",flexWrap:"wrap",rowGap:8,padding:"20px 28px",paddingTop:"max(20px, env(safe-area-inset-top))"},children:[t.jsx(Dc,{height:28}),t.jsxs("div",{className:"cia-row",style:{gap:8},children:[t.jsx("button",{className:"cia-btn cia-btn-icon cia-btn-ghost",onClick:Ke,"aria-label":a("header.toggleTheme"),type:"button",style:{minWidth:44,minHeight:44},children:Ge==="dark"?t.jsx(Zr,{size:16}):t.jsx(Hr,{size:16})}),l?t.jsx("span",{className:"cia-badge",style:{background:"var(--cia-bg-tint)",color:"var(--cia-cta-500)",fontSize:11},children:a("header.previewBadge")}):c!=="perfil"?t.jsx("button",{className:"cia-btn cia-btn-ghost cia-btn-sm",onClick:Ot,type:"button",style:{minHeight:44},children:a("header.skip")}):null]})]}),t.jsx("div",{style:{position:"relative",maxWidth:560,width:"100%",margin:"0 auto",padding:"0 24px"},children:t.jsx($5,{steps:Vi,current:Ui,onStepClick:ee=>{ee===0&&c==="caso"&&d("perfil")}})}),t.jsxs("main",{style:{position:"relative",flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:24,paddingBottom:"max(24px, env(safe-area-inset-bottom))"},children:[c==="perfil"&&t.jsxs("div",{className:"cia-fade-up",style:{width:"100%",maxWidth:560},children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:10},children:a("paso1.eyebrow")}),t.jsx("h1",{ref:He,tabIndex:-1,style:{margin:"0 0 8px",fontSize:30,fontWeight:600,letterSpacing:"-0.03em",color:"var(--cia-text)",outline:"none"},children:a("paso1.title")}),t.jsx("p",{className:"cia-text-2",style:{margin:"0 0 24px",fontSize:15,lineHeight:1.55},children:a("paso1.subtitle")}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[t.jsxs("div",{children:[t.jsx(nr,{children:a("paso1.countryLabel")}),t.jsxs("div",{className:"cia-row",style:{gap:8},children:[t.jsx(Jo,{label:a("paso1.countryCO"),selected:P==="CO",onClick:()=>U("CO")}),t.jsx(Jo,{label:a("paso1.countryUS"),selected:P==="US",onClick:()=>U("US")})]}),t.jsx("p",{className:"cia-text-3",style:{margin:"6px 0 0",fontSize:12},children:a(K?"paso1.countryHelpLocked":"paso1.countryHelp")})]}),t.jsxs("div",{children:[t.jsx(nr,{children:a("paso1.phoneLabel")}),t.jsx(A_,{value:C,allowedCountries:["CO","US"],onChange:ee=>{if(V.current=!0,N(ee),!K){const Oe=dx(ee);Oe&&O(Oe)}},error:Yt,"aria-label":a("paso1.phoneLabel")})]}),t.jsxs("div",{children:[t.jsx(nr,{children:a("paso1.companyLabel")}),t.jsx("input",{value:S,onChange:ee=>_(ee.target.value),placeholder:a("paso1.companyPlaceholder"),"aria-label":a("paso1.companyLabel"),style:{width:"100%",minHeight:44,padding:"0 14px",borderRadius:"var(--cia-r)",border:"1.5px solid var(--cia-border-2)",background:"var(--cia-bg)",color:"var(--cia-text)",fontFamily:"var(--cia-font-sans)",fontSize:14,outline:"none"}})]}),t.jsxs("div",{children:[t.jsx(nr,{children:a("paso1.industryLabel")}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:T4.map(ee=>t.jsx(L4,{label:a(`industries.${M4[ee]}`),selected:R===ee,onClick:()=>A(ee)},ee))})]}),t.jsxs("div",{children:[t.jsx(nr,{children:a("paso1.agentLangLabel")}),t.jsxs("div",{className:"cia-row",style:{gap:8},children:[t.jsx(Jo,{label:a("paso1.langEs"),selected:E==="es",onClick:()=>I("es")}),t.jsx(Jo,{label:a("paso1.langEn"),selected:E==="en",onClick:()=>I("en")})]})]})]}),w&&t.jsx("div",{className:"cia-badge-danger",role:"alert",style:{marginTop:16},children:w}),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-cta cia-btn-lg",style:{width:"100%",justifyContent:"center",marginTop:24},disabled:!It,onClick:Pn,children:[a("paso1.continue")," ",t.jsx(oa,{size:15})]})]}),c==="caso"&&!h&&t.jsxs("div",{className:"cia-fade-up",style:{width:"100%",maxWidth:560},children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:10},children:a("paso2.eyebrow")}),t.jsx("h1",{ref:He,tabIndex:-1,style:{margin:"0 0 8px",fontSize:30,fontWeight:600,letterSpacing:"-0.03em",color:"var(--cia-text)",outline:"none"},children:a("paso2.title")}),t.jsx("p",{className:"cia-text-2",style:{margin:"0 0 24px",fontSize:15,lineHeight:1.55},children:a("paso2.subtitle")}),ma?t.jsx("div",{style:{display:"grid",gap:12},children:[1,2,3,4].map(ee=>t.jsx(ge,{h:78,style:{borderRadius:"var(--cia-r-lg)"}},ee))}):t.jsx("div",{style:{display:"grid",gap:12},children:$e?R4.map(ee=>t.jsx(Bu,{title:Pr[ee.id].name,description:a(`fallbackTemplates.${ee.id}`),icon:ee.icon,selected:u===ee.id,onClick:()=>De(ee.id)},ee.id)):sa.map(ee=>t.jsx(Bu,{title:ee.name,description:ee.description,icon:D4(ee.category),selected:u===ee.templateId,onClick:()=>Se(ee)},ee.templateId))}),w&&t.jsx("div",{className:"cia-badge-danger",role:"alert",style:{marginTop:16},children:w}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{marginTop:18,minHeight:44},onClick:()=>d("perfil"),children:a("paso2.back")})]}),h&&t.jsxs("div",{className:"cia-col cia-fade-up",style:{alignItems:"center",textAlign:"center",gap:18},role:"status","aria-live":"polite",children:[t.jsx("span",{style:{width:56,height:56,borderRadius:16,display:"grid",placeItems:"center",background:"var(--cia-bg-tint)",color:"var(--cia-cta-500)"},children:t.jsx(_t,{size:26})}),t.jsxs("div",{className:"cia-col",style:{gap:6,alignItems:"center"},children:[t.jsx("span",{className:"cia-caret",style:{fontSize:16,fontWeight:600,color:"var(--cia-text)"},children:a(`stages.${lx[g]}`)}),t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:11},children:a("creating.caption")})]})]}),c==="construccion"&&y&&t.jsxs("div",{className:"cia-fade-up",style:{width:"100%",maxWidth:980},children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:10},children:a("paso3.eyebrow")}),t.jsx("h1",{ref:He,tabIndex:-1,style:{margin:"0 0 8px",fontSize:30,fontWeight:600,letterSpacing:"-0.03em",color:"var(--cia-text)",outline:"none"},children:a("paso3.title")}),t.jsx("p",{className:"cia-text-2",style:{margin:"0 0 20px",fontSize:15,lineHeight:1.55},children:a("paso3.subtitle")}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:me?"1fr 300px":"1fr",gap:16,alignItems:"start"},children:[!me&&t.jsx(rx,{agent:ie??y,compact:!0}),t.jsx("div",{style:{height:me?560:Ee?"calc(100dvh - 200px)":"calc(100dvh - 430px)",minHeight:Ee?220:380,border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r-lg)",background:"var(--cia-bg-elev)",overflow:"hidden"},children:l?t.jsx(F4,{companyName:S,onApplied:()=>{const ee=S.trim()||a("companyFallback");L({...$.current??y??{},greeting:a("scriptedPreview.greeting",{company:ee})})}}):t.jsx(y0,{variant:"wizard",agentId:y.id,agentName:y.name,draft:ie??y,onApplyPatch:ke,onPatchApplied:H,kickoffMessage:fe,autoApply:!0,quickActions:[]},y.id)}),me&&t.jsx(rx,{agent:ie??y})]}),te&&t.jsx("div",{className:"cia-badge-danger",role:"alert",style:{marginTop:14},children:te}),t.jsxs("div",{className:"cia-col",style:{alignItems:"center",gap:10,marginTop:20},children:[F&&t.jsxs("span",{className:"cia-mono cia-text-3",style:{fontSize:11,display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(je,{size:12,style:{animation:"spin 1s linear infinite"}})," ",a("paso3.saving")]}),z||l?t.jsxs("button",{type:"button",className:"cia-btn cia-btn-cta cia-btn-lg",style:{width:"100%",justifyContent:"center"},disabled:F,onClick:fa,children:[a("paso3.testNow")," ",t.jsx(oa,{size:15})]}):t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",onClick:fa,children:a("paso3.skipCustomization")})]}),t.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),c==="prueba"&&y&&y.id&&t.jsxs("div",{className:"cia-fade-up",style:{position:"relative",width:"100%",maxWidth:480,display:"flex",flexDirection:"column",alignItems:"center"},children:[!ut.current&&t.jsx(N_,{}),t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:8},children:a(Z?"paso4.eyebrowReport":"paso4.eyebrow")}),t.jsx("h1",{ref:He,tabIndex:-1,style:{margin:"0 0 6px",fontSize:28,fontWeight:600,letterSpacing:"-0.03em",color:"var(--cia-text)",textAlign:"center",outline:"none"},children:a(Z?"paso4.titleReport":"paso4.title")}),!Z&&t.jsx("p",{className:"cia-text-2",style:{margin:"0 0 18px",fontSize:14.5,lineHeight:1.55,textAlign:"center",maxWidth:380},children:a("paso4.subtitle")}),Z?t.jsx(A4,{agentId:y.id,callId:Z.callId,sessionId:Z.sessionId,mock:l?bt:void 0,onRetry:()=>ae(null),onImprove:ze,onFinish:Ze}):t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{width:"100%",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r-lg)"},children:t.jsx(p0,{agent:ie??y,isNew:!1,dirty:!1,onboarding:!0,preview:l,onEnded:qe,onLive:ye})}),t.jsxs("div",{className:"cia-col cia-gap-3",style:{width:"100%",marginTop:14}
953,children:[t.jsx(y4,{agentId:y.id,contactPhone:C,disabled:l,onCallStarted:ee=>{ye(),ae({callId:ee})},onError:ee=>J({tone:"bad",title:a("toasts.callFailedTitle"),desc:ee})}),l&&t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{width:"100%",justifyContent:"center"},onClick:()=>ae({}),children:a("paso4.simulateEnd")})]})]})]})]})]})}function nr({children:e}){return t.jsx("label",{style:{display:"block",marginBottom:7,fontSize:12.5,fontWeight:600,color:"var(--cia-text-2)",letterSpacing:"var(--cia-tracking-tight)"},children:e})}function L4({label:e,selected:a,onClick:n}){return t.jsx("button",{type:"button",onClick:n,"aria-pressed":a,style:{minHeight:44,padding:"0 16px",borderRadius:"var(--cia-r-pill)",border:`1.5px solid ${a?"var(--cia-cta-500)":"var(--cia-border-2)"}`,background:a?"var(--cia-bg-tint)":"var(--cia-bg-elev)",color:a?"var(--cia-cta-600)":"var(--cia-text-2)",fontFamily:"var(--cia-font-sans)",fontSize:13.5,fontWeight:a?600:500,cursor:"pointer",transition:"border-color var(--cia-dur-fast) ease, background var(--cia-dur-fast) ease"},children:e})}function Jo({label:e,selected:a,onClick:n}){return t.jsx("button",{type:"button",onClick:n,"aria-pressed":a,style:{minHeight:44,minWidth:108,padding:"0 18px",borderRadius:"var(--cia-r)",border:`1.5px solid ${a?"var(--cia-brand-500)":"var(--cia-border-2)"}`,background:a?"var(--cia-bg-tint)":"var(--cia-bg-elev)",color:a?"var(--cia-brand-500)":"var(--cia-text-2)",fontFamily:"var(--cia-font-sans)",fontSize:13.5,fontWeight:a?600:500,cursor:"pointer",transition:"border-color var(--cia-dur-fast) ease, background var(--cia-dur-fast) ease"},children:e})}function F4({companyName:e,onApplied:a}){const{t:n}=M("onboarding"),s=e.trim()||n("companyFallback"),[i,r]=m.useState([]),[o,l]=m.useState(null),[c,d]=m.useState(!1),u=m.useRef(!1),p=m.useRef(null);return m.useEffect(()=>{p.current?.scrollIntoView({behavior:"smooth"})},[i,o]),m.useEffect(()=>{if(u.current)return;u.current=!0;const f=[];return f.push(setTimeout(()=>{r(x=>[...x,{id:"p1",role:"assistant",text:n("scriptedPreview.q1",{company:s})}]),l([n("scriptedPreview.toneWarm"),n("scriptedPreview.toneProfessional"),n("scriptedPreview.toneFormal")])},500)),f.push(setTimeout(()=>{r(x=>[...x,{id:"p2",role:"user",text:n("scriptedPreview.toneWarm")}]),l(null)},1700)),f.push(setTimeout(()=>{r(x=>[...x,{id:"p3",role:"assistant",text:n("scriptedPreview.confirm")}]),d(!0),a?.()},2900)),()=>f.forEach(clearTimeout)},[s]),t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[t.jsxs("div",{style:{flex:1,overflowY:"auto",padding:20,display:"flex",flexDirection:"column",gap:10},children:[i.length===0&&t.jsx("div",{className:"cia-text-3",style:{fontSize:12.5,textAlign:"center",marginTop:24},children:n("scriptedPreview.emptyHint")}),i.map(f=>t.jsx("div",{style:{display:"flex",justifyContent:f.role==="user"?"flex-end":"flex-start"},children:t.jsx("div",{style:{maxWidth:"85%",padding:"9px 13px",fontSize:13.5,lineHeight:1.55,borderRadius:f.role==="user"?"var(--cia-r-lg) var(--cia-r-lg) var(--cia-r-sm) var(--cia-r-lg)":"var(--cia-r-lg) var(--cia-r-lg) var(--cia-r-lg) var(--cia-r-sm)",background:f.role==="user"?"var(--cia-brand-500)":"var(--cia-bg-soft)",color:f.role==="user"?"#fff":"var(--cia-text)",border:f.role==="user"?"none":"1px solid var(--cia-border)"},children:f.text})},f.id)),o&&t.jsx("div",{style:{paddingLeft:2},children:t.jsx(Gl,{actions:o.map(f=>({label:f,instruction:f})),onPick:()=>{}})}),t.jsx("div",{ref:p})]}),t.jsx("div",{style:{padding:"10px 20px 14px",borderTop:"1px solid var(--cia-border)"},children:t.jsx("div",{className:"cia-mono cia-text-4",style:{fontSize:10.5,textAlign:"center"},children:n(c?"scriptedPreview.noConnection":"scriptedPreview.typing")})})]})}const j0=["calls","active"],O4=5e3;function $4(e={}){return{queryKey:j0,queryFn:async()=>(await T.get("/calls/active")).data,refetchInterval:e.refetchInterval??O4,refetchIntervalInBackground:!0,refetchOnWindowFocus:!0}}function q4(e){const a=xe(),n=m.useRef(e);n.current=e,m.useEffect(()=>{const s=ns(),i=()=>{a.invalidateQueries({queryKey:j0})},r=o=>{try{n.current?.(o??{})}catch{}i()};return s.on("call:started",i),s.on("call:ended",r),()=>{s.off("call:started",i),s.off("call:ended",r)}},[a])}function w0(e={}){return q4(e.onEnded),se($4(e))}const ux="https://enlassa.ai",Vc={agendamiento:"agendamiento-cal-com",whatsapp:"whatsapp",whatsappPlantillas:"whatsapp-plantillas",whatsappLlamadas:"whatsapp-llamadas"};function lp(e="",a){const s=(a??Ua.getState().resolved)==="en"?"/docs/en":"/docs";return e?`${ux}${s}/${e}/`:`${ux}${s}/`}function Kc(e=""){const a=Ua(n=>n.resolved);return lp(e,a)}function B4({open:e,onClose:a}){const{t:n}=M("nav"),[s,i]=m.useState(""),[r,o]=m.useState(0),l=m.useRef(null),c=m.useRef(null),d=dt(),u=Pe(w=>w.user),p=rt(w=>w.user),f=rt(w=>w.isActive()),x=!f&&u?.role==="superadmin",h=(()=>{const w=x?Vy:Uy,j=f?p:u,C=w.flatMap(S=>S.items.filter(_=>Ky(j,_)).map(_=>({kind:n("palette.goTo"),label:n(_.labelKey),to:_.to,icon:_.icon}))),N=x?[]:[{kind:n("palette.action"),label:n("palette.createAgent"),to:"/agents/new",icon:oa,permission:"agents.manage"},{kind:n("palette.action"),label:n("palette.openPlayground"),to:"/playground",icon:oa,permission:"playground.use"},{kind:n("palette.action"),label:n("palette.addNumber"),to:"/trunks",icon:oa,permission:"phoneNumbers.manage"}].filter(S=>lt(j,S.permission));return[...C,...N]})(),g=(s.trim()?h.filter(w=>(w.label+" "+w.kind).toLowerCase().includes(s.toLowerCase())):h).slice(0,12);m.useEffect(()=>{if(e){i(""),o(0);const w=setTimeout(()=>l.current?.focus(),30);return()=>clearTimeout(w)}},[e]),m.useEffect(()=>{o(w=>g.length===0?0:Math.min(w,g.length-1))},[g.length]),m.useEffect(()=>{if(!c.current)return;
953c.current.querySelector(`[data-palette-idx="${r}"]`)?.scrollIntoView({block:"nearest"})},[r]);function v(w){if(w.key==="ArrowDown")w.preventDefault(),o(j=>g.length===0?0:(j+1)%g.length);else if(w.key==="ArrowUp")w.preventDefault(),o(j=>g.length===0?0:(j-1+g.length)%g.length);else if(w.key==="Enter"){w.preventDefault();const j=g[r];j&&y(j)}else w.key==="Escape"&&a()}function y(w){d({to:w.to}),a()}const k=xt(w=>w.resolved);return e?t.jsx("div",{className:"cia","data-theme":k,style:{position:"fixed",inset:0,zIndex:60},children:t.jsx("div",{className:"cia-palette-overlay",onMouseDown:w=>{w.target===w.currentTarget&&a()},children:t.jsxs("div",{className:"cia-palette-panel",role:"dialog","aria-modal":"true","aria-label":n("palette.dialogAria"),onClick:w=>w.stopPropagation(),children:[t.jsxs("div",{className:"cia-palette-input-row",children:[t.jsx(Mn,{size:16,"aria-hidden":"true",style:{color:"var(--cia-text-3)",flex:"none"}}),t.jsx("input",{ref:l,className:"cia-palette-input",value:s,onChange:w=>{i(w.target.value),o(0)},onKeyDown:v,placeholder:n("palette.searchPlaceholder"),"aria-label":n("palette.searchAria"),autoComplete:"off",spellCheck:!1}),t.jsx("span",{className:"cia-kbd",children:"esc"})]}),t.jsx("div",{ref:c,className:"cia-palette-list",role:"listbox","aria-label":n("palette.results"),children:g.length>0?g.map((w,j)=>{const C=w.icon??oa;return t.jsxs("button",{className:"cia-palette-item","data-selected":j===r?"true":"false","data-palette-idx":j,role:"option","aria-selected":j===r,onClick:()=>y(w),onMouseEnter:()=>o(j),children:[t.jsx(C,{size:15,"aria-hidden":"true",style:{color:"var(--cia-text-3)",flex:"none"}}),t.jsx("span",{style:{flex:1},children:w.label}),t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:w.kind})]},`${w.kind}-${w.to}`)}):t.jsx("div",{style:{padding:"30px 16px",textAlign:"center",color:"var(--cia-text-3)",fontSize:13,fontFamily:"var(--cia-font-sans)"},children:n("palette.noResults",{q:s})})}),t.jsxs("div",{className:"cia-palette-footer",children:[t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx("span",{className:"cia-kbd",children:"↑"}),t.jsx("span",{className:"cia-kbd",children:"↓"}),t.jsx("span",{style:{marginLeft:4},children:n("palette.navigate")})]}),t.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4},children:[t.jsx("span",{className:"cia-kbd",children:"↵"}),t.jsx("span",{style:{marginLeft:4},children:n("palette.open")})]}),t.jsx("span",{style:{flex:1}}),t.jsx("span",{children:"Enlassa AI · v1.0"})]})]})})}):null}const In={operational:{color:"var(--cia-ok-500)",ink:"var(--cia-ok-ink)",Icon:Nt},degraded:{color:"var(--cia-warn-500)",ink:"var(--cia-warn-ink)",Icon:Tt},maintenance:{color:"var(--cia-brand-500)",ink:"var(--cia-info-ink)",Icon:ih},outage:{color:"var(--cia-bad-500)",ink:"var(--cia-bad-ink)",Icon:cs}};function W4({onClose:e}){const{t:a}=M("status"),n=Ua(l=>l.resolved)==="en"?"en":"es",{data:s,isLoading:i}=se({queryKey:["system-status"],queryFn:async()=>(await T.get("/system-status")).data,refetchInterval:3e4}),r=s?.overall??"operational",o=In[r].Icon;return t.jsx(ot,{open:!0,onClose:e,eyebrow:a("eyebrow"),title:a("title"),maxWidth:460,children:i?t.jsx("div",{style:{display:"grid",placeItems:"center",padding:24},children:t.jsx(je,{className:"animate-spin",size:20})}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 14px",borderRadius:"var(--cia-r)",background:`color-mix(in oklab, ${In[r].color} 10%, transparent)`,border:`1px solid color-mix(in oklab, ${In[r].color} 26%, transparent)`},children:[t.jsx(o,{size:18,style:{color:In[r].color,flex:"none"},"aria-hidden":!0}),t.jsx("span",{style:{fontWeight:600,fontSize:14,color:In[r].ink},children:a(`overall.${r}`)})]}),s?.message?.[n]&&t.jsx("p",{style:{fontSize:13,color:"var(--cia-text-2)",margin:0,lineHeight:1.6},children:s.message[n]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2},children:(s?.components??[]).map(l=>{const c=In[l.status].Icon;return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"9px 4px",borderBottom:"1px solid var(--cia-border)"},children:[t.jsx("span",{style:{fontSize:13.5,flex:1},children:a(`component.${l.key}`)}),t.jsx(c,{size:15,style:{color:In[l.status].color},"aria-hidden":!0}),t.jsx("span",{style:{fontSize:12,color:In[l.status].ink,minWidth:82,textAlign:"right"},children:a(`state.${l.status}`)})]},l.key)})}),s?.updatedAt&&t.jsx("p",{style:{fontSize:11,color:"var(--cia-text-4)",fontFamily:"var(--cia-font-mono)",margin:0},children:a("updatedAt",{time:new Date(s.updatedAt).toLocaleTimeString()})})]})})}const U4=8e3;function V4(){const[e,a]=m.useState(()=>Xu()),[n,s]=m.useState(!1);return m.useEffect(()=>{const i=Pv(a);a(Xu());const r=setTimeout(()=>s(!0),U4);return()=>{i(),clearTimeout(r)}},[]),{connected:e,degraded:n&&!e}}function el({icon:e,label:a,onClick:n,tone:s,disabled:i,soon:r,to:o,search:l}){const{t:c}=M("topbar"),d={display:"flex",alignItems:"center",gap:9,textDecoration:"none"},u={"data-tone":s??void 0,"data-disabled":i||r?"true":void 0},p=t.jsxs(t.Fragment,{children:[t.jsx(e,{size:13,"aria-hidden":"true",style:{flex:"none"}}),t.jsx("span",{style:{flex:1},children:a}),r&&t.jsx("span",{className:"cia-soon-tag",children:c("soon")})]});return o&&!i&&!r?t.jsx(et,{to:o,search:l,className:"cia-menu-item",style:d,...u,onClick:n,children:p}):t.jsx("button",{type:"button",className:"cia-menu-item",style:{width:"100%",textAlign:"left"},...u,onClick:i||r?void 0:n,children:p})}function K4(e){const a=Math.max(0,Math.round((Date.now()-e)/1e3));return a<60?`${a}s`:a<3600?`${Math.round(a/60)}m`:`${Math.round(a/3600)}h`}function Wt({title:e,eyebrow:a,actions:n,titleAs:s="h1"}){const i=s,r=xy(z=>z.toggleMobile),o=Pe(z=>z.user),l=rt(z=>z.user),c=rt(z=>z.orgName),d=rt(z=>z.isActive()),{t:u}=M("topbar"),p=d?l:o,f=(p?.name||"U").split(" ").map(z=>z[0]).slice(0,2).join("").toUpperCase(),{data:x}=se({queryKey:["auth-profile"],queryFn:async()=>(await T.get("/auth/profile")).data,enabled:!d,staleTime:6e4}),h=d?null:x?.avatar??null,b=(()=>
953{if(!p)return"";const z=p.role.toUpperCase();return d?`${z} · ${c||u("organization")}`:p.role==="superadmin"?"SUPERADMIN":z})(),g=!d&&o?.role==="superadmin",[v,y]=m.useState(!1),[k,w]=m.useState(!1),[j,C]=m.useState(!1),[N,S]=m.useState(!1),_=m.useRef(null),R=dt(),A=Al(z=>z.alerts),E=Al(z=>z.markAllRead),I=Al(z=>z.clear),P=A.filter(z=>!z.read).length,O=V4();m.useEffect(()=>{if(!v)return;function z(D){_.current&&!_.current.contains(D.target)&&y(!1)}return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[v]),m.useEffect(()=>{if(!v)return;function z(D){D.key==="Escape"&&y(!1)}return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[v]),m.useEffect(()=>{function z(D){(navigator.platform.toUpperCase().includes("MAC")?D.metaKey&&D.key==="k":D.ctrlKey&&D.key==="k")&&(D.preventDefault(),w(te=>!te))}return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[]);function K(){y(!1),Pe.getState().logout(),window.location.href="/login"}const W=xt(z=>z.resolved),V=xt(z=>z.toggle),U=xt(z=>z.mode),X=xt(z=>z.setMode),ie=Ua(z=>z.resolved),de=Ua(z=>z.toggle),{t:$}=M("common");return t.jsxs(t.Fragment,{children:[t.jsxs("header",{className:"cia cia-topbar","data-theme":W,style:{height:60,flex:"none",borderBottom:"1px solid var(--cia-border)",background:"var(--cia-bg)",display:"flex",alignItems:"center",position:"sticky",top:0,zIndex:30,fontFamily:"var(--cia-font-sans)",color:"var(--cia-text)",boxSizing:"border-box"},children:[t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-icon cia-hamburger",style:{width:36,flex:"none",marginLeft:-8},onClick:()=>r(),"aria-label":u("openMenu"),children:t.jsx(QS,{size:18})}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0,flex:1,minWidth:0},children:[a&&t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:1},children:a}),t.jsx(i,{style:{margin:0,fontSize:18,fontWeight:600,letterSpacing:"var(--cia-tracking-tighter)",color:"var(--cia-text)",lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:e})]}),t.jsxs("button",{type:"button",className:"cia-search-btn",onClick:()=>w(!0),"aria-label":u("openCommandSearch"),"aria-keyshortcuts":"Meta+k Control+k",children:[t.jsx(Mn,{size:14,"aria-hidden":"true",style:{flex:"none"}}),t.jsx("span",{className:"cia-search-btn-text",style:{flex:1,textAlign:"left"},children:u("searchPlaceholder")}),t.jsxs("span",{className:"cia-search-btn-kbds",children:[t.jsx("span",{className:"cia-kbd",children:"⌘"}),t.jsx("span",{className:"cia-kbd",children:"K"})]})]}),n&&t.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,flex:"none"},children:n}),O.degraded&&t.jsxs("span",{title:u("liveChannelDownHelp"),"aria-label":u("liveChannelDownHelp"),className:"cia-mono",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10.5,color:"var(--cia-warn-ink)",padding:"3px 8px",borderRadius:999,border:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)",whiteSpace:"nowrap"},children:[t.jsx(N2,{size:12,"aria-hidden":"true"}),u("liveChannelDown")]}),t.jsx(Or,{ariaLabel:u("liveMonitoring"),placement:"bottom-start",width:340,open:j,onOpenChange:z=>{C(z),z&&E()},triggerClassName:"cia-btn cia-btn-ghost cia-btn-icon",triggerLabel:P?u("notificationsUnread",{count:P}):u("notifications"),trigger:t.jsxs(t.Fragment,{children:[t.jsx(Qb,{size:16,"aria-hidden":"true"}),P>0&&t.jsx("span",{className:"cia-iconbtn-badge","data-shape":"square","data-size":"md","aria-hidden":"true",children:P>9?"9+":P})]}),children:({close:z})=>t.jsxs("div",{role:"menu","aria-label":u("liveMonitoring"),style:{margin:-10,maxHeight:420,overflowY:"auto"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--cia-border)",position:"sticky",top:0,background:"var(--cia-bg-elev)"},children:[t.jsx("span",{className:"cia-eyebrow",style:{flex:1},children:u("liveMonitoring")}),A.length>0&&t.jsx("button",{type:"button",onClick:I,style:{background:"none",border:0,cursor:"pointer",fontSize:11,color:"var(--cia-text-3)"},children:u("clear")})]}),A.length===0?t.jsx("div",{style:{padding:20,fontSize:12.5,color:"var(--cia-text-3)",textAlign:"center",lineHeight:1.5},children:u("noAlerts")}):A.map(D=>{const F=D.sentimentLabel==="positive",G=F?"var(--cia-ok-500)":"var(--cia-bad-500)";return t.jsxs("button",{type:"button",role:"menuitem",className:"cia-row-hover",onClick:()=>{z(),R({to:"/live"})}
953,style:{display:"flex",alignItems:"flex-start",gap:10,width:"100%",textAlign:"left",background:"none",border:0,borderBottom:"1px solid var(--cia-border)",padding:"10px 14px",cursor:"pointer",font:"inherit",color:"var(--cia-text)"},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:999,background:G,flex:"none",marginTop:5}}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{fontSize:12.5,fontWeight:500},children:[u(F?"positiveSentiment":"negativeSentiment")," · ",D.agentName]}),t.jsx("div",{style:{fontSize:11,color:"var(--cia-text-3)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.intent||D.number})]}),t.jsx("span",{className:"cia-mono",style:{fontSize:10,color:"var(--cia-text-3)",flex:"none",marginTop:2},children:K4(D.receivedAt)})]},D.id)})]})}),t.jsx(Ra,{label:u("documentation"),children:t.jsx("a",{href:lp("",ie),target:"_blank",rel:"noopener noreferrer",className:"cia-btn cia-btn-ghost cia-btn-icon","aria-label":u("documentation"),children:t.jsx(ua,{size:16,"aria-hidden":"true"})})}),t.jsx(Ra,{label:$(ie==="en"?"switchToSpanish":"switchToEnglish"),children:t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-icon",onClick:de,"aria-label":$(ie==="en"?"switchToSpanish":"switchToEnglish"),style:{fontSize:12,fontWeight:700,letterSpacing:"0.02em"},children:ie==="en"?"EN":"ES"})}),t.jsx(Ra,{label:u(W==="dark"?"lightTheme":"darkTheme"),children:t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-icon",onClick:V,"aria-label":u(W==="dark"?"switchToLight":"switchToDark"),children:W==="dark"?t.jsx(Zr,{size:16,"aria-hidden":"true"}):t.jsx(Hr,{size:16,"aria-hidden":"true"})})}),t.jsxs("div",{ref:_,style:{position:"relative",flex:"none"},children:[t.jsxs("button",{type:"button",className:"cia-user-pill","data-open":v?"true":"false",onClick:()=>y(z=>!z),"aria-haspopup":"menu","aria-expanded":v,"aria-label":u("userMenuFor",{name:p?.name??u("user")}),children:[t.jsx("span",{className:"cia-user-pill-name",children:p?.name}),t.jsx("span",{className:"cia-avatar","aria-hidden":"true",style:h?{overflow:"hidden",padding:0}:void 0,children:h?t.jsx("img",{src:h,alt:"",style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:"inherit"}}):f})]}),v&&t.jsxs("div",{className:"cia-user-menu",role:"menu","aria-label":u("userOptions"),children:[t.jsxs("div",{className:"cia-user-menu-header",children:[t.jsx("div",{style:{fontSize:13,fontWeight:500,color:"var(--cia-text)",letterSpacing:"var(--cia-tracking-tight)"},children:p?.name}),t.jsx("div",{className:"cia-mono cia-text-3",style:{fontSize:11,marginTop:2},children:p?.email}),b&&t.jsx("div",{className:"cia-mono cia-text-3",style:{fontSize:10,marginTop:4,letterSpacing:"0.04em"},children:b})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"2px 12px 10px"},children:[t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10,letterSpacing:"0.04em"},children:u("theme.label")}),t.jsx(Yn,{ariaLabel:u("theme.ariaLabel"),value:U,onChange:X,options:[{value:"light",icon:t.jsx(Zr,{size:14,"aria-hidden":"true"}),ariaLabel:u("theme.light"),title:u("theme.light")},{value:"system",icon:t.jsx(JS,{size:14,"aria-hidden":"true"}),ariaLabel:u("theme.system"),title:u("theme.system")},{value:"dark",icon:t.jsx(Hr,{size:14,"aria-hidden":"true"}),ariaLabel:u("theme.dark"),title:u("theme.dark")}]})]}),t.jsx("div",{role:"separator",style:{height:1,background:"var(--cia-border)",margin:"0 0 4px"}}),!g&&t.jsx(el,{icon:uy,label:u("settings"),to:"/settings",search:{s:"profile"},onClick:()=>y(!1)}),t.jsx(el,{icon:ua,label:u("documentation"),onClick:()=>{window.open(lp("",ie),"_blank","noopener,noreferrer"),y(!1)}}),t.jsx(el,{icon:Hp,label:u("systemStatus"),onClick:()=>{S(!0),y(!1)}}),t.jsx("div",{role:"separator",style:{height:1,background:"var(--cia-border)",margin:"4px 0"}}),t.jsx(el,{icon:eh,label:u("logout"),tone:"danger",onClick:K})]})]})]}),t.jsx(B4,{open:k,onClose:()=>w(!1)}),N&&t.jsx(W4,{onClose:()=>S(!1)})]})}const H4=["completed","failed","no_answer"],Q4=90;function la(e){if(e.endedAt)return!1;const a=e.status??"";return!!a&&!H4.includes(a)}function zh(e){return la(e)&&e.status!=="connected"&&!e.answeredAt}function G4(e,a){if(!zh(e)||!e.startedAt)return null;const n=Date.parse(e.startedAt);return Number.isFinite(n)?Math.max(0,Math.floor((a-n)/1e3)):null}function zr(e,a,n=Q4){const s=G4(e,a);return s!==null&&s>n}function zl(e,a){if(!la(e))return Math.max(0,Math.round(e.durationSeconds??0));const n=e.answeredAt||e.startedAt;if(!n)return 0;const s=Date.parse(n);return Number.isFinite(s)?Math.max(0,Math.floor((a-s)/1e3)):0}function Z4(e){return!!e&&e.some(a=>la(a))}function Y4(e,a={}){return{...e,status:"completed",endedAt:a.endedAt??e.endedAt??new Date().toISOString(),endReason:a.endReason??e.endReason??null,durationSeconds:a.durationSeconds??e.durationSeconds??null}}function Dh(e){if(la(e))return null;if(e.outcome)return e.outcome;if(e.answeredAt)return"answered";const a=(e.endReason||"").toLowerCase(),n={dial_no_answer:"no_answer",participant_timeout:"no_answer",dial_busy:"busy",dial_rejected:"rejected",carrier_failure:"failed",media_failure:"failed",agent_never_joined:"failed",voicemail:"voicemail"};return n[a]?n[a]:/(busy|486|engaged)/.test(a)?"busy":/(reject|decline|forbidden|603|607|403)/.test(a)?"rejected":/(invalid|unallocated|not.?found|congestion|404|480|5\d\d)/.test(a)?"failed":a?"no_answer":null}function X4(e){const a=Dh(e);return a!==null&&a!=="answered"&&a!=="voicemail"}const J4=["caller_hangup","agent_closed","operator_hangup","transfer_completed","user_initiated","max_call_duration"],e3=["dial_no_answer","dial_busy","dial_rejected","rejected","voicemail","silence_timeout","participant_timeout","web_session_abandoned","reconciled_stuck","room_deleted"],t3=["carrier_failure","media_failure","agent_never_joined","
953no_agent","concurrency_limit","portal_error","error"];function k0(e){if(la(e))return"ok";const a=e.endReason||"";return J4.includes(a)?"ok":e3.includes(a)?"warn":t3.includes(a)?"bad":"neutral"}function Ih(e){return la(e)?e.status==="connected"?{ns:"calls",key:"status.live"}:{ns:"calls",key:"status.dialing"}:e.endReason?{ns:"format",key:`endReason.${e.endReason}`}:{ns:"calls",key:`status.${e.status||"created"}`}}function a3(e,a,n){return zr(e,n)?"stalled":zh(e)?"not_started":a==="live"?"silent":"fallback"}const N0=()=>typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function n3(){const e=dt(),{t:a}=M("dashboard"),n=xt(_=>_.resolved),{can:s}=tt(),i=Pe(_=>_.user),r=rt(_=>_.user),c=(rt(_=>_.isActive())?r:i)?.name?.split(" ")[0]||"",d=se({queryKey:["reports","hourly-volume"],queryFn:async()=>(await T.get("/reports/hourly-volume?hours=48")).data}),u=se({queryKey:["reports","daily-volume",84],queryFn:async()=>(await T.get("/reports/daily-volume?days=84")).data}),p=se({queryKey:["reports","top-agents"],queryFn:async()=>(await T.get("/reports/top-agents?days=1")).data}),f=w0(),x=se({queryKey:["agents"],queryFn:async()=>(await T.get("/agents")).data}),h=se({queryKey:["plan-usage"],queryFn:async()=>(await T.get("/organizations/me/plan-usage")).data,staleTime:6e4}),b=se({queryKey:["calls","recent",12],queryFn:async()=>(await T.get("/calls?limit=12")).data}),g=(()=>{const _=new Date().getHours();return _<12?a("greeting.morning"):_<19?a("greeting.afternoon"):a("greeting.evening")})(),[v,y]=m.useState(()=>new Date);m.useEffect(()=>{const _=setInterval(()=>y(new Date),6e4);return()=>clearInterval(_)},[]);const k=-Math.round(v.getTimezoneOffset()/60),w=`GMT${k>=0?"+":""}${k}`,j=(()=>{const _=v.toLocaleDateString(Te(),{weekday:"long",day:"numeric",month:"long"});return _.charAt(0).toUpperCase()+_.slice(1)})(),C=v.toLocaleTimeString(Te(),{hour:"2-digit",minute:"2-digit",hour12:!1}),N=x.data?.length??0,S=f.data?.length??0;return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:a("topbar.eyebrow"),title:a("topbar.title")}),t.jsx("main",{className:"cia","data-theme":n,style:{flex:1,overflowY:"auto",background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-col cia-gap-6",style:{padding:"24px 28px 40px",fontFamily:"var(--cia-font-sans)"},children:[t.jsxs("div",{className:"cia-row cia-gap-4",style:{alignItems:"flex-start"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("h2",{style:{margin:0,fontSize:22,fontWeight:600,letterSpacing:"-0.025em",color:"var(--cia-text)"},children:[g,", ",c,"."," ",t.jsx("span",{style:{color:"var(--cia-text-3)"},children:a("greeting.subtitle")})]}),t.jsxs("p",{className:"cia-text-3",style:{margin:"4px 0 0",fontSize:13.5},children:[j," · ",C," ",w," · ",a("meta.agents",{count:N}),S>0&&t.jsxs(t.Fragment,{children:[", ",a("meta.liveRunning",{n:S})]})]})]}),s("playground.use")&&t.jsxs(et,{to:"/playground",className:"cia-btn cia-btn-outline",children:[t.jsx(rn,{size:14})," ",a("actions.playground")]}),s("agents.manage")&&t.jsxs(et,{to:"/agents/new",className:"cia-btn cia-btn-cta",children:[t.jsx(Fe,{size:14})," ",a("actions.newAgent")]})]}),t.jsx(s3,{hourly:d.data,daily:u.data,planUsage:h.data,loading:d.isLoading}),t.jsxs("div",{className:"cia-dash-split",children:[t.jsx(r3,{calls:f.data,loading:f.isLoading,onOpen:_=>e({to:"/live",search:{call:_}})}),t.jsx(c3,{rows:p.data,agents:x.data,loading:p.isLoading})]}),t.jsxs("div",{className:"cia-dash-split",children:[t.jsx(d3,{hourly:d.data,daily:u.data,loading:d.isLoading}),t.jsx(h3,{calls:b.data?.items,loading:b.isLoading})]})]})})]})}function s3({hourly:e,daily:a,planUsage:n,loading:s}){const{t:i}=M("dashboard"),r=m.useRef(null);m.useEffect(()=>{const x=r.current;if(!x)return;if(N0()){x.classList.add("in");return}const h=requestAnimationFrame(()=>x.classList.add("in"));return()=>cancelAnimationFrame(h)},[s]);const o=m.useMemo(()=>f3(e,i),[e,i]),l=m.useMemo(()=>b3(a),[a]),c=m.useMemo(()=>(a||[]).map(x=>Math.round(x.seconds/60)),[a]);if(s)return t.jsx("div",{className:"cia-grid-4",children:[0,1,2,3].map(x=>t.jsxs("div",{className:"cia-card cia-card-pad",children:[t.jsx("div",{className:"cia-skeleton",style:{height:11,width:"55%"}}
953),t.jsx("div",{className:"cia-skeleton",style:{height:28,width:"40%",marginTop:14}}),t.jsx("div",{className:"cia-skeleton",style:{height:10,width:"70%",marginTop:12}})]},x))});const d=n?.plan,u=n?.usage,p=u&&u.includedMinutes>0?Math.round(u.usedMinutes/u.includedMinutes*100):0,f=u&&u.overageMinutes>0?"bad":p>=80?"warn":"success";return t.jsxs("div",{className:"cia-grid-4 cia-stagger",ref:r,children:[t.jsx(tl,{i:0,label:i("kpi.callsToday"),value:o.callsToday,accent:"brand",delta:o.callsDelta,spark:o.callsSpark}),t.jsx(tl,{i:1,label:i("kpi.minutesSpoken"),value:o.minutesToday,accent:"cta",sub:o.avgPerCall,delta:o.minutesDelta,spark:o.minutesSpark}),t.jsx(tl,{i:2,label:i("kpi.successRate"),value:o.successToday,suffix:o.successToday==="—"?"":"%",accent:"ok",sub:i("kpi.byCompleted"),delta:o.successDelta,spark:l}),t.jsx(tl,{i:3,label:i("kpi.planUsage"),value:d&&u?u.usedMinutes:"—",suffix:d&&u?i("kpi.minSuffix"):"",accent:"sky",sub:d&&u?i("kpi.planSub",{minutes:u.includedMinutes.toLocaleString(Te())}):i("kpi.planNotConfigured"),badge:d&&u?{text:i("kpi.planBadge",{pct:p}),tone:f}:void 0,spark:d?c:void 0})]})}function tl({i:e,label:a,value:n,suffix:s="",sub:i,accent:r,delta:o,badge:l,spark:c}){return t.jsxs("div",{className:"cia-card cia-card-pad cia-stagger-item",style:{"--i":e},children:[t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",marginBottom:10},children:[t.jsx("span",{className:"cia-eyebrow",children:a}),l?t.jsx("span",{className:`cia-badge cia-badge-${l.tone}`,style:{height:18,fontSize:10.5,padding:"0 6px"},children:l.text}):o?t.jsxs("span",{className:`cia-badge ${o.up?"cia-badge-success":"cia-badge-bad"}`,style:{height:18,fontSize:10.5,padding:"0 6px"},children:[o.up?t.jsx(Hg,{size:10}):t.jsx(Vb,{size:10}),o.text]}):null]}),t.jsxs("div",{className:"cia-row",style:{alignItems:"flex-end",justifyContent:"space-between",gap:8},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{className:"cia-kpi-value",children:t.jsx(i3,{value:n,suffix:s})}),i&&t.jsx("div",{className:"cia-mono cia-text-3",style:{fontSize:10.5,marginTop:6},children:i})]}),c&&c.length>1&&t.jsx(I5,{data:c,color:Th(r),width:88,height:36})]})]})}function i3({value:e,suffix:a=""}){const n=m.useRef(null);return m.useEffect(()=>{const s=n.current;if(!s)return;if(typeof e!="number"){s.textContent=String(e);return}if(N0()){s.textContent=e.toLocaleString(Te());return}const i=1100;let r=null,o=0;const l=c=>{r===null&&(r=c);const d=Math.min(1,(c-r)/i),u=1-Math.pow(1-d,3);s.textContent=Math.round(e*u).toLocaleString(Te()),d<1&&(o=requestAnimationFrame(l))};return o=requestAnimationFrame(l),()=>cancelAnimationFrame(o)},[e]),t.jsxs(t.Fragment,{children:[t.jsx("span",{ref:n,children:typeof e=="number"?"0":e}),a]})}function r3({calls:e,loading:a,onOpen:n}){const{t:s}=M("dashboard"),{can:i}=tt(),r=e?.length??0;return t.jsxs("div",{className:"cia-card cia-card-pad",children:[t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",marginBottom:14},children:[t.jsxs("div",{children:[t.jsx("div",{className:"cia-eyebrow",children:s("active.eyebrow")}),t.jsx("h3",{style:{margin:"4px 0 0",fontSize:15,fontWeight:600,color:"var(--cia-text)"},children:s("active.title")})]}),t.jsxs("div",{className:"cia-row cia-gap-2",children:[r>0&&t.jsxs("span",{className:"cia-badge cia-badge-success",children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{width:5,height:5,color:"var(--cia-ok-500)"}}),s("active.nowCount",{n:r})]}),i("calls.view")&&t.jsx(et,{to:"/live",className:"cia-btn cia-btn-sm cia-btn-outline",children:s("active.viewAll")})]})]}),a?t.jsx("div",{className:"cia-col cia-gap-3",style:{paddingTop:4},children:[0,1,2].map(o=>t.jsx("div",{className:"cia-skeleton",style:{height:28}},o))}):r>0?t.jsxs("div",{className:"cia-col",style:{gap:0},children:[t.jsxs("div",{className:"cia-row cia-eyebrow",style:{padding:"0 6px 8px",borderBottom:"1px solid var(--cia-border)"},children:[t.jsx("span",{style:{width:22}}),t.jsx("span",{style:{flex:1.4},children:s("active.colAgent")}),t.jsx("span",{style:{flex:1.2},children:s("active.colNumber")}),t.jsx("span",{style:{flex:.8},children:s("active.colDuration")}),t.jsx("span",{style:{width:80,textAlign:"right"},children:s("active.colAudio")}
953)]}),e.map(o=>t.jsx(o3,{call:o,onOpen:n},o.id))]}):t.jsxs("div",{style:{padding:"34px 0",textAlign:"center"},children:[t.jsx("div",{className:"cia-text-3",style:{fontSize:13},children:s("active.empty")}),i("playground.use")&&t.jsx(et,{to:"/playground",style:{fontSize:13,color:"var(--cia-brand-500)",textDecoration:"none",marginTop:8,display:"inline-block"},children:s("active.tryTest")})]})]})}function o3({call:e,onOpen:a}){const n=la(e),[s,i]=m.useState(()=>Fd(e,Date.now()));m.useEffect(()=>{if(i(Fd(e,Date.now())),!n)return;const o=setInterval(()=>i(Fd(e,Date.now())),1e3);return()=>clearInterval(o)},[e,n]);const r=e.direction==="outbound";return t.jsxs("div",{className:"cia-row",onClick:()=>a(e.id),style:{padding:"12px 6px",borderBottom:"1px solid var(--cia-border)",fontSize:13,cursor:"pointer"},children:[t.jsx("span",{style:{width:22,display:"flex",alignItems:"center"},children:r?t.jsx(ka,{size:14,style:{color:"var(--cia-cta-500)"}}):t.jsx(yn,{size:14,style:{color:"var(--cia-brand-500)"}})}),t.jsx("div",{style:{flex:1.4,minWidth:0,color:"var(--cia-text)"},className:"cia-truncate",children:e.agent?.name||"—"}),t.jsx("div",{style:{flex:1.2},className:"cia-mono cia-text-2",children:e.callerNumber||"—"}),t.jsx("div",{style:{flex:.8},className:"cia-mono cia-text-2",children:s}),t.jsxs("div",{style:{width:80},className:"cia-row",children:[t.jsx("span",{style:{flex:1}}),t.jsx(l3,{})]})]})}function l3(){return t.jsx("div",{className:"cia-row",style:{gap:2,height:16,alignItems:"center"},children:[0,1,2,3,4].map(e=>t.jsx("span",{className:"cia-wbar",style:{height:"100%",background:"var(--cia-ok-500)",animationDelay:`${e*60}ms`,animationDuration:`${.5+e%4*.1}s`}},e))})}function c3({rows:e,agents:a,loading:n}){const{t:s}=M("dashboard"),{can:i}=tt(),r=(a||[]).slice(0,4).map(l=>({agentId:l.id,name:l.name,language:l.language,calls:null})),o=e&&e.length>0?e:r;return t.jsxs("div",{className:"cia-card cia-card-pad",children:[t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",marginBottom:14},children:[t.jsxs("div",{children:[t.jsx("div",{className:"cia-eyebrow",children:s("topAgents.eyebrow")}),t.jsx("h3",{style:{margin:"4px 0 0",fontSize:15,fontWeight:600,color:"var(--cia-text)"},children:s("topAgents.title")})]}),i("agents.view")&&t.jsx(et,{to:"/agents",className:"cia-btn cia-btn-sm cia-btn-outline",children:s("topAgents.viewAll")})]}),n?t.jsx("div",{className:"cia-col cia-gap-2",children:[0,1,2,3].map(l=>t.jsx("div",{className:"cia-skeleton",style:{height:52,borderRadius:8}},l))}):o.length>0?t.jsxs("div",{className:"cia-col cia-gap-2",children:[o.map(l=>t.jsxs(et,{to:"/agents/$agentId",params:{agentId:l.agentId},className:"cia-row cia-gap-3",style:{padding:"10px 12px",border:"1px solid var(--cia-border)",borderRadius:8,textDecoration:"none",color:"inherit"},children:[t.jsx(ss,{id:l.agentId}),t.jsxs("div",{className:"cia-col",style:{flex:1,minWidth:0,gap:1},children:[t.jsx("span",{style:{fontSize:13,fontWeight:500,color:"var(--cia-text)"},className:"cia-truncate",children:l.name||s("agentFallback")}),t.jsxs("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:[to(l.language),l.calls!=null?` · ${s("topAgents.callsToday",{n:l.calls.toLocaleString(Te())})}`:""]})]}),t.jsx(nn,{size:15,style:{color:"var(--cia-text-4)",flex:"none"}})]},l.agentId)),e&&e.length===0&&t.jsx("div",{className:"cia-text-4",style:{fontSize:11,textAlign:"center",marginTop:2},children:s("topAgents.noCallsFallback")})]}):t.jsx("div",{className:"cia-text-3",style:{fontSize:13,textAlign:"center",padding:"24px 0"},children:s("topAgents.empty")})]})}function d3({hourly:e,daily:a,loading:n}){const{t:s}=M("dashboard"),[i,r]=m.useState("hour"),o=s(i==="hour"?"volume.range.hour":i==="day"?"volume.range.day":"volume.range.week");return t.jsxs("div",{className:"cia-card cia-card-pad",children:[t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",marginBottom:18},children:[t.jsxs("div",{children:[t.jsx("div",{className:"cia-eyebrow",children:o}),t.jsx("h3",{style:{margin:"4px 0 0",fontSize:15,fontWeight:600,color:"var(--cia-text)"}
953,children:s("volume.title")})]}),t.jsx("div",{className:"cia-toggle",children:["hour","day","week"].map(l=>t.jsx("button",{onClick:()=>r(l),className:`cia-toggle-btn ${i===l?"cia-toggle-btn-active":""}`,children:s(l==="hour"?"volume.toggle.hour":l==="day"?"volume.toggle.day":"volume.toggle.week")},l))})]}),n?t.jsx("div",{className:"cia-skeleton",style:{height:180,borderRadius:8}}):i==="hour"?t.jsx(u3,{hourly:e||[]}):t.jsx(p3,{daily:a||[],view:i})]})}function u3({hourly:e}){const{t:a}=M("dashboard"),n=m.useMemo(()=>m3(e),[e]),s=720,i=180,r=Math.max(1,...n.map(u=>u.calls))*1.1,o=(s-30)/n.length,l=n.length-1,c=n.some(u=>u.web>0),d=n.reduce((u,p)=>({inbound:u.inbound+p.inbound,outbound:u.outbound+p.outbound,completed:u.completed+p.completed,drops:u.drops+p.drops,calls:u.calls+p.calls}),{inbound:0,outbound:0,completed:0,drops:0,calls:0});return d.calls===0?t.jsx(S0,{}):t.jsxs(t.Fragment,{children:[t.jsxs("svg",{viewBox:`0 0 ${s} ${i}`,style:{width:"100%",display:"block"},children:[[0,.25,.5,.75,1].map(u=>t.jsxs("g",{children:[t.jsx("line",{x1:"30",y1:i-28-(i-50)*u,x2:s,y2:i-28-(i-50)*u,stroke:"var(--cia-border)",strokeDasharray:"2 4"}),t.jsx("text",{x:"0",y:i-24-(i-50)*u,fontSize:"10",fontFamily:"var(--cia-font-mono)",fill:"var(--cia-text-4)",children:Math.round(r*u)})]},u)),n.map((u,p)=>{const f=30+p*o+2,x=o-4,h=(i-50)/r,b=u.inbound*h,g=u.outbound*h,v=u.web*h;let y=i-28;const k=[];return b>0&&(y-=b,k.push(t.jsx("rect",{x:f,y,width:x,height:b,fill:"var(--cia-brand-500)",rx:"1.5"},"in"))),g>0&&(y-=g,k.push(t.jsx("rect",{x:f,y,width:x,height:g,fill:"var(--cia-cta-500)",rx:"1.5"},"out"))),v>0&&(y-=v,k.push(t.jsx("rect",{x:f,y,width:x,height:v,fill:"var(--cia-sky-500)",rx:"1.5"},"web"))),t.jsx("g",{children:k},p)}),n.map((u,p)=>p%6===0?t.jsxs("text",{x:30+p*o+(o-4)/2,y:i-10,fontSize:"10",fontFamily:"var(--cia-font-mono)",fill:"var(--cia-text-4)",textAnchor:"middle",children:[String(u.localHour).padStart(2,"0"),":00"]},p):null),t.jsx("line",{x1:30+l*o+(o-4)/2,y1:"10",x2:30+l*o+(o-4)/2,y2:i-28,stroke:"var(--cia-ok-500)",strokeWidth:"1.5",strokeDasharray:"3 3"}),t.jsx("text",{x:30+l*o-4,y:"16",fontSize:"9.5",fontFamily:"var(--cia-font-mono)",fill:"var(--cia-ok-500)",textAnchor:"end",style:{letterSpacing:"0.04em"},children:a("volume.now")})]}),t.jsxs("div",{className:"cia-row cia-gap-6",style:{marginTop:14,fontSize:12,flexWrap:"wrap"},children:[t.jsx(Wn,{color:"var(--cia-brand-500)",label:a("volume.legend.inbound"),value:d.inbound}),t.jsx(Wn,{color:"var(--cia-cta-500)",label:a("volume.legend.outbound"),value:d.outbound}),c&&t.jsx(Wn,{color:"var(--cia-sky-500)",label:a("volume.legend.web"),value:n.reduce((u,p)=>u+p.web,0)}),t.jsx(Wn,{color:"var(--cia-ok-500)",label:a("volume.legend.completed"),value:d.completed}),t.jsx(Wn,{color:"var(--cia-bad-500)",label:a("volume.legend.drops"),value:d.drops})]})]})}function p3({daily:e,view:a}){const{t:n}=M("dashboard"),s=m.useMemo(()=>a==="day"?Lh(e,14):y3(e,12),[e,a]),i=720,r=180,o=Math.max(1,...s.map(u=>u.calls))*1.1,l=(i-30)/s.length,c=s.reduce((u,p)=>({calls:u.calls+p.calls,completed:u.completed+p.completed,drops:u.drops+p.drops}),{calls:0,completed:0,drops:0});if(c.calls===0)return t.jsx(S0,{});const d=Math.max(1,Math.floor(s.length/5));return t.jsxs(t.Fragment,{children:[t.jsxs("svg",{viewBox:`0 0 ${i} ${r}`,style:{width:"100%",display:"block"},children:[[0,.25,.5,.75,1].map(u=>t.jsxs("g",{children:[t.jsx("line",{x1:"30",y1:r-28-(r-50)*u,x2:i,y2:r-28-(r-50)*u,stroke:"var(--cia-border)",strokeDasharray:"2 4"}),t.jsx("text",{x:"0",y:r-24-(r-50)*u,fontSize:"10",fontFamily:"var(--cia-font-mono)",fill:"var(--cia-text-4)",children:Math.round(o*u)})]},u)),s.map((u,p)=>{const f=30+p*l+2,x=u.calls/o*(r-50);return t.jsx("rect",{x:f,y:r-28-x,width:l-4,height:x,fill:"var(--cia-brand-500)",rx:"1.5"},p)}),s.map((u,p)=>p%d===0?t.jsx("text",{x:30+p*l+(l-4)/2,y:r-10,fontSize:"10",fontFamily:"var(--cia-font-mono)",fill:"var(--cia-text-4)",textAnchor:"middle",children:u.label},p):null)]}),t.jsxs("div",{className:"cia-row cia-gap-6",style:{marginTop:14,fontSize:12,flexWrap:"wrap"},children:[t.jsx(Wn,{color:"var(--cia-brand-500)",label:n("volume.legend.calls"),value:c.calls}),t.jsx(Wn,{color:"var(--cia-ok-500)",label:n("volume.legend.completed"),value:c.completed}),t.jsx(Wn,{color:"var(--cia-bad-500)",label:n("volume.legend.drops"),value:c.drops})]})]})}function S0(){const{t:e}=M("dashboard");return t.jsx("div",{className:"cia-text-3",style:{height:180,display:"flex",alignItems:"center",justifyContent:"center",fontSize:13},children:e("volume.empty")})}function Wn({color:e,label:a,value:n}){return t.jsxs("div",{className:"cia-row cia-gap-2",children:[t.jsx("span",{style:{width:10,height:10,borderRadius:2,background:e,flex:"none"}}),t.jsx("span",{className:"cia-text-2",children:a}),t.jsx("span",{className:"cia-mono",style:{color:"var(--cia-text)",fontWeight:500}
953,children:n.toLocaleString(Te())})]})}function h3({calls:e,loading:a}){const{t:n}=M("dashboard"),s=m.useMemo(()=>(e||[]).map(i=>v3(i,n)).slice(0,6),[e,n]);return t.jsxs("div",{className:"cia-card cia-card-pad",children:[t.jsx("div",{className:"cia-row",style:{justifyContent:"space-between",marginBottom:14},children:t.jsxs("div",{children:[t.jsx("div",{className:"cia-eyebrow",children:n("events.eyebrow")}),t.jsx("h3",{style:{margin:"4px 0 0",fontSize:15,fontWeight:600,color:"var(--cia-text)"},children:n("events.title")})]})}),a?t.jsx("div",{className:"cia-col cia-gap-3",children:[0,1,2,3].map(i=>t.jsx("div",{className:"cia-skeleton",style:{height:30}},i))}):s.length>0?t.jsx("div",{className:"cia-col cia-gap-2",children:s.map((i,r)=>t.jsxs("div",{className:"cia-row cia-gap-3",style:{alignItems:"flex-start",padding:"8px 0"},children:[t.jsx("div",{className:"cia-event-icon",style:{background:`color-mix(in oklab, var(--cia-${i.tone}-500) 13%, transparent)`,color:`var(--cia-${i.tone}-500)`},children:t.jsx(i.Icon,{size:13})}),t.jsxs("div",{className:"cia-col",style:{flex:1,gap:1,minWidth:0},children:[t.jsx("span",{style:{fontSize:13,lineHeight:1.35,color:"var(--cia-text)"},children:i.title}),t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:i.when})]})]},r))}):t.jsx("div",{className:"cia-text-3",style:{fontSize:13,textAlign:"center",padding:"24px 0"},children:n("events.empty")})]})}function Fd(e,a){const n=zl(e,a);return`${String(Math.floor(n/60)).padStart(2,"0")}:${String(n%60).padStart(2,"0")}`}function m3(e){const a=new Map;for(const r of e)a.set(new Date(r.hour).getTime(),r);const n=[],s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours());for(let r=23;r>=0;r--){const o=new Date(i.getTime()-r*36e5),l=a.get(o.getTime());n.push({localHour:o.getHours(),calls:l?.calls??0,inbound:l?.inbound??0,outbound:l?.outbound??0,web:l?.web??0,completed:l?.completed??0,drops:l?.drops??0})}return n}function f3(e,a){const n={callsToday:0,minutesToday:0,successToday:"—",avgPerCall:"—",callsDelta:null,minutesDelta:null,successDelta:null,callsSpark:[],minutesSpark:[]};if(!e)return n;const s=new Map;for(const w of e)s.set(new Date(w.hour).getTime(),w);const i=new Date,r=new Date(i.getFullYear(),i.getMonth(),i.getDate()).getTime(),o=i.getHours();let l=0,c=0,d=0,u=0,p=0,f=0,x=0,h=0;const b=[],g=[];for(let w=0;w<=o;w++){const j=r+w*36e5,C=r-864e5+w*36e5,N=s.get(j),S=s.get(C);l+=N?.calls??0,c+=N?.seconds??0,d+=N?.completed??0,u+=S?.calls??0,p+=S?.seconds??0,f+=S?.completed??0,b.push(N?.calls??0),g.push(Math.round((N?.seconds??0)/60))}for(let w=0;w<24;w++){const j=s.get(r-864e5+w*36e5);x+=j?.calls??0,h+=j?.completed??0}const v=Math.round(c/60),y=l>0?Math.round(d/l*100):null,k=x>0?h/x*100:null;return{callsToday:l,minutesToday:v,successToday:y===null?"—":y,avgPerCall:l>0?a("kpi.avgPerCall",{time:g3(Math.round(c/l))}):"—",callsDelta:px(l,u),minutesDelta:px(v,Math.round(p/60)),successDelta:y!==null&&k!==null?x3(y,k):null,callsSpark:b,minutesSpark:g}}function px(e,a){if(a<=0)return null;const n=Math.round((e-a)/a*100);return{text:`${n>=0?"+":""}${n}%`,up:n>=0}}function x3(e,a){const n=Math.round(e-a);return n===0?null:{text:`${n>=0?"+":""}${n} pts`,up:n>=0}}function g3(e){return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}function b3(e){return e?Lh(e,14).map(a=>a.calls>0?Math.round(a.completed/a.calls*100):0):[]}function Lh(e,a){const n=new Map;for(const o of e)n.set(hx(new Date(o.day)),o);const s=[],i=new Date,r=new Date(i.getFullYear(),i.getMonth(),i.getDate());for(let o=a-1;o>=0;o--){const l=new Date(r.getTime()-o*864e5),c=n.get(hx(l));s.push({label:`${l.getDate()}/${l.getMonth()+1}`,calls:c?.calls??0,completed:c?.completed??0,drops:c?.drops??0})}return s}function y3(e,a){const n=Lh(e,a*7),s=[];for(let i=0;i<a;i++){const r=n.slice(i*7,i*7+7);r.length!==0&&s.push({label:r[0].label,calls:r.reduce((o,l)=>o+l.calls,0),completed:r.reduce((o,l)=>o+l.completed,0),drops:r.reduce((o,l)=>o+l.drops,0)})}return s}function hx(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function v3(e,a){const n=e.agent?.name||a("agentFallback"),s=ts(e.endedAt||e.createdAt);return e.status==="failed"?{tone:"bad",Icon:nt,title:a("events.failed",{who:n}),when:s}:e.status==="no_answer"?{tone:"warn",Icon:Tt,title:a("events.noAnswer",{who:n}),when:s}:e.endReason==="voicemail"?{tone:"warn",Icon:sh,title:a("events.voicemail",{who:n}),when:s}:e.metadata?.transferred?{tone:"brand",Icon:Di,title:a("events.transferred",{who:n}),when:s}:e.analysis?.sentiment?.value==="negative"?{tone:"warn",Icon:Tt,title:a("events.negative",{who:n}),when:s}:e.analysis?.success?.result==="success"?{tone:"ok",Icon:ct,title:a("events.success",{who:n}),when:s}:{tone:"ok",Icon:ct,title:a("events.completed",{who:n}),when:s}}const j3=e=>`${Math.floor(e/60)}:${String(Math.round(e)%60).padStart(2,"0")}`;function C0({archived:e=!1,onEdit:a,onArchive:n,onUnarchive:s}){const{t:i}=M("agentsRoutes"),{can:r}=tt(),o=r("agents.manage"),[l,c]=m.useState(!1),[d,u]=m.useState({top:0,right:0}),p=m.useRef(null),f=m.useRef(null);function x(){if(!p.current)return;const g=p.current.getBoundingClientRect();u({top:g.bottom+4,right:window.innerWidth-g.right}),c(!0)}m.useEffect(()=>{if(!l)return;function g(y){p.current?.contains(y.target)||f.current?.contains(y.target)||c(!1)}const v=()=>c(!1);return document.addEventListener("mousedown",g),window.addEventListener("scroll",v,!0),()=>{document.removeEventListener("mousedown",g),window.removeEventListener("scroll",v,!0)}},[l]);const h=xt(g=>g.resolved),b=l?Ti.createPortal(t.jsx("div",{className:"cia","data-theme":h,children:t.jsxs("div",{ref:f,style:{position:"fixed",top:d.top,right:d.right,width:200,zIndex:9999,background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border-2)",borderRadius:"var(--cia-r)",boxShadow:"var(--cia-sha
953dow-lg)",padding:6,fontFamily:"var(--cia-font-sans)"},children:[t.jsxs("button",{className:"cia-menu-item",onClick:()=>{c(!1),a()},children:[t.jsx(qt,{size:13,style:{flex:"none"}}),i("rowMenu.edit")]}),o&&(e?t.jsxs("button",{className:"cia-menu-item",onClick:()=>{c(!1),s?.()},children:[t.jsx(xS,{size:13,style:{flex:"none"}}),i("rowMenu.unarchive")]}):t.jsxs("button",{className:"cia-menu-item","data-tone":"danger",onClick:()=>{c(!1),n()},children:[t.jsx(bc,{size:13,style:{flex:"none"}}),i("rowMenu.archive")]}))]})}),document.body):null;return t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:p,className:"cia-btn cia-btn-ghost cia-btn-icon",style:{width:28,height:28},onClick:x,title:i("rowMenu.options"),"aria-label":i("rowMenu.options"),"aria-haspopup":"true","aria-expanded":l,children:t.jsx(zi,{size:15})}),b]})}function w3({agent:e,onCancel:a,onConfirm:n,isPending:s}){const{t:i}=M("agentsRoutes"),r=xt(o=>o.resolved);return t.jsx("div",{className:"cia cia-modal-overlay","data-theme":r,onClick:a,children:t.jsxs("div",{className:"cia-modal-card",onClick:o=>o.stopPropagation(),children:[t.jsxs("div",{className:"cia-row cia-gap-3",style:{marginBottom:14},children:[t.jsx("div",{className:"cia-event-icon",style:{width:40,height:40,borderRadius:"var(--cia-r)",background:"color-mix(in oklab, var(--cia-bad-500) 12%, transparent)",color:"var(--cia-bad-500)"},children:t.jsx(bc,{size:18})}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:15,fontWeight:600,color:"var(--cia-text)"},children:i("archiveDialog.title")}),t.jsx("div",{className:"cia-mono cia-text-3",style:{fontSize:11,marginTop:2},children:e.name})]})]}),t.jsxs("p",{className:"cia-text-2",style:{margin:"0 0 20px",fontSize:13.5,lineHeight:1.55},children:[i("archiveDialog.bodyPre")," ",t.jsx("span",{style:{fontWeight:500,color:"var(--cia-text)"},children:e.name})," ",i("archiveDialog.bodyPost")]}),t.jsxs("div",{className:"cia-row cia-gap-3",style:{justifyContent:"flex-end"},children:[t.jsx("button",{className:"cia-btn cia-btn-ghost",onClick:a,disabled:s,children:i("archiveDialog.cancel")}),t.jsxs("button",{className:"cia-btn cia-btn-danger",onClick:n,disabled:s,children:[s&&t.jsx(je,{size:14,style:{animation:"spin 1s linear infinite"}}),i("archiveDialog.confirm")]})]})]})})}function _0({status:e}){const{t:a}=M("agentsRoutes");return e==="archived"?t.jsx("span",{className:"cia-badge",style:{color:"var(--cia-text-4)"},children:a("status.archived")}):e==="published"?t.jsxs("span",{className:"cia-badge cia-badge-success",children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{width:5,height:5,color:"var(--cia-ok-500)"}}),a("status.live")]}):t.jsx("span",{className:"cia-badge",children:a("status.draft")})}function Od({label:e,value:a}){return t.jsxs("div",{className:"cia-col",style:{gap:1},children:[t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:9.5,textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),t.jsx("span",{style:{fontSize:13.5,fontWeight:500,letterSpacing:"-0.01em",color:"var(--cia-text)",fontVariantNumeric:"tabular-nums"},children:a})]})}function k3({agent:e,stat:a,i:n,onEdit:s,onArchive:i,onUnarchive:r}){const{t:o}=M("agentsRoutes"),l=e.greeting?.trim()||o("card.descFallback",{lang:to(e.language)}),c=a&&a.calls>0?`${Math.round(a.completed/a.calls*100)}%`:"—",d=a&&a.calls>0?j3(a.seconds/a.calls):"—";return t.jsxs(et,{to:"/agents/$agentId",params:{agentId:e.id},className:"cia-card cia-card-pad cia-agent-card cia-stagger-item",style:{"--i":n},children:[t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between"},children:[t.jsx(ss,{id:e.id,accent:e.accent,size:36}),t.jsxs("div",{className:"cia-row cia-gap-2",children:[t.jsx(_0,{status:e.status}),t.jsx("span",{onClick:u=>{u.preventDefault(),u.stopPropagation()},children:t.jsx(C0,{archived:e.status==="archived",onEdit:s,onArchive:i,onUnarchive:r})})]})]}),t.jsxs("div",{className:"cia-col",style:{gap:4},children:[t.jsx("h4",{style:{margin:0,fontSize:15,fontWeight:600,letterSpacing:"-0.015em",color:"var(--cia-text)"},children:e.name}),t.jsx("p",{className:"cia-text-3 cia-clamp-2",style:{margin:0,fontSize:12.5,lineHeight:1.5},children:l})]}),t.jsxs("div",{className:"cia-row cia-gap-2",style:{flexWrap:"wrap"},children:[t.jsxs("span",{className:"cia-badge cia-mono",children:[t.jsx(Va,{size:10})," ",to(e.language)]}),t.jsx("span",{className:"cia-badge cia-mono",children:e.llm?.model||"—"})]}),t.jsxs("div",{className:"cia-row",style:{justifyContent:"space-between",paddingTop:12,borderTop:"1px solid var(--cia-border)",marginTop:"auto"},children:[t.jsx(Od,{label:o("card.calls30d"),value:a?a.calls.toLocaleStr
953ing(Te()):"—"}),t.jsx(Od,{label:o("card.average"),value:d}),t.jsx(Od,{label:o("card.success"),value:c})]})]})}const N3=[{id:"cobranza",Icon:$s,accent:"cta"},{id:"leads",Icon:_t,accent:"brand"},{id:"recepcionista",Icon:Tp,accent:"ok"},{id:"nps",Icon:LS,accent:"sky"}];function S3(){const{t:e}=M("agentsRoutes");return t.jsxs("div",{className:"cia-card cia-card-pad",children:[t.jsx("div",{className:"cia-row",style:{justifyContent:"space-between",marginBottom:14},children:t.jsxs("div",{children:[t.jsx("div",{className:"cia-eyebrow",children:e("templates.eyebrow")}),t.jsx("h3",{style:{margin:"4px 0 0",fontSize:15,fontWeight:600,color:"var(--cia-text)"},children:e("templates.title")})]})}),t.jsx("div",{className:"cia-grid-4",style:{gap:12},children:N3.map(a=>t.jsxs(et,{to:"/agents/new",search:{template:a.id},className:"cia-row cia-gap-3 cia-template-card",style:{padding:14,background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r)",textDecoration:"none",color:"inherit"},children:[t.jsx("div",{style:{width:32,height:32,borderRadius:8,flex:"none",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",color:Th(a.accent)},children:t.jsx(a.Icon,{size:15})}),t.jsxs("div",{className:"cia-col",style:{gap:1,minWidth:0,flex:1},children:[t.jsx("span",{className:"cia-truncate",style:{fontSize:13,fontWeight:500,color:"var(--cia-text)"},children:e(`templates.${a.id}.name`)}),t.jsx("span",{className:"cia-text-3 cia-truncate",style:{fontSize:11.5},children:e(`templates.${a.id}.desc`)})]})]},a.id))})]})}function mx({title:e,desc:a}){const{t:n}=M("agentsRoutes"),{can:s}=tt();return t.jsxs("div",{className:"cia-col",style:{alignItems:"center",gap:10,padding:"36px 16px",textAlign:"center"},children:[t.jsx("div",{style:{width:44,height:44,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--cia-bg-tint)",color:"var(--cia-brand-500)"},children:t.jsx(Ft,{size:20})}),t.jsx("div",{style:{fontSize:14,fontWeight:500,color:"var(--cia-text)"},children:e}),t.jsx("div",{className:"cia-text-3",style:{fontSize:12.5,maxWidth:360},children:a}),s("agents.manage")&&t.jsxs(et,{to:"/agents/new",className:"cia-btn cia-btn-cta cia-btn-sm",style:{marginTop:4},children:[t.jsx(Fe,{size:13})," ",n("empty.newAgent")]})]})}function C3({isSaving:e,error:a,onClose:n,onConfirm:s}){const{t:i}=M("agentsRoutes"),r=xt(u=>u.resolved),[o,l]=m.useState(""),c=m.useRef(null);m.useEffect(()=>{requestAnimationFrame(()=>c.current?.focus())},[]);function d(u){u.preventDefault(),o.trim()&&s(o.trim())}return t.jsx("div",{className:"cia cia-modal-overlay","data-theme":r,onClick:n,role:"dialog","aria-modal":"true","aria-label":i("aiModal.ariaLabel"),children:t.jsxs("div",{className:"cia-modal-card",onClick:u=>u.stopPropagation(),style:{maxWidth:440},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:18},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,borderRadius:"var(--cia-r)",background:"color-mix(in oklab, var(--cia-cta-500) 12%, transparent)",flexShrink:0},children:t.jsx(zs,{size:16,style:{color:"var(--cia-cta-500)"},"aria-hidden":!0})}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:15,fontWeight:600,color:"var(--cia-text)"},children:i("aiModal.title")}),t.jsx("div",{className:"cia-text-3",style:{fontSize:12},children:i("aiModal.subtitle")})]})]}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-icon",style:{width:30,height:30},onClick:n,"aria-label":i("aiModal.close"),children:t.jsx(nt,{size:14})})]}),a&&t.jsx("div",{style:{padding:"9px 12px",marginBottom:12,borderRadius:"var(--cia-r-sm)",background:"color-mix(in oklab, var(--cia-bad-500) 10%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-bad-500) 25%, transparent)",color:"var(--cia-bad-500)",fontSize:13},children:a}),t.jsxs("form",{onSubmit:d,style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[t.jsxs("label",{className:"label",htmlFor:"ai-agent-name",children:[i("aiModal.nameLabel"),t.jsx("span",{style:{color:"var(--cia-bad-500)",marginLeft:3},children:"*"})]}),t.jsx("input",{ref:c,id:"ai-agent-name",className:"input",type:"text",placeholder:i("aiModal.namePlaceholder"),value:o,onChange:u=>l(u.target.value),required:!0,maxLength:80}),t.jsx("span",{className:"cia-text-3",style:{fontSize:11.5},children:i("aiModal.nameHint")})]}),t.jsxs("div",{style:{padding:"10px 13px",borderRadius:"var(--cia-r-sm)",background:"color-mix(in oklab, var(--cia-brand-500) 6%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-brand-500) 15%, transparent)",fontSize:12.5,color:"var(--cia-text-2)",lineHeight:1.55},children:[t.jsx("span",{style:{fontWeight:500,color:"var(--cia-text)"},children:i("aiModal.hintTitle")})," ",i("aiModal.hintBody")]}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:10,paddingTop:2},children:[t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost",onClick:n,disabled:e,children:i("aiModal.cancel")}),t.jsx("button",{type:"submit",className:"cia-btn cia-btn-cta cia-btn-sm",disabled:e||!o.trim(),style:{minWidth:120},children:e?t.jsx(je,{size:13,style:{animation:"spin 1s linear infinite"}}):t.jsxs(t.Fragment,{children:[t.jsx(zs,{size:13,"aria-hidden":!0})," ",i("aiModal.continue")]})})]})]})]})})}function _3(){const{t:e}=M("agentsRoutes"),a=xe(),n=dt(),s=xt(E=>E.resolved),{can:i}=tt(),r=i("agents.manage"),[o,l]=m.useState("all"),[c,d]=m.useState("grid"),[u,p]=m.useState(null),[f,x]=m.useState(!1),[h,b]=m.useState(null),{data:g,isLoading:v}=se({queryKey:["agents",{includeArchived:!0}],queryFn:async()=>(await T.get("/agents?includeArchived=true")).data}),y=se({queryKey:["reports","agent-stats",30],queryFn:async()=>(await T.get("/reports/agent-stats?days=30")).data,staleTime:6e4}),k=new Map((y.data||[]).map(E=>[E.agentId,E])),w=oe({mutationFn:async E=>{await T.delete(`/agents/${E}`)},onSuccess:()=>{a.invalidateQueries({queryKey:["agents"]}),p(null)},onError:E=>{console.error("Error archivando agente:",E)}}),j=oe({mutationFn:async E=>{await T.patch(`/agents/${E}`,{status:"draft"})},onSuccess:()=>{a.invalidateQueries({queryKey:["agents"]})},onError:E=>{console.error("Error desarchivando agente:",E)}}),C=oe({mutationFn:async E=>{const{data:I}=await T.post("/agents",{name:E,status:"draft"});return I},onSuccess:E=>{a.invalidateQueries({queryKey:["agents"]}),x(!1),b(null),n({to:"/agents/$agentId",params:{agentId:E.id},search:{builder:"1"}})},onError:E=>{const I=E?.response?.data?.message;b(Array.isArray(I)?I.join(" · "):I||e("aiModal.createError"))}}),N=g||[],S={all:N.length,published:N.filter(E=>E.status==="published").length,draft:N.filter(E=>E.status==="draft").length,archived:N.filter(E=>E.status==="archived").length},_=o==="all"?N:N.filter(E=>E.status===o),R=m.useRef(null);m.useEffect(()=>{const E=R.current;if(!E)return;const I=requestAnimationFrame(()=>E.classList.add("in"));return()=>cancelAnimationFrame(I)},[v,c]);const A=[{id:"all",label:e("filters.all"),count:S.all},{id:"published",label:e("filters.published"),count:S.published},{id:"draft",label:e("filters.draft"),count:S.draft}
953,{id:"archived",label:e("filters.archived"),count:S.archived}];return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("topbar.eyebrow"),title:e("topbar.title")}),t.jsx("main",{className:"cia","data-theme":s,style:{flex:1,overflowY:"auto",background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-col",style:{padding:"24px 28px 40px",gap:20,fontFamily:"var(--cia-font-sans)"},children:[t.jsxs("div",{className:"cia-row cia-gap-3",style:{flexWrap:"wrap"},children:[t.jsx("div",{className:"cia-toggle",children:A.map(E=>t.jsxs("button",{onClick:()=>l(E.id),className:`cia-toggle-btn ${o===E.id?"cia-toggle-btn-active":""}`,style:{display:"flex",alignItems:"center",gap:6},children:[E.label,t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:E.count})]},E.id))}),t.jsx("div",{style:{flex:1}}),t.jsxs("div",{className:"cia-row cia-gap-2",children:[t.jsx("button",{className:"cia-btn cia-btn-ghost cia-btn-icon",onClick:()=>d("grid"),"aria-label":e("view.grid"),"aria-pressed":c==="grid",style:{width:28,height:28,background:c==="grid"?"var(--cia-bg-soft)":"transparent"},children:t.jsx(US,{size:14})}),t.jsx("button",{className:"cia-btn cia-btn-ghost cia-btn-icon",onClick:()=>d("list"),"aria-label":e("view.list"),"aria-pressed":c==="list",style:{width:28,height:28,background:c==="list"?"var(--cia-bg-soft)":"transparent"},children:t.jsx(WS,{size:14})})]}),r&&t.jsxs("button",{className:"cia-btn cia-btn-sm",style:{display:"inline-flex",alignItems:"center",gap:6,background:"var(--cia-cta-500)",color:"#fff",border:"none",fontWeight:600,cursor:"pointer"},onClick:()=>{b(null),x(!0)},title:e("actions.createWithAITitle"),children:[t.jsx(zs,{size:13,"aria-hidden":!0})," ",e("actions.createWithAI")]}),r&&t.jsxs(et,{to:"/agents/new",className:"cia-btn cia-btn-ghost cia-btn-sm",children:[t.jsx(Fe,{size:13})," ",e("actions.newAgent")]})]}),c==="grid"&&t.jsxs("div",{className:"cia-grid-3 cia-stagger",ref:R,children:[r&&t.jsxs(et,{to:"/agents/new",className:"cia-card-dashed",children:[t.jsx("div",{style:{width:44,height:44,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--cia-bg-tint)",color:"var(--cia-brand-500)"},children:t.jsx(Fe,{size:20})}),t.jsx("div",{style:{fontSize:14,fontWeight:500,color:"var(--cia-text)"},children:e("createCard.title")}),t.jsx("div",{className:"cia-mono cia-text-3",style:{fontSize:11},children:e("createCard.hint")})]}),v?[0,1].map(E=>t.jsxs("div",{className:"cia-card cia-card-pad",children:[t.jsx("div",{className:"cia-skeleton",style:{height:36,width:36,borderRadius:8}}),t.jsx("div",{className:"cia-skeleton",style:{height:14,width:"60%",marginTop:14}}),t.jsx("div",{className:"cia-skeleton",style:{height:10,width:"85%",marginTop:10}}),t.jsx("div",{className:"cia-skeleton",style:{height:22,width:"50%",marginTop:14}})]},E)):_.map((E,I)=>t.jsx(k3,{agent:E,stat:k.get(E.id),i:I+1,onEdit:()=>n({to:"/agents/$agentId",params:{agentId:E.id}}),onArchive:()=>p(E),onUnarchive:()=>j.mutate(E.id)},E.id)),!v&&N.length>0&&_.length===0&&t.jsx("div",{style:{gridColumn:"1 / -1"},children:t.jsx(mx,{title:e(o==="archived"?"empty.noArchivedTitle":"empty.noFilterTitle"),desc:e(o==="archived"?"empty.noArchivedDesc":"empty.noFilterDesc")})})]}),c==="list"&&t.jsxs("div",{className:"cia-card",style:{overflow:"hidden"},children:[t.jsxs("div",{className:"cia-row cia-eyebrow",style:{padding:"10px 18px",borderBottom:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)"},children:[t.jsx("span",{style:{flex:2},children:e("list.colAgent")}),t.jsx("span",{style:{flex:1},children:e("list.colLanguage")}),t.jsx("span",{style:{flex:1},children:e("list.colStatus")}),t.jsx("span",{style:{flex:1,textAlign:"right"},children:e("list.colCalls30d")}),t.jsx("span",{style:{flex:1,textAlign:"right"},children:e("list.colSuccess")}),t.jsx("span",{style:{flex:1,textAlign:"right"},children:e("list.colLast")}),t.jsx("span",{style:{width:40}})]}),v?t.jsx("div",{className:"cia-col cia-gap-2",style:{padding:18},children:[0,1,2].map(E=>t.jsx("div",{className:"cia-skeleton",style:{height:30}},E))}):_.length>0?_.map(E=>{const I=k.get(E.id),P=I&&I.calls>0?`${Math.round(I.completed/I.calls*100)}%`:"—";return t.jsxs("div",{className:"cia-list-row",onClick:()=>n({to:"/agents/$agentId",params:{agentId:E.id}}),role:"link",tabIndex:0,onKeyDown:O=>{O.key==="Enter"&&n({to:"/agents/$agentId",params:{agentId:E.id}})},children:[t.jsxs("div",{className:"cia-row cia-gap-3",style:{flex:2,minWidth:0},children:[t.jsx(ss,{id:E.id,accent:E.accent,size:28}),t.jsxs("div",{className:"cia-col",style:{gap:0,minWidth:0},children:[t.jsx("span",{className:"cia-truncate",style:{fontSize:13.5,fontWeight:500,color:"var(--cia-text)"},children:E.name}),t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5},children:E.id})]})]}),t.jsx("div",{style:{flex:1},className:"cia-mono cia-text-2",children:to(E.language)}),t.jsx("div",{style:{flex:1},children:t.jsx(_0,{status:E.status})}),t.jsx("div",{style:{flex:1,textAlign:"right"}
953,className:"cia-mono cia-text-2",children:I?I.calls.toLocaleString(Te()):"—"}),t.jsx("div",{style:{flex:1,textAlign:"right"},className:"cia-mono cia-text-2",children:P}),t.jsx("div",{style:{flex:1,textAlign:"right"},className:"cia-mono cia-text-3",children:I?.lastCallAt?ts(I.lastCallAt):"—"}),t.jsx("div",{style:{width:40,display:"flex",justifyContent:"flex-end"},onClick:O=>O.stopPropagation(),onKeyDown:O=>O.stopPropagation(),children:t.jsx(C0,{archived:E.status==="archived",onEdit:()=>n({to:"/agents/$agentId",params:{agentId:E.id}}),onArchive:()=>p(E),onUnarchive:()=>j.mutate(E.id)})})]},E.id)}):t.jsx(mx,{title:N.length===0?e("empty.firstTitle"):e("empty.noFilterTitle"),desc:N.length===0?e("empty.firstDesc"):e("empty.noFilterDesc")})]}),r&&t.jsx(S3,{})]})}),u&&t.jsx(w3,{agent:u,onCancel:()=>p(null),onConfirm:()=>w.mutate(u.id),isPending:w.isPending}),f&&t.jsx(C3,{isSaving:C.isPending,error:h,onClose:()=>{x(!1),b(null)},onConfirm:E=>C.mutate(E)}),t.jsx("style",{children:"@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }"})]})}const E0=[{tz:"America/Bogota",labelKey:"identity.tz.bogota"},{tz:"America/Lima",labelKey:"identity.tz.lima"},{tz:"America/Guayaquil",labelKey:"identity.tz.guayaquil"},{tz:"America/Mexico_City",labelKey:"identity.tz.mexicoCity"},{tz:"America/Cancun",labelKey:"identity.tz.cancun"},{tz:"America/Tijuana",labelKey:"identity.tz.tijuana"},{tz:"America/Santiago",labelKey:"identity.tz.santiago"},{tz:"America/Argentina/Buenos_Aires",labelKey:"identity.tz.buenosAires"},{tz:"America/Sao_Paulo",labelKey:"identity.tz.saoPaulo"},{tz:"America/Caracas",labelKey:"identity.tz.caracas"},{tz:"America/La_Paz",labelKey:"identity.tz.laPaz"},{tz:"America/Asuncion",labelKey:"identity.tz.asuncion"},{tz:"America/Montevideo",labelKey:"identity.tz.montevideo"},{tz:"America/Santo_Domingo",labelKey:"identity.tz.santoDomingo"},{tz:"America/Panama",labelKey:"identity.tz.panama"},{tz:"America/Costa_Rica",labelKey:"identity.tz.costaRica"},{tz:"America/Guatemala",labelKey:"identity.tz.guatemala"},{tz:"America/El_Salvador",labelKey:"identity.tz.elSalvador"},{tz:"America/Tegucigalpa",labelKey:"identity.tz.tegucigalpa"},{tz:"America/Managua",labelKey:"identity.tz.managua"},{tz:"America/Havana",labelKey:"identity.tz.havana"},{tz:"America/Puerto_Rico",labelKey:"identity.tz.puertoRico"},{tz:"America/New_York",labelKey:"identity.tz.newYork"},{tz:"America/Chicago",labelKey:"identity.tz.chicago"},{tz:"America/Denver",labelKey:"identity.tz.denver"},{tz:"America/Los_Angeles",labelKey:"identity.tz.losAngeles"},{tz:"America/Phoenix",labelKey:"identity.tz.phoenix"},{tz:"Europe/Madrid",labelKey:"identity.tz.madrid"},{tz:"Europe/London",labelKey:"identity.tz.london"},{tz:"Europe/Lisbon",labelKey:"identity.tz.lisbon"},{tz:"UTC",labelKey:"identity.tz.utc"}];function zt({title:e,desc:a,children:n,last:s}){return t.jsxs("div",{className:`grid md:grid-cols-[200px_1fr] gap-x-8 gap-y-4 ${s?"":"pb-7 border-b border-paper-line"}`,children:[t.jsxs("div",{children:[t.jsx("h3",{className:"font-semibold text-[15px]",style:{color:"var(--cia-text)"},children:e}),t.jsx("p",{className:"text-[13px] text-ink-mute mt-1 leading-relaxed",children:a})]}),t.jsx("div",{className:"flex flex-col gap-4",children:n})]})}function Zs({label:e,children:a,className:n=""}){return t.jsxs("div",{className:n,children:[t.jsx("label",{className:"label mb-1.5 block",children:e}),a]})}function qa({children:e}){return t.jsx("p",{className:"text-[11.5px] text-ink-mute mt-1 leading-snug",children:e})}function E3(e){return t.jsx(y0,{variant:"drawer",...e})}const A3={1:{fontSize:15.5,fontWeight:700,color:"var(--cia-text)",marginTop:18},2:{fontSize:14,fontWeight:700,color:"var(--cia-text)",marginTop:14},3:{fontSize:13,fontWeight:650,color:"var(--cia-text-2)",marginTop:12},4:{fontSize:12.5,fontWeight:600,color:"var(--cia-text-2)",marginTop:10},5:{fontSize:12,fontWeight:600,color:"var(--cia-text-3)",marginTop:8},6:{fontSize:12,fontWeight:600,color:"var(--cia-text-3)",marginTop:8}},R3=/^(\s{0,3})(#{1,6})\s+(.*)$/,T3=/^(\s*)([-*•]|\d+[.)])\s+(.*)$/;function $d(e,a){const n=[],s=/(`[^`]+`)|(\{\{\s*[A-Za-z][A-Za-z0-9_]*\s*\}\})|(\*\*[^*]+\*\*)/g;let i=0,r,o=0;for(;r=s.exec(e);){r.index>i&&n.push(e.slice(i,r.index));const l=r[0],c=`${a}-i${o++}`;r[1]?n.push(t.jsx("code",{className:"cia-mono",style:{fontSize:"0.92em",background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",borderRadius:5,padding:"0 4px"},children:l.slice(1,-1)},c)):r[2]?n.push(t.jsx("span",{className:"cia-mono",style:{fontSize:"0.9em",color:"var(--cia-brand-600, var(--cia-text))",background:"color-mix(in oklab, var(--cia-brand-500, #2B52A1) 10%, transparent)",border:"1px solid color-mix(in oklab, var(--cia-brand-500, #2B52A1) 25%, transparent)",borderRadius:999,padding:"0 6px",whiteSpace:"nowrap"},children:l},c)):n.push(t.jsx("strong",{style:{fontWeight:700,color:"var(--cia-text)"},children:l.slice(2,-2)},c)),i=r.index+l.length}return i<e.length&&n.push(e.slice(i)),n.length?n:[e]}function M3({raw:e,lineNo:a,highlighted:n}){const s={margin:0,fontSize:12.5,lineHeight:1.7,color:"var(--cia-text-2)",whiteSpace:"pre-wrap",wordBreak:"break-word",background:n?"color-mix(in oklab, var(--cia-cta-500) 10%, transparent)":"transparent",borderRadius:n?6:0,transition:"background .3s ease"};if(e.trim()==="")return t.jsx("div",{style:{height:8}});const i=R3.exec(e);if(i){const o=i[2].length;return t.jsxs("div",{className:"flex items-baseline gap-2",style:{...s,...A3[o],marginBottom:4}
953,children:[t.jsxs("span",{"aria-hidden":!0,className:"cia-mono",style:{fontSize:9.5,fontWeight:700,color:"var(--cia-text-3)",border:"1px solid var(--cia-border)",borderRadius:4,padding:"1px 4px",flex:"none",transform:"translateY(-1px)"},children:["H",o]}),t.jsx("span",{children:$d(i[3],`h${a}`)})]})}const r=T3.exec(e);return r?t.jsxs("div",{className:"flex gap-2",style:{...s,paddingLeft:4+r[1].length*4},children:[t.jsx("span",{"aria-hidden":!0,style:{color:"var(--cia-cta-500)",flex:"none",fontWeight:700},children:/^\d/.test(r[2])?r[2]:"•"}),t.jsx("span",{children:$d(r[3],`b${a}`)})]}):t.jsx("p",{style:s,children:$d(e,`p${a}`)})}function Ys(e,a){let n=1;for(let s=0;s<a&&s<e.length;s++)e[s]===`
954`&&n++;return n}function P3({parts:e,highlightLine:a,style:n}){const s=m.useMemo(()=>e.map((i,r)=>{if(i.kind==="slot")return t.jsx("div",{style:{margin:"10px 0"},children:i.node},`slot-${i.id}`);const o=i.text.split(`
955`);return t.jsx(m.Fragment,{children:o.map((l,c)=>{const d=i.startLine+c;return t.jsx(M3,{raw:l,lineNo:d,highlighted:a!=null&&d===a},`l-${r}-${c}`)})},`seg-${r}`)}),[e,a]);return t.jsx("div",{style:{padding:"12px 14px",display:"flex",flexDirection:"column",gap:0,...n},children:s})}function z3({current:e,total:a,staleCount:n=0,chainedCount:s=0,onPrev:i,onNext:r,onAcceptAll:o,onRejectAll:l,onClearStale:c,busy:d=!1}){const{t:u}=M("agents");if(a<=0&&n<=0)return null;const p=(x,h)=>t.jsx("button",{type:"button",onClick:h,"aria-label":u(x==="prev"?"studio.nav.prev":"studio.nav.next"),title:u(x==="prev"?"studio.nav.prev":"studio.nav.next"),className:"inline-flex items-center justify-center rounded-lg transition-colors",style:{width:30,height:30,minHeight:30,color:"var(--cia-text-2)",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",cursor:"pointer"},onMouseEnter:b=>{b.currentTarget.style.borderColor="var(--cia-cta-500)",b.currentTarget.style.color="var(--cia-cta-500)"},onMouseLeave:b=>{b.currentTarget.style.borderColor="var(--cia-border)",b.currentTarget.style.color="var(--cia-text-2)"},children:x==="prev"?t.jsx(Rn,{className:"size-4"}):t.jsx(Ut,{className:"size-4"})}),f=(x,h,b,g)=>{const v=x==="accept"?"var(--cia-ok-500)":"var(--cia-text-2)";return t.jsxs("button",{type:"button",onClick:h,disabled:d,className:"inline-flex items-center gap-1.5 rounded-lg font-medium transition-colors",style:{color:v,background:"var(--cia-bg-elev)",border:`1px solid color-mix(in oklab, ${v} 30%, transparent)`,padding:"6px 10px",minHeight:32,fontSize:12,cursor:d?"not-allowed":"pointer",opacity:d?.6:1},children:[b,g]})};return t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{padding:"8px 12px",borderBottom:"1px solid var(--cia-border)",background:"color-mix(in oklab, var(--cia-cta-500) 6%, var(--cia-bg-elev))"},children:[a>0&&t.jsx("span",{style:{fontSize:12,fontWeight:700,color:"var(--cia-text)"},children:u("studio.nav.counter",{current:e,total:a})}),n>0&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-warn-ink)",fontWeight:600},children:u("studio.nav.stale",{count:n})}),n>0&&c&&t.jsxs("button",{type:"button",onClick:c,disabled:d,className:"inline-flex items-center gap-1 rounded-lg font-medium transition-colors",style:{color:"var(--cia-warn-ink)",background:"var(--cia-bg-elev)",border:"1px solid color-mix(in oklab, var(--cia-warn-500) 30%, transparent)",padding:"4px 8px",minHeight:28,fontSize:11,cursor:d?"not-allowed":"pointer",opacity:d?.6:1},children:[t.jsx(PS,{className:"size-3"}),u("studio.nav.clearStale")]}),s>0&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-text-3)",fontWeight:600},children:u("studio.nav.chained",{count:s})}),a>0&&p("prev",i),a>0&&p("next",r),t.jsx("span",{style:{flex:1}}),a>0&&f("accept",o,t.jsx(Dj,{className:"size-3.5"}),u("studio.nav.acceptAll")),a>0&&f("reject",l,t.jsx(cs,{className:"size-3.5"}),u("studio.nav.rejectAll"))]})}const D3=[{mode:"fix",icon:ih,key:"fix"},{mode:"specific",icon:RS,key:"specific"},{mode:"clarity",icon:DS,key:"clarity"}];function I3({onSend:e,onOpenChat:a,streaming:n=!1,onAbort:s,busyTool:i=null,auditCount:r=0,disabled:o=!1,disabledHint:l}){const{t:c}=M("agents"),[d,u]=m.useState(""),p=o||n,f=()=>{const h=d.trim();!h||p||(e(h,"context"),u(""))},x=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),f())};return t.jsxs("div",{style:{borderTop:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)",padding:"10px 12px",display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",style:{fontSize:11,fontWeight:700,color:"var(--cia-cta-500)"},children:[t.jsx(_t,{className:"size-3"}),c("studio.improve.label")]}),D3.map(({mode:h,icon:b,key:g})=>{const y=h==="fix"&&r>0;return t.jsxs("button",{type:"button",disabled:p,onClick:()=>e(c(`studio.improve.prompt.${g}`),h),title:c(`studio.improve.tip.${g}`),className:"inline-flex items-center gap-1.5 rounded-lg font-medium transition-colors",style:{color:y?"var(--cia-warn-ink)":"var(--cia-text-2)",background:y?"color-mix(in oklab, var(--cia-warn-500) 10%, var(--cia-bg-elev))":"var(--cia-bg-elev)",border:`1px solid ${y?"color-mix(in oklab, var(--cia-warn-500) 35%, transparent)":"var(--cia-border)"}`,padding:"6px 10px",minHeight:32,fontSize:11.5,cursor:p?"not-allowed":"pointer",opacity:p?.6:1},onMouseEnter:k=>
955{p||(k.currentTarget.style.borderColor="var(--cia-cta-500)",k.currentTarget.style.color="var(--cia-cta-500)")},onMouseLeave:k=>{k.currentTarget.style.borderColor=y?"color-mix(in oklab, var(--cia-warn-500) 35%, transparent)":"var(--cia-border)",k.currentTarget.style.color=y?"var(--cia-warn-ink)":"var(--cia-text-2)"},children:[t.jsx(b,{className:"size-3.5"}),c(`studio.improve.action.${g}`),y&&t.jsx("span",{className:"cia-mono",style:{fontSize:9.5,fontWeight:700,background:"var(--cia-warn-500)",color:"#fff",borderRadius:999,padding:"0 5px"},children:r})]},h)}),t.jsx("span",{style:{flex:1}}),a&&t.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center gap-1.5 rounded-lg font-medium transition-colors",style:{color:"var(--cia-text-2)",background:"transparent",border:"1px solid var(--cia-border)",padding:"6px 10px",minHeight:32,fontSize:11.5,cursor:"pointer"},children:[t.jsx(sn,{className:"size-3.5"}),c("studio.improve.openChat")]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{value:d,onChange:h=>u(h.target.value),onKeyDown:x,disabled:p,placeholder:c("studio.improve.placeholder"),"aria-label":c("studio.improve.placeholder"),style:{flex:1,minWidth:0,padding:"8px 12px",minHeight:36,borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-elev)",color:"var(--cia-text)",fontSize:12.5,outline:"none"},onFocus:h=>{h.currentTarget.style.borderColor="var(--cia-cta-500)"},onBlur:h=>{h.currentTarget.style.borderColor="var(--cia-border)"}}),n?t.jsxs("button",{type:"button",onClick:s,className:"inline-flex items-center gap-1.5 rounded-lg font-medium",style:{color:"var(--cia-bad-500)",background:"var(--cia-bg-elev)",border:"1px solid color-mix(in oklab, var(--cia-bad-500) 30%, transparent)",padding:"8px 12px",minHeight:36,fontSize:12,cursor:"pointer"},children:[t.jsx(ah,{className:"size-3"}),c("studio.improve.stop")]}):t.jsxs("button",{type:"button",onClick:f,disabled:p||!d.trim(),className:"inline-flex items-center gap-1.5 rounded-lg font-semibold",style:{color:"#fff",background:"var(--cia-cta-500)",border:"1px solid var(--cia-cta-500)",padding:"8px 14px",minHeight:36,fontSize:12,cursor:p||!d.trim()?"not-allowed":"pointer",opacity:p||!d.trim()?.5:1},children:[t.jsx(_t,{className:"size-3.5"}),c("studio.improve.send")]})]}),n&&t.jsxs("p",{className:"inline-flex items-center gap-1.5",style:{margin:0,fontSize:11,color:"var(--cia-text-3)"},"aria-live":"polite",children:[t.jsx(je,{className:"size-3 animate-spin"}),i?c(`studio.improve.busy.${i}`,{defaultValue:c("studio.improve.working")}):c("studio.improve.working")]}),o&&l&&t.jsx("p",{style:{margin:0,fontSize:11,color:"var(--cia-text-3)"},children:l})]})}const L3=()=>({items:[],outline:[],baseHash:"",batches:0});function fx(e,a,n){const s=e.batches+1,i=(a.suggestions??[]).map((l,c)=>({...l,id:`b${s}:${l.id||`s${c+1}`}`,state:"pending",batch:s})),r=new Set(i.map(l=>l.find)),o=e.items.filter(l=>!(l.state==="pending"&&r.has(l.find)));return pi({items:[...o,...i],outline:a.outline??e.outline,baseHash:a.base?.hash??e.baseHash,batches:s},n)}function pi(e,a){const n=a??"";return{...e,items:e.items.map(s=>{if(s.state==="accepted"||s.state==="rejected"||s.state==="stale"&&s.staleReason==="superseded")return s;const i=s.find?n.split(s.find).length-1:0;return i===1?{...s,state:"pending",staleReason:void 0}:i===0&&s.replace&&s.replace.length>=12&&n.includes(s.replace)?{...s,state:"stale",staleReason:"applied"}:i===0&&s.chainedTo?{...s,state:"stale",staleReason:"chained"}:{...s,state:"stale",staleReason:i===0?"missing":"ambiguous"}})}}function xx(e,a,n){return{...e,items:e.items.map(s=>s.id===a?{...s,state:"accepted",appliedText:n}:s)}}function F3(e,a){return{...e,items:e.items.map(n=>n.id===a?{...n,state:"rejected"}:n)}}function O3(e){return{...e,items:e.items.map(a=>a.state==="pending"?{...a,state:"rejected"}:a)}}function gx(e,a,n){const s=e??"",i=a.find??"";if(!i||s.split(i).length-1!==1)return null;const o=s.indexOf(i),l=n??a.replace??"";return s.slice(0,o)+l+s.slice(o+i.length)}function $3(e){return{...e,items:e.items.map(a=>a.state==="stale"&&(a.staleReason==="missing"||a.staleReason==="ambiguous")?{...a,state:"rejected",staleReason:void 0}:a)}}function qd(e){return e.items.filter(a=>a.state==="pending"||a.state==="stale"&&a.staleReason!=="applied"&&a.staleReason!=="superseded").slice().sort((a,n)=>a.anchored&&n.anchored?a.charStart-n.charStart:a.anchored?-1:n.anchored?1:a.id.localeCompare(n.id))}function q3(e){return e.items.filter(a=>a.state==="pending").length}function sr(e,a){const n=e??"",s=a.find??"";return!s||n.split(s).length-1!==1?-1:n.indexOf(s)}
955function B3({value:e,onChange:a,session:n,onSessionChange:s,onImprove:i,onOpenChat:r,streaming:o=!1,onAbort:l,busyTool:c=null,auditCount:d=0,improveDisabled:u=!1,improveDisabledHint:p,toolbarExtras:f,replySlot:x,textareaRef:h}){const{t:b}=M("agents"),[g,v]=m.useState("preview"),[y,k]=m.useState(0),[w,j]=m.useState(null),C=m.useRef({}),N=m.useRef(null),S=h??N,_=m.useMemo(()=>qd(n),[n]),R=q3(n),A=m.useMemo(()=>_.filter(F=>F.state==="pending"),[_]),E=_.filter(F=>F.state==="stale"&&F.staleReason!=="chained").length,I=_.filter(F=>F.staleReason==="chained").length;m.useEffect(()=>{R>0&&g==="markdown"&&v("preview")},[R,g]);const P=m.useRef(0);m.useEffect(()=>{if(n.batches===P.current||(P.current=n.batches,!A.length))return;k(0);const F=A[0],G=sr(e,F);j(G>=0?Ys(e,G):null),requestAnimationFrame(()=>{requestAnimationFrame(()=>{C.current[F.id]?.scrollIntoView({behavior:"smooth",block:"center"})})})},[n.batches,A,e]),m.useEffect(()=>{y>=A.length&&k(Math.max(0,A.length-1))},[A.length,y]);const O=m.useCallback((F,G,te)=>{const B=qd(F).filter(L=>L.state==="pending");if(!B.length){j(null);return}const ne=Math.min(te,B.length-1);k(ne);const me=B[ne],Ee=sr(G,me);j(Ee>=0?Ys(G,Ee):null),requestAnimationFrame(()=>{C.current[me.id]?.scrollIntoView({behavior:"smooth",block:"center"})})},[]),K=m.useCallback((F,G)=>{const te=gx(e,F,G);if(te===null){s(pi(n,e));return}const B=A.findIndex(me=>me.id===F.id),ne=pi(xx(n,F.id,G),te);a(te),s(ne),O(ne,te,Math.max(0,B))},[e,n,A,a,s,O]),W=m.useCallback(F=>{const G=A.findIndex(B=>B.id===F.id),te=F3(n,F.id);s(te),O(te,e,Math.max(0,G))},[n,A,e,s,O]),V=m.useCallback(()=>{let F=e,G=n;const te=qd(n).filter(B=>B.state==="pending").slice().reverse();for(const B of te){const ne=gx(F,B);ne!==null&&(F=ne,G=xx(G,B.id,B.replace))}a(F),s(pi(G,F))},[e,n,a,s]),U=m.useCallback(()=>s(O3(n)),[n,s]),X=m.useCallback(()=>s($3(n)),[n,s]),ie=m.useCallback(F=>{if(!A.length)return;const G=(F%A.length+A.length)%A.length;k(G);const te=A[G],B=sr(e,te);j(B>=0?Ys(e,B):null),requestAnimationFrame(()=>{C.current[te.id]?.scrollIntoView({behavior:"smooth",block:"center"})})},[A,e]),de=m.useMemo(()=>{const F=_.map(ne=>({s:ne,offset:sr(e,ne)})).filter(ne=>ne.offset>=0).sort((ne,me)=>ne.offset-me.offset),G=_.filter(ne=>sr(e,ne)<0),te=[];let B=0;for(const{s:ne,offset:me}of F){me>B&&te.push({kind:"text",text:e.slice(B,me),startLine:Ys(e,B)});const Ee=A.findIndex(L=>L.id===ne.id);te.push({kind:"slot",id:ne.id,node:t.jsx(Nf,{before:ne.find,after:ne.replace,note:ne.note,location:ne.sectionTitle?b("studio.suggestion.inSection",{section:ne.sectionTitle}):b("studio.suggestion.atLine",{line:Ys(e,me)}),state:ne.state,staleReason:ne.state==="stale"?b(`studio.suggestion.stale.${ne.staleReason??"missing"}`):void 0,position:Ee>=0?{index:Ee+1,total:A.length}:void 0,highlighted:Ee>=0&&Ee===y,onAccept:L=>K(ne,L),onReject:()=>W(ne),anchorRef:L=>{C.current[ne.id]=L}})}),B=me+ne.find.length}B<e.length&&te.push({kind:"text",text:e.slice(B),startLine:Ys(e,B)});for(const ne of G)te.push({kind:"slot",id:ne.id,node:t.jsx(Nf,{before:ne.find,after:ne.replace,note:ne.note,location:b("studio.suggestion.unlocated"),state:"stale",staleReason:b(`studio.suggestion.stale.${ne.staleReason??"missing"}`),onReject:()=>W(ne),anchorRef:me=>{C.current[ne.id]=me}})});return te},[e,_,A,y,K,W,b]),$=e.length,z=Math.max(1,Math.round($/4)),D=(F,G,te)=>{const B=g===F,ne=F==="markdown"&&R>0;return t.jsxs("button",{type:"button",onClick:()=>!ne&&v(F),disabled:ne,title:ne?b("studio.view.markdownBlocked",{count:R}):te,className:"inline-flex items-center gap-1.5 rounded-lg font-medium transition-colors",style:{color:B?"var(--cia-cta-500)":"var(--cia-text-3)",background:B?"color-mix(in oklab, var(--cia-cta-500) 10%, transparent)":"transparent",border:`1px solid ${B?"color-mix(in oklab, var(--cia-cta-500) 28%, transparent)":"transparent"}`,padding:"4px 9px",minHeight:28,fontSize:11.5,cursor:ne?"not-allowed":"pointer",opacity:ne?.45:1},children:[G,te]})};return t.jsxs("div",{style:{background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)",borderRadius:"var(--cia-r)",overflow:"hidden"},children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{padding:"8px 12px",borderBottom:"1px solid var(--cia-border)",background:"var(--cia-bg-elev)"},children:[t.jsxs("div",{className:"flex items-center gap-1",children:[D("preview",t.jsx(qs,{className:"size-3.5"}),b("studio.view.preview")),D("markdown",t.jsx(Zb,{className:"size-3.5"}),b("studio.view.markdown"))]}),t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:10.5}
955,children:b("identity.prompt.charsTokens",{chars:$.toLocaleString(Te()),tokens:z.toLocaleString(Te())})}),t.jsx("span",{style:{flex:1}}),f]}),t.jsx(z3,{current:A.length?y+1:0,total:A.length,staleCount:E,chainedCount:I,onPrev:()=>ie(y-1),onNext:()=>ie(y+1),onAcceptAll:V,onRejectAll:U,onClearStale:X,busy:o}),g==="preview"?e.trim()===""?t.jsxs("div",{className:"flex flex-col items-center gap-2",style:{padding:"28px 16px",textAlign:"center"},children:[t.jsx(_t,{className:"size-5",style:{color:"var(--cia-cta-500)"}}),t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-2)",maxWidth:380},children:b("studio.empty.title")}),t.jsx("p",{style:{margin:0,fontSize:11.5,color:"var(--cia-text-3)",maxWidth:380},children:b("studio.empty.desc")})]}):t.jsx("div",{style:{maxHeight:520,overflowY:"auto"},children:t.jsx(P3,{parts:de,highlightLine:w})}):t.jsx("textarea",{ref:S,className:"cia-mono",value:e,onChange:F=>{const G=F.target.value;a(G),n.items.length&&s(pi(n,G))},style:{width:"100%",minHeight:320,border:0,outline:"none",background:"transparent",color:"var(--cia-text)",padding:"12px",resize:"vertical",fontSize:13,lineHeight:1.6}}),x,t.jsx(I3,{onSend:i,onOpenChat:r,streaming:o,onAbort:l,busyTool:c,auditCount:d,disabled:u,disabledHint:p})]})}function W3({text:e,options:a,live:n=!1,onPick:s,onDismiss:i}){const{t:r}=M("agents");return t.jsxs("div",{style:{borderTop:"1px solid var(--cia-border)",background:"var(--cia-bg-elev)",padding:"10px 12px",display:"flex",flexDirection:"column",gap:8},"aria-live":"polite",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",style:{fontSize:11,fontWeight:700,color:"var(--cia-cta-500)"},children:[t.jsx(_t,{className:"size-3"}),r("studio.reply.label")]}),t.jsx("span",{style:{flex:1}}),!n&&i&&t.jsx("button",{type:"button",onClick:i,"aria-label":r("studio.reply.dismiss"),title:r("studio.reply.dismiss"),className:"inline-flex items-center justify-center rounded-lg transition-colors",style:{width:28,height:28,color:"var(--cia-text-3)",background:"transparent",border:"1px solid var(--cia-border)",cursor:"pointer"},onMouseEnter:o=>{o.currentTarget.style.color="var(--cia-text)",o.currentTarget.style.borderColor="var(--cia-border-2)"},onMouseLeave:o=>{o.currentTarget.style.color="var(--cia-text-3)",o.currentTarget.style.borderColor="var(--cia-border)"},children:t.jsx(nt,{className:"size-3.5"})})]}),e&&t.jsx("div",{style:{fontSize:12.5,color:"var(--cia-text)"},children:t.jsx(Mp,{content:e})}),!n&&!!a?.length&&s&&t.jsx(Gl,{actions:a.map(o=>({label:o,instruction:o})),onPick:s})]})}const U3=2500;function V3(e){return{systemPrompt:e.systemPrompt??"",textPrompt:e.textPrompt??"",greeting:e.greeting??"",language:e.language??"es",tools:e.tools??[],analytics:e.analytics??void 0,dynamicVariables:e.dynamicVariables??[],advancedBehavior:e.advancedBehavior??void 0,backgroundAudio:e.backgroundAudio??void 0,knowledge:e.knowledge??null,llm:e.llm??void 0}}function A0(e,a){const n=m.useMemo(()=>V3(a),[a]),s=m.useMemo(()=>JSON.stringify(n),[n]),[i,r]=m.useState(s);return m.useEffect(()=>{const o=setTimeout(()=>r(s),U3);return()=>clearTimeout(o)},[s]),se({queryKey:["agent-audit",e,i],queryFn:async()=>{const{data:o}=await T.post(`/agents/${e}/audit`,JSON.parse(i));return o},enabled:!!e,placeholderData:xc,staleTime:6e4,retry:!1})}const K3=[{token:"{{current_time}}",labelKey:"identity.promptVars.currentTime",needsTz:!0},{token:"{{current_hour}}",labelKey:"identity.promptVars.currentHour",needsTz:!0},{token:"{{current_calendar}}",labelKey:"identity.promptVars.currentCalendar",needsTz:!0},{token:"{{current_timezone}}",labelKey:"identity.promptVars.currentTimezone",needsTz:!0},{token:"{{session_type}}",labelKey:"identity.promptVars.sessionType",needsTz:!0},{token:"{{call_type}}",labelKey:"identity.promptVars.callType",needsTz:!0},{token:"{{system__caller_id}}",labelKey:"identity.promptVars.systemCallerId"},{token:"{{system__called_number}}",labelKey:"identity.promptVars.systemCalledNumber"},{token:"{{system__agent_id}}",labelKey:"identity.promptVars.systemAgentId"},{token:"{{system__current_agent_id}}",labelKey:"identity.promptVars.systemCurrentAgentId"}
955],Bd=[{code:"es",labelKey:"identity.langs.es"},{code:"es-MX",labelKey:"identity.langs.es-MX"},{code:"es-AR",labelKey:"identity.langs.es-AR"},{code:"en-US",labelKey:"identity.langs.en-US"},{code:"pt-BR",labelKey:"identity.langs.pt-BR"}];function H3({agent:e,onChange:a,openBuilderOnMount:n,onOpenKnowledge:s,auditKick:i,onFieldSuggestion:r}){const{t:o}=M("agents"),l=e.advancedBehavior?.firstSpeaker??((e.greeting||"").trim()?"agent":"user");function c(Z){a({advancedBehavior:{...e.advancedBehavior,firstSpeaker:Z}})}const d=e.language||"es",u=e.advancedBehavior?.additionalLanguages??[],p=e.advancedBehavior?.multiLanguage===!0&&u.length===0,f=Bd.filter(Z=>Z.code!==d&&!u.includes(Z.code)),x=Z=>{const ae=Bd.find(pe=>pe.code===Z)?.labelKey;return ae?o(ae):Z};function h(Z){a({advancedBehavior:{...e.advancedBehavior,additionalLanguages:Z}})}function b(Z){!Z||u.includes(Z)||u.length>=1||h([...u,Z])}function g(Z){h(u.filter(ae=>ae!==Z))}const v=e.advancedBehavior?.timezone??"";function y(Z){a({advancedBehavior:{...e.advancedBehavior,timezone:Z}})}const k=d0(e.systemPrompt,e.greeting),w=e.dynamicVariables??[],j=w.filter(Z=>!k.includes(Z.name));function C(Z,ae){const ye={...w.find(bt=>bt.name===Z),...ae},qe={name:Z};ye.defaultValue!==void 0&&ye.defaultValue!==""&&(qe.defaultValue=ye.defaultValue),ye.description!==void 0&&ye.description.trim()!==""&&(qe.description=ye.description);const ut=w.filter(bt=>bt.name!==Z);a({dynamicVariables:[...ut,qe]})}function N(Z){a({dynamicVariables:w.filter(ae=>ae.name!==Z)})}const S=m.useRef(null),[_,R]=m.useState(!1);function A(Z){const ae=e.systemPrompt||"",pe=S.current,ye=pe?.selectionStart??ae.length,qe=pe?.selectionEnd??ae.length;a({systemPrompt:ae.slice(0,ye)+Z+ae.slice(qe)}),R(!1),requestAnimationFrame(()=>{if(!pe)return;pe.focus();const ut=ye+Z.length;pe.setSelectionRange(ut,ut)})}(e.systemPrompt||"").length;const E=k.length>0||j.length>0,[I,P]=m.useState(!1),O=m.useRef(!1);m.useEffect(()=>{n&&e.id&&!O.current&&(O.current=!0,P(!0))},[n,e.id]),m.useEffect(()=>{i&&e.id&&P(!0)},[i,e.id]);function K(){if(!e.id){J({tone:"warn",title:o("identity.toast.saveFirstTitle"),desc:o("identity.toast.improveSaveFirstDesc")});return}P(!0)}function W(Z){a(Ph(e,Z))}const[V,U]=m.useState(L3),[X,ie]=m.useState(null),[de,$]=m.useState(!1),[z,D]=m.useState(null),[F,G]=m.useState(null),te=m.useRef(""),B=m.useRef(null),ne=m.useRef(!1),{send:me,abort:Ee}=m0(e.id,X),{data:L}=A0(e.id,e),re=L?L.counts.error+L.counts.warn:0,ke=m.useCallback(Z=>{ne.current=!0;const ae=Z.promptEdits;if(ae?.suggestions?.length){U(pe=>fx(pe,ae,e.systemPrompt??""));return}if(r){r(Z);return}W(Z.patch)},[e.systemPrompt,e,r]),H=m.useCallback((Z,ae)=>{if(!e.id){J({tone:"warn",title:o("identity.toast.saveFirstTitle"),desc:o("identity.toast.improveSaveFirstDesc")});return}$(!0),D(null),G(null),te.current="",B.current=null,ne.current=!1,me(Z,{onToken:pe=>{te.current=pe},onToolCall:pe=>G(pe),onDraftPatch:ke,onClarify:pe=>{B.current=pe.options??[],pe.question&&(te.current=te.current?`${te.current}
956
957${pe.question}`:pe.question)},onDone:(pe,ye)=>{$(!1),G(null),ye&&ie(ye);const qe=te.current.trim(),ut=B.current;(ut?.length||!ne.current&&qe)&&D({text:qe,options:ut??[]})},onError:pe=>{$(!1),G(null),J({tone:"bad",title:o("studio.error.title"),desc:pe})}},{improveMode:ae})},[e.id,me,ke,o]),fe=m.useCallback(Z=>{a({systemPrompt:Z}),U(ae=>ae.items.length?pi(ae,Z):ae)},[a]);return t.jsxs(t.Fragment,{children:[t.jsx(E3,{agentId:e.id,agentName:e.name,draft:e,open:I,onClose:()=>P(!1),onApplyPatch:W,onboardingMode:n,auditKick:i,onPromptSuggestions:Z=>U(ae=>fx(ae,Z,e.systemPrompt??"")),onFieldSuggestion:r}),t.jsxs("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:[t.jsx(zt,{title:o("identity.section.identityTitle"),desc:o("identity.section.identityDesc"),children:t.jsxs("div",{className:"grid sm:grid-cols-2 2xl:grid-cols-3 gap-x-5 gap-y-5",children:[t.jsx(Zs,{label:o("identity.fields.internalName"),children:t.jsx("input",{className:"input",value:e.name||"",onChange:Z=>a({name:Z.target.value}),placeholder:o("identity.fields.internalNamePlaceholder")})}),t.jsxs(Zs,{label:o("identity.fields.primaryLanguage"),children:[t.jsx("select",{className:"select w-full",value:d,onChange:Z=>a({language:Z.target.value}),children:Bd.map(Z=>t.jsx("option",{value:Z.code,children:o(Z.labelKey)},Z.code))}),t.jsx(qa,{children:o("identity.fields.primaryLanguageHint")})]}),t.jsxs(Zs,{label:o("identity.fields.additionalLanguage"),children:[u.length>0?t.jsx("div",{className:"flex flex-wrap gap-2 h-9 items-center",children:u.map(Z=>t.jsxs("span",{className:"chip bg-brand-50 text-brand-700 border border-brand-200 flex items-center gap-1.5",children:[x(Z),t.jsx("button",{type:"button",onClick:()=>g(Z),className:"text-brand-400 hover:text-rose-500 transition-colors",title:o("identity.fields.removeLanguage"),children:"×"})]},Z))}):f.length>0?t.jsxs("select",{className:"select w-full",value:"",onChange:Z=>b(Z.target.value),children:[t.jsx("option",{value:"",disabled:!0,children:o("identity.fields.addLanguageOption")}),f.map(Z=>t.jsx("option",{value:Z.code,children:o(Z.labelKey)},Z.code))]}):null,t.jsx(qa,{children:o("identity.fields.additionalLanguageHint")}),p&&t.jsx("p",{className:"text-[11.5px] text-amber-600 mt-1.5 bg-amber-50 rounded-lg px-2.5 py-1.5 leading-snug",children:o("identity.fields.legacyMulti")})]}),t.jsxs(Zs,{label:o("identity.fields.timezone"),children:[t.jsxs("select",{className:"select w-full",value:v,onCh
957ange:Z=>y(Z.target.value),children:[t.jsx("option",{value:"",disabled:!0,children:o("identity.fields.timezonePlaceholder")}),E0.map(Z=>t.jsx("option",{value:Z.tz,children:o(Z.labelKey)},Z.tz))]}),t.jsx(qa,{children:o("identity.fields.timezoneHint")})]}),t.jsx(Zs,{label:o("identity.fields.whoFirst"),className:"sm:col-span-2 2xl:col-span-2",children:t.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[t.jsxs("button",{type:"button",onClick:()=>c("agent"),className:`text-left px-3 py-2 rounded-xl border transition-colors ${l==="agent"?"border-brand-600 bg-brand-50 ring-2 ring-brand-300":"border-paper-line hover:border-brand-300"}`,children:[t.jsx("div",{className:"font-medium text-[13px]",children:o("identity.fields.agentGreets")}),t.jsx("div",{className:"text-[11px] text-ink-mute mt-0.5",children:o("identity.fields.agentGreetsDesc")})]}),t.jsxs("button",{type:"button",onClick:()=>c("user"),className:`text-left px-3 py-2 rounded-xl border transition-colors ${l==="user"?"border-brand-600 bg-brand-50 ring-2 ring-brand-300":"border-paper-line hover:border-brand-300"}`,children:[t.jsx("div",{className:"font-medium text-[13px]",children:o("identity.fields.customer")}),t.jsx("div",{className:"text-[11px] text-ink-mute mt-0.5",children:o("identity.fields.customerDesc")})]})]})}),l==="agent"&&t.jsxs(Zs,{label:o("identity.fields.greeting"),className:"sm:col-span-2 2xl:col-span-3",children:[t.jsx("input",{className:"input",value:e.greeting||"",onChange:Z=>a({greeting:Z.target.value}),placeholder:o("identity.fields.greetingPlaceholder")}),t.jsx(qa,{children:o("identity.fields.greetingHint")})]})]})}),t.jsxs(zt,{title:o("identity.section.promptTitle"),desc:o("identity.section.promptDesc"),children:[t.jsx(B3,{value:e.systemPrompt||"",onChange:fe,session:V,onSessionChange:U,onImprove:H,onOpenChat:K,streaming:de,busyTool:F,onAbort:()=>{Ee(),$(!1),G(null)},auditCount:re,improveDisabled:!e.id,improveDisabledHint:e.id?void 0:o("identity.toast.improveSaveFirstDesc"),replySlot:z?t.jsx(W3,{text:z.text,options:z.options,onPick:Z=>{D(null),H(Z,"context")},onDismiss:()=>D(null)}):void 0,textareaRef:S,toolbarExtras:t.jsxs("div",{className:"relative",children:[t.jsx("button",{type:"button",onClick:()=>R(Z=>!Z),className:"inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs font-medium text-brand-700 hover:text-brand-800 hover:bg-brand-50 transition-colors",children:o("identity.prompt.insertVar")}),_&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>R(!1)}),t.jsxs("div",{className:"absolute right-0 mt-1 w-72 rounded-xl border border-paper-line bg-paper-card shadow-lg z-20 p-1",children:[K3.map(Z=>t.jsxs("button",{type:"button",onClick:()=>A(Z.token),className:"w-full text-left px-3 py-2 rounded-lg hover:bg-brand-50 transition-colors",children:[t.jsx("div",{className:"font-mono text-[12px] text-brand-700",children:Z.token}),t.jsx("div",{className:"text-xs text-ink-mute",children:o(Z.labelKey)})]},Z.token)),t.jsx("p",{className:"text-[11px] text-ink-mute px-3 py-2 border-t border-paper-line mt-1",children:o("identity.prompt.varsNeedTzSome")})]})]})]})}),t.jsxs(qa,{children:[o("identity.prompt.varsHintA")," ",t.jsx("code",{className:"font-mono text-[11px] text-brand-700",children:"{{current_time}}"})," ",o("identity.prompt.varsHintB")," ",t.jsx("code",{className:"font-mono text-[11px] text-brand-700",children:"{{nombre}}"})," ",o("identity.prompt.varsHintC")]})]}),t.jsx(zt,{title:o("identity.section.contactVarsTitle"),desc:o("identity.section.contactVarsDesc",{v:"{{variable}}"}),children:E?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-paper-line divide-y divide-paper-line",children:[k.map(Z=>{const ae=w.find(ye=>ye.name===Z),pe=!ae?.defaultValue;return t.jsxs("div",{className:"p-3 flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("code",{className:"font-mono text-[12px] text-brand-700",children:`{{${Z}}}`}),pe?t.jsx("span",{className:"chip text-[10px] bg-amber-50 text-amber-700 border border-amber-200",children:o("identity.contactVars.requiredChip")}):t.jsx("span",{className:"chip chip-mint text-[10px]",children:o("identity.contactVars.hasDefaultChip")})]}),t.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[t.jsx("input",{className:"input h-9 text-sm",placeholder:o("identity.contactVars.defaultPlaceholder"),value:ae?.defaultValue??"",onChange:ye=>C(Z,{defaultValue:ye.target.value})}),t.jsx("input",{className:"input h-9 text-sm",placeholder:o("identity.contactVars.descPlaceholder"),value:ae?.description??"",onChange:ye=>C(Z,{description:ye.target.value})})]})]},Z)}),j.map(Z=>t.jsxs("div",{className:"p-3 flex items-center justify-between gap-3 opacity-60",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("code",{className:"font-mono text-[12px]",children:`{{${Z.name}}}`}),t.jsx("span",{className:"text-xs text-ink-mute ml-2",children:o("identity.contactVars.orphan")})]}),t.jsx("button",{type:"button",onClick:()=>N(Z.name),className:"text-xs text-ink-mute hover:text-rose-500 transition-colors shrink-0",children:o("identity.contactVars.remove")})]},Z.name))]}),t.jsx(qa,{children:o("identity.contactVars.footerHint")})]}):t.jsxs("div",{className:"flex items-center gap-3",style:{padding:"14px 16px",border:"1px dashed var(--cia-border-2)",borderRadius:"var(--cia-r)",color:"var(--cia-text-3)"},children:[t.jsx("code",{className:"font-mono text-[12px] text-brand-700",children:"{{ }}"}),t.jsxs("span",{className:"text-[13px]",children:[o("identity.contactVars.emptyA")," ",t.jsx("code",{className:"font-mono text-[11px] text-brand-700",children:"{{nombre}}"})," ",o("identity.contactVars.emptyB")]})]})}),t.jsx(zt,{title:o("identity.section.knowledgeTitle"),desc:o("identity.section.knowledgeDesc"),last:!0,children:t.jsxs("div",{className:"flex flex-col items-center justify-center text-center gap-3",style:{padding:"28px 16px",border:"1px dashed var(--cia-border-2)",borderRadius:"var(--cia-r-lg)",color:"var(--cia-text-3)"},children:[t.jsx("div",{style:{width:44,height:44,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--cia-bg-tint)",color:"var(--cia-brand-500)"},children:t.jsx(_n,{className:"size-5"})}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx("span",{className:"text-[14px] font-medium",style:{color:"var(--cia-text)"},children:o("identity.knowledge.docsTitle")})}),t.jsx("p",{className:"text-[12.5px]",style:{maxWidth:360},children:o("identity.knowledge.body")}),t.jsxs("button",{type:"button",onClick:s,className:"cia-btn cia-btn-outline cia-btn-sm",title:o("identity.knowledge.configureTitle"),children:[t.jsx(Gb,{className:"size-3.5"}
957)," ",o("identity.knowledge.configure")]})]})})]})]})}function bx({tone:e,text:a}){const n=e==="bad"?"var(--cia-bad-500)":"var(--cia-ok-500)";return t.jsxs("div",{className:"cia-mono",style:{flex:"1 1 200px",minWidth:0,padding:"6px 8px",borderRadius:8,background:`color-mix(in oklab, ${n} 9%, transparent)`,border:`1px solid color-mix(in oklab, ${n} 26%, transparent)`,fontSize:11.5,lineHeight:1.55,color:"var(--cia-text)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[t.jsx("span",{"aria-hidden":!0,style:{color:n,fontWeight:700,marginRight:5},children:e==="bad"?"−":"+"}),a||"—"]})}function Q3({s:e,onAccept:a,onReject:n}){const{t:s}=M("agents"),[i,r]=m.useState(!1),o=e.sensitive&&!i;return t.jsxs("div",{style:{border:"1px solid color-mix(in oklab, var(--cia-cta-500) 30%, transparent)",borderRadius:"var(--cia-r)",background:"var(--cia-bg-elev)",overflow:"hidden"},children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{padding:"7px 10px",borderBottom:"1px solid var(--cia-border)",background:"color-mix(in oklab, var(--cia-cta-500) 7%, var(--cia-bg-soft))"},children:[t.jsx(_t,{className:"size-3",style:{color:"var(--cia-cta-500)",flex:"none"}}),t.jsx("span",{style:{fontSize:11.5,fontWeight:700,color:"var(--cia-text)"},children:s("studio.field.title")}),t.jsx("span",{style:{flex:1}}),e.sensitive&&t.jsxs("span",{className:"inline-flex items-center gap-1",style:{fontSize:10.5,fontWeight:700,color:"var(--cia-warn-ink)"},children:[t.jsx(Tt,{className:"size-3"}),s("studio.field.sensitive")]})]}),e.summary&&t.jsx("p",{style:{margin:0,padding:"8px 10px 0",fontSize:12,color:"var(--cia-text-2)",lineHeight:1.5},children:e.summary}),t.jsx("div",{style:{padding:"8px 10px 0",display:"flex",flexDirection:"column",gap:8},children:e.diff.map(l=>t.jsxs("div",{children:[t.jsx("p",{style:{margin:"0 0 4px",fontSize:10.5,fontWeight:700,letterSpacing:".04em",textTransform:"uppercase",color:"var(--cia-text-3)"},children:l.label||l.field}),t.jsxs("div",{className:"flex gap-2 flex-wrap",children:[t.jsx(bx,{tone:"bad",text:String(l.before??"")}),t.jsx(bx,{tone:"ok",text:String(l.after??"")})]})]},l.field))}),e.sensitive&&t.jsx("div",{style:{padding:"10px 10px 0"},children:t.jsx(mn,{checked:i,onChange:r,label:s("studio.field.confirmSensitive"),description:s("studio.field.confirmSensitiveDesc")})}),t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",style:{padding:10},children:[t.jsxs("button",{type:"button",onClick:a,disabled:o,className:"inline-flex items-center gap-1.5 rounded-lg font-semibold transition-colors",style:{color:o?"var(--cia-text-3)":"#fff",background:o?"var(--cia-bg-soft)":"var(--cia-ok-500)",border:`1px solid ${o?"var(--cia-border)":"var(--cia-ok-500)"}`,padding:"6px 12px",minHeight:32,fontSize:12,cursor:o?"not-allowed":"pointer"},children:[t.jsx(ct,{className:"size-3.5"}),s("studio.field.accept")]}),t.jsxs("button",{type:"button",onClick:n,className:"inline-flex items-center gap-1.5 rounded-lg font-medium transition-colors",style:{color:"var(--cia-text-2)",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",padding:"6px 12px",minHeight:32,fontSize:12,cursor:"pointer"},children:[t.jsx(nt,{className:"size-3.5"}),s("studio.field.reject")]})]})]})}function G3({suggestions:e,onAccept:a,onReject:n}){const s=e.filter(i=>i.state==="pending");return s.length?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10,marginBottom:16},children:s.map(i=>t.jsx(Q3,{s:i,onAccept:()=>a(i.id),onReject:()=>n(i.id)},i.id))}):null}const Z3={systemPrompt:"identity",greeting:"identity",language:"identity",timezone:"identity",dynamicVariables:"identity",tts:"voice",stt:"voice",llm:"behavior",advancedBehavior:"behavior",tools:"tools",analytics:"analytics",knowledgeBaseId:"knowledge",metadata:"limits"};function Y3(e){const a=(e??"").split(".")[0];return Z3[a]??"identity"}const X3=new Set(["systemPrompt"]);function J3(e,a,n){const s=(e.diff??[]).filter(r=>!X3.has(r.field)),i=s.length?Y3(s[0].field):"identity";return{id:a,tab:i,toolName:e.toolName,patch:e.patch,diff:s.length?s:e.diff??[],summary:n,rationale:e.rationale||null,sensitive:!!e.sensitive,state:"pending"}}function eM(e){const a={};for(const n of e)n.state==="pending"&&(a[n.tab]=(a[n.tab]??0)+1);return a}const R0=300*1e3,T0=1800*1e3;async function M0(e){const{data:a}=await T.get("/voices",{params:{provider:e}}
957);return a}async function P0(e){const{data:a}=await T.get("/voices/models",{params:{provider:e}});return a}function Fh(e){return se({queryKey:["voices",e],queryFn:()=>M0(e),staleTime:R0})}function tM(e){return se({queryKey:["voice-models",e],queryFn:()=>P0(e),staleTime:T0})}function aM(){const e=xe();return a=>{e.prefetchQuery({queryKey:["voices",a],queryFn:()=>M0(a),staleTime:R0}),e.prefetchQuery({queryKey:["voice-models",a],queryFn:()=>P0(a),staleTime:T0})}}const nM=["gpt-5.1","gpt-4o","claude-sonnet-4-5"],sM=["eleven_multilingual_v2"],iM=["scheduled","capturing","processing"];function rM({agent:e}){const{t:a}=M("agents"),n=e?.llm?.model||"",s=e?.tts?.model||"",i=e?.tts?.provider||"elevenlabs",r=e?.tts?.voiceId||"",{data:o}=Fh(i),l=!!r&&!!o?.some(f=>f.voiceId===r&&f.isCustom),c=nM.includes(n),d=sM.includes(s),u=c||d||l,p=c?a("tier.reasonBrain"):d?a("tier.reasonVoice"):l?a("tier.reasonCloned"):null;return u?t.jsxs("span",{className:"chip chip-cta text-[11px] inline-flex items-center gap-1",title:a("tier.premiumTitle",{reason:p}),children:[t.jsx(_t,{className:"size-3"}),a("tier.premium")]}):t.jsx("span",{className:"chip text-[11px]",title:a("tier.standardTitle"),children:a("tier.standard")})}function z0(e,a){return`${e}:${a}`}let al=null;const nl=new Map;let xa=null;function Wd(){return al||(al=new Audio,al.preload="none"),al}const cp=ds((e,a)=>{const n=(i,r)=>e(o=>({statuses:{...o.statuses,[i]:r}})),s=i=>e(r=>{if(!(i in r.statuses))return r;const o={...r.statuses};return delete o[i],{statuses:o}});return{statuses:{},toggle:async(i,r,o)=>
957{const l=z0(i,r),c=Wd();if((a().statuses[l]??"idle")==="playing"&&xa===l){c.pause(),n(l,"idle");return}xa&&xa!==l&&(c.pause(),s(xa)),xa=l,n(l,"loading");try{let u=o;if(!u){const x=nl.get(l);if(x)u=x;else{const h=await T.get(`/voices/${i}/${r}/preview`,{responseType:"blob"}),b=URL.createObjectURL(h.data);nl.set(l,b),u=b}}if(xa!==l)return;const p=()=>{xa===l&&n(l,"idle")},f=()=>{xa===l&&n(l,"error")};c.onended=p,c.onerror=f,c.src=u,await c.play(),xa===l&&n(l,"playing")}catch{xa===l&&n(l,"error")}},stop:()=>{if(Wd().pause(),xa){const r=xa;xa=null,e(o=>({statuses:{...o.statuses,[r]:"idle"}}))}},cleanup:()=>{const i=Wd();i.pause(),i.removeAttribute("src"),i.onended=null,i.onerror=null,xa=null;for(const r of nl.values())URL.revokeObjectURL(r);nl.clear(),e({statuses:{}})}}});function oM(e,a){const n=z0(e,a),s=cp(r=>r.statuses[n]??"idle"),i=cp(r=>r.toggle);return{status:s,play:r=>i(e,a,r)}}function lM(){const e=cp(a=>a.cleanup);m.useEffect(()=>e,[e])}const sl=[{id:"elevenlabs",label:"ElevenLabs"},{id:"cartesia",label:"Cartesia"},{id:"openai",label:"OpenAI"}];
957function cM({active:e,onChange:a}){const{t:n}=M("agents"),s=aM(),i=m.useRef([]);function r(o,l){if(o.key!=="ArrowRight"&&o.key!=="ArrowLeft")return;o.preventDefault();const c=o.key==="ArrowRight"?1:-1,d=(l+c+sl.length)%sl.length,u=sl[d].id;a(u),i.current[d]?.focus()}return t.jsx("div",{role:"tablist","aria-label":n("voice.providers.ariaLabel"),className:"flex gap-2",children:sl.map((o,l)=>{const c=o.id===e;return t.jsx("button",{ref:d=>{i.current[l]=d},role:"tab",type:"button","aria-selected":c,tabIndex:c?0:-1,onClick:()=>a(o.id),onMouseEnter:()=>!c&&s(o.id),onFocus:()=>!c&&s(o.id),onKeyDown:d=>r(d,l),className:`h-9 px-4 rounded-full text-sm font-medium border transition-colors
958              focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-300
959              ${c?"border-brand-600 bg-brand-50 text-brand-700 ring-2 ring-brand-300":"border-paper-line text-ink-mute hover:border-brand-300 hover:text-ink"}`,children:o.label},o.id)})})}function dM({models:e,isLoading:a,value:n,onChange:s}){const{t:i}=M("agents"),r=m.useRef([]);if(a)return t.jsxs("div",{className:"flex items-center gap-2 text-sm text-ink-mute py-2",children:[t.jsx(je,{className:"size-4 animate-spin"}),i("voice.model.loading")]});if(e.length===0)return null;function o(l,c){if(l.key!=="ArrowRight"&&l.key!=="ArrowLeft"&&l.key!=="ArrowDown"&&l.key!=="ArrowUp")return;l.preventDefault();const d=l.key==="ArrowRight"||l.key==="ArrowDown",u=(c+(d?1:-1)+e.length)%e.length;s(e[u].model),r.current[u]?.focus()}return t.jsxs("div",{children:[t.jsx("label",{className:"label mb-2 block",children:i("voice.model.label")}),t.jsx("div",{role:"radiogroup","aria-label":i("voice.model.label"),className:"grid sm:grid-cols-2 gap-2",children:e.map((l,c)=>{const d=n===l.model;return t.jsxs("button",{ref:u=>{r.current[c]=u},type:"button",role:"radio","aria-checked":d,tabIndex:d||!n&&c===0?0:-1,onClick:()=>s(l.model),onKeyDown:u=>o(u,c),className:`text-left rounded-xl border px-3 py-2.5 transition-colors
960                focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-300
961                ${d?"border-brand-600 bg-brand-50 ring-2 ring-brand-300":"border-paper-line hover:border-brand-300"}`,children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"font-medium text-sm text-ink",children:l.label}),l.recommended&&t.jsxs("span",{className:"chip chip-brand !h-4 !text-[10px] !px-1.5",children:[t.jsx(fy,{className:"size-2.5"}),i("voice.model.recommended")]})]}),l.latencyHint&&t.jsx("div",{className:"text-[11px] text-ink-mute mt-0.5",children:l.latencyHint})]},l.model)})})]})}function uM({filters:e,onChange:a,genders:n,languages:s}){const{t:i}=M("agents");return t.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[t.jsxs("div",{className:"relative flex-1",children:[t.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 size-4 text-ink-mute pointer-events-none"}),t.jsx("input",{type:"text",className:"input pl-9",placeholder:i("voice.filters.searchPlaceholder"),value:e.query,onChange:r=>a({...e,query:r.target.value}),"aria-label":i("voice.filters.ariaSearch")})]}),n.length>0&&t.jsxs("select",{className:"select sm:w-40",value:e.gender,onChange:r=>a({...e,gender:r.target.value}),"aria-label":i("voice.filters.ariaGender"),children:[t.jsx("option",{value:"",children:i("voice.filters.allGenders")}),n.map(r=>t.jsx("option",{value:r,children:r},r))]}),s.length>0&&t.jsxs("select",{className:"select sm:w-40",value:e.language,onChange:r=>a({...e,language:r.target.value}),"aria-label":i("voice.filters.ariaLanguage"),children:[t.jsx("option",{value:"",children:i("voice.filters.allLanguages")}),s.map(r=>t.jsx("option",{value:r,children:r},r))]})]})}function pM({provider:e,voiceId:a,voiceName:n,previewUrl:s}){const{t:i}=M("agents"),{status:r,play:o}=oM(e,a),l=r==="playing",c=r==="loading",d=r==="error",u=l?i("voice.play.pause",{name:n}):i("voice.play.play",{name:n});return t.jsx("button",{type:"button","aria-label":u,"aria-pressed":l,title:d?i("voice.play.error"):u,onClick:p=>{p.stopPropagation(),o(s)},className:`grid place-items-center size-8 rounded-full border shrink-0 transition-colors
962        focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-300
963        ${l?"border-brand-600 bg-brand-600 text-white":d?"border-rose-200 text-rose-500 hover:bg-rose-50":"border-paper-line text-ink-mute hover:border-brand-300 hover:text-brand-600"}`,children:c?t.jsx(je,{className:"size-4 animate-spin"}):l?t.jsx(Nc,{className:"size-4"}):d?t.jsx(Qg,{className:"size-4"}):t.jsx(rn,{className:"size-4"})})}const yx=["bg-brand-600","bg-brand-500","bg-brand-700","bg-brand-400","bg-mint-600","bg-amber-500"];function hM(e){let a=5381;for(let n=0;n<e.length;n++)a=a*33^e.charCodeAt(n);return a>>>0}function mM(e){const a=hM(e)%yx.length;return yx[a]}function fM(e){const a=(e||"").trim();return a?a[0].toUpperCase():"?"}function xM({voice:e,selected:a,onSelect:n,disabled:s=!1,disabledTooltip:i}){const{t:r}=M("agents"),o=[e.labels.gender,e.labels.accent,e.labels.language].filter(
963Boolean);function l(c){s||(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),n(e))}return t.jsxs("div",{role:"option","aria-selected":a,"aria-disabled":s,tabIndex:s?-1:0,title:s?i:void 0,onClick:()=>{s||n(e)},onKeyDown:l,className:`relative flex items-center gap-3 p-3 rounded-xl border transition-colors
964        focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-300
965        ${s?"opacity-40 cursor-not-allowed border-paper-line bg-paper":a?"border-brand-600 bg-brand-50 ring-2 ring-brand-300 cursor-pointer":"border-paper-line hover:border-brand-300 cursor-pointer"}`,children:[a&&t.jsx("span",{className:"absolute top-2 right-2 grid place-items-center size-5 rounded-full bg-brand-600 text-white",children:t.jsx(ct,{className:"size-3"})}),t.jsx("div",{className:`size-10 rounded-full text-white grid place-items-center text-sm font-bold shrink-0 ${mM(e.voiceId)}`,"aria-hidden":"true",children:fM(e.name)}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:"font-medium text-sm text-ink truncate",children:e.name}),e.isCustom&&t.jsx("span",{className:"chip chip-brand !h-4 !text-[10px] !px-1.5 shrink-0",children:r("voice.card.myVoice")})]}),o.length>0?t.jsx("div",{className:"text-[11px] text-ink-mute font-mono truncate mt-0.5",children:o.join(" · ")}):e.labels.description?t.jsx("div",{className:"text-[11px] text-ink-mute truncate mt-0.5",children:e.labels.description}):null]}),t.jsx(pM,{provider:e.provider,voiceId:e.voiceId,voiceName:e.name,previewUrl:e.previewUrl})]})}const gM=Xa.memo(xM);function bM({voices:e,isLoading:a,isError:n,selectedVoiceId:s,onSelect:i,hasActiveFilters:r,onClearFilters:o,disabledVoiceIds:l,disabledVoiceTooltip:c}){const{t:d}=M("agents");return n?t.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[t.jsx(s2,{className:"size-6 text-ink-mute"}),t.jsx("p",{className:"text-sm text-ink-mute",children:d("voice.grid.errorLoad")})]}):a?t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2",children:Array.from({length:8}).map((u,p)=>t.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border border-paper-line animate-pulse",children:[t.jsx("div",{className:"size-10 rounded-full bg-paper-line shrink-0"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"h-3 w-2/3 rounded bg-paper-line"}),t.jsx("div",{className:"h-2.5 w-1/2 rounded bg-paper-line mt-2"})]}),t.jsx("div",{className:"size-8 rounded-full bg-paper-line shrink-0"})]},p))}):e.length===0?t.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[t.jsx(cy,{className:"size-6 text-ink-mute"}),t.jsx("p",{className:"text-sm text-ink-mute",children:d(r?"voice.grid.emptyFiltered":"voice.grid.emptyNone")}),r&&t.jsx("button",{type:"button",className:"btn btn-outline h-8 px-3 text-sm",onClick:o,children:d("voice.grid.clearFilters")})]}):t.jsx("div",{role:"listbox","aria-label":d("voice.grid.ariaLabel"),className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2 max-h-[420px] overflow-y-auto pr-1",children:e.map(u=>t.jsx(gM,{voice:u,selected:u.voiceId===s,onSelect:i,disabled:l?.has(u.voiceId)??!1,disabledTooltip:l?.has(u.voiceId)?c:void 0},`${u.provider}:${u.voiceId}`))})}var ht;(function(e){e.assertEqual=i=>{};function a(i){}e.assertIs=a;function n(i){throw new Error}e.assertNever=n,e.arrayToEnum=i=>{const r={};for(const o of i)r[o]=o;return r},e.getValidEnumValues=i=>{const r=e.objectKeys(i).filter(l=>typeof i[i[l]]!="number"),o={};for(const l of r)o[l]=i[l];return e.objectValues(o)},e.objectValues=i=>e.objectKeys(i).map(function(r){return i[r]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const r=[];for(const o in i)Object.prototype.hasOwnProperty.call(i,o)&&r.push(o);return r},e.find=(i,r)=>{for(const o of i)if(r(o))return o},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function s(i,r=" | "){return i.map(o=>
vendor: 1,174 bytes, line 965
965typeof o=="string"?`'${o}'`:o).join(r)}e.joinValues=s,e.jsonStringifyReplacer=(i,r)=>typeof r=="bigint"?r.toString():r})(ht||(ht={}));var vx;(function(e){e.mergeShapes=(a,n)=>({...a,...n})})(vx||(vx={}));const Re=ht.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$n=e=>{switch(typeof e){case"undefined":return Re.undefined;case"string":return Re.string;case"number":return Number.isNaN(e)?Re.nan:Re.number;case"boolean":return Re.boolean;case"function":return Re.function;case"bigint":return Re.bigint;case"symbol":return Re.symbol;case"object":return Array.isArray(e)?Re.array:e===null?Re.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Re.promise:typeof Map<"u"&&e instanceof Map?Re.map:typeof Set<"u"&&e instanceof Set?Re.set:typeof Date<"u"&&e instanceof Date?Re.date:Re.object;default:return Re.unknown}},be=ht.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invali
965d_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class An extends Error{get errors(){return this.issues}constructor(a){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=a}format(a){const n=a||function(r){return r.message},s={_errors:[]},i=r=>{for(const o of r.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let l=s,c=0;for(;c<o.path.length;){const d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],c++}}};return i(this),s}static assert(a){if(!(a instanceof An))throw new Error(`Not a ZodError: ${a}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ht.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(a=n=>n.message){const n={},s=[];for(const i of this.issues)if(i.path.length>0){const r=i.path[0];n[r]=n[r]||[],n[r].push(a(i))}else s.push(a(i));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}An.create=e=>new An(e);const dp=(e,a)=>{let n;switch(e.code){case be.invalid_type:e.received===Re.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case be.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ht.jsonStringifyReplacer)}`;break;case be.unrecognized_keys:n=`Unrecognized key(s) in object: ${ht.joinValues(e.keys,", ")}`;break;case be.invalid_union:n="Invalid input";break;case be.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ht.joinValues(e.options)}`;break;case be.invalid_enum_value:n=`Invalid enum value. Expected ${ht.joinValues(e.options)}, received '${e.received}'`;break;case be.invalid_arguments:n="Invalid function arguments";break;case be.invalid_return_type:n="Invalid function return type";break;case be.invalid_date:n="Invalid date";break;case be.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ht.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case be.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case be.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case be.custom:n="Invalid input";break;
vendor: 11,070 bytes, line 965
965case be.invalid_intersection_types:n="Intersection results could not be merged";break;case be.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case be.not_finite:n="Number must be finite";break;default:n=a.defaultError,ht.assertNever(e)}return{message:n}};let yM=dp;function vM(){return yM}const jM=e=>{const{data:a,path:n,errorMaps:s,issueData:i}=e,r=[...n,...i.path||[]],o={...i,path:r};if(i.message!==void 0)return{...i,path:r,message:i.message};let l="";const c=s.filter(d=>!!d).slice().reverse();for(const d of c)l=d(o,{data:a,defaultError:l}).message;return{...i,path:r,message:l}};function Ce(e,a){const n=vM(),s=jM({issueData:a,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===dp?void 0:dp].filter(i=>!!i)});e.common.issues.push(s)}class za{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(a,n){const s=[];for(const i of n){if(i.status==="aborted")return Ue;i.status==="dirty"&&a.dirty(),s.push(i.value)}return{status:a.value,value:s}}static async mergeObjectAsync(a,n){const s=[];for(const i of n){const r=await i.key,o=await i.value;s.push({key:r,value:o})}return za.mergeObjectSync(a,s)}static mergeObjectSync(a,n){const s={};for(const i of n){const{key:r,value:o}=i;if(r.status==="aborted"||o.status==="aborted")return Ue;r.status==="dirty"&&a.dirty(),o.status==="dirty"&&a.dirty(),r.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(s[r.value]=o.value)}return{status:a.value,value:s}}}const Ue=Object.freeze({status:"aborted"}),yr=e=>({status:"dirty",value:e}),Ga=e=>({status:"valid",value:e}),jx=e=>e.status==="aborted",wx=e=>e.status==="dirty",_i=e=>e.status==="valid",nc=e=>typeof Promise<"u"&&e instanceof Promise;var Me;(function(e){e.errToObj=a=>typeof a=="string"?{message:a}:a||{},e.toString=a=>typeof a=="string"?a:a?.message})(Me||(Me={}));class is{constructor(a,n,s,i){this._cachedPath=[],this.parent=a,this.data=n,this._path=s,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const kx=(e,a)=>{if(_i(a))return{success:!0,data:a.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new An(e.common.issues);return this._error=n,this._error}}};function Je(e){if(!e)return{};const{errorMap:a,invalid_type_error:n,required_error:s,description:i}=e;if(a&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return a?{errorMap:a,description:i}:{errorMap:(o,l)=>{const{message:c}=e;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??s??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:i}}class pt{get description(){return this._def.description}_getType(a){return $n(a.data)}_getOrReturnCtx(a,n){return n||{common:a.parent.common,data:a.data,parsedType:$n(a.data),schemaErrorMap:this._def.errorMap,path:a.path,parent:a.parent}}_processInputParams(a){return{status:new za,ctx:{common:a.parent.common,data:a.data,parsedType:$n(a.data),schemaErrorMap:this._def.errorMap,path:a.path,parent:a.parent}}}_parseSync(a){const n=this._parse(a);if(nc(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(a){const n=this._parse(a);return Promise.resolve(n)}parse(a,n){const s=this.safeParse(a,n);if(s.success)return s.data;throw s.error}safeParse(a,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:a,parsedType:$n(a)},i=this._parseSync({data:a,path:s.path,parent:s});return kx(s,i)}"~validate"(a){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:a,parsedType:$n(a)};if(!this["~standard"].async)try{const s=this._parseSync({data:a,path:[],parent:n});return _i(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:a,path:[],parent:n}).then(s=>_i(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(a,n){const s=await this.safeParseAsync(a,n);if(s.success)return s.data;throw s.error}async safeParseAsync(a,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:a,parsedType:$n(a)},i=this._parse({data:a,path:s.path,parent:s}),r=await(nc(i)?i:Promise.resolve(i));return kx(s,r)}refine(a,n){const s=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,r)=>{const o=a(i),l=()=>r.addIssue({code:be.custom,...s(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(a,n){return this._refinement((s,i)=>a(s)?!0:(i.addIssue(typeof n=="function"?n(s,i):n),!1))}_refinement(a){return new Ai({schema:this,typeName:Ve.ZodEffects,effect:{type:"refinement",refinement:a}})}superRefine(a){return this._refinement(a)}constructor(a){this.spa=this.safeParseAsync,this._def=a,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return es.create(this,this._def)}nullable(){return Ri.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pn.create(this)}promise(){return oc.create(this,this._def)}or(a){return ic.create([this,a],this._def)}and(a){return rc.create(this,a,this._def)}transform(a){return new Ai({...Je(this._def),schema:this,typeName:Ve.ZodEffects,effect:{type:"transform",transform:a}})}default(a){const n=typeof a=="function"?a:()=>a;return new pp({...Je(this._def),innerType:this,defaultValue:n,typeName:Ve.ZodDefault})}brand(){return new UM({typeName:Ve.ZodBranded,type:this,...Je(this._def)})}catch(a){const n=typeof a=="function"?a:()=>a;return new hp({...Je(this._def),innerType:this,catchValue:n,typeName:Ve.ZodCatch})}describe(a){const n=this.constructor;return new n({...this._def,description:a})}pipe(a){return Oh.create(this,a)}readonly(){return mp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const wM=/^c[^\s-]{8,}$/i,kM=/^[0-9a-z]+$/,NM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,SM=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,CM=/^[a-z0-9_-]{21}$/i,_M=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,EM=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,AM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,RM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ud;const TM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,MM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,PM=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,zM=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,DM=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,IM=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,D0="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",LM=new RegExp(`^${D0}$`);function I0(e){let a="[0-5]\\d";e.precision?a=`${a}\\.\\d{${e.precision}}`:e.precision==null&&(a=`${a}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${a})${n}`}function FM(e){return new RegExp(`^${I0(e)}$`)}function OM(e){let a=`${D0}T${I0(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),a=`${a}(${n.join("|")})`,new RegExp(`^${a}$`)}function $M(e,a){return!!((a==="v4"||!a)&&TM.test(e)||(a==="v6"||!a)&&PM.test(e))}function qM(e,a){if(!_M.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(s));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||a&&i.alg!==a)}catch{return!1}}function BM(e,a){return!!((a==="v4"||!a)&&MM.test(e)||(a==="v6"||!a)&&zM.test(e))}class Hn extends pt{_parse(a){if(this._def.coerce&&(a.data=String(a.data)),this._getType(a)!==Re.string){const r=this._getOrReturnCtx(a);
vendor: 4,147 bytes, line 965
965return Ce(r,{code:be.invalid_type,expected:Re.string,received:r.parsedType}),Ue}const s=new za;let i;for(const r of this._def.checks)if(r.kind==="min")a.data.length<r.value&&(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),s.dirty());else if(r.kind==="max")a.data.length>r.value&&(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),s.dirty());else if(r.kind==="length"){const o=a.data.length>r.value,l=a.data.length<r.value;(o||l)&&(i=this._getOrReturnCtx(a,i),o?Ce(i,{code:be.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):l&&Ce(i,{code:be.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),s.dirty())}else if(r.kind==="email")AM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"email",code:be.invalid_string,message:r.message}),s.dirty());else if(r.kind==="emoji")Ud||(Ud=new RegExp(RM,"u")),Ud.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"emoji",code:be.invalid_string,message:r.message}),s.dirty());else if(r.kind==="uuid")SM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"uuid",code:be.invalid_string,message:r.message}),s.dirty());else if(r.kind==="nanoid")CM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"nanoid",code:be.invalid_string,message:r.message}),s.dirty());else if(r.kind==="cuid")wM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"cuid",code:be.invalid_string,message:r.message}),s.dirty());else if(r.kind==="cuid2")kM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"cuid2",code:be.invalid_string,message:r.message}),s.dirty());else if(r.kind==="ulid")NM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"ulid",code:be.invalid_string,message:r.message}),s.dirty());else if(r.kind==="url")try{new URL(a.data)}catch{i=this._getOrReturnCtx(a,i),Ce(i,{validation:"url",code:be.invalid_string,message:r.message}),s.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"regex",code:be.invalid_string,message:r.message}),s.dirty())):r.kind==="trim"?a.data=a.data.trim():r.kind==="includes"?a.data.includes(r.value,r.position)||(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),s.dirty()):r.kind==="toLowerCase"?a.data=a.data.toLowerCase():r.kind==="toUpperCase"?a.data=a.data.toUpperCase():r.kind==="startsWith"?a.data.startsWith(r.value)||(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.invalid_string,validation:{startsWith:r.value},message:r.message}),s.dirty()):r.kind==="endsWith"?a.data.endsWith(r.value)||(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.invalid_string,validation:{endsWith:r.value},message:r.message}),s.dirty()):r.kind==="datetime"?OM(r).test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.invalid_string,validation:"datetime",message:r.message}),s.dirty()):r.kind==="date"?LM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.invalid_string,validation:"date",message:r.message}),s.dirty()):r.kind==="time"?FM(r).test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.invalid_string,validation:"time",message:r.message}),s.dirty()):r.kind==="duration"?EM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"duration",code:be.invalid_string,message:r.message}),s.dirty()):r.kind==="ip"?$M(a.data,r.version)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"ip",code:be.invalid_string,message:r.message}),s.dirty()):r.kind==="jwt"?qM(a.data,r.alg)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"jwt",code:be.invalid_string,message:r.message}),s.dirty()):r.kind==="cidr"?BM(a.data,r.version)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"cidr",code:be.invalid_string,message:r.message}),s.dirty()):r.kind==="base64"?DM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"base64",code:be.invalid_string,message:r.message}),s.dirty()):r.kind==="base64url"?IM.test(a.data)||(i=this._getOrReturnCtx(a,i),Ce(i,{validation:"base64url",code:be.invali
vendor: 18,437 bytes, line 965
965d_string,message:r.message}),s.dirty()):ht.assertNever(r);return{status:s.value,value:a.data}}_regex(a,n,s){return this.refinement(i=>a.test(i),{validation:n,code:be.invalid_string,...Me.errToObj(s)})}_addCheck(a){return new Hn({...this._def,checks:[...this._def.checks,a]})}email(a){return this._addCheck({kind:"email",...Me.errToObj(a)})}url(a){return this._addCheck({kind:"url",...Me.errToObj(a)})}emoji(a){return this._addCheck({kind:"emoji",...Me.errToObj(a)})}uuid(a){return this._addCheck({kind:"uuid",...Me.errToObj(a)})}nanoid(a){return this._addCheck({kind:"nanoid",...Me.errToObj(a)})}cuid(a){return this._addCheck({kind:"cuid",...Me.errToObj(a)})}cuid2(a){return this._addCheck({kind:"cuid2",...Me.errToObj(a)})}ulid(a){return this._addCheck({kind:"ulid",...Me.errToObj(a)})}base64(a){return this._addCheck({kind:"base64",...Me.errToObj(a)})}base64url(a){return this._addCheck({kind:"base64url",...Me.errToObj(a)})}jwt(a){return this._addCheck({kind:"jwt",...Me.errToObj(a)})}ip(a){return this._addCheck({kind:"ip",...Me.errToObj(a)})}cidr(a){return this._addCheck({kind:"cidr",...Me.errToObj(a)})}datetime(a){return typeof a=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:a}):this._addCheck({kind:"datetime",precision:typeof a?.precision>"u"?null:a?.precision,offset:a?.offset??!1,local:a?.local??!1,...Me.errToObj(a?.message)})}date(a){return this._addCheck({kind:"date",message:a})}time(a){return typeof a=="string"?this._addCheck({kind:"time",precision:null,message:a}):this._addCheck({kind:"time",precision:typeof a?.precision>"u"?null:a?.precision,...Me.errToObj(a?.message)})}duration(a){return this._addCheck({kind:"duration",...Me.errToObj(a)})}regex(a,n){return this._addCheck({kind:"regex",regex:a,...Me.errToObj(n)})}includes(a,n){return this._addCheck({kind:"includes",value:a,position:n?.position,...Me.errToObj(n?.message)})}startsWith(a,n){return this._addCheck({kind:"startsWith",value:a,...Me.errToObj(n)})}endsWith(a,n){return this._addCheck({kind:"endsWith",value:a,...Me.errToObj(n)})}min(a,n){return this._addCheck({kind:"min",value:a,...Me.errToObj(n)})}max(a,n){return this._addCheck({kind:"max",value:a,...Me.errToObj(n)})}length(a,n){return this._addCheck({kind:"length",value:a,...Me.errToObj(n)})}nonempty(a){return this.min(1,Me.errToObj(a))}trim(){return new Hn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Hn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Hn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(a=>a.kind==="datetime")}get isDate(){return!!this._def.checks.find(a=>a.kind==="date")}get isTime(){return!!this._def.checks.find(a=>a.kind==="time")}get isDuration(){return!!this._def.checks.find(a=>a.kind==="duration")}get isEmail(){return!!this._def.checks.find(a=>a.kind==="email")}get isURL(){return!!this._def.checks.find(a=>a.kind==="url")}get isEmoji(){return!!this._def.checks.find(a=>a.kind==="emoji")}get isUUID(){return!!this._def.checks.find(a=>a.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(a=>a.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(a=>a.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(a=>a.kind==="cuid2")}get isULID(){return!!this._def.checks.find(a=>a.kind==="ulid")}get isIP(){return!!this._def.checks.find(a=>a.kind==="ip")}get isCIDR(){return!!this._def.checks.find(a=>a.kind==="cidr")}get isBase64(){return!!this._def.checks.find(a=>a.kind==="base64")}get isBase64url(){return!!this._def.checks.find(a=>a.kind==="base64url")}get minLength(){let a=null;for(const n of this._def.checks)n.kind==="min"&&(a===null||n.value>a)&&(a=n.value);return a}get maxLength(){let a=null;for(const n of this._def.checks)n.kind==="max"&&(a===null||n.value<a)&&(a=n.value);return a}}Hn.create=e=>new Hn({checks:[],typeName:Ve.ZodString,coerce:e?.coerce??!1,...Je(e)});function WM(e,a){const n=(e.toString().split(".")[1]||"").length,s=(a.toString().split(".")[1]||"").length,i=n>s?n:s,r=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(a.toFixed(i).replace(".",""));return r%o/10**i}class no extends pt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(a){if(this._def.coerce&&(a.data=Number(a.data)),this._getType(a)!==Re.number){const r=this._getOrReturnCtx(a);return Ce(r,{code:be.invalid_type,expected:Re.number,received:r.parsedType}),Ue}let s;const i=new za;for(const r of this._def.checks)r.kind==="int"?ht.isInteger(a.data)||(s=this._getOrReturnCtx(a,s),Ce(s,{code:be.invalid_type,expected:"integer",received:"float",message:r.message}),i.dirty()):r.kind==="min"?(r.inclusive?a.data<r.value:a.data<=r.value)&&(s=this._getOrReturnCtx(a,s),Ce(s,{code:be.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()):r.kind==="max"?(r.inclusive?a.data>r.value:a.data>=r.value)&&(s=this._getOrReturnCtx(a,s),Ce(s,{code:be.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()):r.kind==="multipleOf"?WM(a.data,r.value)!==0&&(s=this._getOrReturnCtx(a,s),Ce(s,{code:be.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()):r.kind==="finite"?Number.isFinite(a.data)||(s=this._getOrReturnCtx(a,s),Ce(s,{code:be.not_finite,message:r.message}),i.dirty()):ht.assertNever(r);return{status:i.value,value:a.data}}gte(a,n){return this.setLimit("min",a,!0,Me.toString(n))}gt(a,n){return this.setLimit("min",a,!1,Me.toString(n))}lte(a,n){return this.setLimit("max",a,!0,Me.toString(n))}lt(a,n){return this.setLimit("max",a,!1,Me.toString(n))}setLimit(a,n,s,i){return new no({...this._def,checks:[...this._def.checks,{kind:a,value:n,inclusive:s,message:Me.toString(i)}]})}_addCheck(a){return new no({...this._def,checks:[...this._def.checks,a]})}int(a){return this._addCheck({kind:"int",message:Me.toString(a)})}positive(a){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Me.toString(a)})}negative(a){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Me.toString(a)})}nonpositive(a){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Me.toString(a)})}nonnegative(a){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Me.toString(a)})}multipleOf(a,n){return this._addCheck({kind:"multipleOf",value:a,message:Me.toString(n)})}finite(a){return this._addCheck({kind:"finite",message:Me.toString(a)})}safe(a){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Me.toString(a)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Me.toString(a)})}get minValue(){let a=null;for(const n of this._def.checks)n.kind==="min"&&(a===null||n.value>a)&&(a=n.value);return a}get maxValue(){let a=null;for(const n of this._def.checks)n.kind==="max"&&(a===null||n.value<a)&&(a=n.value);return a}get isInt(){return!!this._def.checks.find(a=>a.kind==="int"||a.kind==="multipleOf"&&ht.isInteger(a.value))}get isFinite(){let a=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(a===null||s.value<a)&&(a=s.value)}return Number.isFinite(n)&&Number.isFinite(a)}}no.create=e=>new no({checks:[],typeName:Ve.ZodNumber,coerce:e?.coerce||!1,...Je(e)});class so extends pt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(a){if(this._def.coerce)try{a.data=BigInt(a.data)}catch{return this._getInvalidInput(a)}if(this._getType(a)!==Re.bigint)return this._getInvalidInput(a);let s;const i=new za;for(const r of this._def.checks)r.kind==="min"?(r.inclusive?a.data<r.value:a.data<=r.value)&&(s=this._getOrReturnCtx(a,s),Ce(s,{code:be.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()):r.kind==="max"?(r.inclusive?a.data>r.value:a.data>=r.value)&&(s=this._getOrReturnCtx(a,s),Ce(s,{code:be.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()):r.kind==="multipleOf"?a.data%r.value!==BigInt(0)&&(s=this._getOrReturnCtx(a,s),Ce(s,{code:be.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()):ht.assertNever(r);return{status:i.value,value:a.data}}_getInvalidInput(a){const n=this._getOrReturnCtx(a);return Ce(n,{code:be.invalid_type,expected:Re.bigint,received:n.parsedType}),Ue}gte(a,n){return this.setLimit("min",a,!0,Me.toString(n))}gt(a,n){return this.setLimit("min",a,!1,Me.toString(n))}lte(a,n){return this.setLimit("max",a,!0,Me.toString(n))}lt(a,n){return this.setLimit("max",a,!1,Me.toString(n))}setLimit(a,n,s,i){return new so({...this._def,checks:[...this._def.checks,{kind:a,value:n,inclusive:s,message:Me.toString(i)}]})}_addCheck(a){return new so({...this._def,checks:[...this._def.checks,a]})}positive(a){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Me.toString(a)})}negative(a){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Me.toString(a)})}nonpositive(a){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Me.toString(a)})}nonnegative(a){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Me.toString(a)})}multipleOf(a,n){return this._addCheck({kind:"multipleOf",value:a,message:Me.toString(n)})}get minValue(){let a=null;for(const n of this._def.checks)n.kind==="min"&&(a===null||n.value>a)&&(a=n.value);return a}get maxValue(){let a=null;for(const n of this._def.checks)n.kind==="max"&&(a===null||n.value<a)&&(a=n.value);return a}}so.create=e=>new so({checks:[],typeName:Ve.ZodBigInt,coerce:e?.coerce??!1,...Je(e)});class Nx extends pt{_parse(a){if(this._def.coerce&&(a.data=!!a.data),this._getType(a)!==Re.boolean){const s=this._getOrReturnCtx(a);return Ce(s,{code:be.invalid_type,expected:Re.boolean,received:s.parsedType}),Ue}return Ga(a.data)}}Nx.create=e=>new Nx({typeName:Ve.ZodBoolean,coerce:e?.coerce||!1,...Je(e)});class sc extends pt{_parse(a){if(this._def.coerce&&(a.data=new Date(a.data)),this._getType(a)!==Re.date){const r=this._getOrReturnCtx(a);return Ce(r,{code:be.invalid_type,expected:Re.date,received:r.parsedType}),Ue}if(Number.isNaN(a.data.getTime())){const r=this._getOrReturnCtx(a);return Ce(r,{code:be.invalid_date}),Ue}const s=new za;let i;for(const r of this._def.checks)r.kind==="min"?a.data.getTime()<r.value&&(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),s.dirty()):r.kind==="max"?a.data.getTime()>r.value&&(i=this._getOrReturnCtx(a,i),Ce(i,{code:be.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),s.dirty()):ht.assertNever(r);return{status:s.value,value:new Date(a.data.getTime())}}_addCheck(a){return new sc({...this._def,checks:[...this._def.checks,a]})}min(a,n){return this._addCheck({kind:"min",value:a.getTime(),message:Me.toString(n)})}max(a,n){return this._addCheck({kind:"max",value:a.getTime(),message:Me.toString(n)})}get minDate(){let a=null;for(const n of this._def.checks)n.kind==="min"&&(a===null||n.value>a)&&(a=n.value);return a!=null?new Date(a):null}get maxDate(){let a=null;for(const n of this._def.checks)n.kind==="max"&&(a===null||n.value<a)&&(a=n.value);return a!=null?new Date(a):null}}sc.create=e=>new sc({checks:[],coerce:e?.coerce||!1,typeName:Ve.ZodDate,...Je(e)});class Sx extends pt{_parse(a){if(this._getType(a)!==Re.symbol){const s=this._getOrReturnCtx(a);return Ce(s,{code:be.invalid_type,expected:Re.symbol,received:s.parsedType}),Ue}return Ga(a.data)}}Sx.create=e=>new Sx({typeName:Ve.ZodSymbol,...Je(e)});class Cx extends pt{_parse(a){if(this._getType(a)!==Re.undefined){const s=this._getOrReturnCtx(a);return Ce(s,{code:be.invalid_type,expected:Re.undefined,received:s.parsedType}),Ue}return Ga(a.data)}}Cx.create=e=>new Cx({typeName:Ve.ZodUndefined,...Je(e)});class _x extends pt{_parse(a){if(this._getType(a)!==Re.null){const s=this._getOrReturnCtx(a);return Ce(s,{code:be.invalid_type,expected:Re.null,received:s.parsedType}),Ue}return Ga(a.data)}}_x.create=e=>new _x({typeName:Ve.ZodNull,...Je(e)});class Ex extends pt{constructor(){super(...arguments),this._any=!0}_parse(a){return Ga(a.data)}}Ex.create=e=>new Ex({typeName:Ve.ZodAny,...Je(e)});class Ax extends pt{constructor(){super(...arguments),this._unknown=!0}_parse(a){return Ga(a.data)}}Ax.create=e=>new Ax({typeName:Ve.ZodUnknown,...Je(e)});class rs extends pt{_parse(a){const n=this._getOrReturnCtx(a);return Ce(n,{code:be.invalid_type,expected:Re.never,received:n.parsedType}),Ue}}rs.create=e=>new rs({typeName:Ve.ZodNever,...Je(e)});class Rx extends pt{_parse(a){if(this._getType(a)!==Re.undefined){const s=this._getOrReturnCtx(a);return Ce(s,{code:be.invalid_type,expected:Re.void,received:s.parsedType}),Ue}return Ga(a.data)}}Rx.create=e=>new Rx({typeName:Ve.ZodVoid,...Je(e)});class pn extends pt{_parse(a){const{ctx:n,status:s}=this._processInputParams(a),i=this._def;if(n.parsedType!==Re.array)return Ce(n,{code:be.invalid_type,expected:Re.array,received:n.parsedType}),Ue;if(i.exactLength!==null){const o=n.data.length>i.exactLength.value,l=n.data.length<i.exactLength.value;(o||l)&&(Ce(n,{code:o?be.too_big:be.too_small,minimum:l?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(Ce(n,{code:be.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(Ce(n,{code:be.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>i.type._parseAsync(new is(n,o,n.path,l)))).then(o=>za.mergeArray(s,o));const r=[...n.data].map((o,l)=>i.type._parseSync(new is(n,o,n.path,l)));return za.mergeArray(s,r)}get element(){return this._def.type}min(a,n){return new pn({...this._def,minLength:{value:a,message:Me.toString(n)}})}max(a,n){return new pn({...this._def,maxLength:{value:a,message:Me.toString(n)}})}length(a,n){return new pn({...this._def,exactLength:{value:a,message:Me.toString(n)}})}nonempty(a){return this.min(1,a)}}pn.create=(e,a)=>new pn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ve.ZodArray,...Je(a)});function ci(e){if(e instanceof Vt){const a={};for(const n in e.shape){const s=e.shape[n];a[n]=es.create(ci(s))}return new Vt({...e._def,shape:()=>a})}else return e instanceof pn?new pn({...e._def,type:ci(e.element)}):e instanceof es?es.create(ci(e.unwrap())):e instanceof Ri?Ri.create(ci(e.unwrap())):e instanceof Ls?Ls.create(e.items.map(a=>ci(a))):e}class Vt extends pt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const a=this._def.shape(),n=ht.objectKeys(a);return this._cached={shape:a,keys:n},this._cached}_parse(a){if(this._getType(a)!==Re.object){const d=this._getOrReturnCtx(a);return Ce(d,{code:be.invalid_type,expected:Re.object,received:d.parsedType}),Ue}const{status:s,ctx:i}=this._processInputParams(a),{shape:r,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof rs&&this._def.unknownKeys==="strip"))for(const d in i.data)o.includes(d)||l.push(d);const c=[];for(const d of o){const u=r[d],p=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new is(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of l)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")l.length>0&&(Ce(i,{code:be.unrecognized_keys,keys:l}),s.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of l){const p=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new is(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of c){const p=await u.key,f=await u.value;d.push({key:p,value:f,alwaysSet:u.alwaysSet})}return d}).then(d=>za.mergeObjectSync(s,d)):za.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(a){return Me.errToObj,new Vt({...this._def,unknownKeys:"strict",...a!==void 0?{errorMap:(n,s)=>{const i=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:Me.errToObj(a).message??i}:{message:i}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(a){return new Vt({...this._def,shape:()=>({...this._def.shape(),...a})})}merge(a){return new Vt({unknownKeys:a._def.unknownKeys,catchall:a._def.catchall,shape:()=>({...this._def.shape(),...a._def.shape()}),typeName:Ve.ZodObject})}setKey(a,n){return this.augment({[a]:n})}catchall(a){return new Vt({...this._def,catchall:a})}pick(a){const n={};for(const s of ht.objectKeys(a))a[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new Vt({...this._def,shape:()=>n})}omit(a){const n={};for(const s of ht.objectKeys(this.shape))a[s]||(n[s]=this.shape[s]);return new Vt({...this._def,shape:()=>n})}deepPartial(){return ci(this)}partial(a){const n={};for(const s of ht.objectKeys(this.shape)){const i=this.shape[s];a&&!a[s]?n[s]=i:n[s]=i.optional()}return new Vt({...this._def,shape:()=>n})}required(a){const n={};for(const s of ht.objectKeys(this.shape))if(a&&!a[s])n[s]=this.shape[s];else{let r=this.shape[s];for(;r instanceof es;)r=r._def.innerType;n[s]=r}return new Vt({...this._def,shape:()=>n})}keyof(){return L0(ht.objectKeys(this.shape))}}Vt.create=(e,a)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:rs.create(),typeName:Ve.ZodObject,...Je(a)});Vt.strictCreate=(e,a)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:rs.create(),typeName:Ve.ZodObject,...Je(a)});Vt.lazycreate=(e,a)=>new Vt({shape:e,unknownKeys:"strip",catchall:rs.create(),typeName:Ve.ZodObject,...Je(a)});class ic extends pt{_parse(a){const{ctx:n}=this._processInputParams(a),s=this._def.options;function i(r){for(const l of r)if(l.result.status==="valid")return l.result;for(const l of r)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const o=r.map(l=>new An(l.ctx.common.issues));
vendor: 4,118 bytes, line 965
965return Ce(n,{code:be.invalid_union,unionErrors:o}),Ue}if(n.common.async)return Promise.all(s.map(async r=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await r._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let r;const o=[];for(const c of s){const d={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!r&&(r={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(r)return n.common.issues.push(...r.ctx.common.issues),r.result;const l=o.map(c=>new An(c));return Ce(n,{code:be.invalid_union,unionErrors:l}),Ue}}get options(){return this._def.options}}ic.create=(e,a)=>new ic({options:e,typeName:Ve.ZodUnion,...Je(a)});function up(e,a){const n=$n(e),s=$n(a);if(e===a)return{valid:!0,data:e};if(n===Re.object&&s===Re.object){const i=ht.objectKeys(a),r=ht.objectKeys(e).filter(l=>i.indexOf(l)!==-1),o={...e,...a};for(const l of r){const c=up(e[l],a[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===Re.array&&s===Re.array){if(e.length!==a.length)return{valid:!1};const i=[];for(let r=0;r<e.length;r++){const o=e[r],l=a[r],c=up(o,l);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return n===Re.date&&s===Re.date&&+e==+a?{valid:!0,data:e}:{valid:!1}}class rc extends pt{_parse(a){const{status:n,ctx:s}=this._processInputParams(a),i=(r,o)=>{if(jx(r)||jx(o))return Ue;const l=up(r.value,o.value);return l.valid?((wx(r)||wx(o))&&n.dirty(),{status:n.value,value:l.data}):(Ce(s,{code:be.invalid_intersection_types}),Ue)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([r,o])=>i(r,o)):i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}rc.create=(e,a,n)=>new rc({left:e,right:a,typeName:Ve.ZodIntersection,...Je(n)});class Ls extends pt{_parse(a){const{status:n,ctx:s}=this._processInputParams(a);if(s.parsedType!==Re.array)return Ce(s,{code:be.invalid_type,expected:Re.array,received:s.parsedType}),Ue;if(s.data.length<this._def.items.length)return Ce(s,{code:be.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ue;!this._def.rest&&s.data.length>this._def.items.length&&(Ce(s,{code:be.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const r=[...s.data].map((o,l)=>{const c=this._def.items[l]||this._def.rest;return c?c._parse(new is(s,o,s.path,l)):null}).filter(o=>!!o);return s.common.async?Promise.all(r).then(o=>za.mergeArray(n,o)):za.mergeArray(n,r)}get items(){return this._def.items}rest(a){return new Ls({...this._def,rest:a})}}Ls.create=(e,a)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ls({items:e,typeName:Ve.ZodTuple,rest:null,...Je(a)})};class Tx extends pt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(a){const{status:n,ctx:s}=this._processInputParams(a);if(s.parsedType!==Re.map)return Ce(s,{code:be.invalid_type,expected:Re.map,received:s.parsedType}),Ue;const i=this._def.keyType,r=this._def.valueType,o=[...s.data.entries()].map(([l,c],d)=>({key:i._parse(new is(s,l,s.path,[d,"key"])),value:r._parse(new is(s,c,s.path,[d,"value"]))}));if(s.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const c of o){const d=await c.key,u=await c.value;if(d.status==="aborted"||u.status==="aborted")return Ue;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),l.set(d.value,u.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const c of o){const d=c.key,u=c.value;if(d.status==="aborted"||u.status==="aborted")return Ue;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),l.set(d.value,u.value)}return{status:n.value,value:l}}}}Tx.create=(e,a,n)=>new Tx({valueType:a,keyType:e,typeName:Ve.ZodMap,...Je(n)});class io extends pt{_parse(a){const{status:n,ctx:s}=this._processInputParams(a);
vendor: 6,899 bytes, line 965
965if(s.parsedType!==Re.set)return Ce(s,{code:be.invalid_type,expected:Re.set,received:s.parsedType}),Ue;const i=this._def;i.minSize!==null&&s.data.size<i.minSize.value&&(Ce(s,{code:be.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&s.data.size>i.maxSize.value&&(Ce(s,{code:be.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const r=this._def.valueType;function o(c){const d=new Set;for(const u of c){if(u.status==="aborted")return Ue;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const l=[...s.data.values()].map((c,d)=>r._parse(new is(s,c,s.path,d)));return s.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(a,n){return new io({...this._def,minSize:{value:a,message:Me.toString(n)}})}max(a,n){return new io({...this._def,maxSize:{value:a,message:Me.toString(n)}})}size(a,n){return this.min(a,n).max(a,n)}nonempty(a){return this.min(1,a)}}io.create=(e,a)=>new io({valueType:e,minSize:null,maxSize:null,typeName:Ve.ZodSet,...Je(a)});class Mx extends pt{get schema(){return this._def.getter()}_parse(a){const{ctx:n}=this._processInputParams(a);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Mx.create=(e,a)=>new Mx({getter:e,typeName:Ve.ZodLazy,...Je(a)});class Px extends pt{_parse(a){if(a.data!==this._def.value){const n=this._getOrReturnCtx(a);return Ce(n,{received:n.data,code:be.invalid_literal,expected:this._def.value}),Ue}return{status:"valid",value:a.data}}get value(){return this._def.value}}Px.create=(e,a)=>new Px({value:e,typeName:Ve.ZodLiteral,...Je(a)});function L0(e,a){return new Ei({values:e,typeName:Ve.ZodEnum,...Je(a)})}class Ei extends pt{_parse(a){if(typeof a.data!="string"){const n=this._getOrReturnCtx(a),s=this._def.values;return Ce(n,{expected:ht.joinValues(s),received:n.parsedType,code:be.invalid_type}),Ue}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(a.data)){const n=this._getOrReturnCtx(a),s=this._def.values;return Ce(n,{received:n.data,code:be.invalid_enum_value,options:s}),Ue}return Ga(a.data)}get options(){return this._def.values}get enum(){const a={};for(const n of this._def.values)a[n]=n;return a}get Values(){const a={};for(const n of this._def.values)a[n]=n;return a}get Enum(){const a={};for(const n of this._def.values)a[n]=n;return a}extract(a,n=this._def){return Ei.create(a,{...this._def,...n})}exclude(a,n=this._def){return Ei.create(this.options.filter(s=>!a.includes(s)),{...this._def,...n})}}Ei.create=L0;class zx extends pt{_parse(a){const n=ht.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(a);if(s.parsedType!==Re.string&&s.parsedType!==Re.number){const i=ht.objectValues(n);return Ce(s,{expected:ht.joinValues(i),received:s.parsedType,code:be.invalid_type}),Ue}if(this._cache||(this._cache=new Set(ht.getValidEnumValues(this._def.values))),!this._cache.has(a.data)){const i=ht.objectValues(n);return Ce(s,{received:s.data,code:be.invalid_enum_value,options:i}),Ue}return Ga(a.data)}get enum(){return this._def.values}}zx.create=(e,a)=>new zx({values:e,typeName:Ve.ZodNativeEnum,...Je(a)});class oc extends pt{unwrap(){return this._def.type}_parse(a){const{ctx:n}=this._processInputParams(a);if(n.parsedType!==Re.promise&&n.common.async===!1)return Ce(n,{code:be.invalid_type,expected:Re.promise,received:n.parsedType}),Ue;const s=n.parsedType===Re.promise?n.data:Promise.resolve(n.data);return Ga(s.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}}oc.create=(e,a)=>new oc({type:e,typeName:Ve.ZodPromise,...Je(a)});class Ai extends pt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ve.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(a){const{status:n,ctx:s}=this._processInputParams(a),i=this._def.effect||null,r={addIssue:o=>{Ce(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(r.addIssue=r.addIssue.bind(r),i.type==="preprocess"){const o=i.transform(s.data,r);if(s.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return Ue;const c=await this._def.schema._parseAsync({data:l,path:s.path,parent:s});return c.status==="aborted"?Ue:c.status==="dirty"||n.value==="dirty"?yr(c.value):c});{if(n.value==="aborted")return Ue;const l=this._def.schema._parseSync({data:o,path:s.path,parent:s});return l.status==="aborted"?Ue:l.status==="dirty"||n.value==="dirty"?yr(l.value):l}}if(i.type==="refinement"){const o=l=>{const c=i.refinement(l,r);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(s.common.async===!1){const l=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return l.status==="aborted"?Ue:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(l=>l.status==="aborted"?Ue:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(i.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!_i(o))return Ue;const l=i.transform(o.value,r);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>_i(o)?Promise.resolve(i.transform(o.value,r)).then(l=>({status:n.value,value:l})):Ue);ht.assertNever(i)}}Ai.create=(e,a,n)=>new Ai({schema:e,typeName:Ve.ZodEffects,effect:a,...Je(n)});Ai.createWithPreprocess=(e,a,n)=>new Ai({schema:a,effect:{type:"preprocess",transform:e},typeName:Ve.ZodEffects,...Je(n)});class es extends pt{_parse(a){return this._getType(a)===Re.undefined?Ga(void 0):this._def.innerType._parse(a)}unwrap(){return this._def.innerType}}es.create=(e,a)=>new es({innerType:e,typeName:Ve.ZodOptional,...Je(a)});class Ri extends pt{_parse(a){return this._getType(a)===Re.null?Ga(null):this._def.innerType._parse(a)}unwrap(){return this._def.innerType}}Ri.create=(e,a)=>new Ri({innerType:e,typeName:Ve.ZodNullable,...Je(a)});class pp extends pt{_parse(a){const{ctx:n}=this._processInputParams(a);let s=n.data;return n.parsedType===Re.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}pp.create=(e,a)=>new pp({innerType:e,typeName:Ve.ZodDefault,defaultValue:typeof a.default=="function"?a.default:()=>a.default,...Je(a)});class hp extends pt{_parse(a){const{ctx:n}=this._processInputParams(a),s={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return nc(i)?i.then(r=>
965({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new An(s.common.issues)},input:s.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new An(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}hp.create=(e,a)=>new hp({innerType:e,typeName:Ve.ZodCatch,catchValue:typeof a.catch=="function"?a.catch:()=>a.catch,...Je(a)});class Dx extends pt{_parse(a){if(this._getType(a)!==Re.nan){const s=this._getOrReturnCtx(a);return Ce(s,{code:be.invalid_type,expected:Re.nan,received:s.parsedType}),Ue}return{status:"valid",value:a.data}}}Dx.create=e=>new Dx({typeName:Ve.ZodNaN,...Je(e)});class UM extends pt{_parse(a){const{ctx:n}=this._processInputParams(a),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Oh extends pt{_parse(a){const{status:n,ctx:s}=this._processInputParams(a);if(s.common.async)return(async()=>{const r=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?Ue:r.status==="dirty"?(n.dirty(),yr(r.value)):this._def.out._parseAsync({data:r.value,path:s.path,parent:s})})();{const i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?Ue:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(a,n){return new Oh({in:a,out:n,typeName:Ve.ZodPipeline})}}class mp extends pt{_parse(a){const n=this._def.innerType._parse(a),s=i=>(_i(i)&&(i.value=Object.freeze(i.value)),i);return nc(n)?n.then(i=>s(i)):s(n)}unwrap(){return this._def.innerType}}mp.create=(e,a)=>new mp({innerType:e,typeName:Ve.ZodReadonly,...Je(a)});var Ve;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Ve||(Ve={}));const VM=Hn.create;rs.create;pn.create;ic.create;rc.create;Ls.create;Ei.create;oc.create;es.create;Ri.create;function KM({open:e,onClose:a,scope:n,onSuccess:s}){const{t:i}=M("agents"),r=xe(),[o,l]=m.useState(""),[c,d]=m.useState(""),[u,p]=m.useState(null);m.useEffect(()=>{e&&(l(""),d(""),p(null))},[e]),m.useEffect(()=>{if(!e)return;const h=b=>{b.key==="Escape"&&a()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,a]);const f=oe({mutationFn:async()=>{const h=n==="global"?"/admin/voices/import":"/voices/import",{data:b}=await T.post(h,{shareLink:o.trim(),name:c.trim()});return b},onSuccess:h=>{r.invalidateQueries({queryKey:["voices","elevenlabs"]}),r.invalidateQueries({queryKey:["admin-voices"]}),s(h),a()},onError:h=>{const b=h?.response?.data?.message;p(Array.isArray(b)?b.join(" · "):b||i("voice.import.errImportFailed"))}});function x(){p(null);const b=VM().trim().url(i("voice.import.errUrlInvalid")).refine(g=>{try{const v=new URL(g);return/(^|\.)elevenlabs\.io$/.test(v.hostname)&&v.pathname.includes("/share/")}catch{return!1}},i("voice.import.errShareFormat")).safeParse(o);if(!b.success){p(b.error.issues[0]?.message??i("voice.import.errLinkInvalid"));return}if(!c.trim()){p(i("voice.import.errNameRequired"));return}f.mutate()}return e?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black/30 z-40",onClick:a,"aria-hidden":"true"}),t.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"import-voice-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-paper-card rounded-2xl border border-paper-line shadow-xl w-full max-w-lg flex flex-col",onClick:h=>h.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 p-6 border-b border-paper-line",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:i(n==="global"?"voice.import.eyebrowGlobal":"voice.import.eyebrowTenant")}),t.jsx("h2",{id:"import-voice-modal-title",className:"text-lg font-semibold text-ink mt-0.5",children:i("voice.import.title")}),t.jsx("p",{className:"text-sm text-ink-mute mt-1",children:i(n==="global"?"voice.import.subtitleGlobal":"voice.import.subtitleTenant")})]}),t.jsx("button",{className:"btn btn-ghost h-8 w-8 p-0 shrink-0",onClick:a,"aria-label":i("modal.close"),children:t.jsx(nt,{className:"size-4"})})]}),t.jsxs("div",{className:"p-6 flex flex-col gap-5",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-baseline gap-1 mb-1.5",children:[t.jsx("label",{className:"label",children:i("voice.import.shareLinkLabel")}),t.jsx("span",{className:"text-rose-500 text-xs leading-none",children:"*"})]}),t.jsx("input",{className:"input font-mono text-[13px]",type:"text",placeholder:"https://elevenlabs.io/app/voice-library/share/…",value:o,onChange:h=>{l(h.target.value),p(null)},autoFocus:!0}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1.5",children:i("voice.import.shareLinkHint")})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-baseline gap-1 mb-1.5",children:[t.jsx("label",{className:"label",children:i("voice.import.nameLabel")}),t.jsx("span",{className:"text-rose-500 text-xs leading-none",children:"*"})]}),t.jsx("input",{className:"input",type:"text",placeholder:i("voice.import.namePlaceholder"),maxLength:120,value:c,onChange:h=>{d(h.target.value),p(null)}})]}),u&&t.jsx("div",{className:"rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700",children:u})]}),t.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-paper-line",children:[t.jsx("button",{className:"btn btn-outline",onClick:a,disabled:f.isPending,children:i("modal.cancel")}),t.jsx("button",{className:"btn btn-primary",onClick:x,disabled:f.isPending,children:f.isPending?t.jsxs(t.Fragment,{children:[t.jsx(je,{className:"size-4 animate-spin"}),i("voice.import.importing")]}):t.jsxs(t.Fragment,{children:[t.jsx(BS,{className:"size-4"}),i("voice.import.importBtn")]})})]})]})})]}):null}function HM({voiceId:e}){const{t:a}=M("agents");return t.jsxs("div",{className:"flex items-start gap-2 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:[t.jsx(Tt,{className:"size-4 shrink-0 mt-0.5"}),t.jsx("div",{children:t.jsx(wa,{t:a,i18nKey:"voice.unavailable.notice",components:{c0:t.jsx("span",{className:"font-mono text-[12px]"})},values:{voiceId:e}})})]})}const Vd={query:"",gender:"",language:""};function F0({tts:e,onChange:a}){const{can:n}=tt(),{t:s}=M("agents"),[i,r]=m.useState(e?.provider??"elevenlabs"),[o,l]=m.useState(Vd),[c,d]=m.useState(!1),[u,p]=m.useState(e?.provider===i?e?.model:void 0);lM();const f=Fh(i),x=tM(i),h=f.data??[],b=x.data??[],g=e&&e.provider===i?e.voiceId:void 0,{genders:v,languages:y}=m.useMemo(()=>{const I=new Set,P=new Set;for(const O of h)O.labels.gender&&I.add(O.labels.gender),O.labels.language&&P.add(O.labels.language);return{genders:[...I].sort(),languages:[...P].sort()}},[h]),k=m.useMemo(()=>{const I=o.query.trim().toLowerCase();return h.filter(P=>!(I&&!P.name.toLowerCase().includes(I)||o.gender&&P.labels.gender!==o.gender||o.language&&P.labels.language!==o.language))},[h,o]),w=o.query.trim()!==""||o.gender!==""||o.language!=="",j=!f.isLoading&&!f.isError&&e?.provider===i&&!!e?.voiceId&&!h.some(I=>I.voiceId===e.voiceId);function C(I){const P=e?.model&&b.some(W=>W.model===e.model),O=b.find(W=>
965W.recommended)?.model,K=u??(P?e.model:O);a({provider:I.provider,voiceId:I.voiceId,...K?{model:K}:{}})}function N(I){p(I),g&&a({provider:i,voiceId:g,model:I})}function S(I){r(I),l(Vd),p(void 0)}const _=g?e?.model??u:u,A=i==="openai"&&_&&_!=="gpt-4o-mini-tts"?new Set(["marin","cedar"]):new Set,E=s("voice.picker.disabledTooltip");return t.jsxs("div",{className:"flex flex-col gap-5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[t.jsx(cM,{active:i,onChange:S}),i==="elevenlabs"&&n("voices.manage")&&t.jsxs("button",{type:"button",className:"btn btn-outline h-9",onClick:()=>d(!0),children:[t.jsx(Fe,{className:"size-4"}),s("voice.import.title")]})]}),j&&e?.voiceId&&t.jsx(HM,{voiceId:e.voiceId}),t.jsx(dM,{models:b,isLoading:x.isLoading,value:_,onChange:N}),t.jsx(uM,{filters:o,onChange:l,genders:v,languages:y}),t.jsx(bM,{voices:k,isLoading:f.isLoading,isError:f.isError,selectedVoiceId:g,onSelect:C,hasActiveFilters:w,onClearFilters:()=>l(Vd),disabledVoiceIds:A,disabledVoiceTooltip:E}),t.jsx(KM,{open:c,onClose:()=>d(!1),scope:"tenant",onSuccess:I=>{C(I)}})]})}function QM({agent:e,onChange:a}){const{t:n}=M("agents");return t.jsx("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:t.jsxs(zt,{title:n("voice.title"),desc:n("voice.desc"),last:!0,children:[t.jsxs("div",{className:"rounded-xl border border-paper-line bg-paper px-4 py-3 text-sm text-ink-mute",children:[n("voice.sttNotice")," ",t.jsx("span",{className:"font-mono text-[12px]",children:n("voice.sttLocation")}),"."]}),t.jsx(F0,{tts:e.tts,onChange:s=>a({tts:s})})]})})}const $h="-",GM=e=>{const a=YM(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:o=>{const l=o.split($h);return l[0]===""&&l.length!==1&&l.shift(),O0(l,a)||ZM(o)},getConflictingClassGroupIds:(o,l)=>{const c=n[o]||[];return l&&s[o]?[...c,...s[o]]:c}}},O0=(e,a)=>{if(e.length===0)return a.classGroupId;const n=e[0],s=a.nextPart.get(n),i=s?O0(e.slice(1),s):void 0;if(i)return i;if(a.validators.length===0)return;const r=e.join($h);return a.validators.find(({validator:o})=>o(r))?.classGroupId},Ix=/^\[(.+)\]$/,ZM=e=>{if(Ix.test(e)){const a=Ix.exec(e)[1],n=a?.substring(0,a.indexOf(":"));if(n)return"arbitrary.."+n}},YM=e=>{const{theme:a,prefix:n}=e,s={nextPart:new Map,validators:[]};return JM(Object.entries(e.classGroups),n).forEach(([r,o])=>{fp(o,s,r,a)}),s},fp=(e,a,n,s)=>{e.forEach(i=>{if(typeof i=="string"){const r=i===""?a:Lx(a,i);r.classGroupId=n;return}if(typeof i=="function"){if(XM(i)){fp(i(s),a,n,s);return}a.validators.push({validator:i,classGroupId:n});return}Object.entries(i).forEach(([r,o])=>{fp(o,Lx(a,r),n,s)})})},Lx=(e,a)=>{let n=e;
vendor: 4,763 bytes, line 965
965return a.split($h).forEach(s=>{n.nextPart.has(s)||n.nextPart.set(s,{nextPart:new Map,validators:[]}),n=n.nextPart.get(s)}),n},XM=e=>e.isThemeGetter,JM=(e,a)=>a?e.map(([n,s])=>{const i=s.map(r=>typeof r=="string"?a+r:typeof r=="object"?Object.fromEntries(Object.entries(r).map(([o,l])=>[a+o,l])):r);return[n,i]}):e,eP=e=>{if(e<1)return{get:()=>{},set:()=>{}};let a=0,n=new Map,s=new Map;const i=(r,o)=>{n.set(r,o),a++,a>e&&(a=0,s=n,n=new Map)};return{get(r){let o=n.get(r);if(o!==void 0)return o;if((o=s.get(r))!==void 0)return i(r,o),o},set(r,o){n.has(r)?n.set(r,o):i(r,o)}}},$0="!",tP=e=>{const{separator:a,experimentalParseClassName:n}=e,s=a.length===1,i=a[0],r=a.length,o=l=>{const c=[];let d=0,u=0,p;for(let g=0;g<l.length;g++){let v=l[g];if(d===0){if(v===i&&(s||l.slice(g,g+r)===a)){c.push(l.slice(u,g)),u=g+r;continue}if(v==="/"){p=g;continue}}v==="["?d++:v==="]"&&d--}const f=c.length===0?l:l.substring(u),x=f.startsWith($0),h=x?f.substring(1):f,b=p&&p>u?p-u:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:h,maybePostfixModifierPosition:b}};return n?l=>n({className:l,parseClassName:o}):o},aP=e=>{if(e.length<=1)return e;const a=[];let n=[];return e.forEach(s=>{s[0]==="["?(a.push(...n.sort(),s),n=[]):n.push(s)}),a.push(...n.sort()),a},nP=e=>({cache:eP(e.cacheSize),parseClassName:tP(e),...GM(e)}),sP=/\s+/,iP=(e,a)=>{const{parseClassName:n,getClassGroupId:s,getConflictingClassGroupIds:i}=a,r=[],o=e.trim().split(sP);let l="";for(let c=o.length-1;c>=0;c-=1){const d=o[c],{modifiers:u,hasImportantModifier:p,baseClassName:f,maybePostfixModifierPosition:x}=n(d);let h=!!x,b=s(h?f.substring(0,x):f);if(!b){if(!h){l=d+(l.length>0?" "+l:l);continue}if(b=s(f),!b){l=d+(l.length>0?" "+l:l);continue}h=!1}const g=aP(u).join(":"),v=p?g+$0:g,y=v+b;if(r.includes(y))continue;r.push(y);const k=i(b,h);for(let w=0;w<k.length;++w){const j=k[w];r.push(v+j)}l=d+(l.length>0?" "+l:l)}return l};function rP(){let e=0,a,n,s="";for(;e<arguments.length;)(a=arguments[e++])&&(n=q0(a))&&(s&&(s+=" "),s+=n);return s}const q0=e=>{if(typeof e=="string")return e;let a,n="";for(let s=0;s<e.length;s++)e[s]&&(a=q0(e[s]))&&(n&&(n+=" "),n+=a);return n};function oP(e,...a){let n,s,i,r=o;function o(c){const d=a.reduce((u,p)=>p(u),e());return n=nP(d),s=n.cache.get,i=n.cache.set,r=l,l(c)}function l(c){const d=s(c);if(d)return d;const u=iP(c,n);return i(c,u),u}return function(){return r(rP.apply(null,arguments))}}const kt=e=>{const a=n=>n[e]||[];return a.isThemeGetter=!0,a},B0=/^\[(?:([a-z-]+):)?(.+)\]$/i,lP=/^\d+\/\d+$/,cP=new Set(["px","full","screen"]),dP=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uP=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,pP=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,hP=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,mP=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,wn=e=>xi(e)||cP.has(e)||lP.test(e),Ln=e=>$i(e,"length",wP),xi=e=>!!e&&!Number.isNaN(Number(e)),Kd=e=>$i(e,"number",xi),ir=e=>!!e&&Number.isInteger(Number(e)),fP=e=>e.endsWith("%")&&xi(e.slice(0,-1)),Ye=e=>B0.test(e),Fn=e=>dP.test(e),xP=new Set(["length","size","percentage"]),gP=e=>$i(e,xP,W0),bP=e=>$i(e,"position",W0),yP=new Set(["image","url"]),vP=e=>$i(e,yP,NP),jP=e=>$i(e,"",kP),rr=()=>!0,$i=(e,a,n)=>{const s=B0.exec(e);return s?s[1]?typeof a=="string"?s[1]===a:a.has(s[1]):n(s[2]):!1},wP=e=>uP.test(e)&&!pP.test(e),W0=()=>!1,kP=e=>hP.test(e),NP=e=>mP.test(e),SP=()=>{const e=kt("colors"),a=kt("spacing"),n=kt("blur"),s=kt("brightness"),i=kt("borderColor"),r=kt("borderRadius"),o=kt("borderSpacing"),l=kt("borderWidth"),c=kt("contrast"),d=kt("grayscale"),u=kt("hueRotate"),p=kt("invert"),f=kt("gap"),x=kt("gradientColorStops"),h=kt("gradientColorStopPositions"),b=kt("inset"),g=kt("margin"),v=kt("opacity"),y=kt("padding"),k=kt("saturate"),w=kt("scale"),j=kt("sepia"),C=kt("skew"),N=kt("space"),S=kt("translate"),_=()=>["auto","contain","none"],R=()=>["auto","hidden","clip","visible","scroll"],A=()=>["auto",Ye,a],E=()=>[Ye,a],I=()=>["",wn,Ln],P=()=>["auto",xi,Ye],O=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],K=()=>["solid","dashed","dotted","double","none"],W=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],V=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",Ye],X=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ie=()=>[xi,Ye];return{cacheSize:500,separator:":",theme:{colors:[rr],spacing:[wn,Ln],blur:["none","",Fn,Ye],brightness:ie(),borderColor:[e],borderRadius:["n
965one","","full",Fn,Ye],borderSpacing:E(),borderWidth:I(),contrast:ie(),grayscale:U(),hueRotate:ie(),invert:U(),gap:E(),gradientColorStops:[e],gradientColorStopPositions:[fP,Ln],inset:A(),margin:A(),opacity:ie(),padding:E(),saturate:ie(),scale:ie(),sepia:U(),skew:ie(),space:E(),translate:E()},classGroups:{aspect:[{aspect:["auto","square","video",Ye]}],container:["container"],columns:[{columns:[Fn]}],"break-after":[{"break-after":X()}],"break-before":[{"break-before":X()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...O(),Ye]}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:_()}],"overscroll-x":[{"overscroll-x":_()}],"overscroll-y":[{"overscroll-y":_()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",ir,Ye]}],basis:[{basis:A()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Ye]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",ir,Ye]}],"grid-cols":[{"grid-cols":[rr]}],"col-start-end":[{col:["auto",{span:["full",ir,Ye]},Ye]}],"col-start":[{"col-start":P()}],"col-end":[{"col-end":P()}],"grid-rows":[{"grid-rows":[rr]}],"row-start-end":[{row:["auto",{span:[ir,Ye]},Ye]}],"row-start":[{"row-start":P()}],"row-end":[{"row-end":P()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Ye]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Ye]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...V()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...V(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...V(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[g]}],mx:[{mx:[g]}],my:[{my:[g]}],ms:[{ms:[g]}],me:[{me:[g]}],mt:[{mt:[g]}],mr:[{mr:[g]}],mb:[{mb:[g]}],ml:[{ml:[g]}],"space-x":[{"space-x":[N]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[N]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Ye,a]}],"min-w":[{"min-w":[Ye,a,"min","max","fit"]}],"max-w":[{"max-w":[Ye,a,"none","full","min","max","fit","prose",{screen:[Fn]},Fn]}],h:[{h:[Ye,a,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Ye,a,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Ye,a,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Ye,a,"auto","min","max","fit"]}],"font-size":[{text:["base",Fn,Ln]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Kd]}],"font-family":[{font:[rr]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Ye]}],"line-clamp":[{"line-clamp":["none",xi,Kd]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",wn,Ye]}],"list-image":[{"list-image":["none",Ye]}],"list-style-type":[{list:["none","disc","decimal",Ye]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...K(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",wn,Ln]}],"underline-offset":[{"underline-offset":["auto",wn,Ye]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:E()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ye]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Ye]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...O(),bP]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",gP]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},vP]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[h]}
vendor: 5,182 bytes, line 965
965],"gradient-via-pos":[{via:[h]}],"gradient-to-pos":[{to:[h]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[r]}],"rounded-s":[{"rounded-s":[r]}],"rounded-e":[{"rounded-e":[r]}],"rounded-t":[{"rounded-t":[r]}],"rounded-r":[{"rounded-r":[r]}],"rounded-b":[{"rounded-b":[r]}],"rounded-l":[{"rounded-l":[r]}],"rounded-ss":[{"rounded-ss":[r]}],"rounded-se":[{"rounded-se":[r]}],"rounded-ee":[{"rounded-ee":[r]}],"rounded-es":[{"rounded-es":[r]}],"rounded-tl":[{"rounded-tl":[r]}],"rounded-tr":[{"rounded-tr":[r]}],"rounded-br":[{"rounded-br":[r]}],"rounded-bl":[{"rounded-bl":[r]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[v]}],"border-style":[{border:[...K(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:K()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...K()]}],"outline-offset":[{"outline-offset":[wn,Ye]}],"outline-w":[{outline:[wn,Ln]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:I()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[wn,Ln]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Fn,jP]}],"shadow-color":[{shadow:[rr]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...W(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":W()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[s]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Fn,Ye]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[p]}],saturate:[{saturate:[k]}],sepia:[{sepia:[j]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[s]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[k]}],"backdrop-sepia":[{"backdrop-sepia":[j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Ye]}],duration:[{duration:ie()}],ease:[{ease:["linear","in","out","in-out",Ye]}],delay:[{delay:ie()}],animate:[{animate:["none","spin","ping","pulse","bounce",Ye]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[w]}],"scale-x":[{"scale-x":[w]}],"scale-y":[{"scale-y":[w]}],rotate:[{rotate:[ir,Ye]}],"translate-x":[{"translate-x":[S]}],"translate-y":[{"translate-y":[S]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Ye]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Ye]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":E()}],"scroll-mx":[{"scroll-mx":E()}],"scroll-my":[{"scroll-my":E()}],"scroll-ms":[{"scroll-ms":E()}],"scroll-me":[{"scroll-me":E()}],"scroll-mt":[{"scroll-mt":E()}],"scroll-mr":[{"scroll-mr":E()}],"scroll-mb":[{"scroll-mb":E()}],"scroll-ml":[{"scroll-ml":E()}],"scroll-p":[{"scroll-p":E()}],"scroll-px":[{"scroll-px":E()}],"scroll-py":[{"scroll-py":E()}],"scroll-ps":[{"scroll-ps":E()}],"scroll-pe":[{"scroll-pe":E()}],"scroll-pt":[{"scroll-pt":E()}],"scroll-pr":[{"scroll-pr":E()}],"scroll-pb":[{"scroll-pb":E()}],"scroll-pl":[{"scroll-pl":E()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}
965],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Ye]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[wn,Ln,Kd]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},CP=oP(SP);function os(...e){return CP(Gj(e))}const _P=[{type:"none",labelKey:"speech.bgAudio.none"},{type:"office_ambience",labelKey:"speech.bgAudio.office_ambience"},{type:"crowded_room",labelKey:"speech.bgAudio.crowded_room"},{type:"city_ambience",labelKey:"speech.bgAudio.city_ambience"},{type:"forest_ambience",labelKey:"speech.bgAudio.forest_ambience"},{type:"keyboard_typing",labelKey:"speech.bgAudio.keyboard_typing"},{type:"hold_music",labelKey:"speech.bgAudio.hold_music"},{type:"coffee_shop",labelKey:"speech.bgAudio.coffee_shop"},{type:"static_noise",labelKey:"speech.bgAudio.static_noise"}],fs={responseEagerness:.5,dynamicEndpointing:!0,interruptionSensitivity:.5,reminder:{intervalSeconds:15,maxCount:1},silenceTimeoutSeconds:-1,pronunciation:[],outboundGreeting:"afterCallee"},Fx=30,EP=40,AP=3;function RP(e){return e.replace(/\s+/g," ").replace(/^[\s"'«»“”‘’.,;:!?¡¿]+|[\s"'«»“”‘’.,;:!?¡¿]+$/g,"").trim().toLowerCase()}function Xs(e,a,n){return isNaN(e)?a:Math.min(n,Math.max(a,e))}function Ox({label:e,description:a,value:n,min:s=0,max:i=1,step:r=.05,onChange:o,recommended:l,warning:c}){return t.jsxs("div",{className:"flex flex-col gap-1.5",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:e}),t.jsx("div",{className:"text-xs text-ink-mute mt-0.5",children:a})]}),t.jsx("span",{className:"text-xs font-mono tabular-nums shrink-0 mt-0.5 w-8 text-right",style:{color:c?"var(--cia-warn-ink)":"var(--cia-text)"},children:n.toFixed(2)})]}),t.jsx("input",{type:"range",min:s,max:i,step:r,value:n,onChange:d=>o(parseFloat(d.target.value)),className:"w-full accent-brand-600 h-1.5 rounded-full cursor-pointer"}),t.jsxs("div",{className:"flex justify-between text-[10px] text-ink-mute font-mono",children:[t.jsx("span",{children:s.toFixed(1)}),t.jsx("span",{style:l!=null?{color:"var(--cia-ok-500)",fontWeight:600}:void 0,children:l!=null?`${l.toFixed(1)} ✓`:((s+i)/2).toFixed(1)}),t.jsx("span",{children:i.toFixed(1)})]}),c&&t.jsxs("p",{className:"text-xs mt-0.5",style:{color:"var(--cia-warn-ink)",lineHeight:1.5,margin:0},children:[c.message,c.fix?` ${c.fix}`:""]})]})}const or={eagerness:.5,sensitivity:.5,bgVolume:.2};
965function TP({agent:e,onChange:a,auditIssues:n}){const{t:s}=M("agents"),{t:i}=M("agentsRoutes"),r=(...B)=>{const ne=n?.find(me=>B.includes(me.code));if(ne)return{message:i(`audit.code.${ne.code}`,{defaultValue:ne.message,...ne.params??{}}),fix:ne.fixHint?i(`audit.fix.${ne.code}`,{defaultValue:ne.fixHint,...ne.params??{}}):void 0}},[o,l]=m.useState(!1),[c,d]=m.useState(""),[u,p]=m.useState(null),f=m.useId(),x=m.useId(),h=m.useId(),b=m.useId(),g=e.backgroundAudio??{type:"none",volume:or.bgVolume},v=g.type??"none",y=g.volume??or.bgVolume;function k(B){a({backgroundAudio:{type:B,volume:B==="none"?void 0:y}})}function w(B){a({backgroundAudio:{type:v,volume:B}})}const j=e.advancedBehavior??{},C=j.responseEagerness??fs.responseEagerness,N=j.dynamicEndpointing??fs.dynamicEndpointing,S=j.interruptionSensitivity??fs.interruptionSensitivity,_=j.reminder??fs.reminder,R=j.silenceTimeoutSeconds??fs.silenceTimeoutSeconds,A=j.pronunciation??fs.pronunciation,E=j.pauseBeforeSpeaking??0,I=j.outboundGreeting??fs.outboundGreeting,P=j.turnTaking?.mode!=="sensitive",O=j.turnTaking?.ignoreTerms??[],K=O.length>=Fx,W=m.useRef(j.turnTaking?.mode),V=j.textNormalization?.enabled??!1,U=e.language??"es",X=U.startsWith("en")?'"$1,250.00" → "one thousand two hundred fifty dollars"':U.startsWith("pt")?'"R$1.250,00" → "mil duzentos e cinquenta reais"':'"$1.250.000" → "un millón doscientos cincuenta mil pesos"';function ie(B){a({advancedBehavior:{responseEagerness:C,dynamicEndpointing:N,interruptionSensitivity:S,reminder:_,pronunciation:A,...j,...B}})}function de(B){const ne={...j.turnTaking??{},...B};ne.mode===void 0&&delete ne.mode,ne.ignoreTerms?.length||delete ne.ignoreTerms,ie({turnTaking:Object.keys(ne).length>0?ne:void 0})}function $(B){de({mode:B?W.current==="natural"?"natural":void 0:"sensitive"})}function z(B){const ne=B.split(",").map(RP).filter(Boolean),me=[...O],Ee=new Set(me.map(ke=>ke.toLowerCase())),L=[];let re=null;for(const ke of ne){if(ke.length>EP||ke.split(" ").length>AP){re=s("speech.turnTaking.tooLong"),L.push(ke);continue}if(!Ee.has(ke)){if(me.length>=Fx){re=s("speech.turnTaking.limit"),L.push(ke);continue}Ee.add(ke),me.push(ke)}}me.length!==O.length&&de({ignoreTerms:me}),d(L.join(", ")),p(re)}function D(B){de({ignoreTerms:O.filter((ne,me)=>me!==B)}),p(null)}function F(){A.length>=50||ie({pronunciation:[...A,{from:"",to:""}]})}function G(B,ne,me){const Ee=A.map((L,re)=>re===B?{...L,[ne]:me}:L);ie({pronunciation:Ee})}function te(B){ie({pronunciation:A.filter((ne,me)=>me!==B)})}return t.jsxs("div",{className:"rounded-xl border border-paper-line bg-paper overflow-hidden",children:[t.jsxs("button",{type:"button",onClick:()=>l(B=>!B),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-paper-line/30 transition-colors",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(dy,{className:"size-4 text-brand-600"}),t.jsx("span",{className:"text-sm font-semibold text-ink",children:s("speech.header.title")})]}),o?t.jsx(Rn,{className:"size-4 text-ink-mute"}):t.jsx(Ut,{className:"size-4 text-ink-mute"})]}),o&&t.jsxs("div",{className:"border-t border-paper-line p-4 flex flex-col gap-6",children:[t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:s("speech.pause.title")}),t.jsx("p",{className:"text-xs text-ink-mute",children:s("speech.pause.desc")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"number",min:0,max:5,step:.5,value:E,onChange:B=>ie({pauseBeforeSpeaking:Xs(parseFloat(B.target.value),0,5)}),className:"input w-20 font-mono tabular-nums text-center text-sm"}),t.jsx("span",{className:"text-sm text-ink-mute",children:s("speech.seconds")})]}),t.jsx(hn,{id:f,label:s("speech.outboundGreeting.label"),description:s("speech.outboundGreeting.desc"),value:I,onChange:B=>ie({outboundGreeting:B==="onAnswer"?"onAnswer":"afterCallee"}),options:[{value:"afterCallee",label:s("speech.outboundGreeting.afterCallee")},{value:"onAnswer",label:s("speech.outboundGreeting.onAnswer")}],style:{paddingTop:4}})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("label",{className:"text-sm font-medium text-ink",children:s("speech.bgSound.label")}),t.jsx("p",{className:"text-xs text-ink-mute",children:s("speech.bgSound.desc")}
965),t.jsx("select",{value:v,onChange:B=>k(B.target.value),className:"input w-full text-sm",children:_P.map(B=>t.jsx("option",{value:B.type,children:s(B.labelKey)},B.type))}),v!=="none"&&t.jsxs("div",{className:"flex flex-col gap-1.5 pt-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-medium text-ink",children:s("speech.bgSound.volumeLabel")}),t.jsxs("span",{className:"text-xs font-mono tabular-nums text-ink-mute",children:[Math.round(y*100),"%"]})]}),t.jsx("input",{type:"range",min:0,max:1,step:.05,value:y,onChange:B=>w(parseFloat(B.target.value)),className:"w-full accent-brand-600 h-1.5 rounded-full cursor-pointer"}),t.jsxs("div",{className:"flex justify-between text-[10px] text-ink-mute font-mono",children:[t.jsx("span",{children:"0%"}),t.jsxs("span",{style:{color:"var(--cia-ok-500)",fontWeight:600},children:[Math.round(or.bgVolume*100),"% ✓"]}),t.jsx("span",{children:"100%"})]}),(()=>{const B=r("background_audio_loud");return B?t.jsxs("p",{className:"text-xs",style:{color:"var(--cia-warn-ink)",lineHeight:1.5,margin:0},children:[B.message,B.fix?` ${B.fix}`:""]}):null})()]})]}),t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Ox,{label:s("speech.eagerness.label"),description:s("speech.eagerness.desc"),value:C,recommended:or.eagerness,warning:r("eagerness_too_high"),onChange:B=>ie({responseEagerness:Xs(B,0,1)})}),t.jsxs("label",{className:"flex items-center gap-2 cursor-pointer group",children:[t.jsx("input",{type:"checkbox",checked:N,onChange:B=>ie({dynamicEndpointing:B.target.checked}),className:"w-4 h-4 rounded border-paper-line accent-brand-600 cursor-pointer"}),t.jsx("span",{className:"text-sm text-ink group-hover:text-brand-700 transition-colors",children:s("speech.eagerness.dynamicCheckbox")})]})]}),t.jsx(Ox,{label:s("speech.interruption.label"),description:s("speech.interruption.desc"),value:S,recommended:or.sensitivity,warning:r("interruption_and_background","interruption_hypersensitive"),onChange:B=>ie({interruptionSensitivity:Xs(B,0,1)})}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:s("speech.turnTaking.label")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:s("speech.turnTaking.desc")})]}),t.jsx(vt,{checked:P,onChange:$,label:s("speech.turnTaking.label")})]}),(()=>{const B=r("turn_ignore_content_word","turn_natural_off_high_sensitivity");return B?t.jsxs("p",{className:"text-xs",style:{color:"var(--cia-warn-ink)",lineHeight:1.5,margin:0},children:[B.message,B.fix?` ${B.fix}`:""]}):null})(),t.jsxs("div",{className:"flex flex-col gap-1.5 pt-1",children:[t.jsx("label",{htmlFor:x,className:"text-xs font-medium text-ink",children:s("speech.turnTaking.extraLabel")}),t.jsx("p",{id:h,className:"text-[11px] text-ink-mute",style:{margin:0},children:s("speech.turnTaking.extraHint")}),O.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5",children:O.map((B,ne)=>t.jsx(ps,{label:B,onRemove:()=>D(ne),removeLabel:s("speech.turnTaking.remove",{term:B})},`${ne}-${B}`))}),t.jsx("input",{id:x,type:"text",value:c,disabled:!P||K,placeholder:s("speech.turnTaking.extraPlaceholder"),"aria-describedby":u?`${h} ${b}`:h,"aria-invalid":u?!0:void 0,onChange:B=>{const ne=B.target.value;if(ne.includes(",")){z(ne);return}d(ne),u&&p(null)},onKeyDown:B=>{B.nativeEvent.isComposing||(B.key==="Enter"||B.key===",")&&(B.preventDefault(),z(c))},onBlur:()=>{c.trim()&&z(c)},className:"input w-full text-sm disabled:opacity-60 disabled:cursor-not-allowed"}),u?t.jsx("p",{id:b,role:"alert",className:"text-xs",style:{color:"var(--cia-warn-ink)",lineHeight:1.5,margin:0},children:u}):K?t.jsx("p",{className:"text-xs text-ink-mute",style:{margin:0},children:s("speech.turnTaking.limit")}):null]})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:s("speech.reminder.title")}),t.jsx("p",{className:"text-xs text-ink-mute",children:s("speech.reminder.desc")}),t.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"number",min:5,max:120,step:5,value:_.intervalSeconds,onChange:B=>{const ne=Xs(parseInt(B.target.value,10),5,120);ie({reminder:{..._,intervalSeconds:ne}})},className:"input w-20 font-mono tabular-nums text-center text-sm"}),t.jsx("span",{className:"text-sm text-ink-mute",children:s("speech.seconds")})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"number",min:1,max:10,step:1,value:_.maxCount,onChange:B=>{const ne=Xs(parseInt(B.target.value,10),1,10);ie({reminder:{..._,maxCount:ne}})},className:"input w-16 font-mono tabular-nums text-center text-sm"}),t.jsx("span",{className:"text-sm text-ink-mute",children:s("speech.reminder.times",{count:_.maxCount})})]})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 pt-1",children:[t.jsx("span",{className:"text-xs font-medium text-ink",children:s("speech.reminder.messageLabel")}),t.jsx("div",{className:"flex gap-2",children:[{v:"ai",l:s("speech.reminder.modeAi")},{v:"static",l:s("speech.reminder.modeStatic")}].map(B=>{const ne=(_.messageMode??"ai")===B.v;return t.jsx("button",{type:"button",onClick:()=>ie({reminder:{..._,messageMode:B.v}}
965),className:os("rounded-lg border px-2.5 h-8 text-[12px] transition-colors",ne?"border-brand-600 bg-brand-50 text-brand-700":"border-paper-line text-ink-mute hover:border-brand-300"),children:B.l},B.v)})}),t.jsx("textarea",{rows:2,value:_.message??"",onChange:B=>ie({reminder:{..._,message:B.target.value}}),placeholder:(_.messageMode??"ai")==="static"?s("speech.reminder.placeholderStatic"):s("speech.reminder.placeholderAi"),className:"input w-full text-sm resize-none",maxLength:2e3}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:(_.messageMode??"ai")==="static"?s("speech.reminder.footerStatic"):s("speech.reminder.footerAi")})]})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:s("speech.silence.title")}),t.jsxs("p",{className:"text-xs text-ink-mute",children:[s("speech.silence.descA")," ",t.jsx("span",{className:"font-mono",children:"-1"})," ",s("speech.silence.descB")]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"number",min:-1,max:600,step:1,value:R,onChange:B=>ie({silenceTimeoutSeconds:Xs(parseInt(B.target.value,10),-1,600)}),className:"input w-20 font-mono tabular-nums text-center text-sm"}),t.jsx("span",{className:"text-sm text-ink-mute",children:R<=0?s("speech.silence.noLimit"):s("speech.seconds")})]}),R>0&&R<8&&t.jsx("p",{className:"text-xs text-amber-600",children:s("speech.silence.shortWarning")})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:s("speech.textNorm.title")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:s("speech.textNorm.desc")})]}),t.jsx(vt,{checked:V,onChange:()=>ie({textNormalization:{enabled:!V}})})]}),V&&t.jsx("p",{className:"text-xs text-ink-mute bg-paper-line/30 rounded-lg px-3 py-2 font-mono",children:X})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:s("speech.pronunciation.title")}),t.jsx("p",{className:"text-xs text-ink-mute",children:s("speech.pronunciation.desc")}),A.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsxs("div",{className:"grid grid-cols-[1fr_1fr_auto] gap-2 px-1",children:[t.jsx("span",{className:"text-[11px] font-medium text-ink-mute uppercase tracking-wide",children:s("speech.pronunciation.colFrom")}),t.jsx("span",{className:"text-[11px] font-medium text-ink-mute uppercase tracking-wide",children:s("speech.pronunciation.colTo")}),t.jsx("span",{className:"w-7"})]}),A.map((B,ne)=>t.jsxs("div",{className:"grid grid-cols-[1fr_1fr_auto] gap-2 items-center",children:[t.jsx("input",{type:"text",placeholder:"Enlassa AI",value:B.from,maxLength:64,onChange:me=>G(ne,"from",me.target.value),className:"input text-sm"}),t.jsx("input",{type:"text",placeholder:"wee-kall",value:B.to,maxLength:128,onChange:me=>G(ne,"to",me.target.value),className:"input text-sm"}),t.jsx("button",{type:"button",onClick:()=>te(ne),title:s("speech.pronunciation.removeRule"),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",children:t.jsx(nt,{className:"size-4"})})]},ne))]}),A.length<50&&t.jsxs("button",{type:"button",onClick:F,className:"flex items-center gap-1.5 text-sm text-brand-600 hover:text-brand-700 font-medium w-fit mt-1 transition-colors",children:[t.jsx(Fe,{className:"size-4"}),s("speech.pronunciation.addRule")]}),A.length>=50&&t.jsx("p",{className:"text-xs text-ink-mute",children:s("speech.pronunciation.limitReached")})]})]})]})}const MP=[{id:"gpt-4.1-mini",provider:"openai",label:"GPT-4.1 mini",descKey:"behavior.models.gpt41miniDesc"},{id:"gpt-4o",provider:"openai",label:"GPT-4o",descKey:"behavior.models.gpt4oDesc"},{id:"gpt-5.1",provider:"openai",label:"GPT-5.1",descKey:"behavior.models.gpt51Desc"},{id:"claude-haiku-4-5",provider:"anthropic",label:"Claude Haiku 4.5",descKey:"behavior.models.haikuDesc"}];function PP({agent:e,onChange:a,auditIssues:n}){const{t:s}=M("agents"),i=e.llm||{provider:"openai",model:"gpt-4.1-mini",temperature:.7};return t.jsxs("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:[t.jsxs(zt,{title:s("behavior.section.title"),desc:s("behavior.section.desc"),children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-2 block",children:s("behavior.llmLabel")}),t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:MP.map(r=>{const o=i.model===r.id;return t.jsxs("button",{onClick:()=>a({llm:{provider:r.provider,model:r.id,temperature:i.temperature}}),className:`text-left p-3 rounded-xl border ${o?"border-brand-600 bg-brand-50 ring-2 ring-brand-300":"border-paper-line hover:border-brand-300"}`,children:[t.jsx("div",{className:"font-medium text-sm",children:r.label}),t.jsxs("div",{className:"text-[11px] text-ink-mute font-mono mt-0.5",children:[r.provider," · ",r.id]}),t.jsx("div",{className:"text-xs text-ink-mute mt-1",children:s(r.descKey)})]},r.id)})})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("label",{className:"label",children:s("behavior.temperature")}),t.jsx("span",{className:"font-mono text-sm tabular-nums",children:i.temperature.toFixed(2)})]}),t.jsx("input",{type:"range",min:"0",max:"1.2",step:"0.05",value:i.temperature,onChange:r=>a({llm:{...i,temperature:parseFloat(r.target.value)}}),className:"w-full accent-brand-600"}),t.jsxs("div",{className:"flex justify-between text-[11px] font-mono text-ink-mute mt-1",children:[t.jsx("span",{children:s("behavior.deterministic")}),t.jsx("span",{children:s("behavior.creative")})]})]})]}
965),t.jsx(TP,{agent:e,onChange:a,auditIssues:n})]})}const zP=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,il="transferir_a_agente",$x=10,qx=(e,a,n,s)=>{if(e===""||e===null||e===void 0)return s;const i=Math.trunc(Number(e));return Number.isFinite(i)?Math.min(n,Math.max(a,i)):s};function rl(){return{targetAgentId:"",condition:"",transferMessage:"",delayMs:0,keepVoice:!1,keepLanguage:!0,enableFirstMessage:!1}}function U0({checked:e,onChange:a}){return t.jsx(vt,{checked:e,onChange:a})}function Hd({label:e,hint:a,checked:n,onChange:s}){return t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[13px] text-ink",children:e}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:a})]}),t.jsx(U0,{checked:n,onChange:s})]})}function DP({open:e,onClose:a,onSave:n,initial:s,agents:i}){const{t:r}=M("agents"),[o,l]=m.useState(il),[c,d]=m.useState(""),[u,p]=m.useState([rl()]),[f,x]=m.useState(!1),[h,b]=m.useState(5),[g,v]=m.useState(null);if(m.useEffect(()=>{if(!e)return;const C=s?.config??{};l(s?.name||il),d(s?.description??""),p(Array.isArray(C.rules)&&C.rules.length?C.rules.map(N=>({...rl(),...N})):[rl()]),x(C.disableInterruptions===!0),b(typeof C.maxHandoffs=="number"?C.maxHandoffs:5),v(null)},[e,s]),m.useEffect(()=>{if(!e)return;const C=N=>{N.key==="Escape"&&a()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e,a]),!e)return null;function y(C,N){p(S=>S.map((_,R)=>R===C?{..._,...N}:_))}function k(){p(C=>C.length>=$x?C:[...C,rl()])}function w(C){p(N=>N.filter((S,_)=>_!==C))}function j(){v(null);const C=o.trim();if(!zP.test(C))return v(r("tools.transferAgentModal.errNameFormat"));if(u.length===0)return v(r("tools.transferAgentModal.errNoRules"));for(let S=0;S<u.length;S++)if(!u[S].targetAgentId)return v(r("tools.transferAgentModal.errNoTarget",{n:S+1}));const N={id:s?.id||"tool_transfer",type:"transfer",name:C,description:c.trim()||void 0,config:{rules:u.map(S=>({...S.id?{id:S.id}:{},targetAgentId:S.targetAgentId,condition:(S.condition||"").trim(),transferMessage:(S.transferMessage||"").trim(),delayMs:qx(S.delayMs,0,5e3,0),keepVoice:S.keepVoice===!0,keepLanguage:S.keepLanguage!==!1,enableFirstMessage:S.enableFirstMessage===!0})),disableInterruptions:f,maxHandoffs:qx(h,1,10,5)}};n(N),a()}return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black/30 z-40",onClick:a,"aria-hidden":"true"}),t.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"transfer-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-paper-card rounded-2xl border border-paper-line shadow-xl w-full max-w-2xl flex flex-col max-h-[90vh]",onClick:C=>C.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 p-6 border-b border-paper-line",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:r("tools.transferAgentModal.eyebrow")}),t.jsx("h2",{id:"transfer-modal-title",className:"text-lg font-semibold text-ink mt-0.5",children:r("tools.transferAgentModal.title")}),t.jsx("p",{className:"text-sm text-ink-mute mt-1",children:r("tools.transferAgentModal.subtitle")})]}),t.jsx("button",{className:"btn btn-ghost h-8 w-8 p-0 shrink-0",onClick:a,"aria-label":r("modal.close"),children:t.jsx(nt,{className:"size-4"})})]}),t.jsxs("div",{className:"p-6 flex flex-col gap-5 overflow-y-auto",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("modal.toolName")}),t.jsx("input",{className:"input font-mono text-[13px]",type:"text",placeholder:il,value:o,maxLength:64,onChange:C=>l(C.target.value)}),t.jsx("p",{className:"text-xs text-ink-mute mt-1",children:r("tools.transferAgentModal.nameHint",{name:o||il})})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("modal.descriptionOptional")}),t.jsx("textarea",{className:"textarea min-h-[60px] text-[13px]",placeholder:r("tools.transferAgentModal.descriptionPlaceholder"),value:c,maxLength:2e3,onChange:C=>d(C.target.value)})]}),t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:r("tools.transferCommon.rulesTitle")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:r("tools.transferAgentModal.rulesSubtitle")})]}),u.length<$x&&t.jsxs("button",{type:"button",className:"btn btn-outline h-9 shrink-0",onClick:k,children:[t.jsx(Fe,{className:"size-4"}),r("tools.transferCommon.addRule")]})]}),u.map((C,N)=>{const S=i.some(_=>_.id===C.targetAgentId);return t.jsxs("div",{className:"rounded-xl border border-paper-line bg-paper p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-ink",children:[t.jsx(Kb,{className:"size-4 text-brand-600"}),r("tools.transferCommon.ruleN",{n:N+1})]}),u.length>1&&t.jsx("button",{type:"button",onClick:()=>w(N),title:r("tools.transferCommon.removeRule"),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",children:t.jsx(mt,{className:"size-4"})})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-baseline gap-1 mb-1.5",children:[t.jsx("label",{className:"label",children:r("tools.transferAgentModal.targetAgentLabel")}),t.jsx("span",{className:"text-rose-500 text-xs leading-none",children:"*"})]}),t.jsxs("select",{className:"select w-full",value:C.targetAgentId,onChange:_=>y(N,{targetAgentId:_.target.value}),children:[t.jsx("option",{value:"",children:r("tools.transferAgentModal.targetAgentPlaceholder")}),i.map(_=>t.jsx("option",{value:_.id,children:_.name}
965,_.id)),C.targetAgentId&&!S&&t.jsx("option",{value:C.targetAgentId,disabled:!0,children:r("tools.transferAgentModal.agentUnavailable")})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("tools.transferCommon.conditionOptional")}),t.jsx("textarea",{className:"textarea min-h-[52px] text-[13px]",placeholder:r("tools.transferCommon.conditionPlaceholder"),value:C.condition??"",maxLength:1e3,onChange:_=>y(N,{condition:_.target.value})})]}),t.jsxs("div",{className:"grid sm:grid-cols-[1fr_140px] gap-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("tools.transferAgentModal.transferMessageLabel")}),t.jsx("input",{className:"input text-[13px]",type:"text",placeholder:r("tools.transferAgentModal.transferMessagePlaceholder"),value:C.transferMessage??"",maxLength:500,onChange:_=>y(N,{transferMessage:_.target.value})})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("tools.transferAgentModal.delayLabel")}),t.jsx("input",{className:"input text-[13px] font-mono tabular-nums",type:"number",min:0,max:5e3,step:100,value:C.delayMs??0,onChange:_=>y(N,{delayMs:_.target.value===""?0:Number(_.target.value)})})]})]}),t.jsxs("div",{className:"flex flex-col gap-3 rounded-lg bg-paper-card border border-paper-line p-3",children:[t.jsx(Hd,{label:r("tools.transferAgentModal.keepVoiceLabel"),hint:r("tools.transferAgentModal.keepVoiceHint"),checked:C.keepVoice===!0,onChange:_=>y(N,{keepVoice:_})}),t.jsx(Hd,{label:r("tools.transferAgentModal.keepLanguageLabel"),hint:r("tools.transferAgentModal.keepLanguageHint"),checked:C.keepLanguage!==!1,onChange:_=>y(N,{keepLanguage:_})}),t.jsx(Hd,{label:r("tools.transferAgentModal.greetLabel"),hint:r("tools.transferAgentModal.greetHint"),checked:C.enableFirstMessage===!0,onChange:_=>y(N,{enableFirstMessage:_})})]})]},C.id??N)})]}),t.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-paper-line bg-paper p-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[13px] text-ink",children:r("tools.transferAgentModal.noInterruptLabel")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:r("tools.transferAgentModal.noInterruptHint")})]}),t.jsx(U0,{checked:f,onChange:x})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[13px] text-ink",children:r("tools.transferCommon.maxTransfers")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:r("tools.transferAgentModal.maxHandoffsHint")})]}),t.jsx("input",{className:"input text-[13px] font-mono tabular-nums w-20 shrink-0",type:"number",min:1,max:10,value:h,onChange:C=>b(C.target.value===""?5:Number(C.target.value))})]})]}),g&&t.jsx("div",{className:"rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700",children:g})]}),t.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-paper-line",children:[t.jsx("button",{className:"btn btn-outline",onClick:a,children:r("modal.cancel")}),t.jsx("button",{className:"btn btn-primary",onClick:j,children:r(s?"modal.saveChanges":"modal.addTool")})]})]})})]})}const IP=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,LP=/^\+[1-9]\d{1,14}$/,Bx=/^(x-[a-z0-9-]{1,62}|user-to-user)$/i,Qd="transferir_llamada",Wx=10,FP=[{value:"cold",labelKey:"tools.transferCallModal.typeColdLabel",soon:!1,hintKey:"tools.transferCallModal.typeColdHint"},{value:"warm",labelKey:"tools.transferCallModal.typeWarmLabel",soon:!1,hintKey:"tools.transferCallModal.typeWarmHint"}],OP=[{value:"none",labelKey:"tools.transferCallModal.onHoldNone"},{value:"ringtone",labelKey:"tools.transferCallModal.onHoldRingtone"},{value:"relaxing",labelKey:"tools.transferCallModal.onHoldRelaxing"},{value:"uplifting",labelKey:"tools.transferCallModal.onHoldUplifting"}];function $P({checked:e,onChange:a}){return t.jsx(vt,{checked:e,onChange:a})}function ol(){return{destinationNumber:"",condition:"",type:"cold",extension:"",ringSeconds:30,onHold:{type:"none"},displayedCallerId:"agent",customHeaders:{},navigateIvrDtmf:""}}function qP({open:e,onClose:a,onSave:n,initial:s}){const{t:i}=M("agents"),[r,o]=m.useState(Qd),[l,c]=m.useState(""),[d,u]=m.useState([ol()]),[p,f]=m.useState([[]]
965),[x,h]=m.useState(""),[b,g]=m.useState(3),[v,y]=m.useState(null);if(m.useEffect(()=>{if(!e)return;const S=s?.config??{};o(s?.name||Qd),c(s?.description??"");const _=Array.isArray(S.rules)&&S.rules.length?S.rules.map(R=>({...ol(),...R})):[ol()];u(_),f(_.map(R=>Object.entries(R.customHeaders||{}).map(([A,E])=>({key:A,value:String(E)})))),h(S.talkWhileWaiting?.text??""),g(typeof S.maxCallTransfers=="number"?S.maxCallTransfers:3),y(null)},[e,s]),m.useEffect(()=>{if(!e)return;const S=_=>{_.key==="Escape"&&a()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[e,a]),!e)return null;function k(S,_){u(R=>R.map((A,E)=>E===S?{...A,..._}:A))}function w(){d.length>=Wx||(u(S=>[...S,ol()]),f(S=>[...S,[]]))}function j(S){u(_=>_.filter((R,A)=>A!==S)),f(_=>_.filter((R,A)=>A!==S))}function C(S,_){f(R=>R.map((A,E)=>E===S?_:A))}function N(){y(null);const S=r.trim();if(!IP.test(S))return y(i("tools.transferCallModal.errNameFormat"));if(d.length===0)return y(i("tools.transferCallModal.errNoRules"));for(let A=0;A<d.length;A++){const E=(d[A].destinationNumber||"").trim();if(!LP.test(E))return y(i("tools.transferCallModal.errDestE164",{n:A+1}));for(const I of p[A]||[])if(I.key&&!Bx.test(I.key))return y(i("tools.transferCallModal.errSipHeader",{n:A+1,key:I.key}))}const _=d.map((A,E)=>{const I={};for(const P of p[E]||[])P.key&&Bx.test(P.key)&&(I[P.key.trim()]=P.value);return{...A.id?{id:A.id}:{},destinationNumber:(A.destinationNumber||"").trim(),condition:(A.condition||"").trim(),type:A.type||"cold",extension:(A.extension||"").trim(),ringSeconds:A.ringSeconds??30,onHold:A.onHold||{type:"none"},displayedCallerId:A.displayedCallerId||"agent",customHeaders:I,navigateIvrDtmf:(A.navigateIvrDtmf||"").trim(),...A.type==="warm"&&A.waitForRealAgent===!0?{waitForRealAgent:!0,waitForRealAgentSeconds:Math.min(120,Math.max(5,A.waitForRealAgentSeconds??25))}:{},...A.type==="warm"&&(A.whisper?.text||"").trim()?{whisper:{mode:A.whisper?.mode==="static"?"static":"prompt",text:A.whisper.text.trim()}}:{}}}),R={id:s?.id||"tool_transfer_call",type:"transfer_call",name:S,description:l.trim()||void 0,config:{rules:_,...x.trim()?{talkWhileWaiting:{mode:"static",text:x.trim()}}:{},maxCallTransfers:b}};n(R),a()}return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black/30 z-40",onClick:a,"aria-hidden":"true"}),t.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"transfercall-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-paper-card rounded-2xl border border-paper-line shadow-xl w-full max-w-2xl flex flex-col max-h-[90vh]",onClick:S=>S.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 p-6 border-b border-paper-line",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:i("tools.transferCallModal.eyebrow")}),t.jsx("h2",{id:"transfercall-modal-title",className:"text-lg font-semibold text-ink mt-0.5",children:i("tools.transferCallModal.title")}),t.jsx("p",{className:"text-sm text-ink-mute mt-1",children:i("tools.transferCallModal.subtitle")})]}),t.jsx("button",{className:"btn btn-ghost h-8 w-8 p-0 shrink-0",onClick:a,"aria-label":i("modal.close"),children:t.jsx(nt,{className:"size-4"})})]}),t.jsxs("div",{className:"p-6 flex flex-col gap-5 overflow-y-auto",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("modal.toolName")}),t.jsx("input",{className:"input font-mono text-[13px]",type:"text",placeholder:Qd,value:r,maxLength:64,onChange:S=>o(S.target.value)})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("modal.descriptionOptional")}),t.jsx("textarea",{className:"textarea min-h-[56px] text-[13px]",placeholder:i("tools.transferCallModal.descriptionPlaceholder"),value:l,maxLength:2e3,onChange:S=>c(S.target.value)})]}),t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:i("tools.transferCommon.rulesTitle")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:i("tools.transferCallModal.rulesSubtitle")})]}),d.length<Wx&&t.jsxs("button",{type:"button",className:"btn btn-outline h-9 shrink-0",onClick:w,children:[t.jsx(Fe,{className:"size-4"}),i("tools.transferCommon.addRule")]})]}),d.map((S,_)=>t.jsxs("div",{className:"rounded-xl border border-paper-line bg-paper p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-ink",children:[t.jsx(uo,{className:"size-4 text-brand-600"}),i("tools.transferCommon.ruleN",{n:_+1})]}),d.length>1&&t.jsx("button",{type:"button",onClick:()=>j(_),title:i("tools.transferCommon.removeRule"),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",children:t.jsx(mt,{className:"size-4"})})]}),t.jsxs("div",{className:"grid sm:grid-cols-[1fr_120px] gap-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-baseline gap-1 mb-1.5",children:[t.jsx("label",{className:"label",children:i("tools.transferCallModal.destNumberLabel")}),t.jsx("span",{className:"text-rose-500 text-xs leading-none",children:"*"})]}),t.jsx("input",{className:"input font-mono text-[13px]",type:"text",placeholder:"+573009345678",value:S.destinationNumber,maxLength:20,onChange:R=>k(_,{destinationNumber:R.target.value})})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.extensionLabel")}),t.jsx("input",{className:"input font-mono text-[13px]",type:"text",placeholder:i("tools.transferCallModal.extensionPlaceholder"),value:S.extension??"",maxLength:32,onChange:R=>k(_,{extension:R.target.value})})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCommon.conditionOptional")}),t.jsx("textarea",{className:"textarea min-h-[48px] text-[13px]",placeholder:i("tools.transferCommon.conditionPlaceholder"),value:S.condition??"",maxLength:1e3,onChange:R=>k(_,{condition:R.target.value})})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.transferTypeLabel")}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:FP.map(R=>{const A=(S.type||"cold")===R.value;return t.jsxs("button",{type:"button",disabled:R.soon,title:i(R.hintKey),onClick:()=>!R.soon&&k(_,{type:R.value}
965),className:os("rounded-xl border px-3 h-9 text-sm transition-colors",R.soon&&"opacity-50 cursor-not-allowed",A?"border-brand-600 bg-brand-50 text-brand-700 ring-2 ring-brand-300":"border-paper-line text-ink-mute hover:border-brand-300"),children:[i(R.labelKey),R.soon&&t.jsx("span",{className:"ml-1 text-[10px] uppercase",children:i("tools.transferCallModal.soonSuffix")})]},R.value)})})]}),S.type==="warm"&&t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.whisperLabel")}),t.jsx("div",{className:"flex gap-2 mb-1.5",children:[{v:"prompt",l:i("tools.transferCallModal.whisperModePrompt")},{v:"static",l:i("tools.transferCallModal.whisperModeStatic")}].map(R=>{const A=(S.whisper?.mode??"prompt")===R.v;return t.jsx("button",{type:"button",onClick:()=>k(_,{whisper:{mode:R.v,text:S.whisper?.text??""}}),className:os("rounded-lg border px-2.5 h-8 text-[12px] transition-colors",A?"border-brand-600 bg-brand-50 text-brand-700":"border-paper-line text-ink-mute hover:border-brand-300"),children:R.l},R.v)})}),t.jsx("textarea",{className:"textarea min-h-[48px] text-[13px]",placeholder:(S.whisper?.mode??"prompt")==="prompt"?i("tools.transferCallModal.whisperPromptPlaceholder"):i("tools.transferCallModal.whisperStaticPlaceholder"),value:S.whisper?.text??"",maxLength:2e3,onChange:R=>k(_,{whisper:{mode:S.whisper?.mode??"prompt",text:R.target.value}})}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:i("tools.transferCallModal.whisperHint",{detail:(S.whisper?.mode??"prompt")==="prompt"?i("tools.transferCallModal.whisperDetailPrompt"):i("tools.transferCallModal.whisperDetailStatic")})})]}),S.type==="warm"&&t.jsxs("div",{className:"rounded-lg border border-line bg-surface-2 p-3",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[13px] font-medium text-ink",children:i("tools.transferCallModal.waitRealLabel")}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-0.5",children:i("tools.transferCallModal.waitRealHint")})]}),t.jsx($P,{checked:S.waitForRealAgent===!0,onChange:R=>k(_,{waitForRealAgent:R})})]}),S.waitForRealAgent===!0&&t.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.waitRealSecondsLabel")}),t.jsx("input",{className:"input text-[13px] font-mono tabular-nums max-w-[140px]",type:"number",min:5,max:120,value:S.waitForRealAgentSeconds??25,onChange:R=>k(_,{waitForRealAgentSeconds:R.target.value===""?25:Number(R.target.value)})}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:i("tools.transferCallModal.waitRealSecondsHint")})]})]}),t.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.ringMaxLabel")}),t.jsx("input",{className:"input text-[13px] font-mono tabular-nums",type:"number",min:5,max:60,value:S.ringSeconds??30,onChange:R=>k(_,{ringSeconds:R.target.value===""?30:Number(R.target.value)})})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.onHoldLabel")}),t.jsx("select",{className:"select w-full",value:S.onHold?.type||"none",onChange:R=>k(_,{onHold:{type:R.target.value,volume:S.onHold?.volume??.5}}),children:OP.map(R=>t.jsx("option",{value:R.value,children:i(R.labelKey)},R.value))}),(S.onHold?.type??"none")!=="none"&&t.jsxs("div",{className:"mt-2",children:[t.jsx("label",{className:"label mb-1 block text-[11px]",children:i("tools.transferCallModal.volumeLabel",{pct:Math.round((S.onHold?.volume??.5)*100)})}),t.jsx("input",{type:"range",min:0,max:1,step:.05,className:"w-full accent-brand-600",value:S.onHold?.volume??.5,onChange:R=>k(_,{onHold:{type:S.onHold?.type??"none",volume:Number(R.target.value)}})})]})]})]}),t.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.displayedCallerLabel")}),t.jsxs("select",{className:"select w-full",value:S.displayedCallerId||"agent",onChange:R=>k(_,{displayedCallerId:R.target.value}),children:[t.jsx("option",{value:"agent",children:i("tools.transferCallModal.callerAgent")}),t.jsx("option",{value:"caller",children:i("tools.transferCallModal.callerCustomer")})]}),S.displayedCallerId==="caller"&&t.jsx("p",{className:"text-[11px] text-amber-600 mt-1",children:i("tools.transferCallModal.callerWarn")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.navigateIvrLabel")}),t.jsx("input",{className:"input font-mono text-[13px]",type:"text",placeholder:i("tools.transferCallModal.navigateIvrPlaceholder"),value:S.navigateIvrDtmf??"",maxLength:32,onChange:R=>k(_,{navigateIvrDtmf:R.target.value})})]})]}),t.jsx(BP,{rows:p[_]||[],onChange:R=>C(_,R)})]},S.id??_))]}),t.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-paper-line bg-paper p-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:i("tools.transferCallModal.transferPhraseLabel")}),t.jsx("input",{className:"input text-[13px]",type:"text",placeholder:i("tools.transferCallModal.transferPhrasePlaceholder"),value:x,maxLength:300,onChange:S=>h(S.target.value)})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[13px] text-ink",children:i("tools.transferCommon.maxTransfers")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:i("tools.transferCallModal.maxTransfersHint")})]}),t.jsx("input",{className:"input text-[13px] font-mono tabular-nums w-20 shrink-0",type:"number",min:1,max:5,value:b,onChange:S=>g(S.target.value===""?3:Number(S.target.value))})]})]}),v&&t.jsx("div",{className:"rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700",children:v})]}),t.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-paper-line",children:[t.jsx("button",{className:"btn btn-outline",onClick:a,children:i("modal.cancel")}),t.jsx("button",{className:"btn btn-primary",onClick:N,children:i(s?"modal.saveChanges":"modal.addTool")})]})]})})]})}function BP({rows:e,onChange:a}){const{t:n}=M("agents");return t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[t.jsx("label",{className:"label",children:n("tools.transferCallModal.sipHeadersLabel")}),t.jsx("button",{type:"button",className:"text-xs text-brand-700 hover:underline",onClick:()=>a([...e,{key:"",value:""}]),children:n("tools.transferCallModal.addHeader")})]}),e.length===0?t.jsx("p",{className:"text-[11px] text-ink-mute",children:n("tools.transferCallModal.sipHeadersEmpty")}):t.jsx("div",{className:"flex flex-col gap-2",children:e.map((s,i)=>t.jsxs("div",{className:"flex gap-2",children:[t.jsx("input",{className:"input text-[13px] font-mono flex-1",type:"text",placeholder:n("tools.transferCallModal.headerKeyPlaceholder"),value:s.key,maxLength:64,onChange:r=>a(e.map((o,l)=>l===i?{...o,key:r.target.value}:o))}),t.jsx("input",{className:"input text-[13px] flex-1",type:"text",placeholder:n("tools.transferCallModal.headerValuePlaceholder"),value:s.value,maxLength:256,onChange:r=>a(e.map((o,l)=>l===i?{...o,value:r.target.value}:o))}),t.jsx("button",{type:"button",onClick:()=>a(e.filter((r,o)=>o!==i)),title:n("modal.remove"),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors shrink-0",children:t.jsx(mt,{className:"size-4"})})]},i))})]})}const WP=/^[A-Z][A-Z0-9_]{0,63}$/;function xp({open:e,onClose:a,onSubmit:n,saving:s,error:i,mode:r="create",fixedName:o}){const{t:l}=M("misc"),[c,d]=m.useState(""),[u,p]=m.useState(""),[f,x]=m.useState(null),h=r==="rotate";m.useEffect(()=>{e&&(d(o??""),p(""),x(null))},[e,o]);function b(){x(null);const g=(h?o??"":c).trim();if(!h&&!WP.test(g))return x(l("secretModal.errName"));if(!u)return x(l("secretModal.errValue"));n({name:g,value:u})}return t.jsx(ot,{open:e,onClose:a,maxWidth:520,eyebrow:l("secretModal.eyebrow"),title:h?l("secretModal.rotateTitle",{name:o}):l("secretModal.newTitle"),footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"cia-btn cia-btn-outline",onClick:a,disabled:s,children:l("secretModal.cancel")}),t.jsxs("button",{className:"cia-btn cia-btn-cta",onClick:b,disabled:s,children:[s&&t.jsx(je,{className:"animate-spin",size:15}),l(h?"secretModal.rotateBtn":"secretModal.createBtn")]})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"flex-start",padding:12,borderRadius:"var(--cia-r)",background:"var(--cia-bg-tint)"},children:[t.jsx("span",{style:{width:30,height:30,borderRadius:8,background:"var(--cia-bg-elev)",color:"var(--cia-cta-500)",display:"grid",placeItems:"center",flex:"none"},children:t.jsx(Ka,{size:15})}),t.jsxs("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)",lineHeight:1.5},children:[l("secretModal.savedPre")," ",t.jsx("strong",{children:l("secretModal.encrypted")}),l("secretModal.savedPost")]})]}),!h&&t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:l("secretModal.nameLabel")}),t.jsx("input",{className:"input cia-mono",style:{width:"100%",marginTop:4}
965,type:"text",placeholder:"CRM_TOKEN",value:c,maxLength:64,autoFocus:!0,onChange:g=>d(g.target.value.toUpperCase())}),t.jsxs("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:6},children:[l("secretModal.nameHint")," ",t.jsx("code",{className:"cia-mono",children:`{{secrets.${c||l("secretModal.nameToken")}}}`}),"."]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:l(h?"secretModal.valueLabelRotate":"secretModal.valueLabel")}),t.jsx("textarea",{className:"input cia-mono",style:{width:"100%",minHeight:90,marginTop:4,resize:"vertical"},placeholder:l("secretModal.valuePlaceholder"),value:u,autoFocus:h,onChange:g=>p(g.target.value)})]}),(f||i)&&t.jsx(le,{tone:"bad",children:f||i})]})})}const hi=["org-secrets"];function UP(){const{t:e}=M("misc"),a=xe();Pe(g=>g.user?.role);const{can:n}=tt(),s=n("secrets.manage"),[i,r]=m.useState(!1),[o,l]=m.useState(null),[c,d]=m.useState(null),{data:u,isLoading:p,error:f}=se({queryKey:hi,queryFn:async()=>(await T.get("/secrets")).data}),x=oe({mutationFn:async g=>(await T.post("/secrets",g)).data,onSuccess:g=>{a.invalidateQueries({queryKey:hi}),r(!1),J({tone:"ok",title:e("secretsManager.toastSaved",{name:g.name})})},onError:g=>d(Gd(g))}),h=oe({mutationFn:async g=>(await T.post(`/secrets/${g.id}/rotate`,{value:g.value})).data,onSuccess:g=>{a.invalidateQueries({queryKey:hi}),l(null),J({tone:"ok",title:e("secretsManager.toastRotated",{name:g.name})})},onError:g=>d(Gd(g))}),b=oe({mutationFn:async g=>(await T.delete(`/secrets/${g}`)).data,onSuccess:()=>{a.invalidateQueries({queryKey:hi}),J({tone:"ok",title:e("secretsManager.toastDeleted")})},onError:g=>J({tone:"bad",title:Gd(g)})});return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[t.jsxs("p",{style:{fontSize:13.5,color:"var(--cia-text-3)",maxWidth:560,margin:0,lineHeight:1.6},children:[e("secretsManager.introPre")," ","(",t.jsx("code",{className:"cia-mono",style:{fontSize:12},children:"{{secrets.NOMBRE}}"}),")"," ",e("secretsManager.introPost")]}),s&&t.jsxs("button",{className:"cia-btn cia-btn-primary",style:{flex:"none"},onClick:()=>{d(null),r(!0)},children:[t.jsx(Fe,{size:15})," ",e("secretsManager.newSecret")]})]}),p?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[0,1,2].map(g=>t.jsx("div",{className:"cia-card",style:{padding:16},children:t.jsx(ge,{w:"50%",h:14})},g))}):f?t.jsx(le,{tone:"bad",children:e("secretsManager.loadError")}):!u||u.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{icon:yi,title:e("secretsManager.emptyTitle"),desc:e("secretsManager.emptyDesc",{interpolation:{prefix:"[[",suffix:"]]"}}),action:s?{label:e("secretsManager.newSecret"),onClick:()=>{d(null),r(!0)}}:void 0,mini:!0})}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:u.map(g=>t.jsxs("div",{className:"cia-card cia-fade-up",style:{padding:16,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{style:{minWidth:0,flex:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx(Ka,{size:15,style:{color:"var(--cia-brand-500)",flex:"none"}}),t.jsx("span",{className:"cia-mono",style:{fontSize:13,wordBreak:"break-all"},children:g.name}),t.jsxs("span",{className:"cia-badge cia-mono",style:{fontSize:11},children:["••••",g.lastFour]})]}),t.jsx("p",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)",marginTop:4},children:e("secretsManager.updated",{date:Be(g.updatedAt)})})]}),s&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:"none"},children:[t.jsxs("button",{className:"cia-btn cia-btn-outline cia-btn-sm",onClick:()=>{d(null),l(g)},children:[t.jsx(Di,{size:14})," ",e("secretsManager.rotate")]}),t.jsxs("button",{className:"cia-btn cia-btn-outline cia-btn-sm",style:{color:"var(--cia-bad-500)"},onClick:async()=>{await pa({message:e("secretsManager.deleteConfirm",{name:g.name}),danger:!0})&&b.mutate(g.id)},children:[t.jsx(mt,{size:14})," ",e("secretsManager.delete")]})]})]},g.id))}),t.jsx(xp,{open:i,onClose:()=>r(!1),onSubmit:g=>{d(null),x.mutate(g)},saving:x.isPending,error:c,mode:"create"}),t.jsx(xp,{open:!!o,onClose:()=>l(null),onSubmit:g=>{o&&(d(null),h.mutate({id:o.id,value:g.value}))},saving:h.isPending,error:c,mode:"rotate",fixedName:o?.name})]})}function Gd(e){const a=e?.response?.data?.message;return Array.isArray(a)?a.join(" · "):a||he.t("misc:errors.generic")}function Ux({onInsert:e}){const{t:a}=M("misc"),n=xe(),[s,i]=m.useState(!1),[r,o]=m.useState(!1),[l,c]=m.useState(null),{data:d}=se({queryKey:hi,queryFn:async()=>(await T.get("/secrets")).data}),u=oe({mutationFn:async p=>(await T.post("/secrets",p)).data,onSuccess:p=>{n.invalidateQueries({queryKey:hi}),o(!1),e(`{{secrets.${p.name}}}`)},onError:p=>c(Array.isArray(p?.response?.data?.message)?p.response.data.message.join(" · "):p?.response?.data?.message??a("secretPicker.error"))});return t.jsxs("div",{className:"relative",children:[t.jsxs("button",{type:"button",className:"btn btn-ghost h-8 text-xs whitespace-nowrap",onClick:()=>i(p=>!p),children:[t.jsx(Ka,{className:"size-3.5"}),a("secretPicker.btn"),t.jsx(Ut,{className:"size-3"})]}),s&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>i(!1),"aria-hidden":"true"}),t.jsxs("div",{className:"absolute right-0 z-20 mt-1 w-60 rounded-xl border border-paper-line bg-paper-card shadow-lg p-1 max-h-64 overflow-y-auto",children:[(d??[]).map(p=>t.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 rounded-lg text-xs font-mono hover:bg-paper-line/50",onClick:()=>{e(`{{secrets.${p.name}}}`),i(!1)},children:[p.name," ",t.jsxs("span",{className:"text-ink-mute",children:["••••",p.lastFour]})]}
965,p.id)),(!d||d.length===0)&&t.jsx("p",{className:"px-3 py-2 text-[11px] text-ink-mute",children:a("secretPicker.empty")}),t.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 rounded-lg text-xs text-brand-600 hover:bg-brand-50 flex items-center gap-1.5 border-t border-paper-line mt-1 pt-2",onClick:()=>{i(!1),c(null),o(!0)},children:[t.jsx(Fe,{className:"size-3.5"}),a("secretPicker.create")]})]})]}),t.jsx(xp,{open:r,onClose:()=>o(!1),onSubmit:p=>{c(null),u.mutate(p)},saving:u.isPending,error:l,mode:"create"})]})}const VP=["GET","POST","PUT","PATCH","DELETE"],Vx=/^[a-z][a-z0-9_]{0,63}$/,KP=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;function HP(){return`tool_http_${Math.random().toString(36).slice(2,10)}`}function QP({open:e,onClose:a,onSave:n,initial:s,takenNames:i}){const{t:r}=M("agents"),[o,l]=m.useState(""),[c,d]=m.useState(""),[u,p]=m.useState("GET"),[f,x]=m.useState(""),[h,b]=m.useState([]),[g,v]=m.useState([]),[y,k]=m.useState(""),[w,j]=m.useState(""),[C,N]=m.useState("static"),[S,_]=m.useState(5e3),[R,A]=m.useState(!0),[E,I]=m.useState([]),[P,O]=m.useState(null);if(m.useEffect(()=>{if(!e)return;const V=s?.config??{};l(s?.name??""),d(s?.description??""),p(V.method??"GET"),x(V.url??""),b((V.parameters??[]).map(U=>({name:U.name??"",type:U.type??"string",location:U.location??"query",required:U.required===!0,description:U.description??"",enumCsv:Array.isArray(U.enumValues)?U.enumValues.join(", "):""}))),v((V.headers??[]).map(U=>({key:U.key??"",valueTemplate:U.valueTemplate??""}))),k(V.bodyTemplate??""),j(V.waitingPhrase?.text??""),N(V.waitingPhrase?.mode==="prompt"?"prompt":"static"),_(typeof V.timeoutMs=="number"?V.timeoutMs:5e3),A(V.retryOnce!==!1),I((V.responseAssignments??[]).map(U=>({variable:U.variable??"",path:U.path??""}))),O(null)},[e,s]),m.useEffect(()=>{if(!e)return;const V=U=>U.key==="Escape"&&a();return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[e,a]),!e)return null;const K=u==="GET";function W(){O(null);const V=o.trim();if(!KP.test(V))return O(r("tools.httpModal.errNameInvalid"));if(new Set((i??[]).map($=>$.toLowerCase())).has(V.toLowerCase()))return O(r("tools.httpModal.errNameTaken",{name:V}));const X=f.trim();if(!/^https:\/\//i.test(X))return O(r("tools.httpModal.errUrlHttps"));if(/\{\{\s*secrets\./.test(X))return O(r("tools.httpModal.errUrlSecret",{code:"{{secrets.X}}"}));const ie=new Set;for(const $ of h){const z=$.name.trim();if(!Vx.test(z))return O(r("tools.httpModal.errParamInvalid",{name:z}));if(ie.has(z))return O(r("tools.httpModal.errParamDuplicate",{name:z}));ie.add(z)}for(const $ of E)if(($.variable.trim()||$.path.trim())&&!Vx.test($.variable.trim()))return O(r("tools.httpModal.errAssignInvalid",{name:$.variable}));const de={id:s?.id??HP(),type:"http_request",name:V,description:c.trim()||void 0,config:{enabled:s?.config?.enabled!==!1,method:u,url:X,parameters:h.filter($=>$.name.trim()).map($=>{const z=$.enumCsv.split(",").map(D=>D.trim()).filter(Boolean);return{name:$.name.trim(),type:$.type,location:$.location,required:$.required,description:$.description.trim()||void 0,...z.length?{enumValues:z}:{}}}),headers:g.filter($=>$.key.trim()).map($=>({key:$.key.trim(),valueTemplate:$.valueTemplate})),...!K&&y.trim()?{bodyTemplate:y}:{},...w.trim()?{waitingPhrase:{mode:C,text:w.trim()}}:{},timeoutMs:Math.min(1e4,Math.max(1e3,Number(S)||5e3)),retryOnce:R,responseAssignments:E.filter($=>$.variable.trim()&&$.path.trim()).map($=>({variable:$.variable.trim(),path:$.path.trim()}))}};n(de),a()}return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black/30 z-40",onClick:a,"aria-hidden":"true"}),t.jsx("div",{role:"dialog","aria-modal":"true",className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-paper-card rounded-2xl border border-paper-line shadow-xl w-full max-w-2xl flex flex-col max-h-[90vh]",onClick:V=>V.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 p-6 border-b border-paper-line",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:r("tools.httpModal.eyebrow")}),t.jsx("h2",{className:"text-lg font-semibold text-ink mt-0.5",children:s?r("tools.httpModal.titleEdit",{name:s.name}):r("tools.httpModal.titleNew")}),t.jsx("p",{className:"text-sm text-ink-mute mt-1",children:r("tools.httpModal.subtitle")})]}),t.jsx("button",{className:"btn btn-ghost h-8 w-8 p-0 shrink-0",onClick:a,"aria-label":r("modal.close"),children:t.jsx(nt,{className:"size-4"})})]}),t.jsxs("div",{className:"p-6 flex flex-col gap-6 overflow-y-auto",children:[t.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("tools.httpModal.nameLabel")}),t.jsx("input",{className:"input font-mono text-[13px]",value:o,maxLength:64,onChange:V=>l(V.target.value),placeholder:"consultar_cliente"}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:r("tools.httpModal.nameHint")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("tools.httpModal.whenToUseLabel")}),t.jsx("input",{className:"input text-sm",value:c,maxLength:2e3,onChange:V=>d(V.target.value),placeholder:r("tools.httpModal.whenToUsePlaceholder")})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("tools.httpModal.endpointLabel")}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("select",{className:"input w-28 shrink-0 text-sm",value:u,onChange:V=>p(V.target.value),children:VP.map(V=>t.jsx("option",{value:V,children:V},V))}),t.jsx("input",{className:"input font-mono text-[13px] flex-1",value:f,onChange:V=>x(V.target.value),placeholder:"https://api.tu-sistema.com/clientes/{documento}"})]}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1.5",children:t.jsx(wa,{t:r,i18nKey:"tools.httpModal.urlHint",components:{c0:t.jsx("code",{className:"font-mono"}),c1:t.jsx("code",{className:"font-mono"})},values:{v0:"{documento}",v1:"{{system.caller_number}}"}})})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("label",{className:"label",children:r("tools.httpModal.paramsLabel")}),t.jsxs("button",{type:"button",className:"btn btn-ghost h-7 text-xs",onClick:()=>b(V=>[...V,{name:"",type:"string",location:"query",required:!1,description:"",enumCsv:""}]),children:[t.jsx(Fe,{className:"size-3.5"}),r("modal.add")]})]}),h.length===0?t.jsx("p",{className:"text-xs text-ink-mute",children:r("tools.httpModal.paramsEmpty")}):t.jsx("div",{className:"flex flex-col gap-2",children:h.map((V,U)=>t.jsxs("div",{className:"rounded-xl border border-paper-line p-3 flex flex-col gap-2",children:[t.jsxs("div",{className:"flex gap-2",children:[t.jsx("input",{className:"input font-mono text-[12px] flex-1",placeholder:"documento",value:V.name,onChange:X=>Za(b,U,{name:X.target.value})}),t.jsxs("select",{className:"input w-28 text-xs shrink-0",value:V.type,onCh
965ange:X=>Za(b,U,{type:X.target.value}),children:[t.jsx("option",{value:"string",children:r("tools.httpModal.paramTypeString")}),t.jsx("option",{value:"integer",children:r("tools.httpModal.paramTypeInteger")}),t.jsx("option",{value:"number",children:r("tools.httpModal.paramTypeNumber")}),t.jsx("option",{value:"boolean",children:r("tools.httpModal.paramTypeBoolean")})]}),t.jsxs("select",{className:"input w-24 text-xs shrink-0",value:V.location,onChange:X=>Za(b,U,{location:X.target.value}),children:[t.jsx("option",{value:"query",children:r("tools.httpModal.paramLocQuery")}),t.jsx("option",{value:"body",children:r("tools.httpModal.paramLocBody")}),t.jsx("option",{value:"path",children:r("tools.httpModal.paramLocPath")})]}),t.jsx("button",{type:"button",className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 shrink-0",onClick:()=>b(X=>X.filter((ie,de)=>de!==U)),children:t.jsx(mt,{className:"size-4"})})]}),t.jsxs("div",{className:"flex gap-2 items-center",children:[t.jsx("input",{className:"input text-xs flex-1",placeholder:r("tools.httpModal.paramDescPlaceholder"),value:V.description,onChange:X=>Za(b,U,{description:X.target.value})}),t.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-ink-mute shrink-0",children:[t.jsx("input",{type:"checkbox",checked:V.required,onChange:X=>Za(b,U,{required:X.target.checked})}),r("tools.httpModal.paramRequired")]})]}),t.jsx("input",{className:"input text-xs font-mono",placeholder:r("tools.httpModal.enumCsvPlaceholder"),value:V.enumCsv,onChange:X=>Za(b,U,{enumCsv:X.target.value})})]},U))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("label",{className:"label",children:r("tools.httpModal.headersLabel")}),t.jsxs("button",{type:"button",className:"btn btn-ghost h-7 text-xs",onClick:()=>v(V=>[...V,{key:"",valueTemplate:""}]),children:[t.jsx(Fe,{className:"size-3.5"}),r("modal.add")]})]}),g.length===0?t.jsx("p",{className:"text-xs text-ink-mute",children:t.jsx(wa,{t:r,i18nKey:"tools.httpModal.headersEmpty",components:{c0:t.jsx("code",{className:"font-mono"}),c1:t.jsx("code",{className:"font-mono"})},values:{v1:"Bearer {{secrets.TU_TOKEN}}"}})}):t.jsx("div",{className:"flex flex-col gap-2",children:g.map((V,U)=>t.jsxs("div",{className:"flex gap-2 items-center",children:[t.jsx("input",{className:"input font-mono text-[12px] w-44 shrink-0",placeholder:"Authorization",value:V.key,onChange:X=>Za(v,U,{key:X.target.value})}),t.jsx("input",{className:"input font-mono text-[12px] flex-1",placeholder:r("tools.httpModal.headerValuePlaceholder",{code:"{{secrets.CRM_TOKEN}}"}),value:V.valueTemplate,onChange:X=>Za(v,U,{valueTemplate:X.target.value})}),t.jsx(Ux,{onInsert:X=>Za(v,U,{valueTemplate:(V.valueTemplate||"")+X})}),t.jsx("button",{type:"button",className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 shrink-0",onClick:()=>v(X=>X.filter((ie,de)=>de!==U)),children:t.jsx(mt,{className:"size-4"})})]},U))})]}),!K&&t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"label",children:r("tools.httpModal.bodyLabel")}),t.jsx(Ux,{onInsert:V=>k(U=>U+V)})]}),t.jsx("textarea",{className:"input text-xs font-mono min-h-[88px]",placeholder:`{
966  "documento": "{{args.documento}}",
967  "origen": "llamada"
968}`,value:y,onChange:V=>k(V.target.value)}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1.5",children:r("tools.httpModal.bodyHint")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("tools.httpModal.waitingLabel")}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("input",{className:"input text-sm flex-1",placeholder:r("tools.httpModal.waitingPlaceholder"),value:w,onChange:V=>j(V.target.value)}),t.jsxs("select",{className:"input w-40 text-xs shrink-0",value:C,onChange:V=>N(V.target.value),children:[t.jsx("option",{value:"static",children:r("tools.httpModal.waitingModeStatic")}),t.jsx("option",{value:"prompt",children:r("tools.httpModal.waitingModePrompt")})]})]})]}),t.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("tools.httpModal.timeoutLabel")}),t.jsx("input",{type:"number",className:"input text-sm",min:1e3,max:1e4,step:500,value:S,onChange:V=>_(Number(V.target.value))})]}),t.jsxs("label",{className:"flex items-center gap-2 text-sm text-ink-soft mt-7",children:[t.jsx("input",{type:"checkbox",checked:R,onChange:V=>A(V.target.checked)}),r("tools.httpModal.retryLabel")]})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("label",{className:"label",children:r("tools.httpModal.responseVarsLabel")}),t.jsxs("button",{type:"button",className:"btn btn-ghost h-7 text-xs",onClick:()=>I(V=>[...V,{variable:"",path:""}]),children:[t.jsx(Fe,{className:"size-3.5"}),r("modal.add")]})]}),E.length===0?t.jsx("p",{className:"text-xs text-ink-mute",children:t.jsx(wa,{t:r,i18nKey:"tools.httpModal.responseVarsEmpty",components:{c0:t.jsx("code",{className:"font-mono"}),c1:t.jsx("code",{className:"font-mono"})}})}):t.jsx("div",{className:"flex flex-col gap-2",children:E.map((V,U)=>t.jsxs("div",{className:"flex gap-2 items-center",children:[t.jsx("input",{className:"input font-mono text-[12px] w-44 shrink-0",placeholder:"saldo",value:V.variable,onChange:X=>Za(I,U,{variable:X.target.value})}),t.jsx("span",{className:"text-ink-mute text-xs",children:"←"}),t.jsx("input",{className:"input font-mono text-[12px] flex-1",placeholder:"data.balance",value:V.path,onChange:X=>Za(I,U,{path:X.target.value})}),t.jsx("button",{type:"button",className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 shrink-0",onClick:()=>I(X=>X.filter((ie,de)=>de!==U)),children:t.jsx(mt,{className:"size-4"})})]},U))})]}),P&&t.jsx("div",{className:"rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700",children:P})]}),t.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-paper-line",children:[t.jsx("button",{className:"btn btn-outline",onClick:a,children:r("modal.cancel")}),t.jsx("button",{className:"btn btn-primary",onClick:W,children:r(s?"modal.save":"modal.addTool")})]})]})})]})}function Za(e,a,n){e(s=>s.map((i,r)=>r===a?{...i,...n}:i))}const GP=["calendar_availability","calendar_book","calendar_reschedule","calendar_cancel"];async function V0(){try{return(await T.get("/scheduling/connections")).data}catch(e){const a=e?.response?.status;if(a===501||a===404||a===403)return null;throw e}}function Kx(e){return e?.config?.enabled!==!1&&e?.enabled!==!1}const ZP=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;function YP(){return`tool_cal_${Math.random().toString(36).slice(2,10)}`}function XP({open:e,onClose:a,onSave:n,initial:s,takenNames:i,agentTimeZone:r,toolType:o="calendar_availability"}){const{t:l}=M("agents"),c=Kc(Vc.agendamiento),d=s?.type??o,u=d==="calendar_book",p=d==="calendar_cancel",f=d==="calendar_reschedule"||p,x=u?"Book":p?"Cancel":d==="calendar_reschedule"?"Reschedule":"Availability",h=u?"agendar_cita":p?"cancelar_cita":d==="calendar_reschedule"?"reagendar_cita":"consultar_disponibilidad",[b,g]=m.useState(""),[v,y]=m.useState(""),[k,w]=m.useState(""),[j,C]=m.useState(""),[N,S]=m.useState(""),[_,R]=m.useState(3),[A,E]=m.useState(""),[I,P]=m.useState(!1),[O,K]=m.useState(null),{data:W,isLoading:V}=se({queryKey:["calendar-connections"],queryFn:V0,enabled:e}),{data:U,isLoading:X}=se({queryKey:["calendar-event-types",k],queryFn:async()=>(await T.get(`/scheduling/connections/${k}/event-types`)).data,enabled:e&&!!k});if(m.useEffect(()=>{if(!e)return;const F=s?.config??{};g(s?.name??h),y(s?.description??""),w(String(F.connectionId??"")),C(F.eventTypeId?String(F.eventTypeId):""),S(String(F.timeZone??"")),R(Number(F.maxSlots)>=1&&Number(F.maxSlots)<=3?Number(F.maxSlots):3),E(String(F.waitPhrase??"")),P(F.disableInterruptions===!0),K(null)},[e,s,h]),!e)return null;const ie=U?.eventTypes??[],de=ie.find(F=>String(F.id)===j),$=!!de?.bookingFields?.some(F=>F.name==="email"&&F.required&&!F.hidden),z=N||r||"";function D(){K(null);const F=b.trim();if(!ZP.test(F))return K(l("tools.calendarModal.errName"));if(new Set((i??[]).map(te=>te.toLowerCase())).has(F.toLowerCase()))return K(l("tools.calendarModal.errNameTaken",{name:F}));if(!k)return K(l("tools.calendarModal.errConnection"));if(!f&&!j)return K(l("tools.calendarModal.errEventType"));if(!z)return K(l("tools.calendarModal.errTimeZone"));n({id:s?.id??YP(),type:d,name:F,description:v.trim()||void 0,config:{...s?.config?.enabled===!1?{enabled:!1}:{},connectionId:k,...f?{}:{eventTypeId:Number(j)},...N?{timeZone:N}:{},...u?{}:{maxSlots:_},...A.trim()?{waitPhrase:A.trim()}:{},...I?{disableInterruptions:!0}:{}}})}return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black/30 z-40",onClick:a,"aria-hidden":"true"}),t.jsx("div",{role:"dialog","aria-modal":"true",className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-paper-card rounded-2xl border border-paper-line shadow-xl w-full max-w-2xl flex flex-col max-h-[90vh]",onClick:F=>F.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 p-6 border-b border-paper-line",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:l("tools.calendarModal.eyebrow")}),t.jsx("h2",{className:"text-lg font-semibold text-ink mt-0.5",children:s?l("tools.calendarModal.titleEdit",{name:s.name}):l(`tools.calendarModal.titleNew${x}`)}),t.jsx("p",{className:"text-sm text-ink-mute mt-1",children:t.jsx(wa,{t:l,i18nKey:`tools.calendarModal.subtitle${x}`,components:{1:t.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"underline"})}})})]}),t.jsx("button",{className:"btn btn-ghost h-8 w-8 p-0 shrink-0",onClick:a,"aria-label":l("modal.close"),children:t.jsx(nt,{className:"size-4"})})]}),t.jsxs("div",{className:"p-6 flex flex-col gap-6 overflow-y-auto",children:[O&&t.jsx(le,{tone:"bad",children:O}),!V&&(W??[]).length===0&&t.jsx(le,{tone:"warn",children:l("tools.calendarModal.noConnections")}),t.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:l("tools.calendarModal.nameLabel")}),t.jsx("input",{className:"input font-mono text-[13px]",value:b,onChange:F=>g(F.target.value),placeholder:h,maxLength:64}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:l("tools.calendarModal.nameHint")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:l("tools.calendarModal.connectionLabel")}),t.jsxs("select",{className:"select w-full",value:k,onChange:F=>{w(F.target.value),C("")},children:[t.jsx("option",{value:"",children:l("tools.calendarModal.connectionPlaceholder")}),(W??[]).map(F=>t.jsx("option",{value:F.id,children:F.label}
968,F.id))]}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:l("tools.calendarModal.connectionHint")})]})]}),f&&t.jsx("p",{className:"text-xs text-ink-mute -mt-1",children:l(p?"tools.calendarModal.cancelExplainer":"tools.calendarModal.rescheduleExplainer")}),!f&&t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:l("tools.calendarModal.eventTypeLabel")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("select",{className:"select w-full",value:j,onChange:F=>C(F.target.value),disabled:!k||X,children:[t.jsx("option",{value:"",children:l("tools.calendarModal.eventTypePlaceholder")}),ie.map(F=>t.jsxs("option",{value:String(F.id),children:[F.title,F.lengthInMinutes?` · ${F.lengthInMinutes} min`:""]},F.id))]}),X&&t.jsx(je,{className:"size-4 animate-spin text-ink-mute"})]}),de&&t.jsxs("div",{className:"text-[11px] text-ink-mute mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[$&&t.jsx("span",{className:"chip chip-amber",children:l("tools.calendarModal.requiresEmail")}),!!de.minimumBookingNotice&&t.jsx("span",{children:l("tools.calendarModal.notice",{n:de.minimumBookingNotice})}),de.hidden&&t.jsx("span",{className:"chip chip-rose",children:l("tools.calendarModal.hidden")})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:l("tools.calendarModal.descriptionLabel")}),t.jsx("textarea",{className:"input min-h-[72px]",value:v,onChange:F=>y(F.target.value),placeholder:l("tools.calendarModal.descriptionPlaceholder"),maxLength:2e3}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:l("tools.calendarModal.descriptionHint")})]}),t.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:l("tools.calendarModal.timeZoneLabel")}),t.jsxs("select",{className:"select w-full",value:N,onChange:F=>S(F.target.value),children:[t.jsx("option",{value:"",children:r?l("tools.calendarModal.timeZoneInherited",{tz:r}):l("tools.calendarModal.timeZoneNoneInherited")}),E0.map(F=>t.jsx("option",{value:F.tz,children:l(F.labelKey)},F.tz))]}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:l("tools.calendarModal.timeZoneHint")})]}),!u&&!f&&t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:l("tools.calendarModal.maxSlotsLabel")}),t.jsx("select",{className:"select w-full",value:String(_),onChange:F=>R(Number(F.target.value)),children:[1,2,3].map(F=>t.jsx("option",{value:String(F),children:F},F))}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:l("tools.calendarModal.maxSlotsHint")})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:l("tools.calendarModal.waitLabel")}),t.jsx("input",{className:"input",value:A,onChange:F=>E(F.target.value),placeholder:l("tools.calendarModal.waitPlaceholder"),maxLength:160}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:l("tools.calendarModal.waitHint")})]}),t.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[t.jsx("input",{type:"checkbox",className:"mt-0.5",checked:I,onChange:F=>P(F.target.checked)}),t.jsxs("span",{children:[t.jsx("span",{className:"text-sm font-medium",children:l("tools.calendarModal.noInterruptLabel")}),t.jsx("span",{className:"block text-[11px] text-ink-mute mt-0.5",children:l("tools.calendarModal.noInterruptHint")})]})]}),t.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-brand-600 hover:underline inline-flex items-center gap-1 w-fit",children:[l("tools.calendarModal.guideLink"),t.jsx(Ja,{className:"size-3"})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 p-6 border-t border-paper-line",children:[t.jsx("button",{className:"btn btn-ghost h-9",onClick:a,children:l("tools.calendarModal.cancel")}),t.jsx("button",{className:"btn btn-primary h-9 px-4",onClick:D,children:l("tools.calendarModal.save")})]})]})})]})}const JP="tool_end_call";function ez(e){const a=e||[],n=a.find(i=>i?.type==="end_call");return n?n.config?.enabled!==!1:a.filter(i=>i?.type!=="send_dtmf"&&i?.type!=="voicemail_detection").length===0}function tz(e){const a=(e||[]).find(n=>n?.type==="send_dtmf");return a?a.config?.enabled!==!1:!0}function az(e){return(e||[]).find(n=>n?.type==="voicemail_detection")?.config?.enabled===!0}function nz(e){return(e||[]).find(a=>a?.type==="transfer")}function sz(e){return(e||[]).find(a=>a?.type==="transfer_call")}
968function iz({agent:e,onChange:a}){const{t:n}=M("agents"),s=ez(e.tools),i=tz(e.tools),r=az(e.tools),o=nz(e.tools),l=sz(e.tools),{data:c}=se({queryKey:["phone-numbers"],queryFn:async()=>(await T.get("/phone-numbers")).data,enabled:!!l}),d=(c??[]).some(ae=>!ae.shared&&!ae.rotating),u=!!l&&c!==void 0&&!d,[p,f]=m.useState(!1),[x,h]=m.useState(!1),[b,g]=m.useState(!1),[v,y]=m.useState(null),[k,w]=m.useState(!1),[j,C]=m.useState(null),[N,S]=m.useState("calendar_availability"),_=(e.tools||[]).filter(ae=>ae?.type==="http_request"),R=(e.tools||[]).filter(ae=>GP.includes(ae?.type)),{data:A,isLoading:E,isError:I}=se({queryKey:["calendar-connections"],queryFn:V0}),P=A===null,O=R.length>0||!P&&!E,W=[...["end_call","finalizar_llamada","colgar","terminar_llamada","send_dtmf","transfer","transfer_call","voicemail_detection","transferir_a_agente","transferir_llamada","transferir_a_numero_externo"],...(e.tools||[]).filter(ae=>ae?.id!==v?.id&&ae?.id!==j?.id&&typeof ae?.name=="string").map(ae=>ae.name)],{data:V}=se({queryKey:["agents"],queryFn:async()=>(await T.get("/agents")).data}),U=(V??[]).filter(ae=>ae.id!==e.id).map(ae=>({id:ae.id,name:ae.name,language:ae.language}));function X(ae){const pe=(e.tools||[]).filter(ye=>ye?.type!=="end_call");pe.push({id:JP,type:"end_call",name:"end_call",config:{enabled:ae}}),a({tools:pe})}function ie(ae){const pe=(e.tools||[]).filter(ye=>ye?.type!=="send_dtmf");pe.push({id:"tool_send_dtmf",type:"send_dtmf",name:"send_dtmf",config:{enabled:ae}}),a({tools:pe})}function de(ae){const pe=(e.tools||[]).filter(ye=>ye?.type!=="voicemail_detection");pe.push({id:"tool_voicemail_detection",type:"voicemail_detection",name:"voicemail_detection",config:{enabled:ae}}),a({tools:pe})}function $(ae){const pe=(e.tools||[]).filter(ye=>ye?.type!=="transfer");a({tools:[...pe,ae]})}function z(){a({tools:(e.tools||[]).filter(ae=>ae?.type!=="transfer")})}function D(ae){if(!o)return;const pe=(e.tools||[]).filter(ye=>ye?.type!=="transfer");a({tools:[...pe,{...o,config:{...o.config,enabled:ae}}]})}function F(ae){const pe=(e.tools||[]).filter(ye=>ye?.type!=="transfer_call");a({tools:[...pe,ae]})}function G(ae){const pe=(e.tools||[]).filter(ye=>ye?.id!==ae.id);a({tools:[...pe,ae]})}function te(ae){const pe=(e.tools||[]).filter(ye=>ye?.id!==ae.id);a({tools:[...pe,ae]}),w(!1),C(null)}function B(ae){a({tools:(e.tools||[]).filter(pe=>pe?.id!==ae)})}function ne(ae,pe){a({tools:(e.tools||[]).map(ye=>ye?.id===ae?{...ye,config:{...ye.config||{},enabled:pe}}:ye)})}function me(ae){a({tools:(e.tools||[]).filter(pe=>pe?.id!==ae)})}function Ee(ae,pe){a({tools:(e.tools||[]).map(ye=>ye?.id===ae?{...ye,config:{...ye.config||{},enabled:pe}}:ye)})}function L(){a({tools:(e.tools||[]).filter(ae=>ae?.type!=="transfer_call")})}function re(ae){if(!l)return;const pe=(e.tools||[]).filter(ye=>ye?.type!=="transfer_call");a({tools:[...pe,{...l,config:{...l.config,enabled:ae}}]})}const ke=Array.isArray(o?.config?.rules)?o.config.rules.length:0,H=Array.isArray(l?.config?.rules)?l.config.rules.length:0,fe=o?o.config?.enabled!==!1:!1,Z=l?l.config?.enabled!==!1:!1;return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:t.jsxs(zt,{title:n("tools.section.title"),desc:n("tools.section.desc"),last:!0,children:[t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(Ts,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("tools.endCall.title")}),t.jsx(vt,{checked:s,onChange:()=>X(!s)})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:n("tools.endCall.desc")})]})]}),t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(Kb,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("tools.transfer.title")}),o?t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t.jsx("span",{title:n(fe?"tools.common.active":"tools.common.pausedTitle"),className:"inline-flex",children:t.jsx(vt,{checked:fe,onChange:()=>D(!fe)})}),t.jsxs("button",{type:"button",className:"btn btn-outline h-8",onClick:()=>f(!0),children:[t.jsx(qt,{className:"size-3.5"}),n("tools.common.edit")]}),t.jsx("button",{type:"button",onClick:z,title:n("tools.common.deleteTitle"),"aria-label":n("tools.common.deleteTitle"),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",children:t.jsx(mt,{className:"size-4"})})]}):t.jsx("button",{type:"button",className:"btn btn-outline h-8 shrink-0",onClick:()=>f(!0),children:n("tools.common.configure")})]}),t.jsxs("p",{className:"text-xs text-ink-mute mt-1.5",children:[n("tools.transfer.descBase")," ",o?`${n("tools.common.configuredCount",{count:ke})}${fe?"":n("tools.common.pausedSuffix")}`:n("tools.transfer.descNotConfigured")]})]})]}),t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(uo,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("tools.transferCall.title")}),l?t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t.jsx("span",{title:n(Z?"tools.common.active":"tools.common.pausedTitle"),className:"inline-flex",children:t.jsx(vt,{checked:Z,onChange:()=>re(!Z)})}),t.jsxs("button",{type:"button",className:"btn btn-outline h-8",onClick:()=>h(!0),children:[t.jsx(qt,{className:"size-3.5"}),n("tools.common.edit")]}),t.jsx("button",{type:"button",onClick:L,title:n("tools.common.deleteTitle"),"aria-label":n("tools.common.deleteTitle"),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",children:t.jsx(mt,{className:"size-4"})})]}):t.jsx("button",{type:"button",className:"btn btn-outline h-8 shrink-0",onClick:()=>h(!0),children:n("tools.common.configure")})]}),t.jsxs("p",{className:"text-xs text-ink-mute mt-1.5",children:[n("tools.transferCall.descBase")," ",l?`${n("tools.common.configuredCount",{count:H})}${Z?"":n("tools.common.pausedSuffix")}`:n("tools.transferCall.descNotConfigured")]}),u&&t.jsx("div",{className:"mt-2",children:t.jsx(le,{tone:"info",children:n("tools.transferCall.lentTrunkNotice")})})]})]}),t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(Xp,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("tools.sendDtmf.title")}),t.jsx(vt,{checked:i,onChange:()=>ie(!i)})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:n("tools.sendDtmf.desc")})]})]}),t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(sh,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("tools.voicemail.title")}),t.jsx(vt,{checked:r,onChange:()=>de(!r)})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:t.jsx(wa,{t:n,i18nKey:"tools.voicemail.desc",components:{b0:t.jsx("strong",{}),b1:t.jsx("strong",{}),b2:t.jsx("strong",{})}})})]})]}),O&&t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(Ps,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("tools.calendar.title")}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t.jsxs("button",{type:"button",className:"btn btn-outline h-8",onClick:()=>{C(null),S("calendar_availability"),w(!0)},children:[t.jsx(Fe,{className:"size-3.5"}),n("tools.calendar.addAvailability")]}),t.jsxs("button",{type:"button",className:"btn btn-outline h-8",onClick:()=>{C(null),S("calendar_book"),w(!0)},children:[t.jsx(Fe,{className:"size-3.5"}),n("tools.calendar.addBook")]}),t.jsxs("button",{type:"button",className:"btn btn-outline h-8",onClick:()=>{C(null),S("calendar_reschedule"),w(!0)},children:[t.jsx(Fe,{className:"size-3.5"}),n("tools.calendar.addReschedule")]}),t.jsxs("button",{type:"button",className:"btn btn-outline h-8",onClick:()=>{C(null),S("calendar_cancel"),w(!0)},children:[t.jsx(Fe,{className:"size-3.5"}),n("tools.calendar.addCancel")]})]})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:n("tools.calendar.desc")}),I&&t.jsx("div",{className:"mt-3",children:t.jsx(le,{tone:"warn",children:n("tools.calendar.readFailed")})}),P&&R.length>0&&t.jsx("div",{className:"mt-3",children:t.jsx(le,{tone:"warn",children:n("tools.calendar.moduleOff")})}),!I&&!P&&(A??[]).length===0&&t.jsx("div",{className:"mt-3",children:t.jsx(le,{tone:"warn",children:n("tools.calendar.noConnections")})}),R.some(ae=>ae.type==="calendar_book"&&Kx(ae))&&!R.some(ae=>ae.type==="calendar_availability"&&Kx(ae))&&t.jsx("div",{className:"mt-3",children:t.jsx(le,{tone:"warn",children:n("tools.calendar.bookNeedsAvailability")})}),R.length>0&&t.jsx("div",{className:"flex flex-col gap-2 mt-3",children:R.map(ae=>{const pe=ae.config??{},ye=pe.enabled!==!1,qe=(A??[]).find(ut=>ut.id===pe.connectionId);return t.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-paper-line px-3 py-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"font-mono text-[12px] text-ink",children:ae.name}),t.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-brand-50 text-brand-700",children:n(ae.type==="calendar_book"?"tools.calendar.kindBook":ae.type==="calendar_reschedule"?"tools.calendar.kindReschedule":ae.type==="calendar_cancel"?"tools.calendar.kindCancel":"tools.calendar.kindAvailability")}),!ye&&t.jsx("span",{className:"text-[10px] text-ink-mute",children:n("tools.common.pausedSuffix")})]}),t.jsxs("div",{className:"text-[11px] text-ink-mute truncate",children:[qe?qe.label:n("tools.calendar.missingConnection"),pe.timeZone?` · ${pe.timeZone}`:"",ae.type==="calendar_availability"?` · ${n("tools.calendar.slotCount",{count:pe.maxSlots??3})}`:""]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t.jsx("span",{title:n(ye?"tools.common.active":"tools.common.pausedTitle"),className:"inline-flex",children:t.jsx(vt,{checked:ye,onChange:()=>ne(ae.id,!ye)})}),t.jsxs("button",{type:"button",className:"btn btn-outline h-8",onClick:()=>{C(ae),w(!0)},children:[t.jsx(qt,{className:"size-3.5"}),n("tools.common.edit")]}),t.jsx("button",{type:"button",title:n("tools.common.deleteTitle"),"aria-label":n("tools.common.deleteTitle"),onClick:()=>B(ae.id),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",children:t.jsx(mt,{className:"size-4"})})]})]},ae.id)})})]})]}),t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(Va,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("tools.http.title")}),t.jsxs("button",{type:"button",className:"btn btn-outline h-8 shrink-0",onClick:()=>{y(null),g(!0)},children:[t.jsx(Fe,{className:"size-3.5"}),n("tools.common.add")]})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:n("tools.http.desc")}),_.length>0&&t.jsx("div",{className:"flex flex-col gap-2 mt-3",children:_.map(ae=>{const pe=ae.config?.enabled!==!1,ye=Array.isArray(ae.config?.parameters)?ae.config.parameters.length:0,qe=ae.config?.url||"";let ut="";try{ut=new URL(qe).host}catch{ut=qe.replace(/^https?:\/\//i,"").split("/")[0]}return t.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-paper-line px-3 py-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"font-mono text-[12px] text-ink",children:ae.name}),t.jsx("span",{className:"font-mono text-[10px] px-1.5 py-0.5 rounded bg-brand-50 text-brand-700",children:ae.config?.method}),!pe&&t.jsx("span",{className:"text-[10px] text-ink-mute",children:n("tools.common.pausedSuffix")})]}),t.jsxs("div",{className:"text-[11px] text-ink-mute truncate",title:ae.description||void 0,children:[ut&&t.jsxs("span",{children:[ut," · "]}),n("tools.http.paramCount",{count:ye}),ae.description?` — ${ae.description}`:""]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t.jsx("span",{title:n(pe?"tools.common.active":"tools.common.pausedTitle"),className:"inline-flex",children:t.jsx(vt,{checked:pe,onChange:()=>Ee(ae.id,!pe)})}),t.jsxs("button",{type:"button",className:"btn btn-outline h-8",onClick:()=>{y(ae),g(!0)},children:[t.jsx(qt,{className:"size-3.5"}),n("tools.common.edit")]}),t.jsx("button",{type:"button",title:n("tools.common.deleteTitle"),"aria-label":n("tools.common.deleteTitle"),onClick:()=>me(ae.id),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",children:t.jsx(mt,{className:"size-4"})})]})]},ae.id)})})]})]})]})}),t.jsx(DP,{open:p,onClose:()=>f(!1),onSave:$,initial:o??null,agents:U}),t.jsx(qP,{open:x,onClose:()=>h(!1),onSave:F,initial:l??null}),t.jsx(XP,{open:k,onClose:()=>{w(!1),C(null)},onSave:te,initial:j,takenNames:W,agentTimeZone:e.advancedBehavior?.timezone??null,toolType:N}),t.jsx(QP,{open:b,onClose:()=>{g(!1),y(null)},onSave:G,initial:v,takenNames:W})]})}const Hx=[{value:"string",labelKey:"analytics.dpTypes.string",hintKey:"dataPoint.types.string"},{value:"enum",labelKey:"analytics.dpTypes.enum",hintKey:"dataPoint.types.enum"},{value:"boolean",labelKey:"analytics.dpTypes.boolean",hintKey:"dataPoint.types.boolean"},{value:"integer",labelKey:"analytics.dpTypes.integer",hintKey:"dataPoint.types.integer"},{value:"number",labelKey:"analytics.dpTypes.number",hintKey:"dataPoint.types.number"}
968],rz=/^[a-z][a-z0-9_]*$/;function oz({open:e,onClose:a,onSave:n,initial:s,existingNames:i}){const{t:r}=M("agents"),[o,l]=m.useState(""),[c,d]=m.useState(""),[u,p]=m.useState("string"),[f,x]=m.useState([]),[h,b]=m.useState([]),[g,v]=m.useState(!1),[y,k]=m.useState(""),[w,j]=m.useState(""),[C,N]=m.useState(null);if(m.useEffect(()=>{e&&(l(s?.name??""),d(s?.description??""),p(s?.type??"string"),x(s?.enumValues??[]),b(s?.examples??[]),v(s?.required??!1),k(""),j(""),N(null))},[e,s]),m.useEffect(()=>{if(!e)return;const A=E=>{E.key==="Escape"&&a()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e,a]),!e)return null;function S(){const A=y.trim();if(A){if(f.includes(A)){k("");return}f.length>=20||(x([...f,A]),k(""))}}function _(){const A=w.trim();if(A){if(h.includes(A)||h.length>=10){j("");return}b([...h,A]),j("")}}function R(){N(null);const A=o.trim();if(!A)return N(r("dataPoint.errNameRequired"));if(!rz.test(A))return N(r("dataPoint.errNameFormat"));if(i.includes(A))return N(r("dataPoint.errNameDuplicate"));if(!c.trim())return N(r("dataPoint.errDescRequired"));if(u==="enum"&&f.length===0)return N(r("dataPoint.errEnumRequired"));const E={id:s?.id,name:A,description:c.trim(),type:u,...u==="enum"?{enumValues:f}:{},...u==="string"&&h.length?{examples:h}:{},...g?{required:!0}:{}};n(E),a()}return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black/30 z-40",onClick:a,"aria-hidden":"true"}),t.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"datapoint-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:t.jsxs("div",{className:"bg-paper-card rounded-2xl border border-paper-line shadow-xl w-full max-w-lg flex flex-col max-h-[90vh]",onClick:A=>A.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 p-6 border-b border-paper-line",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:r("dataPoint.eyebrow")}),t.jsx("h2",{id:"datapoint-modal-title",className:"text-lg font-semibold text-ink mt-0.5",children:r(s?"dataPoint.titleEdit":"dataPoint.titleNew")}),t.jsx("p",{className:"text-sm text-ink-mute mt-1",children:r("dataPoint.subtitle")})]}),t.jsx("button",{className:"btn btn-ghost h-8 w-8 p-0 shrink-0",onClick:a,"aria-label":r("modal.close"),children:t.jsx(nt,{className:"size-4"})})]}),t.jsxs("div",{className:"p-6 flex flex-col gap-5 overflow-y-auto",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-baseline gap-1 mb-1.5",children:[t.jsx("label",{className:"label",children:r("dataPoint.identifierLabel")}),t.jsx("span",{className:"text-rose-500 text-xs leading-none",children:"*"})]}),t.jsx("input",{className:"input font-mono text-[13px]",type:"text",placeholder:"monto_solicitado",value:o,maxLength:64,onChange:A=>l(A.target.value),autoFocus:!0})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("dataPoint.typeLabel")}),t.jsx("select",{className:"select w-full",value:u,onChange:A=>p(A.target.value),children:Hx.map(A=>t.jsx("option",{value:A.value,children:r(A.labelKey)},A.value))}),t.jsx("p",{className:"text-xs text-ink-mute mt-1",children:r(Hx.find(A=>A.value===u)?.hintKey??"")})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-baseline gap-1 mb-1.5",children:[t.jsx("label",{className:"label",children:r("dataPoint.descriptionLabel")}),t.jsx("span",{className:"text-rose-500 text-xs leading-none",children:"*"})]}),t.jsx("textarea",{className:"textarea min-h-[80px] text-[13px]",placeholder:r("dataPoint.descriptionPlaceholder"),value:c,maxLength:500,onChange:A=>d(A.target.value)})]}),u==="enum"&&t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-baseline gap-1 mb-1.5",children:[t.jsx("label",{className:"label",children:r("dataPoint.enumValuesLabel")}),t.jsx("span",{className:"text-rose-500 text-xs leading-none",children:"*"})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("input",{className:"input text-sm flex-1",type:"text",placeholder:r("dataPoint.enumValuePlaceholder"),value:y,maxLength:64,onChange:A=>k(A.target.value),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),S())}}),t.jsxs("button",{type:"button",className:"btn btn-outline",onClick:S,children:[t.jsx(Fe,{className:"size-4"}),r("modal.add")]})]}),f.length>0&&t.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:f.map(A=>t.jsxs("span",{className:"chip bg-brand-50 text-brand-700 border border-brand-200 flex items-center gap-1.5",children:[A,t.jsx("button",{type:"button",onClick:()=>x(f.filter(E=>E!==A)),className:"text-brand-400 hover:text-rose-500 transition-colors",title:r("modal.remove"),children:"×"})]},A))})]}),u==="string"&&t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:r("dataPoint.examplesLabel")}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("input",{className:"input text-sm flex-1",type:"text",placeholder:r("dataPoint.examplePlaceholder"),value:w,maxLength:128,onChange:A=>j(A.target.value),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),_())}}),t.jsxs("button",{type:"button",className:"btn btn-outline",onClick:_,children:[t.jsx(Fe,{className:"size-4"}),r("modal.add")]})]}),h.length>0&&t.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:h.map(A=>t.jsxs("span",{className:"chip bg-paper-line/50 text-ink-soft flex items-center gap-1.5",children:[A,t.jsx("button",{type:"button",onClick:()=>b(h.filter(E=>E!==A)),className:"text-ink-mute hover:text-rose-500 transition-colors",title:r("modal.remove"),children:"×"})]},A))})]}),t.jsxs("label",{className:"flex items-center gap-2 cursor-pointer group",children:[t.jsx("input",{type:"checkbox",checked:g,onChange:A=>v(A.target.checked),className:"w-4 h-4 rounded border-paper-line accent-brand-600 cursor-pointer"}),t.jsx("span",{className:"text-sm text-ink group-hover:text-brand-700 transition-colors",children:r("dataPoint.markExpected")})]}),C&&t.jsx("div",{className:"rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700",children:C})]}),t.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-paper-line",children:[t.jsx("button",{className:"btn btn-outline",onClick:a,children:r("modal.cancel")}),t.jsx("button",{className:"btn btn-primary",onClick:R,children:r(s?"modal.saveChanges":"dataPoint.saveNew")})]})]})})]})}const lz=[{id:"gpt-4.1-mini",label:"GPT-4.1 mini",descKey:"analytics.models.gpt41miniDesc"},{id:"gpt-4o",label:"GPT-4o",descKey:"analytics.models.gpt4oDesc"},{id:"gpt-5.1",label:"GPT-5.1",descKey:"analytics.models.gpt51Desc"}],cz="gpt-4.1-mini",Qx={string:{labelKey:"analytics.dpTypes.string",Icon:f2},enum:{labelKey:"analytics.dpTypes.enum",Icon:sy},boolean:{labelKey:"analytics.dpTypes.boolean",Icon:h2},integer:{labelKey:"analytics.dpTypes.integer",Icon:bS},number:{labelKey:"analytics.dpTypes.number",Icon:Xp}};function ll({checked:e,onChange:a}){return t.jsx(vt,{checked:e,onChange:a})}
968function dz({agent:e,onChange:a}){const{t:n}=M("agents"),s=e.analytics??{},i=s.summaryEnabled??!0,r=s.summarizePrompt??"",o=s.successEvaluation?.enabled??!0,l=s.successEvaluation?.prompt??"",c=s.sentimentEnabled??!0,d=s.liveSentimentEnabled??!1,u=dt(),{data:p}=se({queryKey:["org","capabilities"],queryFn:async()=>(await T.get("/organizations/me/capabilities")).data,staleTime:5*6e4}),f=p?.liveSentiment??!0,x=s.dataPoints??[],h=s.analysisModel??cz,[b,g]=m.useState(!1),[v,y]=m.useState(null);function k(S){a({analytics:{summaryEnabled:i,summarizePrompt:r,successEvaluation:{enabled:o,prompt:l},sentimentEnabled:c,liveSentimentEnabled:d,dataPoints:x,analysisModel:h,...s.extractFields?{extractFields:s.extractFields}:{},...s.successCriteria?{successCriteria:s.successCriteria}:{},...S}})}function w(){y(null),g(!0)}function j(S,_){y({dp:S,index:_}),g(!0)}function C(S){k(v?{dataPoints:x.map((_,R)=>R===v.index?S:_)}:{dataPoints:[...x,S]})}function N(S){k({dataPoints:x.filter((_,R)=>R!==S)})}return t.jsxs("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:[t.jsx(zt,{title:n("analytics.section1.title"),desc:n("analytics.section1.desc"),children:t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(dy,{className:"size-4 text-brand-600"}),t.jsx("label",{className:"label !normal-case !text-sm !font-medium !text-ink !tracking-normal",children:n("analytics.section1.modelLabel")})]}),t.jsx("p",{className:"text-xs text-ink-mute",children:n("analytics.section1.modelDesc")}),t.jsx("select",{className:"select w-full max-w-sm",value:h,onChange:S=>k({analysisModel:S.target.value}),children:lz.map(S=>t.jsxs("option",{value:S.id,children:[S.label," — ",n(S.descKey)]},S.id))})]})}),t.jsxs(zt,{title:n("analytics.builtins.title"),desc:n("analytics.builtins.desc"),children:[t.jsxs("div",{className:"rounded-xl border border-paper-line bg-paper p-4 flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(_n,{className:"size-4 text-brand-600 mt-0.5"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:n("analytics.builtins.summaryTitle")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:n("analytics.builtins.summaryDesc")})]})]}),t.jsx(ll,{checked:i,onChange:S=>k({summaryEnabled:S})})]}),i&&t.jsx("textarea",{className:"textarea min-h-[60px] text-[13px] mt-1",placeholder:n("analytics.builtins.summaryPlaceholder"),value:r,maxLength:1e3,onChange:S=>k({summarizePrompt:S.target.value})})]}),t.jsxs("div",{className:"rounded-xl border border-paper-line bg-paper p-4 flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(Nt,{className:"size-4 text-brand-600 mt-0.5"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:n("analytics.builtins.successTitle")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:n("analytics.builtins.successDesc")})]})]}),t.jsx(ll,{checked:o,onChange:S=>k({successEvaluation:{enabled:S,prompt:l||n("analytics.successDefaultPrompt")}})})]}),o&&t.jsx("textarea",{className:"textarea min-h-[60px] text-[13px] mt-1",placeholder:n("analytics.successDefaultPrompt"),value:l,maxLength:1e3,onChange:S=>k({successEvaluation:{enabled:!0,prompt:S.target.value}})})]}),t.jsx("div",{className:"rounded-xl border border-paper-line bg-paper p-4",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(py,{className:"size-4 text-brand-600 mt-0.5"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:n("analytics.builtins.sentimentTitle")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:n("analytics.builtins.sentimentDesc")})]})]}),t.jsx(ll,{checked:c,onChange:S=>k({sentimentEnabled:S})})]})}),f?t.jsx("div",{className:"rounded-xl border border-paper-line bg-paper p-4",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex items-start gap-2 flex-1 min-w-0",children:[t.jsx(Hp,{className:"size-4 text-brand-600 mt-0.5 shrink-0"}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"text-sm font-medium text-ink flex items-center gap-2 flex-wrap",children:[n("analytics.live.title"),t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded-full bg-brand-100 text-brand-700",children:n("analytics.live.premiumBadge")})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:t.jsx(wa,{t:n,i18nKey:"analytics.live.descAllowed",components:{b0:t.jsx("strong",{}),b1:t.jsx("strong",{})}})})]})]}),t.jsx(ll,{checked:d,onChange:S=>k({liveSentimentEnabled:S})})]})}):t.jsx("div",{className:"rounded-xl border-2 p-4",style:{borderColor:"var(--cia-cta-500)",background:"color-mix(in oklab, var(--cia-cta-500) 7%, transparent)"},children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(_t,{className:"size-4 mt-0.5 shrink-0",style:{color:"var(--cia-cta-500)"}}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-sm font-semibold text-ink flex items-center gap-2 flex-wrap",children:[n("analytics.live.title"),t.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded-full",style:{background:"var(--cia-cta-500)",color:"#fff"},children:n("analytics.live.growthBadge")})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-1 leading-relaxed",children:t.jsx(wa,{t:n,i18nKey:"analytics.live.upsell",components:{b0:t.jsx("strong",{}),b1:t.jsx("strong",{}),b2:t.jsx("strong",{}),b3:t.jsx("strong",{})}})}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 flex items-center gap-2 text-sm mt-3",onClick:()=>u({to:"/plan"}),children:[t.jsx(_t,{className:"size-4"})," ",n("analytics.live.upgradeBtn")]})]})]})})]}),t.jsx(zt,{title:n("analytics.dataCollection.title"),desc:n("analytics.dataCollection.desc"),last:!0,children:t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("div",{className:"flex items-center justify-end gap-3",children:x.length<25&&t.jsxs("button",{type:"button",className:"btn btn-outline h-9",onClick:w,children:[t.jsx(Fe,{className:"size-4"}),n("analytics.dataCollection.add")]})}),x.length===0?t.jsx("div",{className:"rounded-xl border border-dashed border-paper-line p-6 text-center",children:t.jsx("p",{className:"text-sm text-ink-mute",children:n("analytics.dataCollection.empty")})}):t.jsx("div",{className:"flex flex-col gap-2",children:x.map((S,_)=>{const R=Qx[S.type]??Qx.string,A=R.Icon;return t.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-paper-line bg-paper px-3 py-2.5",children:[t.jsx(A,{className:"size-4 text-brand-600 shrink-0"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"font-mono text-[13px] text-ink truncate",children:S.name}),t.jsx("span",{className:"chip chip-brand !h-4 !text-[10px]",children:n(R.labelKey)}),S.required&&t.jsx("span",{className:"chip chip-amber !h-4 !text-[10px]",children:n("analytics.dataCollection.requiredChip")})]}),S.description&&t.jsx("p",{className:"text-xs text-ink-mute truncate mt-0.5",children:S.description})]}),t.jsx("button",{type:"button",onClick:()=>j(S,_),title:n("analytics.dataCollection.editTitle"),className:"p-1.5 rounded-lg text-ink-mute hover:text-brand-700 hover:bg-brand-50 transition-colors",children:t.jsx(qt,{className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>N(_),title:n("analytics.dataCollection.deleteTitle"),className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",children:t.jsx(mt,{className:"size-4"})})]},S.id??`${S.name}-${_}`)})})]})}),t.jsx(oz,{open:b,onClose:()=>g(!1),onSave:C,initial:v?.dp??null,existingNames:x.filter((S,_)=>_!==v?.index).map(S=>S.name)})]})}async function a9(){try{return(await T.get("/whatsapp/templates")).data}catch(e){const a=e?.response?.status;if(a===501||a===404||a===403)return null;throw e}}async function uz(){try{return(await T.get("/whatsapp/accounts")).data}catch(e){const a=e?.response?.status;if(a===501||a===404)return null;throw e}}function n9(e){return(e??[]).filter(a=>a.status==="active")}function s9(e){return e?.businessName?.trim()||e?.wabaId||""}function qh(){const e=xe();return()=>
968{e.invalidateQueries({queryKey:["whatsapp","templates"]}),e.invalidateQueries({queryKey:["wa-templates-for-campaign"]})}}function Bh(e,a){a?.id&&e.setQueryData(["whatsapp","templates"],n=>n&&{...n,items:[a,...n.items.filter(s=>s.id!==a.id)]})}function pz(e){const a=e?.response?.data?.message;return Array.isArray(a)?a.filter(n=>typeof n=="string").join(" ")||null:typeof a=="string"&&a.trim()?a:null}function i9(){const{t:e}=M("misc"),a=xe(),n=qh(),s=oe({mutationFn:async c=>(await T.post(`/whatsapp/templates/${c}/submit`)).data,onSuccess:c=>{Bh(a,c),n(),J(c?.status==="approved"?{tone:"ok",title:e("whatsapp.plantillas.toast.aprobadaEnElActo",{nombre:c.name})}:{tone:"ok",title:e("whatsapp.plantillas.toast.enviada"),desc:e("whatsapp.plantillas.toast.enviadaDesc")})},onError:()=>n()}),i=oe({mutationFn:async c=>(await T.delete(`/whatsapp/templates/${c}`)).data,onSuccess:()=>{n(),J({tone:"ok",title:e("whatsapp.plantillas.toast.eliminada")})}}),r=oe({mutationFn:async()=>(await T.post("/whatsapp/templates/verificar")).data,onSuccess:c=>{n(),J(c.revisadas===0?{tone:"info",title:e("whatsapp.plantillas.toast.verificadaVacia")}:{tone:"ok",title:e("whatsapp.plantillas.toast.verificada",{count:c.revisadas}),desc:e("whatsapp.plantillas.toast.verificadaResueltas",{count:c.resueltas})})},onError:c=>J({tone:"bad",title:pz(c)??e("whatsapp.templates.verifyFailed")})});return{pedirEnvio:c=>pa({title:e("whatsapp.plantillas.confirmarEnvio.titulo",{nombre:c.name}),message:e(c.status==="rejected"?"whatsapp.plantillas.confirmarEnvio.mensajeRechazada":"whatsapp.plantillas.confirmarEnvio.mensaje"),confirmLabel:e("whatsapp.plantillas.confirmarEnvio.confirmar"),cancelLabel:e("whatsapp.plantillas.cancelar"),onConfirm:async()=>{await s.mutateAsync(c.id)}}),pedirBorrado:c=>{const d=oS(c),u=d.tipo==="desconocido"?e("whatsapp.plantillas.confirmarBorrado.usoDesconocido"):d.tipo==="ninguna"?e("whatsapp.plantillas.confirmarBorrado.usoNinguna"):e("whatsapp.plantillas.confirmarBorrado.usoCampanas",{count:d.total}),p=c.status==="draft"?e("whatsapp.plantillas.confirmarBorrado.borrador"):e("whatsapp.plantillas.confirmarBorrado.enElProveedor");return pa({title:e("whatsapp.plantillas.confirmarBorrado.titulo",{nombre:c.name}),message:`${p} ${u}`,confirmLabel:e("whatsapp.plantillas.confirmarBorrado.confirmar"),cancelLabel:e("whatsapp.plantillas.cancelar"),danger:!0,onConfirm:async()=>{await i.mutateAsync(c.id)}})},verificar:r,enviando:s.isPending}}function r9(){const e=xe(),a=qh();return oe({mutationFn:async({id:n,pedido:s})=>n?(await T.patch(`/whatsapp/templates/${n}`,{category:s.category,components:s.components})).data:(await T.post("/whatsapp/templates",{accountId:s.accountId,name:s.name,language:s.language,category:s.category,components:s.components})).data,onSuccess:n=>{Bh(e,n),a()}})}function o9(){const e=xe(),a=qh();return oe({mutationFn:async n=>(await T.post(`/whatsapp/templates/${n}/submit`)).data,onSuccess:n=>Bh(e,n),onSettled:()=>a()})}function l9(){return oe({mutationFn:async e=>(await T.post("/whatsapp/templates/draft-with-ai",{proposito:e.proposito.trim(),category:e.category,language:e.language})).data})}const Wh=[{value:"call.analyzed",key:"callAnalyzed"},{value:"plan.usage.threshold",key:"planUsageThreshold"},{value:"plan.limit.reached",key:"planLimitReached"},{value:"plan.spend_cap.reached",key:"planSpendCapReached"},{value:"meeting.summarized",key:"meetingSummarized"},{value:"appointment.booked",key:"appointmentBooked"},{value:"appointment.failed",key:"appointmentFailed"},{value:"campaign.started",key:"campaignStarted"},{value:"campaign.completed",key:"campaignCompleted"},{value:"trial.exhausted",key:"trialExhausted"},{value:"whatsapp.account.disconnected",key:"whatsappAccountDisconnected"},{value:"whatsapp.template.status_changed",key:"whatsappTemplateStatusChanged"},{value:"whatsapp.number.quality_changed",key:"whatsappNumberQualityChanged"},{value:"whatsapp.conversation.handoff",key:"whatsappConversationHandoff"},{value:"whatsapp.conversation.closed",key:"whatsappConversationClosed"},{value:"contact.created",key:"contactCreated"},{value:"flow.event",key:"flowEvent"}],hz=e=>e.startsWith("whatsapp.");function mz({open:e,onClose:a,onSubmit:n,saving:s,error:i,initial:r,scopeLabel:o,nivelDeAgente:l=!1,canalDeWhatsapp:c}){const{t:d}=M("misc"),[u,p]=m.useState(""),[f,x]=m.useState(""),[h,b]=m.useState(["call.analyzed"]),[g,v]=m.useState(null);m.useEffect(()=>{e&&(p(r?.url??""),x(r?.description??""),b(r?.events&&r.events.length>0?r.events:["call.analyzed"]),v(null))},[e,r]);function y(w){b(j=>j.includes(w)?j.filter(C=>C!==w):[...j,w])}function k(){v(null);const w=u.trim();
968if(!w)return v(d("webhookModal.errUrlRequired"));if(!/^https:\/\//i.test(w))return v(d("webhookModal.errUrlHttps"));if(h.length===0)return v(d("webhookModal.errEvents"));n({url:w,description:f.trim()||void 0,events:h})}return t.jsx(ot,{open:e,onClose:a,maxWidth:560,eyebrow:o,title:d(r?"webhookModal.editTitle":"webhookModal.newTitle"),footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"cia-btn cia-btn-outline",onClick:a,disabled:s,children:d("webhookModal.cancel")}),t.jsxs("button",{className:"cia-btn cia-btn-cta",onClick:k,disabled:s,children:[s&&t.jsx(je,{className:"animate-spin",size:15}),d(r?"webhookModal.save":"webhookModal.create")]})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)",lineHeight:1.5},children:[d("webhookModal.introPre")," ",t.jsx("strong",{children:d("webhookModal.introStrong")})," ",d("webhookModal.introPost")]}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:d("webhookModal.urlLabel")}),t.jsx("input",{className:"input cia-mono",style:{width:"100%",marginTop:4},type:"url",placeholder:"https://tu-sistema.com/webhooks/conectaia",value:u,autoFocus:!0,onChange:w=>p(w.target.value)}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:6},children:d("webhookModal.urlHint")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:d("webhookModal.nameLabel")}),t.jsx("input",{className:"input",style:{width:"100%",marginTop:4},type:"text",placeholder:d("webhookModal.namePlaceholder"),value:f,maxLength:120,onChange:w=>x(w.target.value)})]}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",style:{display:"block",marginBottom:6},children:d("webhookModal.eventsLabel")}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Wh.filter(w=>hz(w.value)?l?!1:c!==!1||!!r?.events?.includes(w.value):!0).map(w=>{const j=h.includes(w.value);return t.jsxs("button",{type:"button",onClick:()=>y(w.value),style:{display:"flex",alignItems:"flex-start",gap:10,textAlign:"left",cursor:"pointer",padding:"10px 12px",borderRadius:"var(--cia-r)",border:`1.5px solid ${j?"var(--cia-cta-500)":"var(--cia-border)"}`,background:j?"var(--cia-bg-tint)":"var(--cia-bg-elev)",transition:"border-color var(--cia-dur-fast), background var(--cia-dur-fast)"},children:[t.jsx("span",{style:{width:18,height:18,borderRadius:6,flex:"none",marginTop:1,display:"grid",placeItems:"center",background:j?"var(--cia-cta-500)":"transparent",border:j?"none":"1.5px solid var(--cia-border-2)",color:"#fff"},children:j&&t.jsx(ct,{size:12,strokeWidth:3})}),t.jsxs("span",{style:{minWidth:0},children:[t.jsx("span",{style:{fontSize:13,fontWeight:500},children:d(`webhookModal.event.${w.key}.label`)}),t.jsxs("span",{style:{display:"block",fontSize:11,color:"var(--cia-text-3)"},children:[t.jsx("code",{className:"cia-mono",children:w.value})," — ",d(`webhookModal.event.${w.key}.hint`)]})]})]},w.value)})}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:6},children:d("webhookModal.eventsHint")}),l?t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:4},children:d("webhookModal.whatsappSoloOrganizacion")}):c===!1?t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:4},children:d("webhookModal.whatsappCanalApagado")}):null]}),(g||i)&&t.jsx(le,{tone:"bad",children:g||i})]})})}const fz=e=>e==="call.analyzed"||e.startsWith("whatsapp."),Gx=e=>Wh.find(a=>a.value===e)?.key??null,xz={success:"chip-mint",failed:"chip-rose",pending:"chip-amber"};function K0({agentId:e}){const{t:a}=M("misc"),n=xe();Pe(W=>W.user?.role);const{can:s}=tt(),i=s("webhooks.manage"),r=e??"org",[o,l]=m.useState(!1),[c,d]=m.useState(null),[u,p]=m.useState(null),[f,x]=m.useState(!1),[h,b]=m.useState(null),[g,v]=m.useState(null),y=W=>J({title:W,tone:"ok"}),k=["webhook-endpoints",r],{data:w,isLoading:j,error:C}=se({queryKey:k,queryFn:async()=>(await T.get("/webhook-endpoints",{params:{agentId:e??"__org__"}})).data}),N=oe({mutationFn:async W=>(await T.post("/webhook-endpoints",{...W,...e?{agentId:e}:{}})).data,onSuccess:W=>{n.invalidateQueries({queryKey:k}
968),l(!1),p({url:W.endpoint.url,secret:W.secret})},onError:W=>v(lr(W))}),S=oe({mutationFn:async W=>(await T.patch(`/webhook-endpoints/${W.id}`,W.body)).data,onSuccess:()=>{n.invalidateQueries({queryKey:k}),l(!1),d(null)},onError:W=>v(lr(W))}),_=oe({mutationFn:async W=>({url:W.url,secret:(await T.post(`/webhook-endpoints/${W.id}/rotate-secret`)).data.secret}),onSuccess:W=>p(W),onError:W=>J({tone:"bad",title:lr(W)})}),R=oe({mutationFn:async W=>(await T.post(`/webhook-endpoints/${W.id}/test`,W.event?{event:W.event}:void 0)).data,onSuccess:W=>{const V=W?.eventType?Gx(W.eventType):null;y(V?a("webhooks.flashTestEvento",{evento:a(`webhookModal.event.${V}.label`)}):a("webhooks.flashTest"))},onError:W=>J({tone:"bad",title:lr(W)})}),A=se({queryKey:["whatsapp","accounts"],enabled:!e&&o,queryFn:uz,retry:!1}),E=A.data===null?!1:A.data?!0:void 0,I=oe({mutationFn:async W=>(await T.delete(`/webhook-endpoints/${W}`)).data,onSuccess:()=>{n.invalidateQueries({queryKey:k}),y(a("webhooks.flashDeleted"))},onError:W=>J({tone:"bad",title:lr(W)})});function P(){d(null),v(null),l(!0)}function O(W){d(W),v(null),l(!0)}async function K(W){try{await navigator.clipboard.writeText(W),x(!0),setTimeout(()=>x(!1),1800)}catch{}}return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsx("p",{className:"text-sm text-ink-mute max-w-xl",children:a(e?"webhooks.descAgent":"webhooks.descOrg")}),i&&t.jsxs("button",{className:"btn btn-primary h-9 px-4 shrink-0",onClick:P,children:[t.jsx(Fe,{className:"size-4"}),a("webhooks.newWebhook")]})]}),u&&t.jsxs("div",{className:"rounded-xl border border-brand-200 bg-brand-50 p-4 flex flex-col gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2 text-brand-800 text-sm font-semibold",children:[t.jsx(Ka,{className:"size-4"}),a("webhooks.secretTitle")]}),t.jsxs("p",{className:"text-xs text-ink-mute",children:[a("webhooks.secretHintPre")," ",t.jsx("code",{className:"font-mono",children:"webhook-signature"})," ",a("webhooks.secretHintMid")," ",t.jsx("span",{className:"font-mono",children:u.url}),"."]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("code",{className:"flex-1 font-mono text-[12px] bg-white border border-paper-line rounded-lg px-3 py-2 break-all",children:u.secret}),t.jsxs("button",{className:"btn btn-outline h-9",onClick:()=>K(u.secret),children:[f?t.jsx(ct,{className:"size-4 text-mint-600"}):t.jsx(bn,{className:"size-4"}),a(f?"webhooks.copied":"webhooks.copy")]})]}),t.jsx("button",{className:"text-xs text-ink-mute hover:text-ink w-fit mt-1",onClick:()=>p(null),children:a("webhooks.saved")})]}),j?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[0,1].map(W=>t.jsx("div",{className:"cia-card",style:{padding:16},children:t.jsx(ge,{w:"60%",h:14})},W))}):C?t.jsx(le,{tone:"bad",children:a("webhooks.loadError")}):!w||w.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{icon:Ec,title:a(e?"webhooks.emptyAgentTitle":"webhooks.emptyOrgTitle"),desc:a(e?"webhooks.emptyAgentDesc":"webhooks.emptyOrgDesc"),action:i?{label:a("webhooks.newWebhook"),onClick:()=>{d(null),v(null),l(!0)}}:void 0,mini:!0})}):t.jsx("div",{className:"flex flex-col gap-3",children:w.map(W=>t.jsxs("div",{className:"card p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"font-mono text-[13px] text-ink break-all",children:W.url}),t.jsx("span",{className:os("chip",W.enabled?"chip-mint":"bg-paper-line/60 text-ink-mute"),children:W.enabled?a("webhooks.active"):a("webhooks.inactive")})]}),W.description&&t.jsx("p",{className:"text-xs text-ink-mute mt-1",children:W.description}),t.jsx("div",{className:"flex items-center gap-2 mt-1.5",children:W.events.map(V=>t.jsx("span",{className:"chip chip-brand !h-4 !text-[10px]",children:V},V))})]}),i&&t.jsx("label",{className:"flex items-center gap-2 cursor-pointer shrink-0",children:t.jsx(vt,{checked:W.enabled,onChange:()=>S.mutate({id:W.id,body:{enabled:!W.enabled}})})})]}),t.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap border-t border-paper-line pt-3",children:[t.jsxs("button",{className:"btn btn-ghost h-8 text-xs",onClick:()=>b(h===W.id?null:W.id),children:[h===W.id?t.jsx(Rn,{className:"size-3.5"}):t.jsx(Ut,{className:"size-3.5"}),a("webhooks.deliveries")]}),i&&t.jsxs(t.Fragment,{children:[(()=>{const V=W.events.filter(fz);if(V.length<=1){const U=V[0];return t.jsxs("button",{className:"btn btn-ghost h-8 text-xs",onClick:()=>
968R.mutate({id:W.id,event:U&&U!=="call.analyzed"?U:void 0}),disabled:R.isPending,children:[t.jsx(Gr,{className:"size-3.5"}),a("webhooks.test")]})}return t.jsx(vn,{trigger:t.jsxs(t.Fragment,{children:[t.jsx(Gr,{className:"size-3.5"}),a("webhooks.test"),t.jsx(Ut,{className:"size-3.5"})]}),triggerClassName:"btn btn-ghost h-8 text-xs","aria-label":a("webhooks.testMenu",{url:W.url}),disabled:R.isPending,align:"start",items:V.map(U=>{const X=Gx(U);return{key:U,label:X?a(`webhookModal.event.${X}.label`):U,onSelect:()=>R.mutate({id:W.id,event:U})}})})})(),t.jsxs("button",{className:"btn btn-ghost h-8 text-xs",onClick:()=>_.mutate(W),disabled:_.isPending,children:[t.jsx(Ka,{className:"size-3.5"}),a("webhooks.rotateSecret")]}),t.jsxs("button",{className:"btn btn-ghost h-8 text-xs",onClick:()=>O(W),children:[t.jsx(qt,{className:"size-3.5"}),a("webhooks.edit")]}),t.jsxs("button",{className:"btn btn-ghost h-8 text-xs text-rose-500 hover:bg-rose-50",onClick:async()=>{await pa({message:a("webhooks.deleteConfirm"),danger:!0})&&I.mutate(W.id)},children:[t.jsx(mt,{className:"size-3.5"}),a("webhooks.delete")]})]})]}),h===W.id&&t.jsx(gz,{endpointId:W.id})]},W.id))}),t.jsx(mz,{open:o,onClose:()=>{l(!1),d(null)},onSubmit:W=>{v(null),c?S.mutate({id:c.id,body:W}):N.mutate(W)},saving:N.isPending||S.isPending,error:g,initial:c,scopeLabel:a(e?"webhooks.scopeAgent":"webhooks.scopeOrg"),nivelDeAgente:!!e,canalDeWhatsapp:E})]})}function gz({endpointId:e}){const{t:a}=M("misc"),{data:n,isLoading:s}=se({queryKey:["webhook-deliveries",e],queryFn:async()=>(await T.get(`/webhook-endpoints/${e}/deliveries`)).data});return s?t.jsxs("div",{className:"text-xs text-ink-mute py-2",children:[t.jsx(je,{className:"size-3.5 animate-spin inline mr-1.5"}),a("webhooks.delivery.loading")]}):!n||n.length===0?t.jsx("p",{className:"text-xs text-ink-mute py-2",children:a("webhooks.delivery.empty")}):t.jsx("div",{className:"rounded-lg border border-paper-line overflow-hidden",children:t.jsxs("table",{className:"w-full text-xs",children:[t.jsx("thead",{className:"bg-paper border-b border-paper-line",children:t.jsxs("tr",{className:"text-[10px] font-mono tracking-wider text-ink-mute",children:[t.jsx("th",{className:"text-left px-3 py-2",children:a("webhooks.delivery.colDate")}),t.jsx("th",{className:"text-left px-3 py-2",children:a("webhooks.delivery.colEvent")}),t.jsx("th",{className:"text-left px-3 py-2",children:a("webhooks.delivery.colStatus")}),t.jsx("th",{className:"text-left px-3 py-2",children:a("webhooks.delivery.colHttp")}),t.jsx("th",{className:"text-left px-3 py-2",children:a("webhooks.delivery.colAttempts")})]})}),t.jsx("tbody",{children:n.map(i=>t.jsxs("tr",{className:"border-t border-paper-line",children:[t.jsx("td",{className:"px-3 py-2 font-mono text-ink-soft whitespace-nowrap",children:Be(i.createdAt)}),t.jsx("td",{className:"px-3 py-2 font-mono",children:i.eventType}),t.jsx("td",{className:"px-3 py-2",children:t.jsx("span",{className:os("chip !h-5 !text-[10px]",xz[i.status]),children:a(`webhooks.delivery.status.${i.status}`,{defaultValue:i.status})})}),t.jsx("td",{className:"px-3 py-2 font-mono",children:i.responseStatus??(i.error?t.jsx(Tt,{className:"size-3.5 text-rose-500 inline"}):"—")}),t.jsx("td",{className:"px-3 py-2 font-mono tabular-nums",children:i.attempts})]},i.id))})]})})}function lr(e){const a=e?.response?.data?.message;return Array.isArray(a)?a.join(" · "):a||he.t("misc:errors.generic")}function bz({agent:e,onChange:a}){const{can:n}=tt(),s=n("phoneNumbers.manage"),{t:i}=M("agents"),r=xe(),o=e.id,{data:l,isLoading:c}=se({queryKey:["phone-numbers"],queryFn:async()=>(await T.get("/phone-numbers")).data}),d=oe({mutationFn:async({id:h,newAgentId:b})=>{await T.patch(`/phone-numbers/${h}/assign`,{agentId:b})},onSuccess:()=>{r.invalidateQueries({queryKey:["phone-numbers"]})}});if(!o)return t.jsx("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:t.jsx(zt,{title:i("deploy.noAgentTitle"),desc:i("deploy.noAgentDesc"),last:!0,children:t.jsx("div",{className:"text-sm text-ink-mute",children:i("deploy.noAgentBody")})})});const u=(l||[]).filter(h=>!h.shared&&!h.rotating),p=u.filter(h=>h.agentId===o),f=u.filter(h=>!h.agentId),x=u.filter(h=>h.agentId&&h.agentId!==o);return t.jsxs("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:[t.jsx(zt,{title:i("deploy.numbersTitle"),desc:i("deploy.numbersDesc"),children:c?t.jsx("div",{className:"text-sm text-ink-mute",children:i("deploy.loading")}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{children:[t.jsx("label",{className:"label mb-2 block",children:i("deploy.mineLabel",{n:p.length})}),p.length===0?t.jsx("div",{className:"text-sm text-ink-mute",children:i("deploy.mineEmpty")}):t.jsx("div",{className:"flex flex-col gap-2",children:p.map(h=>t.jsx(Zd,{n:h,children:t.jsxs("button",{className:"btn btn-outline h-8",disabled:d.isPending||!s,title:s?void 0:i("common:noPermission"),onClick:()=>d.mutate({id:h.id,newAgentId:null}),children:[d.isPending?t.jsx(je,{className:"size-3.5 animate-spin"}):t.jsx(g2,{className:"size-3.5"}),i("deploy.remove")]})},h.id))})]}),t.jsxs("section",{children:[t.jsx("label",{className:"label mb-2 block",children:i("deploy.availableLabel",{n:f.length})}),f.length===0?t.jsx("div",{className:"text-sm text-ink-mute",children:i("deploy.availableEmpty")}):t.jsx("div",{className:"flex flex-col gap-2",children:f.map(h=>t.jsx(Zd,{n:h,children:t.jsxs("button",{className:"btn btn-primary h-8",disabled:d.isPending||!s,title:s?void 0:i("common:noPermission"),onClick:()=>d.mutate({id:h.id,newAgentId:o}),children:[d.isPending?t.jsx(je,{className:"size-3.5 animate-spin"}):t.jsx(Jp,{className:"size-3.5"}),i("deploy.assign")]})},h.id))})]}),x.length>0&&t.jsxs("section",{children:[t.jsx("label",{className:"label mb-2 block",children:i("deploy.othersLabel",{n:x.length})}),t.jsx("div",{className:"flex flex-col gap-2 opacity-70",children:x.map(h=>t.jsx(Zd,{n:h,children:t.jsx("span",{className:"text-xs font-mono text-ink-mute",children:h.agentId})},h.id))})]})]})}),t.jsx(zt,{title:i("deploy.recordingTitle"),desc:i("deploy.recordingDesc"),children:t.jsx(yz,{value:e.recording??null,onChange:h=>a?.({recording:h})})}),t.jsx(zt,{title:i("deploy.webhookTitle"),desc:i("deploy.webhookDesc"),last:!0,children:t.jsx(K0,{agentId:o})})]})}
968function yz({value:e,onChange:a}){const{t:n}=M("agents"),s=e??{},i=!!s.enabled,r=!!s.consentAnnounce,o=l=>a({...s,...l});return t.jsx("section",{children:t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(Ta,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("deploy.recording.title")}),t.jsx(vt,{checked:i,onChange:()=>o({enabled:!i})})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:n("deploy.recording.desc")}),i&&t.jsxs("div",{className:"mt-4 flex flex-col gap-3 border-t border-paper-line pt-4",children:[t.jsxs("label",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"text-sm",children:n("deploy.recording.consentToggle")}),t.jsx(vt,{checked:r,onChange:()=>o({consentAnnounce:!r})})]}),r&&t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1 block text-xs",children:n("deploy.recording.consentMsgLabel")}),t.jsx("textarea",{className:"input min-h-[64px] text-sm",placeholder:n("deploy.recording.consentPlaceholder"),maxLength:500,value:s.consentMessage??"",onChange:l=>o({consentMessage:l.target.value})}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:n("deploy.recording.consentHint")})]}),t.jsxs("div",{className:"border-t border-paper-line pt-3",children:[t.jsx("span",{className:"label text-xs mb-1.5 block",children:n("deploy.recording.retentionLabel")}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[t.jsx("input",{type:"radio",checked:!!s.retentionDays&&s.retentionDays>0,onChange:()=>o({retentionDays:s.retentionDays&&s.retentionDays>0?s.retentionDays:90})}),t.jsx("span",{children:n("deploy.recording.deleteAfter")}),t.jsx("input",{type:"number",min:1,max:365,value:s.retentionDays&&s.retentionDays>0?s.retentionDays:90,disabled:!(s.retentionDays&&s.retentionDays>0),onChange:l=>o({retentionDays:Math.min(Math.max(Math.round(Number(l.target.value)||1),1),365)}),className:"input h-8 w-20 text-sm disabled:opacity-50"}),t.jsx("span",{children:n("deploy.recording.days")}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:n("deploy.recording.maxDays")})]}),t.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[t.jsx("input",{type:"radio",checked:!s.retentionDays||s.retentionDays<=0,onChange:()=>o({retentionDays:null})}),t.jsx("span",{children:n("deploy.recording.keepForever")})]})]}),t.jsx("p",{className:"text-[11px] text-ink-mute mt-1",children:n("deploy.recording.retentionHint")})]})]})]})]})})}function Zd({n:e,children:a}){const{t:n}=M("agents");return t.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-paper-line p-3",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("div",{className:"size-9 rounded-lg bg-brand-50 grid place-items-center",children:t.jsx(Ma,{className:"size-4 text-brand-700"})}),t.jsxs("div",{children:[t.jsx("div",{className:"font-mono text-sm",children:e.e164}),t.jsxs("div",{className:"text-xs text-ink-mute",children:[e.label||n("deploy.row.noLabel"),!e.active&&n("deploy.row.inactive")]})]})]}),a]})}const vz=()=>new Promise(()=>{}),jz="linear-gradient(180deg,rgba(255,255,255,.26),rgba(255,255,255,0) 52%),linear-gradient(135deg,#FBB24E 0%,#F39221 40%,#EE7C14 72%,#2B52A1 138%)";function wz({wc:e,agentName:a}){const{t:n}=M("agents"),s=e.bubble?.accentColor||"#2B52A1",i=e.bubble?.style==="pill",r=e.bubble?.position==="bl",o=m.useMemo(()=>({agentName:a,voiceEnabled:e.voiceEnabled!==!1,chatEnabled:e.chatEnabled!==!1,languages:(e.languages??[]).filter(c=>
968c.code?.trim()),accentColor:s,theme:e.theme??"light",welcomeMessage:e.welcomeMessage||null,avatar:e.avatar||null,launcher:i?"pill":"round"}),[a,e,s,i]),l=o.theme==="dark"||o.theme==="auto"&&typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light";return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:n("widget.previewTitle")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:n("widget.previewHint")})]}),t.jsx("div",{className:"cia","data-theme":l,style:{width:340,maxWidth:"100%",height:520,borderRadius:18,overflow:"hidden",border:"1px solid var(--cia-border)",boxShadow:"var(--cia-shadow-lg)",background:"var(--cia-bg)",color:"var(--cia-text)",display:"flex",flexDirection:"column"},children:t.jsx(Ij,{uiConfig:o,connect:vz,preview:!0})},`${l}|${o.voiceEnabled}|${o.chatEnabled}`),t.jsx("div",{style:{display:"flex",justifyContent:r?"flex-start":"flex-end",width:340,maxWidth:"100%"},children:i?t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:9,borderRadius:14,padding:"13px 18px",background:jz,color:"#fff",font:'600 14px/1 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',letterSpacing:".01em",whiteSpace:"nowrap",boxShadow:"0 8px 22px rgba(243,146,33,.42), 0 1px 2px rgba(0,0,0,.12), inset 0 1px 0 rgba(255,255,255,.5), inset 0 -1px 0 rgba(0,0,0,.12)"},children:[t.jsx(rn,{size:14,fill:"#fff","aria-hidden":!0}),e.bubble?.label||"Demo"]}):t.jsx("span",{style:{width:60,height:60,borderRadius:"50%",display:"grid",placeItems:"center",background:s,color:"#fff",boxShadow:"0 6px 20px rgba(0,0,0,.18)"},children:t.jsx(Ta,{size:26,"aria-hidden":!0})})}),i&&t.jsx("p",{className:"text-[11px] text-ink-mute",children:n("widget.launcherPillHint")})]})}const kz={enabled:!1,voiceEnabled:!0,chatEnabled:!0,allowedOrigins:[],languages:[],maxSessionSeconds:600,bubble:{position:"br",accentColor:"#2B52A1"}};function Nz({agent:e,onChange:a}){const{t:n}=M("agents"),s=e.id,i={...kz,...e.widgetConfig??{}},[r,o]=m.useState(!1);function l(x){a({widgetConfig:{...i,...x}})}function c(x){l({bubble:{...i.bubble??{},...x}})}if(!s)return t.jsx("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:t.jsx(zt,{title:n("widget.noAgentTitle"),desc:n("widget.noAgentDesc"),last:!0,children:t.jsx("div",{className:"text-sm text-ink-mute",children:n("widget.noAgentBody")})})});const u=`<script src="${window.location.origin}/w.js" data-agent="${s}" async><\/script>`;async function p(){try{await navigator.clipboard.writeText(u),o(!0),setTimeout(()=>o(!1),1800)}catch{}}const f=i.allowedOrigins??[];return t.jsxs("div",{className:"grid gap-7 max-w-[1500px] items-start xl:grid-cols-[minmax(0,1fr),380px]",children:[t.jsxs(zt,{title:n("widget.title"),desc:n("widget.desc"),last:!0,children:[t.jsxs("div",{className:"flex items-start gap-4 p-4 rounded-xl border border-paper-line",children:[t.jsx("div",{className:"size-10 shrink-0 rounded-xl bg-brand-50 grid place-items-center",children:t.jsx(Va,{className:"size-5 text-brand-600"})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"font-medium text-sm",children:n("widget.enableTitle")}),t.jsx(vt,{checked:i.enabled,onChange:()=>l({enabled:!i.enabled})})]}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:n("widget.enableDesc")})]})]}),t.jsx("section",{className:"grid sm:grid-cols-2 gap-3",children:[{key:"voiceEnabled",title:n("widget.voiceTitle"),desc:n("widget.voiceDesc")},{key:"chatEnabled",title:n("widget.chatTitle"),desc:n("widget.chatDesc")}].map(x=>{const h=i[x.key]!==!1;return t.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-paper-line p-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:x.title}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:x.desc})]}),t.jsx(vt,{checked:h,onChange:()=>l({[x.key]:!h})})]},x.key)})}),t.jsxs("section",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("label",{className:"label",children:n("widget.langsLabel")}),t.jsxs("button",{type:"button",className:"btn btn-ghost h-7 text-xs",onClick:()=>l({languages:[...i.languages??[],{code:"",label:""}]}),children:[t.jsx(Fe,{className:"size-3.5"}),n("widget.add")]})]}),t.jsx("p",{className:"text-xs text-ink-mute mb-2",children:n("widget.langsDesc")}),(i.languages??[]).length>0&&t.jsx("div",{className:"flex flex-col gap-2",children:(i.languages??[]).map((x,h)=>t.jsxs("div",{className:"flex gap-2 items-center",children:[t.jsx("input",{className:"input font-mono text-[12px] w-24 shrink-0",placeholder:"es",value:x.code,maxLength:12,onChange:b=>l({languages:(i.languages??[]).map((g,v)=>v===h?{...g,code:b.target.value.toLowerCase()}:g)})}),t.jsx("input",{className:"input text-sm flex-1",placeholder:n("widget.langLabelPlaceholder"),value:x.label??"",maxLength:40,onChange:b=>l({languages:(i.languages??[]).map((g,v)=>v===h?{...g,label:b.target.value}:g)})}),t.jsx("button",{type:"button",className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 shrink-0",onClick:()=>l({languages:(i.languages??[]).filter((b,g)=>g!==h)}),children:t.jsx(mt,{className:"size-4"})})]},h))})]}),t.jsxs("section",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsx("label",{className:"label",children:n("widget.originsLabel")}),t.jsxs("button",{type:"button",className:"btn btn-ghost h-7 text-xs",onClick:()=>l({allowedOrigins:[...f,""]}),children:[t.jsx(Fe,{className:"size-3.5"}),n("widget.add")]})]}),t.jsxs("p",{className:"text-xs text-ink-mute mb-2",children:[n("widget.originsDesc")," ",t.jsx("code",{className:"font-mono",children:n("widget.exampleUrl")}),"."]}),f.length===0?t.jsx("p",{className:"text-xs text-rose-500",children:n("widget.originsEmpty")}):t.jsx("div",{className:"flex flex-col gap-2",children:f.map((x,h)=>t.jsxs("div",{className:"flex gap-2 items-center",children:[t.jsx("input",{className:"input font-mono text-[13px] flex-1",placeholder:n("widget.exampleUrl"),value:x,onChange:b=>l({allowedOrigins:f.map((g,v)=>v===h?b.target.value:g)})}),t.jsx("button",{type:"button",className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 shrink-0",onClick:()=>l({allowedOrigins:f.filter((b,g)=>g!==h)}),children:t.jsx(mt,{className:"size-4"})})]},h))})]}),t.jsxs("section",{className:"grid sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("widget.bubbleColor")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"color",className:"h-9 w-12 rounded-lg border border-paper-line bg-transparent",value:i.bubble?.accentColor??"#2B52A1",onChange:x=>c({accentColor:x.target.value})}),t.jsx("input",{className:"input font-mono text-xs flex-1",value:i.bubble?.accentColor??"#2B52A1",onChange:x=>c({accentColor:x.target.value})})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("widget.position")}),t.jsxs("select",{className:"input text-sm",value:i.bubble?.position??"br",onChange:x=>c({position:x.target.value}),children:[t.jsx("option",{value:"br",children:n("widget.posBR")}),t.jsx("option",{value:"bl",children:n("widget.posBL")})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("widget.buttonText")}),t.jsx("input",{className:"input text-sm",placeholder:n("widget.buttonPlaceholder"),maxLength:60,value:i.bubble?.label??"",onChange:x=>c({label:x.target.value})})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("widget.maxSession")}),t.jsx("input",{type:"number",className:"input text-sm",min:60,max:1800,step:30,value:i.maxSessionSeconds??600,onChange:x=>l({maxSessionSeconds:Number(x.target.value)})})]})]}),t.jsxs("section",{className:"grid sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("widget.themeLabel")}),t.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{v:"light",icon:Zr,label:n("widget.themeLight"),swatch:"#FFFFFF"},{v:"dark",icon:Hr,label:n("widget.themeDark"),swatch:"#0A0F1F"},{v:"auto",icon:iy,label:n("widget.themeAuto"),swatch:"linear-gradient(90deg,#FFFFFF 50%,#0A0F1F 50%)"}].map(x=>{const h=(i.theme??"light")===x.v;return t.jsxs("button",{type:"button",onClick:()=>l({theme:x.v}),"aria-pressed":h,className:`flex flex-col items-center gap-1.5 rounded-xl border p-2.5 text-[11px] transition-colors ${h?"border-brand-600 bg-brand-50 text-brand-700 font-medium":"border-paper-line text-ink-mute hover:border-brand-300"}`,children:[t.jsx("span",{className:"h-6 w-9 rounded-md border border-paper-line",style:{background:x.swatch},"aria-hidden":!0}),t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx(x.icon,{className:"size-3"})," ",x.label]})]},x.v)})})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("widget.launcherLabel")}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{v:"round",label:n("widget.launcherRound")},{v:"pill",label:n("widget.launcherPill")}].map(x=>{const h=(i.bubble?.style??"round")===x.v;return t.jsxs("button",{type:"button",onClick:()=>c({style:x.v}),"aria-pressed":h,className:`flex flex-col items-center gap-1.5 rounded-xl border p-2.5 text-[11px] transition-colors ${h?"border-brand-600 bg-brand-50 text-brand-700 font-medium":"border-paper-line text-ink-mute hover:border-brand-300"}`,children:[x.v==="round"?t.jsx("span",{className:"size-6 rounded-full",style:{background:i.bubble?.accentColor||"#2B52A1"},"aria-hidden":!0}):t.jsx("span",{className:"h-6 w-12 rounded-lg",style:{background:"linear-gradient(135deg,#FBB24E,#F39221 55%,#2B52A1 140%)"},"aria-hidden":!0}),x.label]},x.v)})})]}),t.jsxs("div",{className:"sm:col-span-2",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"label",children:n("widget.welcomeLabel")}),t.jsxs("span",{className:"text-[11px] text-ink-mute font-mono",children:[(i.welcomeMessage??"").length,"/200"]})]}),t.jsx("textarea",{className:"input text-sm w-full resize-none",rows:2,maxLength:200,placeholder:n("widget.welcomePlaceholder"),value:i.welcomeMessage??"",onChange:x=>
968l({welcomeMessage:x.target.value})}),t.jsx("p",{className:"text-xs text-ink-mute mt-1",children:n("widget.welcomeDesc")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("widget.avatarLabel")}),t.jsx("input",{className:"input text-sm w-24 text-center text-lg",maxLength:8,placeholder:"👩‍💼",value:i.avatar??"",onChange:x=>l({avatar:x.target.value})}),t.jsx("p",{className:"text-xs text-ink-mute mt-1",children:n("widget.avatarDesc")})]})]}),t.jsxs("section",{className:"border-t border-paper-line pt-6",children:[t.jsx("label",{className:"label mb-1 block",children:n("widget.embedLabel")}),t.jsxs("p",{className:"text-xs text-ink-mute mb-3",children:[n("widget.embedDescA")," ",t.jsx("code",{className:"font-mono",children:"</body>"})," ",n("widget.embedDescB")]}),t.jsxs("div",{className:"flex items-stretch gap-2",children:[t.jsx("code",{className:"flex-1 font-mono text-[12px] bg-paper border border-paper-line rounded-lg px-3 py-2.5 break-all",children:u}),t.jsxs("button",{className:"btn btn-outline shrink-0",onClick:p,children:[r?t.jsx(ct,{className:"size-4 text-mint-600"}):t.jsx(bn,{className:"size-4"}),n(r?"widget.copied":"widget.copy")]})]}),t.jsxs("p",{className:"text-xs text-ink-mute mt-2",children:[n("widget.varsNoteA"),t.jsx("code",{className:"font-mono text-[11px]",children:"{{nombre}}"}),n("widget.varsNoteB")," ",t.jsx("code",{className:"font-mono text-[11px]",children:`data-vars='{"nombre":"Juan"}'`})," ",n("widget.varsNoteC")]}),t.jsxs("details",{className:"mt-3 text-xs text-ink-mute",children:[t.jsx("summary",{className:"cursor-pointer font-medium text-ink select-none",children:n("widget.attrsTitle")}),t.jsx("p",{className:"mt-2 mb-1.5",children:n("widget.attrsDesc")}),t.jsx("div",{className:"flex flex-col gap-1.5",children:[{code:'data-accent="#ff5a36"',key:"attrAccent"},{code:'data-position="bl"',key:"attrPosition"},{code:`data-label="${n("widget.buttonPlaceholder")}"`,key:"attrLabel"},{code:'data-autoopen="1"',key:"attrAutoopen"},{code:'data-launcher="pill"',key:"attrLauncher"},{code:`data-vars='{"nombre":"Juan"}'`,key:"attrVars"},{code:'data-api="https://api.tudominio.com"',key:"attrApi"}].map(x=>t.jsxs("div",{children:[t.jsx("code",{className:"font-mono text-[11px] text-ink",children:x.code})," — ",n(`widget.${x.key}`)]},x.key))})]})]})]}),t.jsx("div",{className:"xl:sticky xl:top-4",children:t.jsx(wz,{wc:i,agentName:e.name||""})})]})}const Sz={maxCallDurationSeconds:0,maxCallsPerDay:0};function Cz({agent:e,onChange:a}){const{t:n}=M("agents"),s={...Sz,...e.callLimits??{}};function i(o){a({callLimits:{...s,...o}})}const r=Math.round((s.maxCallDurationSeconds??0)/60);return t.jsx("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:t.jsx(zt,{title:n("limits.title"),desc:n("limits.desc"),last:!0,children:t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-5 max-w-[640px]",children:[t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("limits.maxDuration")}),t.jsx("input",{type:"number",className:"input text-sm",min:0,max:28800,step:30,value:s.maxCallDurationSeconds??0,onChange:o=>i({maxCallDurationSeconds:Math.max(0,Number(o.target.value)||0)})}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:s.maxCallDurationSeconds?n("limits.durationHintSet",{min:r}):n("limits.durationHintNone")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"label mb-1.5 block",children:n("limits.maxPerDay")}),t.jsx("input",{type:"number",className:"input text-sm",min:0,max:1e5,step:1,value:s.maxCallsPerDay??0,onChange:o=>i({maxCallsPerDay:Math.max(0,Number(o.target.value)||0)})}),t.jsx("p",{className:"text-xs text-ink-mute mt-1.5",children:s.maxCallsPerDay?n("limits.perDayHintSet",{n:s.maxCallsPerDay}):n("limits.perDayHintNone")})]})]})})})}const H0=2048,_z=120,Zx=5e3,Yx=20,Xx=50,Q0=200,Yd=12e3,Ez=60,Az=5*6e4,G0=30*6e4,Rz=24*36e5,Tz=["unknown","embedding_failed","storage_not_configured","storage_quota_exceeded"],Mz=132,Pz=["crawl_timeout","url_fetch_failed","embedding_failed","expired","unknown","storage_not_configured","storage_quota_exceeded"],zz=["crawl_no_pages","crawl_regressed"],Dz=!0,Jx=["/tag/","/etiqueta/","/etiqueta-producto/","/product-tag/","/author/","/autor/"];function ro(e){if(typeof e!="string")return!1;const a=e.trim();if(!a||a.length>H0)return!1;let n;try{n=new URL(a)}catch{return!1}return!(n.protocol!=="https:"||!n.hostname||n.username||n.password)}function Iz(e){if(!ro(e))return!1;const a=new URL(String(e).trim());return a.pathname==="/"&&!a.search&&!a.hash}function eg(e){const a=[];for(const n of String(e??"").split(/\r?\n/)){let s=n.trim();if(s){if(/^https?:\/\//i.test(s))try{s=new URL(s).pathname||"/"}catch{}s.startsWith("/")||(s=`/${s}`),a.includes(s)||a.push(s)}}return a}function tg(e,a){if(e.length>a)return"addUrl.errPrefijoMax";for(const n of e){if(n.length>Q0)return"addUrl.errPrefijoLargo";if(!n.startsWith("/")||/[?#\s]/.test(n))return"addUrl.errPrefijoCaracteres"}return null}function Lz(e){if(typeof e!="string"||e.length>H0)return"";try{const a=new URL(e.trim());return a.protocol!=="https:"&&a.protocol!=="http:"?"":a.hostname.toLowerCase().replace(/^www\./,"").slice(0,_z)}catch{return""}}function Z0(e){return e==null?Zx:Math.max(0,Math.min(e,Zx))}const lc=e=>e?Date.parse(e):NaN;
968function cc(e,a=Date.now()){if(!e?.running)return!1;const n=lc(e.heartbeatAt);if(Number.isFinite(n))return n>a-Az;const s=lc(e.startedAt);return Number.isFinite(s)?s>a-2*G0:!1}function Y0(e,a=Date.now()){if(!e?.pendingCrawlAt||!e.lastError||!Tz.includes(e.lastError))return!1;const n=lc(e.pendingCrawlAt);return Number.isFinite(n)&&n>a-Rz}function Fz(e,a=Date.now()){if(Y0(e,a))return 0;const n=lc(e?.lastCrawlAt);if(!Number.isFinite(n))return 0;const s=n+Ez*6e4-a;return s>0?Math.ceil(s/6e4):0}function Oz(e){const a=Math.max(1,Math.floor(Number(e)||0)),n=s=>Math.max(1,Math.min(G0/6e4,Math.ceil(s)));return{min:n(a*.3/60),max:n(a*.6/60)}}function X0(e){const a=e?.progress;if(!a)return null;const n=Math.max(0,Number(a.included)||0),s=Math.max(n,n+Math.max(0,Number(a.pending)||0));return{hechas:n,total:s}}const ag=new Set(Pz),$z=new Set(zz),qz=Mz;function Bz(e,a=Date.now()){const n=e.crawl;if(!n)return"nunca_completo";if(n.running)return"en_curso";if((n.autoRecrawl??"weekly")!=="weekly")return"auto_off";const s=n.lastCrawlAt?Date.parse(n.lastCrawlAt):NaN;if(!Number.isFinite(s))return"nunca_completo";if(s>a-qz*36e5)return"reciente";const i=e.errorCode??n.lastError??null;return e.status==="ready"?i===null||ag.has(i)||$z.has(i)?null:"error_permanente":e.status==="failed"?i!==null&&ag.has(i)?null:"error_permanente":"estado"}function Wz(e){const a=Bz(e,Number.POSITIVE_INFINITY);return a!=="error_permanente"&&a!=="nunca_completo"?null:{motivo:a,codigo:e.errorCode??e.crawl?.lastError??null}}function Uz(e,a,n){const s=a?.autoRecrawl==="weekly"||a?.autoRecrawl==="off"?a.autoRecrawl:n;return{...e,autoRecrawl:s}}const Qt={list:["kb","list"],usage:["kb","usage"],detail:e=>["kb","detail",e],docs:e=>["kb","docs",e],pages:e=>["kb","pages",e],sitePages:(e,a,n,s,i)=>["kb","pages",e,a,n,s,i]},Vz=e=>e==="pending"||e==="processing";function Hc(){return se({queryKey:Qt.list,queryFn:async()=>{try{const{data:e}=await T.get("/knowledge-bases");return{available:!0,bases:e}}catch(e){const a=e?.response?.status;if(a===501||a===404)return{available:!1,bases:[]};throw e}},staleTime:15e3})}function J0(e=!0){return se({queryKey:Qt.usage,queryFn:async()=>(await T.get("/knowledge-bases/usage")).data,enabled:e,staleTime:15e3})}function Kz(e){return se({queryKey:Qt.detail(e??""),queryFn:async()=>(await T.get(`/knowledge-bases/${e}`)).data,enabled:!!e,staleTime:15e3})}function Hz(e){return se({queryKey:Qt.docs(e??""),queryFn:async()=>(await T.get(`/knowledge-bases/${e}/documents`)).data,enabled:!!e,refetchInterval:a=>{const n=a.state.data;return n?.some(s=>Vz(s.status))?4e3:n?.some(s=>cc(s.crawl))?15e3:!1}})}function Qz(e,a,n,s=!0){return se({queryKey:Qt.sitePages(e??"",a??"",n.status,n.offset,n.limit),queryFn:async()=>(await T.get(`/knowledge-bases/${e}/documents/${a}/pages`,{params:{...n.status!=="all"?{status:n.status}:{},offset:n.offset,limit:n.limit}})).data,enabled:s&&!!e&&!!a,placeholderData:i=>i,staleTime:15e3})}function Gz(){const e=xe();m.useEffect(()=>{let a;try{a=ns()}catch{return}const n=s=>{if(!s?.docId||!s?.kbId)return;const i=s.status==="processing"||s.crawl?.running===!0;e.setQueryData(Qt.docs(s.kbId),r=>r?.map(o=>o.id===s.docId?{...o,status:s.status,chunkCount:s.chunkCount??o.chunkCount,tokenCount:s.tokenCount??o.tokenCount,errorCode:s.errorCode??null,progressPct:typeof s.progressPct=="number"?s.progressPct:s.status==="ready"&&!i?100:o.progressPct,crawl:s.crawl!==void 0?s.crawl:o.crawl}:o)),!i&&(e.invalidateQueries({queryKey:Qt.docs(s.kbId)}),e.invalidateQueries({queryKey:Qt.list}),e.invalidateQueries({queryKey:Qt.usage}),e.invalidateQueries({queryKey:Qt.pages(s.kbId)}))};return a.on("knowledge:ingest",n),()=>{a.off("knowledge:ingest",n)}},[e])}function qi(e,a){e.invalidateQueries({queryKey:Qt.list}),e.invalidateQueries({queryKey:Qt.usage}),a&&(e.invalidateQueries({queryKey:Qt.detail(a)}),e.invalidateQueries({queryKey:Qt.docs(a)}),e.invalidateQueries({queryKey:Qt.pages(a)}))}function Zz(){const e=xe();return oe({mutationFn:async a=>(await T.post("/knowledge-bases",a)).data,onSuccess:()=>qi(e)})}function Yz(){const e=xe();return oe({mutationFn:async a=>(await T.patch(`/knowledge-bases/${a.kbId}`,{name:a.name,description:a.description})).data,onSuccess:(a,n)=>qi(e,n.kbId)})}function Xz(){const e=xe();return oe({mutationFn:async a=>(await T.delete(`/knowledge-bases/${a}`)).data,onSuccess:()=>qi(e)})}function Jz(){const e=xe();return oe({mutationFn:async a=>{const n=new FormData;return n.append("file",a.file),a.title&&n.append("title",a.title),a.lang&&n.append("lang",a.lang),(await T.post(`/knowledge-bases/${a.kbId}/documents/file`,n,{timeout:18e4,onUploadProgress:s=>{s.total&&a.onProgress?.(Math.round(s.loaded/s.total*100))}})).data},onSuccess:(a,n)=>qi(e,n.kbId)})}function eD(){const e=xe();return oe({mutationFn:async a=>(await T.post(`/knowledge-bases/${a.kbId}/documents`,a.body)).data,onSuccess:(a,n)=>qi(e,n.kbId)})}function tD(){const e=xe();return oe({mutationFn:async a=>(await T.delete(`/knowledge-bases/${a.kbId}/documents/${a.docId}`)).data,onSuccess:(a,n)=>qi(e,n.kbId)})}function aD(){const e=xe();return oe({mutationFn:async a=>(await T.post(`/knowledge-bases/${a.kbId}/documents/${a.docId}/reingest`,void 0,a.force?{params:{force:"1"}}:void 0)).data,onSuccess:(a,n)=>
968{e.invalidateQueries({queryKey:Qt.docs(n.kbId)}),e.invalidateQueries({queryKey:Qt.list}),e.invalidateQueries({queryKey:Qt.pages(n.kbId)})}})}function ng(){const e=xe();return oe({mutationFn:async a=>(await T.patch(`/knowledge-bases/${a.kbId}/documents/${a.docId}`,{...a.promptMode!==void 0?{promptMode:a.promptMode}:{},...a.autoRecrawl!==void 0?{autoRecrawl:a.autoRecrawl}:{}})).data,onSuccess:(a,n)=>{e.setQueryData(Qt.docs(n.kbId),s=>s?.map(i=>{if(i.id!==n.docId)return i;if(n.autoRecrawl!==void 0&&i.crawl){const r=Uz(i.crawl,a?.crawl,n.autoRecrawl);return n.promptMode===void 0?{...i,crawl:r}:{...i,...a,crawl:r}}return{...i,...a}}))}})}function nD(){return oe({mutationFn:async e=>(await T.post(`/knowledge-bases/${e.kbId}/search-preview`,{query:e.query,topK:e.topK})).data})}const sD=["kb_referenced_without_kb","kb_web_browsing_implied","kb_attached_but_empty"],cr=3,iD=/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/;function sg(e){const a=typeof e?.url=="string"?e.url.trim():"";if(a&&ro(a))return a;const n=typeof e?.fuentes=="string"?e.fuentes.split(","):[];for(const s of n){const i=s.trim().toLowerCase();if(!iD.test(i))continue;const r=`https://${i}/`;if(ro(r))return r}}const rD=["auto","retrieval","inject"];function oD({agent:e,onChange:a,auditIssues:n,dirty:s=!1,agentId:i=null}){const{t:r}=M("agents"),{t:o}=M("agentsRoutes"),l=dt(),c=ha(),d=Hc(),[u,p]=m.useState(!1),{refetch:f}=d;m.useEffect(()=>{if(!u)return;const E=()=>{document.visibilityState==="visible"&&f()};return document.addEventListener("visibilitychange",E),window.addEventListener("focus",E),()=>{document.removeEventListener("visibilitychange",E),window.removeEventListener("focus",E)}},[u,f]);function x(E){if(s){window.open(c.buildLocation({to:"/knowledge",search:E}).href,"_blank","noopener"),p(!0);return}l({to:"/knowledge",search:{...E,...i?{volver:i}:{}}})}const h=e.knowledge??null,b=h?.kbIds??[],g=h?.mode??"auto",v=h?.grounding!=="off";function y(E,I,P=v){a({knowledge:E.length?{kbIds:E,...I!=="auto"?{mode:I}:{},...h?.topK!=null?{topK:h.topK}:{},...P?{}:{grounding:"off"}}:null})}function k(E){const I=b.includes(E)?b.filter(P=>P!==E):b.length>=cr?b:[...b,E];y(I,g)}const w=d.data?.bases??[],j=d.data?.available!==!1,C=b.length>=cr,N=(n??[]).filter(E=>sD.includes(E.code)),S=w.filter(E=>b.includes(E.id)).reduce((E,I)=>E+(Number(I.totalTokens)||0),0),_=S>Yd,R=E=>E.toLocaleString(Te());function A(E){const{code:I}=E;if(I==="kb_referenced_without_kb"){const P=sg(E.params);return P?{label:r("knowledge.ctaCreateFromSite"),onClick:()=>x({nueva:"1",sitio:P}),icon:Va}:{label:r("knowledge.ctaCreate"),onClick:()=>x({nueva:"1"}),icon:Fe}}if(I==="kb_web_browsing_implied"&&b[0]){const P=sg(E.params);return P?{label:r("knowledge.ctaAddSiteToKb"),onClick:()=>x({kb:b[0],sitio:P}),icon:Va}:void 0}if(I==="kb_attached_but_empty"&&b[0])return{label:r("knowledge.manage"),onClick:()=>x({kb:b[0]}),icon:Ja}}return t.jsxs("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:[N.length>0&&t.jsxs("div",{className:"flex flex-col gap-2.5","data-testid":"kb-audit-banners",children:[N.map(E=>t.jsx(le,{tone:"warn",title:o(`audit.code.${E.code}`,{defaultValue:E.message,...E.params??{}}),action:A(E),children:E.fixHint?o(`audit.fix.${E.code}`,{defaultValue:E.fixHint,...E.params??{}}):null},E.code)),s&&N.some(E=>A(E))&&t.jsx(qa,{children:r("knowledge.opensInNewTab")})]}),t.jsx(zt,{title:r("knowledge.title"),desc:r("knowledge.desc",{max:cr}),children:d.isLoading?t.jsx("div",{className:"flex flex-col gap-3",children:[0,1].map(E=>t.jsx(ge,{w:"100%",h:64,r:10},E))}):d.error?t.jsx(le,{tone:"bad",children:r("knowledge.loadError")}):!j||w.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{mini:!0,icon:ua,title:r("knowledge.empty.title"),desc:r("knowledge.empty.desc"),action:{label:r("knowledge.empty.cta"),onClick:()=>x({}),icon:ua}})}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex flex-col gap-2.5",children:w.map(E=>t.jsx(lD,{kb:E,checked:b.includes(E.id),disabled:!b.includes(E.id)&&C,onToggle:()=>k(E.id),onManage:()=>x({kb:E.id})},E.id))}),t.jsx(qa,{children:b.length>0?r("knowledge.selectedCount",{count:b.length,max:cr}):r("knowledge.maxHint",{max:cr})})]})}),t.jsxs(zt,{title:r("knowledge.mode.title"),desc:r("knowledge.mode.desc"),children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:rD.map(E=>t.jsx(Bu,{title:E==="auto"?`${r("knowledge.mode.auto")} · ${r("knowledge.mode.autoBadge")}`:r(`knowledge.mode.${E}`),description:r(`knowledge.mode.${E}Desc`),selected:g===E,disabled:b.length===0||E==="inject"&&_,onClick:()=>y(b,E)},E))}),b.length===0&&t.jsx(qa,{children:r("knowledge.mode.needsKb")}),b.length>0&&_&&g==="inject"?t.jsx(le,{tone:"warn",action:{label:r("knowledge.mode.switchToAuto"),onClick:()=>y(b,"auto")},children:r("knowledge.mode.injectTooBigSelected",{tokens:R(S),max:R(Yd)})}):b.length>0&&_?t.jsx(qa,{children:r("knowledge.mode.injectTooBig",{tokens:R(S),max:R(Yd)})}):null]}),t.jsxs(zt,{title:r("knowledge.grounding.title"),desc:r("knowledge.grounding.desc"),last:!0,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsx("label",{htmlFor:"kb-grounding-switch",style:{fontSize:13.5,fontWeight:600,color:"var(--cia-text)",cursor:b.length?"pointer":"default"},children:r("knowledge.grounding.label")}),t.jsx(vt,{id:"kb-grounding-switch",checked:b.length>0&&v,disabled:b.length===0,onChange:E=>y(b,g,E),label:r("knowledge.grounding.label")})]}),b.length===0?t.jsx(qa,{children:r("knowledge.grounding.needsKb")}):v?t.jsx(qa,{children:r("knowledge.grounding.hintOn")}):t.jsx(le,{tone:"warn",children:r("knowledge.grounding.hintOff")})]})]})}function lD({kb:e,checked:a,disabled:n,onToggle:s,onManage:i}){const{t:r}=M("agents");return t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",ga
968p:12,padding:"12px 14px",borderRadius:"var(--cia-r)",border:`1px solid ${a?"var(--cia-brand-300)":"var(--cia-border)"}`,background:a?"var(--cia-bg-tint)":"var(--cia-bg-elev)",transition:"border-color 150ms, background 150ms"},children:[t.jsx(mn,{checked:a,onChange:s,disabled:n,label:t.jsx("span",{className:"text-[13.5px] font-medium",style:{color:"var(--cia-text)"},children:e.name}),description:t.jsxs("span",{className:"flex flex-col gap-1.5",style:{minWidth:0},children:[e.description&&t.jsx("span",{className:"text-[12px] text-ink-mute",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:e.description}),t.jsxs("span",{className:"flex items-center gap-1.5 flex-wrap",children:[t.jsx("span",{className:"cia-badge",children:r("knowledge.docsReady",{count:e.docCount})}),e.pendingCount>0&&t.jsxs("span",{className:"cia-badge cia-badge-warn",title:r("knowledge.processingHint"),children:[t.jsx(je,{className:"animate-spin",size:11,"aria-hidden":!0})," ",r("knowledge.processingChip",{count:e.pendingCount})]})]})]}),style:{flex:1,minWidth:0}}),a&&t.jsxs("button",{type:"button",onClick:i,className:"cia-btn cia-btn-ghost cia-btn-sm",style:{flex:"none"},title:r("knowledge.manage"),children:[t.jsx(Ja,{size:13})," ",r("knowledge.manage")]})]})}function Uh({titulo:e,heredado:a,separar:n,propio:s,onSeparar:i,onHeredar:r,resumen:o,children:l}){const{t:c}=M("agentsRoutes");
968return t.jsxs("div",{className:"cia-card",style:{padding:18,display:"flex",flexDirection:"column",gap:s?16:0,borderStyle:s?"solid":"dashed"},children:[t.jsxs("div",{className:"cia-row",style:{alignItems:"flex-start",gap:14,justifyContent:"space-between"},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontWeight:600,fontSize:14},children:e}),t.jsxs("div",{style:{fontSize:13,color:"var(--cia-text-soft)",marginTop:3,display:"flex",alignItems:"center",gap:7},children:[!s&&t.jsx("span",{"aria-hidden":!0,style:{width:7,height:7,borderRadius:"50%",background:"var(--cia-text-soft)",flex:"0 0 auto"}}),t.jsx("span",{children:s?o??c("editor.canal.herencia.propio"):a})]})]}),s?t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",onClick:r,children:c("editor.canal.herencia.volver")}):t.jsx("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",onClick:i,children:n})]}),s?l:null]})}const Js={rapida:3,normal:6,paciente:10};function cD({agent:e,onChange:a}){const{t:n}=M("agentsRoutes"),s=e.channels?.text??{},i=!!(e.textPrompt??"").trim(),[r,o]=m.useState(!1),l=i||r,c=d=>{const u={...s,...d};for(const p of Object.keys(u)){const f=u[p];(f===void 0||f===""||f==="auto")&&delete u[p]}a({channels:Object.keys(u).length?{text:u}:{}})};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-3)",lineHeight:1.6},children:n("editor.wa.intro")}),t.jsxs(Uh,{titulo:n("editor.canal.waGuion.fila"),heredado:n("editor.canal.waGuion.hereda"),separar:n("editor.canal.waGuion.separar"),propio:l,resumen:i?n("editor.canal.waGuion.propio",{chars:(e.textPrompt??"").length}):n("editor.canal.waGuion.vacio"),onSeparar:()=>{o(!0),a({textPrompt:e.systemPrompt??""})},onHeredar:()=>{o(!1),a({textPrompt:null})},children:[t.jsx("textarea",{id:"wa-guion",className:"cia-input",rows:16,value:e.textPrompt??"",onChange:d=>a({textPrompt:d.target.value}),style:{resize:"vertical",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:12.5,lineHeight:1.6}}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.5},children:n("editor.canal.waGuion.ayudaPropio")})]}),l?null:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("label",{htmlFor:"wa-anexo",style:{fontSize:13,fontWeight:600},children:n("editor.wa.anexo.label")}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.5},children:n("editor.wa.anexo.ayuda")}),t.jsx("textarea",{id:"wa-anexo",className:"cia-input",rows:5,maxLength:1500,value:s.anexoDeGuion??"",onChange:d=>c({anexoDeGuion:d.target.value}),placeholder:n("editor.wa.anexo.ejemplo"),style:{resize:"vertical",fontFamily:"inherit",lineHeight:1.55}}),t.jsxs("span",{style:{fontSize:11,color:"var(--cia-text-3)",alignSelf:"flex-end"},children:[(s.anexoDeGuion??"").length," / 1500"]})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600},children:n("editor.wa.opciones.label")}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.5},children:n("editor.wa.opciones.ayuda")}),t.jsx(Yn,{size:"sm",ariaLabel:n("editor.wa.opciones.label"),value:s.opciones??"auto",onChange:d=>c({opciones:d}),options:[{value:"auto",label:n("editor.wa.opciones.auto")},{value:"solo_confirmar",label:n("editor.wa.opciones.soloConfirmar")},{value:"nunca",label:n("editor.wa.opciones.nunca")}]})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600},children:n("editor.wa.notaDeVoz.label")}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.5},children:n("editor.wa.notaDeVoz.ayuda")}),t.jsx(Yn,{size:"sm",ariaLabel:n("editor.wa.notaDeVoz.label"),value:s.notaDeVoz??"espejo",onChange:d=>c({notaDeVoz:d}),options:[{value:"nunca",label:n("editor.wa.notaDeVoz.nunca")},{value:"espejo",label:n("editor.wa.notaDeVoz.espejo")},{value:"siempre",label:n("editor.wa.notaDeVoz.siempre")}]}),s.notaDeVoz==="siempre"?t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-warn-fg, var(--cia-text-2))",lineHeight:1.5},children:n("editor.wa.notaDeVoz.avisoCosto")}):null,t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,marginTop:4,paddingTop:12,borderTop:"1px solid var(--cia-border)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600},children:n("editor.wa.textoConAudio.label")}),t.jsx(vt,{checked:s.textoConLaNotaDeVoz!==!1,onChange:d=>c({textoConLaNotaDeVoz:d}),disabled:s.notaDeVoz==="nunca",label:n("editor.wa.textoConAudio.label")})]}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.5},children:n("editor.wa.textoConAudio.ayuda")}),s.notaDeVoz==="nunca"?t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.5},children:n("editor.wa.textoConAudio.noAplica")}):s.textoConLaNotaDeVoz===!1?t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-warn-fg, var(--cia-text-2))",lineHeight:1.5},children:n("editor.wa.textoConAudio.avisoApagado")}):null]})]}),(()=>{const d=s.esperaSegundos,u=Object.keys(Js).find(f=>Js[f]===d),p=typeof d!="number"?"hereda":u??"propia";return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600},children:n("editor.wa.espera.label")}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.5},children:n("editor.wa.espera.ayuda")}),t.jsx("div",{className:"cia-scroll-x",style:{maxWidth:"100%"},children:t.jsx(Yn,{size:"sm",ariaLabel:n("editor.wa.espera.label"),value:p,onChange:f=>c({esperaSegundos:f==="hereda"||f==="propia"?f==="propia"?d:void 0:Js[f]}),options:[{value:"hereda",label:n("editor.wa.espera.hereda")},{value:"rapida",label:n("editor.wa.espera.rapida",{segundos:Js.rapida})},{value:"normal",label:n("editor.wa.espera.normal",{segundos:Js.normal})},{value:"paciente",label:n("editor.wa.espera.paciente",{segundos:Js.paciente})},...p==="propia"?[{value:"propia",label:n("editor.wa.espera.propia",{segundos:d})}]:[]]})})]})})(),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"12px 14px",borderRadius:10,background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)"},children:[t.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:"var(--cia-text-2)"},children:n("editor.wa.noAplica.titulo")}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.6},children:n("editor.wa.noAplica.saludo")}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.6},children:n("editor.wa.noAplica.voz")})]})]})}
968function dD({agent:e,onChange:a}){const{t:n}=M("agentsRoutes"),s=e.channels?.text??{},i=e.tts?.provider??"elevenlabs",r=Fh(i),o=d=>d?r.data?.find(u=>u.voiceId===d)?.name??d:n("editor.canal.waVoz.sinVoz"),l=d=>{const u={...s,...d};for(const p of Object.keys(u)){const f=u[p];(f===void 0||f===""||f==="auto")&&delete u[p]}a({channels:Object.keys(u).length?{text:u}:{}})},c=!!s.voiceId;return t.jsx("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:t.jsxs(zt,{title:n("editor.canal.waVoz.titulo"),desc:n("editor.canal.waVoz.desc"),last:!0,children:[t.jsx(Uh,{titulo:n("editor.canal.waVoz.fila"),heredado:n("editor.canal.waVoz.hereda",{voz:o(e.tts?.voiceId)}),separar:n("editor.canal.waVoz.separar"),propio:c,resumen:n("editor.canal.waVoz.propia",{voz:o(s.voiceId)}),onSeparar:()=>l({voiceId:e.tts?.voiceId}),onHeredar:()=>l({voiceId:void 0}),children:t.jsx(F0,{tts:{...e.tts,voiceId:s.voiceId},onChange:d=>l({voiceId:d.voiceId})})}),s.notaDeVoz==="nunca"?t.jsx("p",{style:{margin:0,fontSize:12,color:"var(--cia-text-3)",lineHeight:1.6},children:n("editor.canal.waVoz.avisoApagada")}):null]})})}function uD(e){return(e.tools??[]).filter(a=>a&&typeof a.name=="string"&&a.name.trim())}function pD({agent:e,onChange:a}){const{t:n}=M("agentsRoutes"),s=e.channels?.text??{},i=uD(e),r=new Set(s.herramientasApagadas??[]),[o,l]=m.useState(!1),c=o||r.size>0,d=p=>{const f={...s,...p};for(const x of Object.keys(f)){const h=f[x];(h===void 0||h===""||h==="auto")&&delete f[x],Array.isArray(h)&&h.length===0&&delete f[x]}a({channels:Object.keys(f).length?{text:f}:{}})},u=(p,f)=>{const x=new Set(r);f?x.delete(p):x.add(p),d({herramientasApagadas:[...x]})};return t.jsx("div",{className:"flex flex-col gap-7 max-w-[1500px]",children:t.jsx(zt,{title:n("editor.canal.waTools.titulo"),desc:n("editor.canal.waTools.desc"),last:!0,children:i.length===0?t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-3)",lineHeight:1.6},children:n("editor.canal.waTools.sinHerramientas")}):t.jsxs(Uh,{titulo:n("editor.canal.waTools.fila"),heredado:n("editor.canal.waTools.hereda",{count:i.length}),separar:n("editor.canal.waTools.separar"),propio:c,resumen:n("editor.canal.waTools.propio",{activas:i.length-r.size,total:i.length}),onSeparar:()=>l(!0),onHeredar:()=>{l(!1),d({herramientasApagadas:[]})},children:[t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2},children:i.map(p=>{const f=!r.has(p.name);return t.jsxs("label",{className:"cia-row",style:{justifyContent:"space-between",gap:14,padding:"9px 0",cursor:"pointer"},children:[t.jsxs("span",{style:{minWidth:0},children:[t.jsx("span",{style:{fontSize:13.5,display:"block"},children:p.name}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:p.type})]}),t.jsx(vt,{checked:f,onChange:x=>u(p.name,x),label:p.name})]},p.id??p.name)})}),t.jsx("p",{style:{margin:0,fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.6},children:n("editor.canal.waTools.avisoRenombre")})]})})})}function hD(e){const a=e.channels?.text??{},n=(e.textPrompt??"").trim();return[n,n?"":a.anexoDeGuion?.trim(),a.modelo?.trim(),a.opciones,a.notaDeVoz,a.textoConLaNotaDeVoz===!1?"sí":"",typeof a.esperaSegundos=="number"?"sí":"",a.voiceId?.trim(),a.herramientasApagadas?.length?"sí":""].filter(Boolean).length}function mD({canal:e,onCanal:a,agent:n}){const{t:s}=M("agentsRoutes"),i=hD(n);return t.jsxs("div",{className:"cia-row",style:{padding:"8px 28px",gap:12,alignItems:"center",background:"var(--cia-bg-soft)",borderBottom:"1px solid var(--cia-border)"},children:[t.jsx(Yn,{size:"sm",ariaLabel:s("editor.canal.aria"),value:e,onChange:a,options:[{value:"voice",label:s("editor.canal.voz")},{value:"text",label:i?s("editor.canal.whatsappCon",{count:i}):s("editor.canal.whatsapp")}]}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)",minWidth:0},children:s(e==="text"?"editor.canal.avisoTexto":"editor.canal.avisoVoz")})]})}function fD({report:e,onClick:a}){const{t:n}=M("agentsRoutes");if(!e)return null;const{counts:s,issues:i}=e,r=s.error>0?"error":s.warn>0?"warn":"ok",o=s.error+s.warn,l=r==="error"?"var(--cia-bad-500)":r==="warn"?"var(--cia-warn-500)":"var(--cia-ok-500)",c=r==="error"?"var(--cia-bad-ink)":r==="warn"?"var(--cia-warn-ink)":"var(--cia-ok-ink)",d=r==="error"?n("editor.audit.problems",{count:o}):r==="warn"?n("editor.audit.warnings",{count:o}):n("editor.audit.ok"),u=r==="error"?i2:r==="warn"?Sc:ho,p=i.slice(0,4).map(h=>`• ${n(`audit.code.${h.code}`,{defaultValue:h.message,...h.params??{}})}`).join(`
969`),f=i[0],x=f?.fixHint?n(`audit.fix.${f.code}`,{defaultValue:f.fixHint,...f.params??{}}):"";return t.jsxs("button",{type:"button",onClick:a,title:[d,p,x&&`→ ${x}
969`,n("editor.audit.cta")].filter(Boolean).join(`
970`),"aria-label":d,className:"inline-flex items-center gap-1.5 transition-colors",style:{height:24,padding:"0 10px",borderRadius:"var(--cia-r-pill)",border:`1px solid color-mix(in oklab, ${l} 35%, transparent)`,background:`color-mix(in oklab, ${l} ${r==="ok"?6:10}%, transparent)`,color:c,fontSize:11,fontWeight:600,fontFamily:"var(--cia-font-sans)",letterSpacing:"var(--cia-tracking-tight)",cursor:"pointer",flex:"none"},onMouseEnter:h=>{h.currentTarget.style.background=`color-mix(in oklab, ${l} ${r==="ok"?12:18}%, transparent)`},onMouseLeave:h=>{h.currentTarget.style.background=`color-mix(in oklab, ${l} ${r==="ok"?6:10}%, transparent)`},children:[t.jsx(u,{size:12,"aria-hidden":"true"}),d]})}const e1=[{id:"identity",icon:my},{id:"voice",icon:l2},{id:"behavior",icon:ES},{id:"tools",icon:Ec},{id:"knowledge",icon:ua},{id:"analytics",icon:us},{id:"deploy",icon:Va},{id:"widget",icon:Zb},{id:"limits",icon:Qa}];function xD(e){if(!e||typeof e!="object"||Array.isArray(e))return;const a={};for(const[n,s]of Object.entries(e))(typeof s=="string"||typeof s=="number"&&Number.isFinite(s))&&(a[n]=s);return Object.keys(a).length?a:void 0}function gD(e){const a=e?.response?.data;if(e?.response?.status!==422||a?.code!=="agent_audit_blocked")return null;const s=(Array.isArray(a?.issues)?a.issues:[]).filter(i=>i&&typeof i.code=="string"&&i.code).map(i=>({code:i.code,severity:typeof i.severity=="string"?i.severity:"",message:typeof i.message=="string"?i.message:"",params:xD(i.params)}));return{message:typeof a?.message=="string"?a.message:"",issues:s}}function ig(e){return e.startsWith("kb_")?"knowledge":e==="tool_unknown_reference"||e==="end_call_effectively_off"?"tools":"identity"}function bD(e){return e1.some(a=>a.id===e)?e:"identity"}const rg={name:"",language:"es",greeting:"Hola, ¿en qué le puedo ayudar?",systemPrompt:["Eres un asistente telefónico.","Hablas en español neutro de Latinoamérica.","Sé breve, claro, profesional y empático.","Responde en máximo 2 oraciones por turno."].join(" "),stt:{provider:"deepgram",model:"nova-3"},llm:{provider:"openai",model:"gpt-4.1-mini",temperature:.7},tts:void 0,vad:{minSilenceDuration:.55,minSpeechDuration:.05,prefixPaddingDuration:.3},interruptSpeechDuration:.5,status:"draft"};function t1({agentId:e,template:a,initialTab:n,openBuilderOnMount:s}){const{t:i}=M("agentsRoutes"),r=dt(),o=xe(),l=xt(L=>L.resolved),{can:c}=tt(),d=c("agents.manage"),u=d&&c("agents.operate"),[p,f]=m.useState(()=>bD(n)),x=!e,[h,b]=m.useState("voice"),[g,v]=m.useState(()=>{if(x&&a&&Pr[a]){const L=Pr[a];return{...rg,...L.preset,name:L.name}}return rg}),[y,k]=m.useState(null),[w,j]=m.useState(null),C=A0(e??void 0,g),[N,S]=m.useState(0),[_,R]=m.useState([]),A=m.useRef(0),E=m.useCallback(L=>{const re=`fs${++A.current}`,ke=sv(L.i18n??null,L.previewText)||"",H=J3(L,re,ke);R(fe=>[...fe,H])},[]),I=m.useCallback(L=>{R(re=>{const ke=re.find(H=>H.id===L);return ke&&v(H=>Ph(H,ke.patch)),re.map(H=>H.id===L?{...H,state:"accepted"}:H)})},[]),P=m.useCallback(L=>R(re=>re.map(ke=>ke.id===L?{...ke,state:"rejected"}:ke)),[]),O=m.useMemo(()=>eM(_),[_]),K=m.useMemo(()=>Object.entries(O).filter(([L,re])=>L!==p&&re>0).map(([L,re])=>({tabId:L,count:re})),[O,p]),W=K.reduce((L,re)=>L+re.count,0),V=m.useMemo(()=>_.filter(L=>L.tab===p),[_,p]),U=m.useRef(null),X=(L,re)=>{k({type:L,message:re}),setTimeout(()=>k(null),4e3)},ie=L=>{const re=gD(L);return j(re),re?(re.issues[0]&&f(ig(re.issues[0].code)),!0):!1},de=L=>{const re=L.params??C.data?.issues?.find(H=>H.code===L.code)?.params??{},ke=i(`audit.code.${L.code}`,{defaultValue:L.message||L.code,...re});return ke.includes("{{")&&L.message||ke},{data:$,isLoading:z}=se({queryKey:["agent",e],queryFn:async()=>(await T.get(`/agents/${e}`)).data,enabled:!!e});m.useEffect(()=>{$&&(v($),U.current=JSON.stringify(bs($)))},[$]);const D=m.useMemo(()=>x?(g.name||"").trim().length>0:U.current===null?!1:JSON.stringify(bs(g))!==U.current,[g,x]),F=oe({mutationFn:async()=>{if(x){const{data:re}=await T.post("/agents",g);return re}const{data:L}=await T.patch(`/agents/${e}`,bs(g));return L},onSuccess:L=>{o.invalidateQueries({queryKey:["agents"]}),o.invalidateQueries({queryKey:["agent",e]}),U.current=JSON.stringify(bs(L)),j(null),x?r({to:"/agents/$agentId",params:{agentId:L.id}}):X("success",i("editor.feedback.saved"))},onError:L=>{ie(L)||X("error",L?.response?.data?.message||i("editor.feedback.saveError"))}}),G=oe({mutationFn:async()=>{await T.patch(`/agents/${e}`,bs(g));const{data:L}=await T.post(`/agents/${e}/publish`);return L},onSuccess:L=>{o.invalidateQueries({queryKey:["agents"]}),o.invalidateQueries({queryKey:["agent",e]}),U.current=JSON.stringify(bs(L)),j(null),v(re=>({...re,status:"published"})),X("success",i("editor.feedback.published"))},onError:L=>{ie(L)||X("error",L?.response?.data?.message||i("editor.feedback.publishError"))}}),te=oe({mutationFn:async()=>{const{data:L}=await T.post(`/agents/${e}/duplicate`);return L},onSuccess:L=>r({to:"/agents/$agentId",params:{agentId:L.id}})});function B(L){v(re=>({...re,...L}))}const ne=F.isPending||G.isPending,me=ne?"saving":D?"dirty":"saved",Ee=g.tools?.length??0;return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:i("editor.topbarEyebrow"),title:i(x?"editor.titleNew":"editor.titleEdit")}),t.jsxs("main",{className:"cia cia-creator-grid","data-theme":l,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:[t.jsx("div",{className:"cia-scroll",style:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",borderRight:"1px solid var(--cia-border)",overflowY:"auto"},children:z&&!x?t.jsx("div",{style:{padding:48,textAlign:"center",color:"var(--cia-text-3)",fontSize:13},children:i("editor.loading")}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{position:"sticky",top:0,zIndex:5,background:"var(--cia-bg)"},children:[t.jsxs("div",{style:{background:"var(--cia-bg)",borderBottom:"1px solid var(--cia-border)",padding:"14px 28px",display:"flex",alignItems:"center",gap:12},children:[t.jsx("button",{onClick:()=>r({to:"/agents"}),className:"cia-btn cia-btn-ghost cia-btn-icon",style:{width:30,height:30,flex:"none"},"aria-label":i("editor.back"),children:t.jsx(gn,{size:16})}),t.jsx(iT,{id:g.id||"nuevo",value:g.accent,onChange:L=>B({accent:L}),size:38}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("input",{value:g.name||"",onChange:L=>B({name:L.target.value}),readOnly:!d,title:d?void 0:i("common:noPermission"),placeholder:i("editor.namePlaceholder"),style:{background:"transparent",border:0,outline:"none",font:"inherit",fontFamily:"var(--cia-font-sans)",fontSize:17,fontWeight:600,letterSpacing:"-0.02em",color:"var(--cia-text)",width:"100%",padding:0}}),t.jsxs("div",{className:"cia-row cia-gap-2",style:{marginTop:2},children:[t.jsx("span",{className:"cia-mono cia-text-3",style:{fontSize:11},children:g.id||"ag_…"}),t.jsx("span",{style:{width:3,height:3,borderRadius:999,background:"var(--cia-border-strong)",flex:"none"}}),t.jsx(yD,{state:me,isNew:x})]})]}),t.jsx(rM,{agent:g}),t.jsx(vD,{status:g.status,isNew:x}),!x&&t.jsx(fD,{report:C.data,onClick:()=>{f("identity"),S(Date.now())}}),!x&&t.jsxs(t.Fragment,{children:[d&&t.jsxs("button",{onClick:()=>te.mutate(),className:"cia-btn cia-btn-outline cia-btn-sm",disabled:te.isPending,title:i("editor.duplicateTitle"),children:[t.jsx(bn,{size:13})," ",i("editor.duplicate")]}),t.jsxs("button",{className:"cia-btn cia-btn-outline cia-btn-sm",disabled:!0,title:i("editor.versionsTitle"),style:{opacity:.55,cursor:"not-allowed"},children:[t.jsx(wc,{size:13})," ",i("editor.versions"),t.jsx("span",{className:"cia-soon-tag",children:i("editor.soon")})]}),d&&t.jsxs("button",{onClick:()=>F.mutate(),className:"cia-btn cia-btn-outline cia-btn-sm",disabled:ne||!D,title:i("editor.saveTitle"),children:[F.isPending?t.jsx(je,{size:13,style:{animation:"spin 1s linear infinite"}}):t.jsx(ly,{size:13}),i("editor.save")]})]}),(x?d:u)&&t.jsxs("button",{onClick:()=>x?F.mutate():G.mutate(),disabled:ne,className:"cia-btn cia-btn-primary cia-btn-sm",children:[ne?t.jsx(je,{size:13,style:{animation:"spin 1s linear infinite"}}):t.jsx(ct,{size:13}),i(x?"editor.create":"editor.saveAndPublish")]})]}),t.jsx(mD,{canal:h,onCanal:b,agent:g}),t.jsx("div",{className:"cia-row",style:{padding:"0 28px",gap:4,borderBottom:"1px solid var(--cia-border)",background:"var(--cia-bg)",flexWrap:"wrap"},children:e1.map(L=>{const re=L.icon,ke=p===L.id;return t.jsxs("button",{onClick:()=>f(L.id),className:"cia-row cia-gap-2",style:{padding:"12px 14px",background:"transparent",border:0,borderBottom:`2px solid ${ke?"var(--cia-brand-500)":"transparent"}`,marginBottom:-1,color:ke?"var(--cia-text)":"var(--cia-text-3)",font:"inherit",fontFamily:"var(--cia-font-sans)",fontSize:13,fontWeight:ke?500:400,cursor:"pointer",whiteSpace:"nowrap"},children:[t.jsx(re,{size:15}),i(`editor.tabs.${L.id}`),L.id==="tools"&&Ee>0&&t.jsx("span",{className:"cia-badge",style:{height:16,fontSize:10,padding:"0 5px"},children:Ee}
970),(O[L.id]??0)>0&&t.jsx("span",{title:i("editor.suggestions.tabDot",{count:O[L.id]}),"aria-label":i("editor.suggestions.tabDot",{count:O[L.id]}),style:{width:7,height:7,borderRadius:999,background:"var(--cia-cta-500)",flex:"none",boxShadow:"0 0 0 3px color-mix(in oklab, var(--cia-cta-500) 22%, transparent)"}})]},L.id)})})]}),y&&t.jsx("div",{style:{padding:"12px 28px 0"},children:t.jsx("div",{className:y.type==="success"?"cia-badge cia-badge-success":"cia-badge cia-badge-bad",role:"alert",style:{height:"auto",padding:"8px 12px",fontSize:13},children:y.message})}),w&&t.jsx("div",{style:{padding:"12px 28px 0"},"data-testid":"wa-save-blocked",children:t.jsx(le,{tone:"bad",title:w.message||i("editor.feedback.saveError"),children:w.issues.length>0?t.jsx("ul",{style:{listStyle:"none",margin:"4px 0 0",padding:0,display:"flex",flexDirection:"column",gap:6},children:w.issues.map(L=>{const re=ig(L.code);return t.jsxs("li",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},children:[t.jsx("span",{style:{flex:"1 1 220px",minWidth:0,overflowWrap:"anywhere"},children:de(L)}),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{color:"inherit",flex:"none"},onClick:()=>f(re),children:[i(`editor.tabs.${re}`),t.jsx(oa,{size:12,"aria-hidden":!0})]})]},L.code)})}):null})}),!d&&t.jsx("div",{style:{padding:"12px 28px 0"},children:t.jsx(le,{tone:"info",children:i("editor.readOnly")})}),t.jsxs("fieldset",{disabled:!d,style:{border:0,margin:0,padding:0,minWidth:0},children:[W>0&&t.jsx("div",{style:{padding:"12px 28px 0"},children:t.jsxs("div",{className:"cia-row cia-gap-2",style:{padding:"8px 12px",borderRadius:"var(--cia-r)",border:"1px solid color-mix(in oklab, var(--cia-cta-500) 30%, transparent)",background:"color-mix(in oklab, var(--cia-cta-500) 7%, var(--cia-bg-elev))",flexWrap:"wrap"},children:[t.jsx(_t,{size:14,style:{color:"var(--cia-cta-500)",flex:"none"}}),t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text)"},children:i("editor.suggestions.elsewhere",{count:W})}),t.jsx("span",{style:{flex:1}}),K.map(L=>t.jsxs("button",{type:"button",onClick:()=>f(L.tabId),className:"cia-btn cia-btn-ghost cia-btn-sm",children:[i(`editor.tabs.${L.tabId}`),t.jsx("span",{className:"cia-badge",style:{height:16,fontSize:10,padding:"0 5px"},children:L.count})]},L.tabId))]})}),t.jsxs("div",{style:{padding:"24px 28px 60px"},children:[t.jsx(G3,{suggestions:V,onAccept:I,onReject:P}),h==="text"&&p==="identity"?t.jsx(cD,{agent:g,onChange:B}):null,t.jsx("div",{style:{display:p==="identity"&&h==="voice"?"contents":"none"},children:t.jsx(H3,{agent:g,onChange:B,openBuilderOnMount:s,onOpenKnowledge:()=>f("knowledge"),auditKick:N,onFieldSuggestion:E})}),p==="voice"&&(h==="text"?t.jsx(dD,{agent:g,onChange:B}):t.jsx(QM,{agent:g,onChange:B})),p==="behavior"&&t.jsx(PP,{agent:g,onChange:B,auditIssues:C.data?.issues}),p==="tools"&&(h==="text"?t.jsx(pD,{agent:g,onChange:B}):t.jsx(iz,{agent:g,onChange:B})),p==="knowledge"&&t.jsx(oD,{agent:g,onChange:B,auditIssues:C.data?.issues,dirty:D,agentId:e}),p==="analytics"&&t.jsx(dz,{agent:g,onChange:B}),p==="deploy"&&t.jsx(bz,{agent:g,onChange:B}),p==="widget"&&t.jsx(Nz,{agent:g,onChange:B}),p==="limits"&&t.jsx(Cz,{agent:g,onChange:B})]})]})]})}),t.jsx("div",{className:"cia-creator-test cia-scroll",style:{minWidth:0,background:"var(--cia-bg-soft)",overflowY:"auto"},children:t.jsx(p0,{agent:g,isNew:x,dirty:D})})]}),t.jsx("style",{children:"@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }"})]})}function yD({state:e,isNew:a}){const{t:n}=M("agentsRoutes");if(a&&e!=="saving")return t.jsxs("span",{className:"cia-row cia-gap-2 cia-mono",style:{fontSize:11,color:"var(--cia-text-3)"},children:[t.jsx(qt,{size:11})," ",n("editor.saveIndicator.unsaved")]});const s={saved:{icon:ct,color:"var(--cia-ok-600)",label:n("editor.saveIndicator.saved")},saving:{icon:je,color:"var(--cia-brand-500)",label:n("editor.saveIndicator.saving")},dirty:{icon:qt,color:"var(--cia-warn-ink)",label:n("editor.saveIndicator.dirty")}}[e],i=s.icon;return t.jsxs("span",{className:"cia-row cia-gap-2 cia-mono",style:{fontSize:11,color:s.color},children:[t.jsx(i,{size:11,style:e==="saving"?{animation:"spin 1s linear infinite"}:void 0}),s.label]})}function vD({status:e,isNew:a}){const{t:n}=M("agentsRoutes");return a?t.jsx("span",{className:"cia-badge",children:n("editor.statusPill.new")}):e==="published"?t.jsxs("span",{className:"cia-badge cia-badge-success",children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{width:5,height:5,color:"var(--cia-ok-500)"}}),n("editor.statusPill.live")]}):e==="archived"?t.jsx("span",{className:"cia-badge",style:{color:"var(--cia-text-4)"},children:n("editor.statusPill.archived")}):t.jsx("span",{className:"cia-badge",children:n("editor.statusPill.draft")})}const jD=840*1e3,wD=300*1e3,kD=3e4,cl={status:"off",segments:[],cutoffTs:null,agentState:null,speaking:null};function ND(e,a){const[n,s]=m.useState(cl),i=m.useRef(null),r=m.useRef(null),o=m.useRef(0);return m.useEffect(()=>{if(!e||!a){s(cl);return}const l=++o.current,c=()=>o.current===l;let d=null,u=null,p=null,f,x,h,b,g=0;const v=()=>{if(f&&clearTimeout(f),x&&clearTimeout(x),b&&clearInterval(b),u?.(),p?.(),u=null,p=null,d)try{d.disconnect()}catch{}d=null,i.current=null},y=()=>{v(),c()&&(s({...cl,status:"failed"}),g<2&&(h=setTimeout(()=>void k(),kD)))},k=async()=>
970{if(g++,!!c()){s(j=>({...cl,status:"connecting",segments:j.segments}));try{const{data:j}=await T.post(`/calls/${e}/observe`,{});if(!c())return;const C=Lj();if(d=C,i.current=C,u=Gg(C,{onSegment:N=>{c()&&(N.role==="user"&&(r.current=Date.now()),s(S=>({...S,segments:Fj(S.segments,N)})))}}),p=Oj(C,N=>{c()&&s(S=>({...S,agentState:N}))}),C.on(fr.Disconnected,()=>{c()&&y()}),await C.connect(j.url,j.token,{autoSubscribe:!1}),!c())return v();s(N=>({...N,status:"live",cutoffTs:new Date().toISOString(),agentState:$j(C)})),b=setInterval(()=>{c()&&s(N=>{const S=qj(N.segments,Date.now(),r.current),_=N.agentState==="speaking";return N.speaking&&N.speaking.user===S&&N.speaking.agent===_?N:{...N,speaking:{agent:_,user:S}}})},250),x=setTimeout(v,jD)}catch{y()}}},w=()=>{document.visibilityState==="hidden"?f=setTimeout(v,wD):f&&(clearTimeout(f),f=void 0)};return document.addEventListener("visibilitychange",w),k(),()=>{o.current++,document.removeEventListener("visibilitychange",w),h&&clearTimeout(h),v(),r.current=null}},[e,a]),n}const SD={end_call:"Finalizar llamada",finalizar_llamada:"Finalizar llamada",transfer:"Transferir a otro agente",transferir:"Transferir a otro agente",transfer_call:"Transferir a número externo",transferir_llamada:"Transferir a número externo",http_request:"Consulta a sistema externo",send_dtmf:"Enviar tonos (DTMF)",voicemail_detection:"Detección de buzón"};function a1(e){return SD[e]??e}function Dl(e){return e==="outbound"?{Icon:ka,color:"var(--cia-cta-500)",label:he.t("calls:dir.outbound")}:e==="web"?{Icon:Va,color:"var(--cia-sky-500)",label:he.t("calls:dir.web")}:{Icon:yn,color:"var(--cia-brand-500)",label:he.t("calls:dir.inbound")}}function Dr(e){return e.direction==="web"?he.t("calls:callNumber.webSession"):lv(e)||"—"}function CD(e){const a=e.metadata?.liveSignals?.sentimentLabel;return a==="positive"?{label:"positive",color:"var(--cia-ok-500)"}:a==="negative"?{label:"negative",color:"var(--cia-bad-500)"}:null}function _D(e){const a=e.agent;return a?.accent??a?.metadata?.accent??null}function og(e,a){const s=(Array.isArray(e?.tools)?e.tools:[]).find(r=>r?.type===a);if(!s)return{ok:!1,reason:"absent",rules:[]};if(s.config?.enabled===!1)return{ok:!1,reason:"disabled",rules:[]};const i=Array.isArray(s.config?.rules)?s.config.rules:[];return i.length===0?{ok:!1,reason:"norules",rules:[]}:{ok:!0,rules:i}}function gp(e){const a=e?.response?.status,n=e?.response?.data?.message||e?.message;return a===429?he.t("calls:errors.rateLimit"):a===403?he.t("calls:errors.forbidden"):Array.isArray(n)?n.join(" · "):n||he.t("calls:errors.generic")}function ED(e){return e?e.length<=4?e:`··· ${e.slice(-4)}`:""}function AD(e,a){if(!a)return new Date(e).toLocaleTimeString();const n=Math.max(0,Math.floor((new Date(e).getTime()-new Date(a).getTime())/1e3));return`${Math.floor(n/60)}:${(n%60).toString().padStart(2,"0")}`}function RD({initialCallId:e}={}){const{t:a}=M("calls"),n=xt($=>$.resolved),[s,i]=m.useState(null),[r,o]=m.useState([]),[l,c]=m.useState(()=>Date.now()),[d,u]=m.useState(null),[p,f]=m.useState(null),{data:x,isLoading:h,isError:b,error:g,refetch:v,isFetching:y}=w0({onEnded:$=>{i(z=>(!z||!($.callId===z.id||!!$.roomName&&$.roomName===z.roomName)||f($),z))}}),{can:k}=tt(),w=k("calls.operate"),{data:j}=se({queryKey:["agents"],queryFn:async()=>(await T.get("/agents")).data,enabled:w}),C=Z4(x)||!!s&&la(s);m.useEffect(()=>{if(!C)return;const $=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval($)},[C]),m.useEffect(()=>{if(r.length===0){u(null);return}const $=r[r.length-1],z=$.role==="agent"?"agent":$.role==="user"?"user":null;if(u(z),!z)return;const D=Math.min(16e3,Math.max(1800,Math.round($.text.length/14*1e3))),F=setTimeout(()=>u(null),D);return()=>clearTimeout(F)},[r]);const N=s?x?.find($=>$.id===s.id):void 0,S=Array.isArray(x)&&!b,_=N||(s&&(S||p)?Y4(s,p??{}):s);m.useEffect(()=>{const $=ns(),z=D=>{_&&D.roomName===_.roomName&&o(F=>F.some(G=>G.timestamp===D.timestamp&&G.role===D.role&&G.text===D.text)?F:[...F,D])};return $.on("transcript",z),()=>{$.off("transcript",z)}},[_?.roomName]),m.useEffect(()=>{s&&(ns().emit("subscribe:call",{roomName:s.roomName}),o(s.transcript.map(z=>({roomName:s.roomName,...z}))))},[s?.id]),m.useEffect(()=>{if(!_?.transcript?.length)return;const $=_.roomName;o(z=>{const D=Bj(z,_.transcript);return D===z?z:D.map(F=>({roomName:$,...F}))})},[_?.id,_?.transcript?.length]);const R=!!_&&la(_),A=ND(_?.id??null,R),E=Wj({history:r,segments:A.segments,cutoffTs:A.cutoffTs,live:A.status==="live"}),I=A.speaking?A.speaking.agent?"agent":A.speaking.user?"user":null:d,P=m.useRef(!1);m.useEffect(()=>{if(P.current||!e||!x)return;P.current=!0;const $=x.find(z=>z.id===e);if($){i($);return}T.get(`/calls/${e}`).then(({data:z})=>{const D=Dh(z);J({tone:D&&D!=="answered"?"warn":"info",title:D?a("empty.callEndedWith",{outcome:he.t(`format:endReason.${z.endReason}`,{defaultValue:a(`item.outcome.${D}`,{defaultValue:D})})}):a("empty.callGone")})}).catch(()=>J({tone:"info",title:a("empty.callGone")}))},[x,e,a]),m.useEffect(()=>{f(null)},[s?.id]);const O=$=>zr($,l)||$.liveUnconfirmed===!0,K=(x??[]).filter(O),W=(x??[]).filter($=>!O($)),V=W.length,U=W.filter($=>$.direction==="inbound").length,X=W.filter($=>$.direction==="outbound").length,ie=V>0?Math.round(W.reduce(($,z)=>$+zl(z,l),0)/V):0;function de(){if(!_||r.length===0)return;const $=B=>B==="agent"?_.agent?.name||a("who.agent"):a(B==="user"?"who.client":"who.system"),z=`${a("export.header",{agent:_.agent?.name||"",number:Dr(_),direction:Dl(_.direction).label})}
971${"=".repeat(52)}
972
973`,D=r.map(B=>`[${B.timestamp?new Date(B.timestamp).toLocaleTimeString():""}] ${$(B.role)}: ${B.text}`).join(`
974`),F=new Blob([z+D+`
975`],{type:"text/plain;charset=utf-8;"}),G=URL.createObjectURL(F),te=document.createElement("a");te.href=G,te.download=`${a("export.filename")}-${_.id}.txt`,te.click(),URL.revokeObjectURL(G)}return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:a("topbar.liveEyebrow"),title:a("topbar.liveTitle")}),t.jsxs("main",{className:"cia cia-live flex-1 overflow-hidden","data-theme":n,style:{display:"grid",gridTemplateColumns:"360px 1fr",minHeight:0,background:"var(--cia-bg)",color:"var(--cia-text)"},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",borderRight:"1px solid var(--cia-border)",overflow:"hidden",minHeight:0},children:[t.jsxs("div",{style:{padding:"18px 20px",borderBottom:"1px solid var(--cia-border)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[V>0&&t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{color:"var(--cia-ok-500)"},"aria-hidden":"true"}),t.jsx("h3",{style:{margin:0,fontSize:14,fontWeight:600},children:a("list.activeCalls",{count:V})}),K.length>0&&t.jsx("span",{className:"cia-badge",style:{color:"var(--cia-warn-ink)",fontSize:10.5},children:a("list.stalledCount",{count:K.length})})]}),t.jsxs("div",{className:"cia-mono",style:{display:"flex",gap:12,fontSize:11,color:"var(--cia-text-3)"},children:[t.jsxs("span",{children:[a("list.inbound")," ",t.jsx("span",{style:{color:"var(--cia-text-2)"},children:U})]}),t.jsx("span",{"aria-hidden":"true",children:"·"}),t.jsxs("span",{children:[a("list.outbound")," ",t.jsx("span",{style:{color:"var(--cia-text-2)"},children:X})]}),t.jsx("span",{"aria-hidden":"true",children:"·"}),t.jsxs("span",{children:[a("list.avg")," ",t.jsx("span",{style:{color:"var(--cia-text-2)"},children:Ca(ie)})]})]})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",overflow:"auto",flex:1},className:"cia-scroll",children:h&&!x?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:20},children:[0,1,2].map($=>t.jsx(ge,{h:44},$))}):b?t.jsx("div",{style:{padding:20},children:t.jsx(le,{tone:"bad",title:a("empty.errorTitle"),action:{label:a("empty.errorRetry"),onClick:()=>void v(),loading:y},children:gp(g)})}):(x?.length??0)>0?[...W,...K].map($=>
975{const z=_?.id===$.id,D=zr($,l),{Icon:F,color:G}=Dl($.direction),te=CD($);return t.jsxs("button",{onClick:()=>i($),style:{display:"flex",alignItems:"center",gap:12,padding:"14px 20px",background:te?`color-mix(in oklab, ${te.color} 9%, ${z?"var(--cia-bg-tint)":"transparent"})`:z?"var(--cia-bg-tint)":"transparent",border:0,borderBottom:"1px solid var(--cia-border)",borderLeft:`3px solid ${te?te.color:z?"var(--cia-brand-500)":"transparent"}`,textAlign:"left",color:"inherit",font:"inherit",cursor:"pointer"},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[t.jsx(F,{size:12,style:{color:G,flex:"none"},"aria-hidden":"true"}),t.jsx("span",{style:{fontSize:13,fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:$.agent?.name||"—"}),te&&t.jsx("span",{className:te.label==="negative"?"cia-dot cia-dot-pulse":"cia-dot",style:{color:te.color,width:7,height:7,flex:"none"},title:te.label==="negative"?a("item.sentNegTitle"):a("item.sentPosTitle"),"aria-hidden":"true"})]}),t.jsx("span",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)"},children:Dr($)})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4,flex:"none"},children:[D&&t.jsx("span",{className:"cia-badge",style:{color:"var(--cia-warn-ink)",fontSize:10.5},children:a("header.stalled")}),t.jsx("span",{className:"cia-mono",style:{fontSize:12,color:"var(--cia-text-2)"},children:Ca(zl($,l))}),t.jsx(w5,{active:$.status==="connected",color:"var(--cia-ok-500)",bars:4,height:12})]})]},$.id)}):t.jsx(st,{mini:!0,icon:vi,title:a("empty.listTitle"),desc:a("empty.listDesc")})})]}),_?t.jsxs("div",{style:{display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0,background:"var(--cia-bg-soft)"},children:[t.jsxs("div",{style:{padding:"20px 32px",borderBottom:"1px solid var(--cia-border)",background:"var(--cia-bg)",flexShrink:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:14},children:[t.jsx(ss,{id:_.agentId,accent:_D(_),size:40}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("h2",{style:{margin:0,fontSize:17,fontWeight:600},children:_.agent?.name||"—"}),(()=>{if(!la(_)){const F=Ih(_),G=k0(_),te=G==="ok"?"var(--cia-ok-500)":G==="warn"?"var(--cia-warn-ink)":G==="bad"?"var(--cia-bad-500)":"var(--cia-text-3)";return t.jsxs("span",{className:"cia-badge",style:{color:te},children:[a("header.ended")," · ",he.t(`${F.ns}:${F.key}`)]})}const z=zr(_,l)||_.liveUnconfirmed===!0,D=_.status==="connected";return t.jsxs("span",{className:D?"cia-badge cia-badge-success":"cia-badge",style:z?{color:"var(--cia-warn-ink)"}:void 0,children:[!z&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"cia-dot cia-dot-pulse",style:{width:5,height:5},"aria-hidden":"true"})," "]}),a(D?"header.onCall":z?"header.stalled":"header.dialing")]})})()]}),t.jsxs("div",{className:"cia-mono",style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:2},children:[Dr(_)," · ",Dl(_.direction).label," · ",Ca(zl(_,l))]})]}),w&&la(_)&&t.jsx(MD,{call:_,agents:j,onHungUp:()=>i(null)})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,width:56,color:I==="agent"?"var(--cia-cta-500)":"var(--cia-text-3)"},children:a("wave.agent")}),t.jsx("div",{style:{flex:1},children:t.jsx(gf,{active:I==="agent",color:"var(--cia-cta-500)"})})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,marginTop:6},children:[t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,width:56,color:I==="user"?"var(--cia-brand-500)":"var(--cia-text-3)"},children:a("wave.client")}),t.jsx("div",{style:{flex:1},children:t.jsx(gf,{active:I==="user",color:"var(--cia-brand-500)"})})]})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1.5fr 1fr",gap:14,padding:22,flex:1,minHeight:0},className:"cia-live-body",children:[t.jsxs("div",{className:"cia-card",style:{padding:18,dis
975play:"flex",flexDirection:"column",minHeight:0,overflow:"hidden"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:14,flexShrink:0},children:[t.jsx("span",{className:"cia-eyebrow",children:a("transcript.liveTitle")}),t.jsx(TD,{status:A.status}),t.jsx("span",{style:{flex:1}}),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",onClick:de,disabled:r.length===0,title:a("transcript.exportTitle"),children:[t.jsx(Tn,{size:12})," ",a("transcript.export")]})]}),t.jsx("div",{className:"cia-scroll",style:{flex:1,minHeight:0,overflowY:"auto"},children:E.length>0?t.jsx(vo,{messages:E,autoScroll:!0,liveRegion:!0,agentName:_.agent?.name||a("common.agentFallback"),userLabel:a("common.client")}):(()=>{const $=a3(_,A.status,l),z=$==="stalled";return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:z?"var(--cia-warn-ink)":"var(--cia-text-3)",fontSize:12,padding:"8px 0"},children:[z?t.jsx(Tt,{size:13,"aria-hidden":"true"}):t.jsx(Xb,{size:13,style:{color:"var(--cia-brand-500)"},"aria-hidden":"true"}),t.jsx("span",{children:a($==="not_started"?"transcript.waitingNotStarted":$==="stalled"?"transcript.waitingStalled":$==="silent"?"transcript.waitingSilent":"transcript.waitingFallback")}),$==="silent"&&t.jsx("span",{className:"cia-thinking-caret"})]})})()})]}),t.jsx("div",{className:"cia-scroll",style:{minHeight:0,overflowY:"auto"},children:t.jsx(FD,{call:_,speaking:I,agentState:A.status==="live"?A.agentState:null,turnsShown:E.filter($=>$.role==="user").length})})]})]}):t.jsx("div",{style:{display:"grid",placeItems:"center",background:"var(--cia-bg-soft)"},children:t.jsx(st,{icon:vi,title:a("empty.selectTitle"),desc:a("empty.selectDesc")})})]})]})}function TD({status:e}){const{t:a}=M("calls");if(e==="off")return null;const n=e==="live"?{color:"var(--cia-ok-500)",label:a("transcript.rtOn"),pulse:!0}:e==="connecting"?{color:"var(--cia-warn-500)",label:a("transcript.rtConnecting"),pulse:!1}:{color:"var(--cia-text-3)",label:a("transcript.rtFallback"),pulse:!1};return t.jsxs("span",{className:"cia-mono",style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10,color:"var(--cia-text-3)"},title:e==="failed"?a("transcript.rtFallbackHelp"):void 0,children:[t.jsx("span",{className:n.pulse?"cia-dot cia-dot-pulse":"cia-dot",style:{color:n.color,width:6,height:6},"aria-hidden":"true"}),n.label]})}function MD({call:e,agents:a,onHungUp:n}){const{t:s}=M("calls"),i=xe(),[r,o]=m.useState(!1),[l,c]=m.useState(null),d=og(e.agent,"transfer_call"),u=og(e.agent,"transfer"),p=oe({mutationFn:()=>T.post(`/calls/${e.id}/hangup`),onSuccess:()=>{J({title:s("controls.hangupOk"),tone:"ok"}),i.invalidateQueries({queryKey:["calls","active"]}),o(!1),n()},onError:h=>J({title:s("controls.hangupErr"),desc:gp(h),tone:"bad"})}),f=oe({mutationFn:h=>T.post(`/calls/${e.id}/transfer`,h),onSuccess:()=>{J({title:s("controls.transferOk"),tone:"ok"}),c(null)},onError:h=>J({title:s("controls.transferErr"),desc:gp(h),tone:"bad"})}),x=s("controls.notConfigured");return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:"none"},children:[t.jsxs("button",{type:"button",className:"cia-btn cia-btn-sm cia-btn-outline",disabled:!d.ok,onClick:()=>c("transfer_call"),title:d.ok?s("controls.externalTransferTitle"):x,style:d.ok?void 0:{opacity:.5,cursor:"not-allowed"},children:[t.jsx(uo,{size:14})," ",s("controls.externalTransfer")]}),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-sm cia-btn-outline",disabled:!u.ok,onClick:()=>c("transfer"),title:u.ok?s("controls.transferAgentTitle"):x,style:u.ok?void 0:{opacity:.5,cursor:"not-allowed"},children:[t.jsx(Bs,{size:14})," ",s("controls.transferAgent")]}),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-sm",onClick:()=>o(!0),title:s("controls.hangupTitle"),style:{color:"var(--cia-bad-500)",border:"1px solid color-mix(in oklab, var(--cia-bad-500) 40%, var(--cia-border-2))"},children:[t.jsx(Ts,{size:14})," ",s("controls.hangup")]}),r&&t.jsx(PD,{title:s("confirm.hangupTitle"),desc:s("confirm.hangupDesc"),confirmLabel:s("controls.hangup"),pending:p.isPending,danger:!0,onCancel:()=>o(!1),onConfirm:()=>p.mutate()}),l&&t.jsx(zD,{kind:l,rules:(l==="transfer_call"?d:u).rules,agents:a,pending:f.isPending,onCancel:()=>c(null),onConfirm:(h,b)=>f.mutate({kind:l,ruleId:h,message:b})})]})}function PD({title:e,desc:a,confirmLabel:n,pending:s,danger:i,onCancel:r,onConfirm:o}){const{t:l}=M("calls"),c=xt(d=>d.resolved);return t.jsx("div",{className:"cia cia-modal-overlay","data-theme":c,onClick:r,children:t.jsxs("div",{className:"cia-modal-card",onClick:d=>d.stopPropagation(),style:{maxWidth:380},children:[t.jsx("h3",{style:{margin:0,fontSize:16,fontWeight:600},children:e}),t.jsx("p",{style:{margin:"8px 0 0",fontSize:13,color:"var(--cia-text-3)",lineHeight:1.5},children:a}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:18},children:[t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",onClick:r,disabled:s,children:l("common.cancel")}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-sm",onClick:o,disabled:s,style:i?{background:"var(--cia-bad-500)",color:"#fff"}:void 0,children:s?t.jsx(je,{className:"animate-spin",size:14}):n})]})]})})}function zD({kind:e,rules:a,agents:n,pending:s,onCancel:i,onConfirm:r}){const{t:o}=M("calls"),l=xt(b=>b.resolved),[c,d]=m.useState(a.length===1?a[0]?.id:void 0),[u,p]=m.useState(""),f=a.length>1,x=o(e==="transfer_call"?"transfer.titleExternal":"transfer.titleAgent"),h=b=>e==="transfer"?n?.find(v=>v.id===b.targetAgentId)?.name||b.condition||o("transfer.otherAgent"):b.condition||ED(b.destinationNumber)||o("transfer.destination");return t.jsx("div",{className:"cia cia-modal-overlay","data-theme":l,onClick:i,children:t.jsxs("div",{className:"cia-modal-card",onClick:b=>b.stopPropagation(),style:{maxWidth:460},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[e==="transfer_call"?t.jsx(uo,{size:16,style:{color:"var(--cia-cta-500)"}}):t.jsx(Bs,{size:16,style:{color:"var(--cia-cta-500)"}}),t.jsx("h3",{style:{margin:0,fontSize:16,fontWeight:600},children:x})]}),t.jsx("p",{style:{margin:"0 0 14px",fontSize:12.5,color:"var(--cia-text-3)",lineHeight:1.5},children:o("transfer.desc")}),f&&t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("label",{className:"cia-eyebrow",style:{display:"block",marginBottom:6},children:o("transfer.destinationLabel")}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.map(b=>t.jsx("button",{type:"button",onClick:()=>d(b.id),style:{display:"flex",alignItems:"center",gap:8,padding:"9px 12px",borderRadius:"var(--cia-r-sm)",border:`1px solid ${c===b.id?"var(--cia-brand-500)":"var(--cia-border)"}`,background:c===b.id?"var(--cia-bg-tint)":"var(--cia-bg-elev)",color:"var(--cia-text)",cursor:"pointer",textAlign:"left",font:"inherit",fontSize:13},children:h(b)},b.id))})]}),t.jsx("label",{className:"cia-eyebrow",style:{display:"block",marginBottom:6},children:o("transfer.messageLabel")}),t.jsx("textarea",{className:"input",value:u,maxLength:500,onChange:b=>p(b.target.value),placeholder:o("transfer.messagePlaceholder"),style:{width:"100%",minHeight:72,resize:"vertical",fontSize:13}}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:18},children:[t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",onClick:i,disabled:s,children:o("common.cancel")}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta cia-btn-sm",onClick:()=>r(c,u.trim()),disabled:s||f&&!c,children:s?t.jsx(je,{className:"animate-spin",size:14}):o("transfer.submit")})]})]})})}const DD=["nombre","name","cliente","customer","full_name","nombre_completo","first_name"];
975function ID(e){const a=e.trim().split(/\s+/).filter(Boolean);return a.length===0||e==="—"?"?":a.length===1?a[0].slice(0,2).toUpperCase():(a[0][0]+a[a.length-1][0]).toUpperCase()}function lg(e){switch(e){case"positive":return{text:he.t("calls:analysis.sentiment.positive"),color:"var(--cia-ok-500)"};case"negative":return{text:he.t("calls:analysis.sentiment.negative"),color:"var(--cia-bad-500)"};case"neutral":return{text:he.t("calls:analysis.sentiment.neutral"),color:"var(--cia-brand-500)"};default:return{text:he.t("calls:signals.undetermined"),color:"var(--cia-text-3)"}}}function LD(e){const a=Array.isArray(e.events)?e.events:[];for(let n=a.length-1;n>=0;n--)if(a[n].type==="turn_latency"){const s=Number(a[n].data?.e2eMs);if(Number.isFinite(s)&&s>0)return Math.round(s)}return null}function dr({label:e,value:a,color:n,bar:s}){return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:s!=null?5:0},children:[t.jsx("span",{style:{flex:1,fontSize:12,color:"var(--cia-text-3)"},children:e}),t.jsx("span",{className:"cia-mono",style:{fontSize:12,color:n||"var(--cia-text)",maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",textAlign:"right"},title:a,children:a})]}),s!=null&&t.jsx("div",{style:{height:4,background:"var(--cia-bg-soft)",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{width:`${Math.max(0,Math.min(100,s))}%`,height:"100%",background:n||"var(--cia-brand-500)",borderRadius:4}})})]})}function FD({call:e,speaking:a,agentState:n,turnsShown:s}){const{t:i}=M("calls"),r=dt(),o=e.inputVariables?Object.entries(e.inputVariables):[],l=o.find(([w])=>DD.includes(w.toLowerCase())),c=l?String(l[1]):Dr(e),d=o.filter(([w])=>w!==l?.[0]),u=Dl(e.direction),p=e.metadata?.liveSignals??null,f=!!e.agent?.analytics?.liveSentimentEnabled,x=la(e),h=LD(e),b=s,g=n==="thinking"?{text:i("signals.agentThinking"),color:"var(--cia-cta-500)"}:n==="speaking"||a==="agent"?{text:i("signals.agentSpeaking"),color:"var(--cia-cta-500)"}:a==="user"?{text:i("signals.clientSpeaking"),color:"var(--cia-brand-500)"}:n==="listening"?{text:i("signals.agentListening"),color:"var(--cia-text-3)"}:{text:i("signals.listening"),color:"var(--cia-text-3)"},v=g.text,y=g.color,k=Array.isArray(e.toolCalls)?e.toolCalls:[];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{className:"cia-card",style:{padding:18},children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:10},children:i("panel.client")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:d.length?12:0},children:[t.jsx("div",{style:{width:38,height:38,borderRadius:"50%",display:"grid",placeItems:"center",color:"#fff",fontWeight:600,fontSize:13,background:"linear-gradient(135deg, var(--cia-sky-500), var(--cia-brand-500))",flex:"none"},children:ID(c)}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:14,fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c}),t.jsxs("div",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)",display:"flex",alignItems:"center",gap:6},children:[t.jsx(u.Icon,{size:11,style:{color:u.color}})," ",u.label," · ",Dr(e)]})]})]}),d.length>0&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:d.map(([w,j])=>t.jsx(Gy,{k:w,v:String(j)},w))})]}),t.jsxs("div",{className:"cia-card",style:{padding:18},children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:10},children:i("panel.signals")}),p&&(p.sentimentLabel==="positive"||p.sentimentLabel==="negative")&&(()=>{const w=p.sentimentLabel==="negative",j=w?"var(--cia-bad-500)":"var(--cia-ok-500)";return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12,padding:"10px 12px",borderRadius:"var(--cia-r-sm)",background:`color-mix(in oklab, ${j} 14%, transparent)`,border:`1px solid color-mix(in oklab, ${j} 36%, transparent)`,color:j,fontSize:12.5,fontWeight:600},children:[t.jsx("span",{className:w?"cia-dot cia-dot-pulse":"cia-dot",style:{color:j,width:8,height:8,flex:"none"},"aria-hidden":"true"}),i(w?"signals.negBanner":"signals.posBanner")]})})(),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx(dr,{label:i("signals.state"),value:v,color:y}),t.jsx(dr,{label:i("signals.lastLatency"),value:h!=null?`${h} ms`:"—"}),t.jsx(dr,{label:i("signals.userTurns"),value:String(b)}),p?t.jsxs(t.Fragment,{children:[t.jsx(dr,{label:i("signals.sentiment"),value:lg(p.sentimentLabel).text,color:lg(p.sentimentLabel).color,bar:p.sentiment!=null?(p.sentiment+1)/2*100:null}),t.jsx(dr,{label:i("signals.intent"),value:p.intent||i("signals.undetermined")}),p.live?t.jsxs("p",{style:{margin:0,fontSize:10.5,color:"var(--cia-ok-500)",display:"flex",alignItems:"center",gap:5},children:[t.jsx("span",{className:"cia-dot",style:{width:5,height:5,background:"var(--cia-ok-500)"}})," ",i("signals.liveAnalysis")]}):t.jsx("p",{style:{margin:0,fontSize:10.5,color:"var(--cia-text-3)"},children:i("signals.computedAtEnd")})]}):t.jsx("div",{style:{borderTop:"1px solid var(--cia-border)",paddingTop:10,fontSize:12,color:"var(--cia-text-3)",display:"flex",alignItems:"flex-start",ga
975p:8},children:f&&x?t.jsxs(t.Fragment,{children:[t.jsx(Xb,{size:13,style:{color:"var(--cia-brand-500)",flex:"none",marginTop:1}})," ",i("signals.analyzing")]}):t.jsxs(t.Fragment,{children:[t.jsx(_t,{size:13,style:{color:"var(--cia-cta-500)",flex:"none",marginTop:1}}),t.jsxs("div",{style:{lineHeight:1.5},children:[i("signals.premiumP1"),t.jsx("strong",{children:i("signals.premiumRealtime")}),i("signals.premiumP2"),t.jsx("strong",{children:i("signals.premiumDetail")}),i("signals.premiumP3"),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-cta cia-btn-sm",style:{marginTop:10,display:"inline-flex"},onClick:()=>r({to:"/agents/$agentId",params:{agentId:e.agentId},search:{tab:"analytics"}}),children:[t.jsx(_t,{size:13})," ",i("signals.activate")]})]})]})})]})]}),t.jsxs("div",{className:"cia-card",style:{padding:18},children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:10},children:i("panel.actions")}),k.length>0?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:k.map(w=>t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("div",{style:{flex:1,minWidth:0},children:t.jsx(k5,{status:w.status,label:a1(w.name),at:AD(w.at,e.startedAt),latencyMs:w.latencyMs})}),t.jsx("span",{style:{flex:"none",fontSize:9.5,padding:"2px 7px",borderRadius:999,fontWeight:600,letterSpacing:"0.04em",background:w.source==="operator"?"color-mix(in oklab, var(--cia-cta-500) 16%, transparent)":"color-mix(in oklab, var(--cia-brand-500) 14%, transparent)",color:w.source==="operator"?"var(--cia-cta-500)":"var(--cia-brand-500)"},children:w.source==="operator"?i("actionsPanel.portal"):i("actionsPanel.ai")})]},w.id))}):t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)"},children:i("actionsPanel.empty")})]})]})}const OD=["disabled","enabling","enabled","disabling","failed"],n1=new Set(["enabling","disabling"]);function $D(e,a){const n=e.callingStatus,s=n!==null&&OD.includes(n),i=s&&n1.has(n),r=n==="enabled"||n==="enabling",l={encendido:r,enTransicion:i,chip:n==="enabling"||n==="disabling"||n==="enabled"||n==="failed"?n:null},c=u=>({...l,deshabilitado:!0,bloqueo:u});if(!s)return{...l,encendido:!1,chip:null,deshabilitado:!0,bloqueo:"estado_desconocido"};if(!a)return c("sin_permiso");if(e.elegibilidad?.coexistencia)return c("coexistencia");if(i)return c("transicion");if(r)return{...l,deshabilitado:!1,bloqueo:null};const d=e.elegibilidad;if(d){if(d.agenteConTransferencia)return c("agente_con_transferencia");if(!d.agenteAsignado)return c("sin_agente");if(!d.sipConfigurado)return c("plataforma_sin_sip");if(!d.cidrsCargados)return c("plataforma_sin_cidrs")}return{...l,deshabilitado:!1,bloqueo:null}}function cg(e){return e==="plataforma_sin_sip"||e==="plataforma_sin_cidrs"}const qD=5e3;function BD(e){return e!=null&&n1.has(e)?qD:!1}const c9={enabled:!1,enabledOrgIds:[],sipHostname:null,sipPort:5061},d9={min:1024,max:65535};function u9(e,a){return{calling:{[e]:a}}}function p9(e,a){const n={};return WD(e.enabledOrgIds,a.enabledOrgIds)||(n.enabledOrgIds=a.enabledOrgIds),(e.sipHostname??null)!==(a.sipHostname??null)&&(n.sipHostname=a.sipHostname??null),e.sipPort!==a.sipPort&&(n.sipPort=a.sipPort),Object.keys(n).length?{calling:n}:null}function WD(e,a){return e===null||a===null?e===a:e.length===a.length&&e.every((n,s)=>n===a[s])}function UD(e){const a=new Set,n=[];for(const s of e.split(/[\s,]+/)){const i=s.trim();!i||a.has(i)||(a.add(i),n.push(i))}return n}function h9(e,a){return a?null:UD(e)}function m9(e){const a=e.trim().toLowerCase();return a||null}function f9(e){const a=e.trim();if(a==="")return null;const n=Number(a);return Number.isInteger(n)?n:null}const VD=["iniciada_por_el_usuario","sin_tarifa","sin_pais","tarifa_cero"],KD=["pstn","whatsapp","web"];function dc(e){return e?.medium==="whatsapp"}const HD="misc";function QD(e){return e&&VD.includes(e)?`${HD}:whatsapp.callCost.motivo.${e}`:null}function GD(e,a){const n=a?.motivo??null,s=QD(n),i=typeof e=="number"&&Number.isFinite(e)?e:null;return!a&&i===null?{estado:"sin_costear",usd:null,motivo:null,claveDeMotivo:null}:i===null?{estado:"sin_cotizar",usd:null,motivo:n,claveDeMotivo:s}:i===0&&n?{estado:"cero_con_motivo",usd:0,motivo:n,claveDeMotivo:s}:{estado:"estimado",usd:i,motivo:n,claveDeMotivo:s}}
975function s1(e){return e?"≥ ≈":"≈"}const x9=["outbound","inbound"],g9=1,b9={min:1,max:60},i1=6,ZD=e=>({country:e.country,direction:e.direction,precio:e.usdPerMinute.toFixed(8),pulso:String(e.pulseSeconds),nota:e.note??"",updatedAt:e.updatedAt,esNueva:!1}),y9=()=>({country:"",direction:"outbound",precio:"",pulso:String(i1),nota:"",updatedAt:null,esNueva:!0}),dg=e=>`${e.country.trim().toUpperCase()}|${e.direction}`;function YD(e){return!!e.country.trim()&&!!e.direction&&e.precio.trim()!==""&&Number.isFinite(Number(e.precio))}function v9(e){return e.precio.trim()!==""&&Number(e.precio)===0&&!e.nota.trim()}function j9(e,a){const n=new Map(a.map(s=>[dg(s),ZD(s)]));return e.filter(s=>{if(!YD(s))return!1;const i=n.get(dg(s));return i?Number(i.precio)!==Number(s.precio)||Number(i.pulso)!==Number(s.pulso||i1)||(i.nota??"")!==(s.nota??""):!0})}function w9(e){return{tarifas:e.map(a=>{const n=a.pulso.trim()===""?null:Number(a.pulso),s=a.nota.trim();return{country:a.country.trim().toUpperCase(),direction:a.direction,usdPerMinute:Number(a.precio),...n!==null&&Number.isInteger(n)?{pulseSeconds:n}:{},...s?{note:s}:{}}})}}function k9(e){if(!e)return"sin_medir";if(e.divergenciaPct===null||e.divergenciaPct===void 0||!Number.isFinite(e.divergenciaPct))return"sin_dato";if(typeof e.fueraDeTolerancia=="boolean")return e.fueraDeTolerancia?"fuera":"dentro";const a=typeof e.toleranciaPct=="number"?e.toleranciaPct:10;return e.divergenciaPct>a?"fuera":"dentro"}function XD(e,a,n){return e?.habilitadas?n?{clase:"nada",motivo:"cargando"}:a?a.puedeLlamar===!0?{clase:"llamar"}:a.puedePedirPermiso===!0?{clase:"pedir_permiso"}:a.puedeLlamar===!1&&a.puedePedirPermiso===!1?{clase:"nada",motivo:"no_autoriza"}:{clase:"nada",motivo:"no_se_sabe"}:{clase:"nada",motivo:"no_se_sabe"}:{clase:"nada",motivo:"sin_llamadas"}}function JD(e,a=Date.now()){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?Math.max(0,Math.floor((n-a)/864e5)):null}const r1=new Set(["XX","T1","A1","A2"]);function eI(e){if(!e)return null;const a=e.trim().toUpperCase();if(!/^[A-Z]{2}$/.test(a))return null;if(r1.has(a))return a;try{return new Intl.DisplayNames([Te()],{type:"region"}).of(a)??a}catch{return a}}function tI(e){if(!e)return"";const a=e.trim().toUpperCase();return!/^[A-Z]{2}$/.test(a)||r1.has(a)?"":String.fromCodePoint(...[...a].map(n=>127462+n.charCodeAt(0)-65))}function o1(e){const a=eI(e);if(!a)return null;const n=tI(e);return n?`${n} ${a}`:a}const aI={ok:"chip chip-mint",warn:"chip chip-amber",bad:"chip chip-rose",neutral:"chip"};function No({call:e,status:a}){const{t:n}=M(["calls","format"]),s=e??{status:a??"created",endReason:null},{ns:i,key:r}=Ih(s),o=k0(s);return t.jsx("span",{className:aI[o],children:n(`${i}:${r}`,{defaultValue:s.endReason||s.status||""})})}const nI={success:"chip-mint",failure:"chip-rose",unknown:"bg-paper-line/60 text-ink-mute"},sI={positive:"chip-mint",neutral:"bg-paper-line/60 text-ink-mute",negative:"chip-rose"},iI=()=>t.jsx("span",{className:"text-ink-mute",children:"—"});function rI({result:e}){const{t:a}=M("calls"),n=e||"unknown",s=nI[n]??"bg-paper-line/60 text-ink-mute";return t.jsx("span",{className:`chip ${s}`,children:a(`analysis.goal.${n}`,{defaultValue:String(n)})})}function oI({value:e}){const{t:a}=M("calls");if(!e||e==="unknown")return t.jsx(iI,{});const n=sI[e]??"bg-paper-line/60 text-ink-mute";return t.jsx("span",{className:`chip ${n}`,children:a(`analysis.sentiment.${e}`,{defaultValue:e})})}function l1({call:e,compact:a=!1}){const{t:n}=M(["calls","misc"]),s=GD(e.waCallCostUsd,e.waCallCostMeta),i=s.motivo&&s.claveDeMotivo?n(s.claveDeMotivo,{defaultValue:s.motivo}):s.motivo??null;return t.jsxs("span",{className:"inline-flex flex-col items-end gap-0.5 min-w-0",children:[t.jsxs("span",{className:"font-mono tabular-nums",children:[s.estado==="sin_costear"&&t.jsx("span",{className:"text-ink-mute italic text-[11px]",children:n("calls:callCost.pendiente")}),s.estado==="sin_cotizar"&&t.jsx("span",{className:"text-ink-mute",children:"—"}),s.estado==="cero_con_motivo"&&t.jsx("span",{children:"$0.00"}),s.estado==="estimado"&&s.usd!==null&&t.jsxs("span",{children:["≈ $",s.usd.toFixed(4)," ",t.jsx("span",{className:"text-ink-mute font-normal",children:n("calls:meta.usd")})]})]}),i&&t.jsx("span",{className:"text-[10px] text-ink-mute text-right",children:i}),!a&&t.jsx("span",{className:"text-[10px] text-ink-mute text-right",children:n("calls:callCost.facturaDirecta")})]})}const lI=6;function c1(e){return e.toFixed(lI)}function vr(e,a=3){return String(parseFloat(e.toFixed(a)))}function ei(e){return e==null?0:typeof e=="number"?e:e.subtotal}function cI(e,a){const n=[];if(a.stt!==void 0)if(typeof a.stt=="object"&&a.stt!==null){const s=a.stt,i=s.unit==="minute"?"/min":`/${s.unit}`;n.push({label:he.t("calls:cost.stt"),providerModel:`${s.provider} · ${s.model}`,rateLabel:s.ratePerUnit!=null?`$${Number(s.ratePerUnit)}${i}`:null,subtotal:s.subtotal,extra:s.quantity>0?he.t("calls:cost.minAudio",{n:vr(s.quantity)}):null})}else n.push({label:he.t("calls:cost.stt"),providerModel:e.sttModel||"—",rateLabel:null,subtotal:typeof a.stt=="number"?a.stt:null});if(a.tts!==void 0)if(typeof a.tts=="object"&&a.tts!==null){const s=a.tts,i=s.unit==="1k-characters"?"/1K chars":`/${s.unit}`;n.push({label:he.t("calls:cost.tts"),providerModel:`${s.provider} · ${s.model}`,rateLabel:s.ratePerUnit!=null?`$${Number(s.ratePerUnit)}${i}`:null,subtotal:s.subtotal,extra:s.quantity>0?he.t("calls:cost.chars",{n:Math.round(s.quantity*1e3).toLocaleStr
975ing(Te())}):null})}else n.push({label:he.t("calls:cost.tts"),providerModel:e.ttsModel||"—",rateLabel:null,subtotal:typeof a.tts=="number"?a.tts:null});if(a.llm!==void 0)if(typeof a.llm=="object"&&a.llm!==null){const s=a.llm,i=s.promptTokens>0&&s.cachedTokens>0?Math.round(s.cachedTokens/s.promptTokens*100):null;let r=null;if(s.rates){const o=[];s.rates.inputPerMTokens!=null&&o.push(he.t("calls:cost.rateIn",{v:Number(s.rates.inputPerMTokens)})),s.rates.cacheWritePerMTokens!=null&&o.push(he.t("calls:cost.rateWrite",{v:Number(s.rates.cacheWritePerMTokens)})),s.rates.cachedInputPerMTokens!=null&&o.push(he.t("calls:cost.rateCache",{v:Number(s.rates.cachedInputPerMTokens)})),s.rates.outputPerMTokens!=null&&o.push(he.t("calls:cost.rateOut",{v:Number(s.rates.outputPerMTokens)})),r=o.length>0?he.t("calls:cost.ratePer1M",{parts:o.join(" · ")}):null}n.push({label:he.t("calls:cost.llm"),providerModel:`${s.provider} · ${s.model}`,rateLabel:r,subtotal:s.subtotal,extra:he.t("calls:cost.tokens",{p:s.promptTokens.toLocaleString(Te()),c:s.cachedTokens.toLocaleString(Te()),o:s.completionTokens.toLocaleString(Te())}),cachePct:i})}else n.push({label:he.t("calls:cost.llm"),providerModel:e.llmModel||"—",rateLabel:null,subtotal:typeof a.llm=="number"?a.llm:null});if(a.telephony&&typeof a.telephony=="object"){const s=a.telephony;n.push({label:he.t("calls:cost.telephony"),providerModel:`${s.provider} · ${s.model}`,rateLabel:s.ratePerUnit!=null?`$${Number(s.ratePerUnit)}/min`:null,subtotal:s.subtotal,extra:s.quantity>0?he.t("calls:cost.minBilled",{n:vr(s.quantity)}):null})}if(a.telephonyTransfer&&typeof a.telephonyTransfer=="object"){const s=a.telephonyTransfer;n.push({label:he.t("calls:cost.telephonyTransfer"),providerModel:`${s.provider} · ${s.model}`,rateLabel:s.ratePerUnit!=null?`$${Number(s.ratePerUnit)}/min`:null,subtotal:s.subtotal,extra:s.quantity>0?he.t("calls:cost.minLegDest",{n:vr(s.quantity)}):null})}if(a.compute&&typeof a.compute=="object"){const s=a.compute;n.push({label:he.t("calls:cost.compute"),providerModel:`${s.provider} · ${s.model}`,rateLabel:s.ratePerUnit!=null?`$${Number(s.ratePerUnit)}/min`:null,subtotal:s.subtotal,extra:s.quantity>0?he.t("calls:cost.minBilled",{n:vr(s.quantity)}):null})}return n}function Xd({label:e,value:a,sub:n}){return t.jsxs("div",{className:"card p-3 flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:e}),t.jsx("span",{className:"text-base font-bold text-ink font-mono tabular-nums leading-tight truncate",children:a}),n&&t.jsx("span",{className:"text-[10px] text-ink-mute font-mono",children:n})]})}function dI({row:e,durationMin:a}){const{t:n}=M("calls"),s=a&&e.subtotal!=null?e.subtotal/a:null;return t.jsx("div",{className:"py-2.5 border-b border-paper-line last:border-0",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"text-xs text-ink-mute",children:e.label}),t.jsx("span",{className:"text-[11px] font-mono text-ink-soft truncate",children:e.providerModel}),e.extra&&t.jsxs("span",{className:"text-[10px] text-ink-mute font-mono inline-flex items-center gap-1.5",children:[e.extra,e.cachePct!=null&&t.jsx("span",{className:"chip chip-mint text-[10px] px-1.5 py-0",children:n("cost.cacheChip",{pct:e.cachePct})})]})]}),t.jsxs("div",{className:"flex flex-col items-end gap-0.5 shrink-0",children:[e.rateLabel&&t.jsx("span",{className:"text-[10px] text-ink-mute font-mono",children:e.rateLabel}),t.jsx("span",{className:"text-xs font-mono text-ink font-medium",children:e.subtotal!==null?`$${c1(e.subtotal)}`:t.jsx("span",{className:"text-ink-mute italic text-[11px]",children:n("cost.pending")})}),s!==null&&t.jsx("span",{className:"text-[10px] text-ink-mute font-mono",children:n("cost.approxPerMin",{value:s.toFixed(4)})})]})]})})}function uI({addOn:e}){const{t:a}=M("calls"),n=e.promptTokens!=null||e.completionTokens!=null?a("cost.tokensPO",{p:(e.promptTokens??0).toLocaleString(Te()),o:(e.completionTokens??0).toLocaleStr
975ing(Te())}):null;return t.jsx("div",{className:"py-2.5 border-b border-paper-line last:border-0",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"text-xs text-ink-mute",children:a(`addon.${e.type}`,{defaultValue:e.type})}),t.jsxs("span",{className:"text-[11px] font-mono text-ink-soft truncate",children:[e.provider," · ",e.model]}),n&&t.jsx("span",{className:"text-[10px] text-ink-mute font-mono",children:n})]}),t.jsx("div",{className:"flex flex-col items-end gap-0.5 shrink-0",children:t.jsx("span",{className:"text-xs font-mono text-ink font-medium",children:e.subtotal!==null?`$${c1(e.subtotal)}`:t.jsx("span",{className:"text-ink-mute italic text-[11px]",children:a("cost.noRate")})})})]})})}function pI({call:e}){const{t:a}=M("calls"),n=e.costBreakdown??null,s=n?.addOns?.filter(Boolean)??[];if(e.costUsd==null&&!n)return t.jsxs("div",{className:"card p-6 flex flex-col items-center text-center gap-3",children:[t.jsx("div",{className:"size-12 rounded-full bg-paper-line/60 grid place-items-center",children:t.jsx(jc,{className:"size-5 text-ink-mute"})}),t.jsx("p",{className:"text-sm text-ink leading-relaxed max-w-sm",children:a("cost.emptyTitle")}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:a("cost.emptyDesc")})]});const i=n?cI(e,n):[],r=n?ei(n.stt)+ei(n.tts)+ei(n.llm)+ei(n.telephony)+ei(n.telephonyTransfer)+ei(n.compute):0,o=s.reduce((x,h)=>x+(typeof h.subtotal=="number"?h.subtotal:0),0),l=r+o,c=e.costUsd??n?.total??l,d=e.durationSeconds>0?e.durationSeconds/60:null,u=d?c/d:null,p=n!=null&&Math.abs(c-l)>1e-4,f=[...n?.warnings??[],...s.flatMap(x=>x.warnings??[])];return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[t.jsx(Xd,{label:a("cost.totalCost"),value:`$${c.toFixed(4)}`,sub:a("units.usd")}),t.jsx(Xd,{label:a("cost.duration"),value:e.durationSeconds>0?Ca(e.durationSeconds):"—",sub:d!=null?a("units.minValue",{value:vr(d)}):void 0}),t.jsx(Xd,{label:a("cost.average"),value:u!=null?`$${u.toFixed(4)}`:"—",sub:a("cost.perMinute")})]}),dc(e)&&t.jsxs("div",{className:"card px-4 py-3 flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"text-xs text-ink-mute",children:a("callCost.label")}),t.jsx("span",{className:"text-[10px] text-ink-mute",children:a("callCost.noSuma")})]}),t.jsx(l1,{call:e})]}),n?t.jsxs("div",{className:"card overflow-hidden",children:[i.length>0&&t.jsx("div",{className:"px-4 py-1 flex flex-col gap-0",children:i.map(x=>t.jsx(dI,{row:x,durationMin:d},x.label))}),s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-4 pt-3 pb-1 border-t border-paper-line bg-paper/40",children:t.jsx("span",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:a("cost.addOns")})}),t.jsx("div",{className:"px-4 py-1 flex flex-col gap-0 bg-paper/40",children:s.map((x,h)=>t.jsx(uI,{addOn:x},`${x.type}-${h}`))})]}),p&&t.jsx("div",{className:"px-4 py-2 border-t border-paper-line",children:t.jsx("p",{className:"text-[10px] text-ink-mute leading-snug",children:a("cost.totalsDiverge")})}),f.length>0&&t.jsx("div",{className:"px-4 py-2 bg-amber-50 border-t border-amber-100",children:f.map((x,h)=>t.jsx("p",{className:"text-[11px] text-amber-700 leading-snug",children:x},h))})]}):t.jsx("div",{className:"card p-4",children:t.jsx("p",{className:"text-sm text-ink-mute italic",children:a("cost.noBreakdown")})})]})}function Jd({label:e,value:a,sub:n}){return t.jsxs("div",{className:"card p-3 flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:e}),t.jsx("span",{className:"text-base font-bold text-ink font-mono tabular-nums leading-tight truncate",children:a}),n&&t.jsx("span",{className:"text-[10px] text-ink-mute leading-snug",children:n})]})}function xs({label:e,note:a,children:n}){return t.jsx("div",{className:"py-2.5 border-b border-paper-line last:border-0",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"text-xs text-ink-mute",children:e}),a&&t.jsx("span",{className:"text-[10px] text-ink-mute leading-snug",children:a})]}),t.jsx("div",{className:"shrink-0 text-xs text-ink font-mono text-right",children:n})]})})}function hI({call:e}){const{t:a}=M("calls"),n=e.billing??null;if(!n)return t.jsxs("div",{className:"card p-6 flex flex-col items-center text-center gap-3",children:[t.jsx("div",{className:"size-12 rounded-full bg-paper-line/60 grid place-items-center",children:t.jsx(co,{className:"size-5 text-ink-mute"})}),t.jsx("p",{className:"text-sm text-ink leading-relaxed max-w-sm",children:a("usage.emptyTitle")}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:a("usage.emptyDesc")})]});const s=(n.weightedSeconds/60).toFixed(1),i=n.billableSeconds>e.durationSeconds,r=n.overageSeconds>0,o=n.amountUsd!=null?Number(n.amountUsd):null;return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[t.jsx(Jd,{label:a("usage.planMinutes"),value:a("units.minValue",{value:s}),sub:a("usage.deductedFromPlan")}),t.jsx(Jd,{label:a("usage.billedDuration"),value:Ca(n.billableSeconds),sub:i?a("usage.minApplied"):void 0}),t.jsx(Jd,{label:a("usage.estCost"),value:o!=null?`$${o.toFixed(2)}`:"—",sub:o!=null?a("units.usd"):n.planCode?a("usage.planNoRate"):a("usage.noPlan")})]}),t.jsxs("div",{className:"card overflow-hidden",children:[t.jsx("div",{className:"px-4 pt-3 pb-1",children:t.jsx("span",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase",children:a("usage.detailTitle")})}),t.jsxs("div",{className:"px-4 py-1 flex flex-col gap-0",children:[t.jsx(xs,{label:a("usage.realDuration"),children:Ca(e.durationSeconds)}),i&&t.jsx(xs,{label:a("usage.minBillableApplied"),note:a("usage.minBillableNote",{s:n.minBillableSeconds}),children:t.jsx("span",{className:"chip chip-amber text-[11px]",children:a("usage.minChip",{s:n.minBillableSeconds})})}),t.jsx(xs,{label:a("usage.agentRate"),note:n.premium?a("usage.premiumNote"):void 0,children:n.premium?t.jsxs("span",{className:"chip chip-cta text-[11px] inline-flex items-center gap-1",children:[t.jsx(_t,{className:"size-3"}),a("usage.premiumChip",{mult:n.multiplier})]}):t.jsx("span",{className:"chip text-[11px]",children:a("usage.standardChip")})}),n.planCode&&t.jsx(xs,{label:a("usage.plan"),children:n.planCode.charAt(0).toUpperCase()+n.planCode.slice(1)}),n.planCode&&n.planRatePerMin!=null&&t.jsxs(xs,{label:a("usage.planRate"),children:["$",Number(n.planRatePerMin),"/min"]}),r&&t.jsx("div",{className:"py-2.5 -mx-4 px-4 bg-amber-50 border-b border-paper-line last:border-0",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"text-xs font-medium text-amber-700",children:a("usage.overage")}),t.jsx("span",{className:"text-[10px] text-amber-700 leading-snug",children:a("usage.overageNote")})]}),t.jsx("span",{className:"shrink-0 text-xs font-mono text-amber-700 text-right",children:a("usage.overageCalc",{min:(n.overageSeconds/60).toFixed(1),rate:Number(n.overageRatePerMin??0),total:Number(n.overageUsd).toFixed(2)})})]})}),!r&&n.planCode&&t.jsx(xs,{label:a("usage.cycleUsage"),children:t.jsx("span",{className:"chip chip-mint text-[11px]",children:a("usage.included")})}
975),(n.billableAddOns??[]).map(l=>t.jsx(xs,{label:l.type==="live_analysis"?a("usage.liveAnalysis"):l.type,note:l.type==="live_analysis"?a("usage.liveAnalysisNote"):void 0,children:t.jsxs("span",{className:"text-xs font-mono text-ink",children:["+$",Number(l.amountUsd).toFixed(2)]})},l.type))]})]})]})}function mI(e){const a=new Date(e);if(isNaN(a.getTime()))return he.t("format:dash");const n=String(a.getHours()).padStart(2,"0"),s=String(a.getMinutes()).padStart(2,"0"),i=String(a.getSeconds()).padStart(2,"0");return`${n}:${s}:${i}`}function fI(e){return he.t(`calls:kb.degraded.${e}`,{defaultValue:e})}function xI({call:e}){const{t:a}=M("calls"),{data:n,isLoading:s,error:i}=se({queryKey:["call-kb-retrieval",e.roomName],queryFn:async()=>{try{return(await T.get(`/knowledge-bases/calls/${encodeURIComponent(e.roomName)}/retrieval-logs`)).data}catch(o){const l=o?.response?.status;if(l===404||l===501)return[];throw o}},enabled:!!e.roomName,staleTime:3e4});if(s)return t.jsx("div",{className:"flex flex-col gap-2",children:[0,1].map(o=>t.jsx(ge,{w:"100%",h:56,r:10},o))});if(i)return t.jsx(le,{tone:"bad",children:a("kb.loadError")});const r=n??[];return r.length===0?t.jsx("div",{className:"card p-0",children:t.jsx(st,{mini:!0,icon:ua,title:a("kb.emptyTitle"),desc:a("kb.emptyDesc")})}):t.jsx("div",{className:"flex flex-col gap-2.5",children:r.map(o=>t.jsx(gI,{log:o},o.id))})}function gI({log:e}){const{t:a}=M("calls"),n=e.chunks&&e.chunks.length>0;return t.jsxs("details",{className:"card group",children:[t.jsxs("summary",{className:"cursor-pointer list-none p-3 select-none",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"text-[10px] font-mono text-ink-mute tabular-nums shrink-0",children:mI(e.createdAt)}),t.jsxs("span",{className:"text-xs text-ink break-words min-w-0 flex-1",children:["「",e.query,"」"]}),t.jsx("span",{className:"text-[10px] font-mono text-ink-mute tabular-nums shrink-0",children:a("kb.tookMs",{ms:e.tookMs})})]}),t.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[e.resultCount>0?t.jsx("span",{className:"chip chip-mint text-[11px]",children:a("kb.injected",{count:e.resultCount})}):t.jsx("span",{className:"chip bg-paper-line/60 text-ink-mute text-[11px]",children:a("kb.
975noResults")}),e.degraded&&t.jsx("span",{className:"chip chip-rose text-[11px]",title:a("kb.degradedTitle"),children:fI(e.degraded)}),e.cacheHit&&t.jsx("span",{className:"chip bg-paper-line/60 text-ink-mute text-[11px]",children:a("kb.cacheHit")}),e.embeddingMs!=null&&t.jsx("span",{className:"text-[10px] font-mono text-ink-mute tabular-nums",children:a("kb.embeddingMs",{ms:e.embeddingMs})})]})]}),n?t.jsx("div",{className:"px-3 pb-3 flex flex-col gap-2 border-t border-paper-line pt-2.5",children:e.chunks.map((s,i)=>t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-mono text-ink-mute",children:[t.jsxs("span",{className:"shrink-0",children:["#",i+1]}),t.jsx("span",{className:"text-ink truncate",children:s.docName}),s.distance!=null&&t.jsxs("span",{className:"shrink-0 tabular-nums",children:["· ",a("kb.distance",{value:s.distance.toFixed(2)})]})]}),t.jsx("p",{className:"mt-1 mb-0 text-[11px] font-mono text-ink-soft leading-relaxed whitespace-pre-wrap break-words line-clamp-3",children:s.preview})]},`${s.docId}-${i}`))}):t.jsx("div",{className:"px-3 pb-3 border-t border-paper-line pt-2.5",children:t.jsx("p",{className:"m-0 text-[11px] text-ink-mute italic",children:a("kb.
975noChunks")})})]})}const bI=new Set(["end_call"]),yI=2e3;function vI(e,a){if(!e?.length)return[];const n=a.endedAt?new Date(a.endedAt).getTime():NaN;return e.map(s=>{if(!bI.has(s.name)||!Number.isFinite(n)||!s.at)return s;const i=new Date(s.at).getTime();return!Number.isFinite(i)||i>=n?s:{...s,at:new Date(n).toISOString(),...n-i>=yI?{requestedAt:s.at}:{}}})}function jr({children:e}){return t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute uppercase mb-2",children:e})}const jI={success:"chip-mint",failure:"chip-rose",unknown:"bg-paper-line/60 text-ink-mute"},wI={positive:"chip-mint",neutral:"bg-paper-line/60 text-ink-mute",negative:"chip-rose",unknown:"bg-paper-line/60 text-ink-mute"};function kI(e){return e==null||e===""?"—":typeof e=="boolean"?e?he.t("calls:value.yes"):he.t("calls:value.no"):typeof e=="number"?t.jsx("span",{className:"tabular-nums",children:e}):typeof e=="object"?JSON.stringify(e):String(e)}const ug={bridged:"chip-mint",failed:"chip-rose"};function NI(e){return e?["caller_gone","voicemail","timeout","transfer_completed","caller_hangup"].includes(e)?he.t(`calls:transfer.reason.${e}`):he.t("calls:transfer.reason.default"):null}function SI({t:e}){const{t:a}=M("calls"),n=e?.type==="external",s=a(n?"transfer.rowExternal":"transfer.rowInternal"),i=n&&e?.state?ug[e.state]:null,r=n&&e?.state&&ug[e.state]?a(`transfer.state.${e.state}`):null,o=NI(e?.reason);return t.jsxs("div",{className:"py-2 border-b border-paper-line last:border-0",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"text-xs text-ink",children:s}),e?.at&&t.jsx("span",{className:"text-[11px] text-ink-mute font-mono shrink-0",children:Be(e.at)})]}),t.jsxs("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:[n&&e?.mode&&t.jsx("span",{className:"chip bg-paper-line/60 text-ink-mute text-[11px]",children:a(`transfer.mode.${e.mode}`,{defaultValue:e.mode})}),r&&i&&t.jsx("span",{className:`chip text-[11px] ${i}`,children:r}),o&&t.jsxs("span",{className:"text-[11px] text-ink-mute",children:["· ",o]})]})]})}function CI({value:e}){const{t:a}=M("calls"),[n,s]=m.useState(!1);return t.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard?.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),1500)},()=>{})},className:"inline-flex items-center gap-1 font-mono text-xs text-ink hover:text-brand-700 transition-colors",title:a("detail.copy"),children:[t.jsx("span",{className:"truncate max-w-[180px]",children:e}),n?t.jsx(ct,{className:"size-3 text-mint-600 shrink-0"}):t.jsx(bn,{className:"size-3 text-ink-mute shrink-0"})]})}function Oa({label:e,children:a}){return t.jsxs("div",{className:"flex items-center justify-between gap-4 py-1",children:[t.jsx("span",{className:"text-[11px] text-ink-mute shrink-0",children:e}),t.jsx("span",{className:"text-xs text-ink text-right min-w-0",children:a})]})}function _I({call:e,orgId:a}){const{t:n}=M("calls"),s=e.recordingStatus??"none",i=a?`?organizationId=${encodeURIComponent(a)}`:"",r=s==="recording"||s==="processing"||s==="ready",{data:o,isLoading:l}=se({queryKey:["recording",e.id,a??"mine"],queryFn:async()=>(await T.get(`/calls/${e.id}/recording${i}`)).data,enabled:r,refetchInterval:f=>f.state.data&&f.state.data.status==="processing"?8e3:!1,staleTime:3e4}),c=o?.status??s,d=o?.status==="ready"?o.url:void 0,u=o?.durationMs??e.recordingDurationMs??null,p=Ca(u!=null?Math.round(u/1e3):e.durationSeconds);return c==="none"||c==="failed"||!r&&!l?t.jsxs("div",{className:"card p-3 flex items-center gap-3 opacity-90",children:[t.jsx("div",{className:"shrink-0 size-9 rounded-full bg-paper-line/70 grid place-items-center text-ink-mute",children:t.jsx(Ap,{className:"size-4"})}),t.jsx("div",{className:"flex-1 min-w-0",children:t.jsx("p",{className:"text-xs text-ink-mute",children:n("recording.unavailable")})})]}):c==="recording"||c==="processing"||l&&!d?t.jsxs("div",{className:"card p-3 flex items-center gap-3 opacity-90",children:[t.jsx("div",{className:"shrink-0 size-9 rounded-full bg-paper-line/70 grid place-items-center text-ink-mute",children:t.jsx(je,{className:"size-4 animate-spin"})}),t.jsx("div",{className:"flex-1 min-w-0",children:t.jsx("p",{className:"text-xs text-ink-mute",children:n(c==="recording"?"recording.recording":"recording.processing")})}),t.jsx("span",{className:"text-[10px] font-mono text-ink-mute",children:p})]}):t.jsx(EI,{url:d,downloadUrl:o?.status==="ready"?o.downloadUrl:void 0,filename:o?.status==="ready"?o.filename:void 0,totalLabel:p,callId:e.id})}const pg=Array.from({length:56},(e,a)=>.3+.7*Math.abs(Math.sin(a*1.7)*Math.cos(a*.55)));function EI({url:e,downloadUrl:a,filename:n,totalLabel:s,callId:i}){const{t:r}=M("calls"),o=m.useRef(null),[l,c]=m.useState(!1),[d,u]=m.useState(0),[p,f]=m.useState(0),x=p>0?Math.min(1,d/p):0,h=()=>{const g=o.current;g&&(g.paused?g.play():g.pause())},b=g=>{const v=o.current;if(!v||!p)return;const y=g.currentTarget.getBoundingClientRect(),k=Math.min(1,Math.max(0,(g.clientX-y.left)/y.width));v.currentTime=k*p,u(v.currentTime)};return t.jsxs("div",{className:"card p-3",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("button",{type:"button",onClick:h,className:"shrink-0 size-10 rounded-full grid place-items-center text-white hover:opacity-90 transition-opacity",style:{background:"var(--cia-brand-500)"},"aria-label":r(l?"recording.pause":"recording.play"),children:l?t.jsx(Nc,{className:"size-4"}):t.jsx(rn,{className:"size-4 translate-x-px"})}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{onClick:b,className:"flex items-center gap-[2px] h-8 cursor-pointer","aria-label":r("recording.progress"),children:pg.map((g,v)=>t.jsx("span",{style:{flex:1,height:`${Math.round(g*100)}%`,borderRadius:2,alignSelf:"center",background:v/pg.length<=x?"var(--cia-brand-500)":"var(--cia-border)",transition:"background-color 80ms linear"}},v))}),t.jsxs("div",{className:"flex items-center justify-between mt-1",children:[t.jsx("span",{className:"text-[10px] font-mono text-ink-mute tabular-nums",children:Ca(Math.floor(d))}),t.jsx("span",{className:"text-[10px] font-mono text-ink-mute tabular-nums",children:s})]})]}),t.jsx("a",{href:a??e,download:n??`${r("recording.filename")}-${i}.ogg`,className:"shrink-0 p-2 rounded-lg text-ink-mute hover:text-brand-600 hover:bg-paper-line/60 transition-colors",title:r("recording.download"),"aria-label":r("recording.download"),children:t.jsx(Tn,{className:"size-4"})})]}),t.jsx("audio",{ref:o,src:e,preload:"none",onPlay:()=>c(!0),onPause:()=>c(!1),onEnded:()=>c(!1),onTimeUpdate:g=>u(g.currentTarget.currentTime),onLoadedMetadata:g=>f(g.currentTarget.duration||0)})]})}function gs({label:e,children:a}){return t.jsxs("div",{className:"flex items-center justify-between gap-3 py-2 border-b border-paper-line last:border-0",children:[t.jsx("span",{className:"text-xs text-ink-mute shrink-0",children:e}),t.jsx("span",{className:"text-xs text-ink text-right",children:a})]})}function AI({call:e}){const{t:a}=M("calls"),n=e.analysis?.success?.result,s=e.analysis?.sentiment?.value,i=e.analysis?.intent?.value;return t.jsxs("section",{children:[t.jsx(jr,{children:a("analysisEn.title")}),t.jsxs("div",{className:"card px-4 py-1",children:[t.jsx(gs,{label:a("analysisEn.callSuccessful"),children:t.jsx("span",{className:`chip ${jI[n||"unknown"]??"bg-paper-line/60 text-ink-mute"}`,children:a(`analysis.goal.${n||"unknown"}`,{defaultValue:String(n??"")})})}),t.jsx(gs,{label:a("analysisEn.callStatus"),children:t.jsx(No,{call:e})}),t.jsx(gs,{label:a("analysisEn.userSentiment"),children:s?t.jsx("span",{className:`chip ${wI[s]??"bg-paper-line/60 text-ink-mute"}`,children:a(`analysis.sentiment.${s}`,{defaultValue:s})}):t.jsx("span",{className:"text-ink-mute",children:"—"})}
975),t.jsx(gs,{label:a("analysisEn.disconnectReason"),children:t.jsx("span",{className:"font-mono",children:a_(e.endReason)})}),e.closeReason&&t.jsx(gs,{label:a("analysisEn.closeReason"),children:t.jsx("span",{children:e.closeReason})}),t.jsx(gs,{label:a("analysisEn.e2eLatency"),children:t.jsx("span",{className:"font-mono tabular-nums",children:e.avgLatencyMs!=null?`${e.avgLatencyMs}ms`:"—"})}),t.jsx(gs,{label:a("analysisEn.userIntent"),children:i?t.jsx("span",{className:"text-right",title:i,children:i}):t.jsx("span",{className:"text-ink-mute",children:"—"})})]})]})}const RI={call_started:"text-brand-600",call_ended:"text-ink-mute",turn_latency:"text-ink-soft",llm_input_tokens:"text-ink-soft",tool_invocation:"text-brand-700",tool_result:"text-mint-600",transfer:"text-amber-700",voicemail:"text-amber-700",webhook_triggered:"text-ink-soft",kb_search:"text-brand-600",call_answered:"text-brand-600",greeting_started:"text-brand-600",stt_finalize_forced:"text-ink-soft",agent_false_interruption:"text-ink-soft",bargein:"text-ink-mute"};function d1(e){return e.type==="bargein"&&e.data?.kind==="cut"}function TI(e){return d1(e)?"text-amber-700":RI[e.type]??"text-ink-mute"}function MI(e){return e.type==="bargein"&&!d1(e)?"text-ink-mute":"text-ink-soft"}function PI(e){const a=new Date(e);if(isNaN(a.getTime()))return"—";const n=String(a.getHours()).padStart(2,"0"),s=String(a.getMinutes()).padStart(2,"0"),i=String(a.getSeconds()).padStart(2,"0"),r=String(a.getMilliseconds()).padStart(3,"0");return`${n}:${s}:${i}.${r}`}function zI({events:e}){const{t:a}=M("calls");if(!e||e.length===0)return t.jsx("p",{className:"text-sm text-ink-mute italic",children:a("logs.empty")});const n=[...e].sort((s,i)=>new Date(s.at).getTime()-new Date(i.at).getTime());return t.jsx("div",{className:"card p-3 bg-paper max-h-[420px] overflow-y-auto cia-scroll",children:t.jsx("div",{className:"font-mono text-[11px] leading-relaxed",children:n.map((s,i)=>t.jsxs("div",{className:"flex gap-2 py-1 border-b border-paper-line/60 last:border-0",children:[t.jsx("span",{className:"text-ink-mute shrink-0 tabular-nums",children:PI(s.at)}),t.jsx("span",{className:os("shrink-0",TI(s)),children:s.type}),t.jsx("span",{className:os("break-all",MI(s)),children:s.message})]},i))})})}function hg({data:e}){const{t:a}=M("calls"),n=Object.entries(e);return n.length===0?t.jsx("p",{className:"text-sm text-ink-mute italic",children:a("data.noVars")}):t.jsx("table",{className:"w-full text-xs",children:t.jsx("tbody",{children:n.map(([s,i])=>t.jsxs("tr",{className:"border-b border-paper-line last:border-0",children:[t.jsx("td",{className:"py-1.5 pr-4 font-mono text-ink-mute align-top whitespace-nowrap",children:s}),t.jsx("td",{className:"py-1.5 text-ink break-words font-mono",children:kI(i)})]},s))})})}function DI({callId:e,onClose:a,withCost:n=!1,orgId:s}){const{t:i}=M("calls"),o=Pe(y=>y.user)?.role==="superadmin",l=n&&o,[c,d]=m.useState("data"),[u,p]=m.useState(!1),f=m.useRef(null),x=s?`?organizationId=${encodeURIComponent(s)}`:"",{data:h,isLoading:b}=se({queryKey:["call",e,s??"mine"],queryFn:async()=>(await T.get(`/calls/${e}${x}`)).data,enabled:!!e});if(m.useEffect(()=>{if(!e)return;const y=k=>{k.key==="Escape"&&a()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[e,a]),m.useEffect(()=>{d("data"),p(!1)},[e]),!e)return null;const g=[{id:"data",label:i("tabs.data"),icon:Jb},...h?.billing?[{id:"usage",label:i("tabs.usage"),icon:co}]:[],...l?[{id:"cost",label:i("tabs.cost"),icon:jc}]:[],...h?.events?.some(y=>y.type==="kb_search")?[{id:"kb",label:i("tabs.kb"),icon:ua}]:[],{id:"logs",label:i("tabs.logs"),icon:Qr},...l?[{id:"pcap",label:i("tabs.pcap"),icon:Tu}]:[]],v=(h?.llmPromptTokens||0)+(h?.llmCompletionTokens||0);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black/20 z-40 lg:hidden",onClick:a,"aria-hidden":"true"}),t.jsxs("aside",{className:"fixed inset-y-0 right-0 z-50 w-full max-w-[520px] lg:static lg:inset-auto lg:z-auto lg:w-[440px] lg:max-w-none lg:shrink-0 bg-paper-card border-l border-paper-line overflow-y-auto cia-scroll flex flex-col",children:[t.jsxs("div",{className:"sticky top-0 bg-paper-card border-b border-paper-line px-5 py-3 flex items-center justify-between gap-3 z-10",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute",children:i("detail.eyebrow")}),t.jsx("h2",{className:"text-base font-semibold text-ink truncate",children:b||!h?i("detail.loading"):h.agent?.name||"—"})]}),t.jsx("button",{onClick:a,className:"shrink-0 p-1.5 rounded-lg hover:bg-paper text-ink-mute hover:text-ink transition-colors","aria-label":i("common.close"),children:t.jsx(nt,{className:"size-5"})})]}),b&&t.jsx("div",{className:"flex-1 grid place-items-center text-sm text-ink-mute",children:i("detail.loadingDetail")}),!b&&h&&t.jsxs("div",{className:"flex flex-col gap-4 p-5",children:[t.jsx("section",{children:t.jsxs("div",{className:"card p-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("span",{className:"text-sm font-semibold text-ink truncate",children:Be(h.startedAt||h.createdAt)}),t.jsxs("span",{className:"chip bg-paper-line/60 text-ink-mute text-[11px]",children:[h.direction==="web"?i("dir.web"):dc(h)?i("medium.whatsapp"):i("detail.callType")," ·"," ",i(`dir.${h.direction}`,{defaultValue:h.direction})]})]}),t.jsx(No,{call:h})]}),t.jsxs("div",{className:"divide-y divide-paper-line/70",children:[t.jsx(Oa,{label:i("meta.callId"),children:t.jsx(CI,{value:h.id})}),h.direction==="web"?t.jsxs(t.Fragment,{children:[t.jsx(Oa,{label:i("meta.session"),children:t.jsx("span",{className:"font-mono",children:i("meta.browserWebrtc")})}),(h.clientCountry||h.clientIp)&&t.jsx(Oa,{label:i("meta.visitorOrigin"),children:t.jsxs("span",{className:"font-mono",title:i("meta.ipMasked"),children:[o1(h.clientCountry)??i("meta.countryUnknown"),h.clientIp?` · ${h.clientIp}`:""]})}),h.clientUserAgent&&t.jsx(Oa,{label:i("meta.visitorDevice"),children:t.jsx("span",{className:"text-[11px] break-all",children:h.clientUserAgent})})]}):t.jsxs(t.Fragment,{children:[t.jsx(Oa,{label:i("meta.origin"),children:h.metadata?.rotatingDid&&!h.callerNumber?t.jsx("span",{children:i("meta.rotatingOrigin")}):t.jsx("span",{className:"font-mono",children:As(h.callerNumber)})}),t.jsx(Oa,{label:i("meta.destination"),children:t.jsx("span",{className:"font-mono",children:As(h.calleeNumber)})})]}),t.jsx(Oa,{label:i("meta.period"),children:t.jsxs("span",{className:"font-mono text-[11px]",children:[Be(h.startedAt)," → ",Be(h.endedAt)]})}),t.jsx(Oa,{label:i("meta.duration"),children:t.jsx("span",{className:"font-mono",children:Ca(h.durationSeconds)})}),dc(h)&&t.jsx(Oa,{label:i("callCost.label"),children:t.jsx(l1,{call:h})}),h.billing&&t.jsx(Oa,{label:i("meta.usage"),children:t.jsxs("button",{type:"button",onClick:()=>{d("usage"),f.current?.scrollIntoView({behavior:"smooth"})},className:"inline-flex items-center gap-1 font-mono font-semibold text-ink hover:text-brand-700 transition-colors",title:i("meta.usageTitle"),children:[(h.billing.weightedSeconds/60).toFixed(1)," ",t.jsx("span",{className:"text-ink-mute font-normal",children:i("meta.min")}),h.billing.premium&&t.jsxs("span",{className:"chip chip-cta text-[10px] px-1.5 py-0",children:["×",h.billing.multiplier]}),t.jsx(ca,{className:"size-3 text-ink-mute"})]})}),l&&h.costUsd!=null&&t.jsx(Oa,{label:i("meta.totalCost"),children:t.jsxs("button",{type:"button",onClick:()=>{d("cost"),f.current?.scrollIntoView({behavior:"smooth"})},className:"inline-flex items-center gap-1 font-mono font-semibold text-ink hover:text-brand-700 transition-colors",title:i("meta.costTitle"),children:["$",h.costUsd.toFixed(4)," ",t.jsx("span",{className:"text-ink-mute font-normal",children:i("meta.usd")}),t.jsx(ca,{className:"size-3 text-ink-mute"})]})}),l&&v>0&&t.jsx(Oa,{label:i("meta.llmTokens"),children:t.jsxs("span",{className:"font-mono tabular-nums",children:[v.toLocaleStr
975ing(Te()),h.llmCachedTokens?t.jsxs("span",{className:"text-ink-mute font-normal",children:[" ",i("meta.cacheSuffix",{n:h.llmCachedTokens.toLocaleString(Te())})]}):null]})})]}),t.jsx("div",{className:"mt-3",children:t.jsx(_I,{call:h,orgId:s})})]})}),t.jsx(AI,{call:h}),t.jsxs("section",{children:[t.jsx(jr,{children:i("summary.title")}),t.jsx("div",{className:"card p-4",children:h.summary?t.jsx("p",{className:"text-sm text-ink leading-relaxed",children:h.summary}):t.jsx("p",{className:"text-sm text-ink-mute italic",children:i("summary.empty")})})]}),t.jsxs("button",{type:"button",onClick:()=>p(!0),className:"w-full flex items-center justify-between gap-3 card p-4 hover:border-brand-300 transition-colors text-left",children:[t.jsxs("span",{className:"flex items-center gap-2.5 min-w-0",children:[t.jsx("span",{className:"size-9 rounded-lg bg-brand-50 text-brand-600 grid place-items-center shrink-0",children:t.jsx(sn,{className:"size-4"})}),t.jsxs("span",{className:"flex flex-col min-w-0",children:[t.jsx("span",{className:"text-sm font-medium text-ink",children:i("transcript.open")}),t.jsx("span",{className:"text-xs text-ink-mute",children:h.transcript?.length?i("transcript.messages",{count:h.transcript.length}):i("transcript.none")})]})]}),t.jsx(ca,{className:"size-4 text-ink-mute shrink-0"})]}),t.jsxs("section",{ref:f,children:[t.jsx("div",{className:"flex gap-1 mb-4",children:g.map(y=>{const k=y.icon;return t.jsxs("button",{onClick:()=>d(y.id),title:y.label,className:os("flex-1 min-w-0 flex items-center justify-center gap-1.5 px-1.5 h-8 rounded-lg text-[12.5px] transition-colors",c===y.id?"bg-brand-100 text-brand-700 font-medium":"text-ink-mute hover:text-ink hover:bg-paper-line/50"),children:[t.jsx(k,{className:"size-4 shrink-0"}),t.jsx("span",{className:"truncate",children:y.label})]},y.id)})}),c==="usage"&&h.billing&&t.jsx(hI,{call:h}),c==="cost"&&l&&t.jsx(pI,{call:h}),c==="data"&&t.jsxs("div",{className:"flex flex-col gap-5",children:[t.jsxs("div",{children:[t.jsx(jr,{children:i("data.inputTitle")}),t.jsx("div",{className:"card p-4",children:h.inputVariables&&Object.keys(h.inputVariables).length>0?t.jsx(hg,{data:h.inputVariables}):t.jsx("p",{className:"text-sm text-ink-mute italic",children:i("data.noInput")})})]}),t.jsxs("div",{children:[t.jsx(jr,{children:i("data.outputTitle")}),t.jsx("div",{className:"card p-4",children:h.extractedFields&&Object.keys(h.extractedFields).length>0?t.jsx(hg,{data:h.extractedFields}):t.jsx("p",{className:"text-sm text-ink-mute italic",children:i("summary.empty")})})]}),Array.isArray(h.metadata?.transfers)&&h.metadata.transfers.length>0&&t.jsxs("div",{children:[t.jsx(jr,{children:i("data.transfers")}),t.jsx("div",{className:"card p-4",children:h.metadata.transfers.map((y,k)=>t.jsx(SI,{t:y},k))})]}),h.metadata&&Object.keys(h.metadata).length>0&&t.jsxs("details",{className:"group",children:[t.jsxs("summary",{className:"cursor-pointer text-[10px] font-mono tracking-wider text-ink-mute uppercase mb-2 list-none flex items-center gap-1 select-none",children:[t.jsx("span",{className:"group-open:rotate-90 transition-transform inline-block",children:"▶"}),i("data.rawMetadata")]}),t.jsx("div",{className:"card p-3 mt-2",children:t.jsx("pre",{className:"text-[11px] font-mono text-ink-soft whitespace-pre-wrap break-all leading-relaxed",children:JSON.stringify(h.metadata,null,2)})})]})]}),c==="kb"&&t.jsx(xI,{call:h}),c==="logs"&&t.jsx(zI,{events:h.events??[]}),c==="pcap"&&l&&t.jsxs("div",{className:"card p-6 flex flex-col items-center text-center gap-3",children:[t.jsx("div",{className:"size-12 rounded-full bg-paper-line/60 grid place-items-center",children:t.jsx(Tu,{className:"size-5 text-ink-mute"})}),t.jsx("p",{className:"text-sm text-ink leading-relaxed max-w-sm",children:i("pcap.desc")}),t.jsxs("button",{type:"button",disabled:!0,className:"btn btn-outline h-9 opacity-60 cursor-not-allowed inline-flex items-center gap-2",title:i("pcap.soonTitle"),children:[t.jsx(yi,{className:"size-4"}),i("pcap.download")]}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:i("pcap.soon")})]})]})]})]}),u&&t.jsx(ot,{open:!0,onClose:()=>p(!1),title:i("transcript.modalTitle"),maxWidth:720,children:h?.transcript&&h.transcript.length>0?t.jsx("div",{className:"cia-scroll",style:{maxHeight:"min(70vh, 620px)",overflowY:"auto",marginRight:-6,paddingRight:6},children:t.jsx(vo,{messages:h.transcript,toolCalls:vI(h.toolCalls,{endedAt:h.endedAt}),toolLabel:a1,agentName:h.agent?.name||i("common.agentFallback"),userLabel:i("common.client")}
975)}):t.jsx("p",{className:"text-sm text-ink-mute italic",children:i("transcript.noneAvailable")})})]})}function u1(e){return e.status==="queued"||e.status==="running"}function ti(e){return e?{params:{organizationId:e}}:{}}const ys={preview:(e,a)=>T.post("/calls/export/preview",e,ti(a)).then(n=>n.data),downloadNow:async(e,a)=>{const n=await T.post("/calls/export",e,{params:{format:a.format,...a.organizationId?{organizationId:a.organizationId}:{}},responseType:"blob"});ao(n.data,ac(n,`llamadas.${a.format}`))},create:(e,a,n)=>T.post("/calls/exports",{...e,...a},ti(n)).then(s=>s.data),list:e=>T.get("/calls/exports",ti(e)).then(a=>a.data),get:(e,a)=>T.get(`/calls/exports/${e}`,ti(a)).then(n=>n.data),download:async(e,a)=>{const{data:n}=await T.get(`/calls/exports/${e}/download`,ti(a));return CT(n.url),n},remove:(e,a)=>T.delete(`/calls/exports/${e}`,ti(a)).then(n=>n.data)};function wr(e){const a=Number(e);if(!Number.isFinite(a)||a<=0)return"0 KB";const n=["B","KB","MB","GB","TB"];let s=0,i=a;for(;i>=1024&&s<n.length-1;)i/=1024,s++;const r=i<10&&s>1?2:i<100&&s>1?1:0;return`${i.toFixed(r)} ${n[s]}`}function II({open:e,onClose:a,kind:n,selection:s,organizationId:i,scopeLabel:r}){const{t:o}=M("calls"),l=xe(),[c,d]=m.useState("csv"),[u,p]=m.useState(!0),[f,x]=m.useState(!0),h=se({queryKey:["callExport","preview",i??"mine",JSON.stringify(s)],queryFn:()=>ys.preview(s,i),enabled:e&&!!s,staleTime:15e3}),b=h.data,g=se({queryKey:["callExport","list",i??"mine"],queryFn:()=>ys.list(i),enabled:e,refetchInterval:j=>j.state.data?.some(u1)?2500:!1}),[v]=m.useState(()=>new Set);m.useEffect(()=>{for(const j of g.data??[])j.status==="ready"&&!v.has(j.id)&&(v.add(j.id),J({title:o("bulkExport.readyToast"),desc:o("bulkExport.readyToastDesc",{filename:j.filename??"",size:wr(j.bytes)}),tone:"ok",duration:0,action:{label:o("bulkExport.downloadNow"),onClick:()=>void ys.download(j.id,i)}}))},[g.data,v,o,i]);const y=oe({mutationFn:async()=>s?n==="data"&&b?.syncAllowed&&(c==="csv"||b.xlsxAllowed)?(await ys.downloadNow(s,{format:c,organizationId:i}),null):ys.create(s,n==="audio"?{kind:"audio",includeTranscript:u,subfoldersByDate:f}:{kind:"data",format:c,includeTranscript:u},i):null,onSuccess:j=>{j?(J({title:o("bulkExport.queued"),tone:"info"}),l.invalidateQueries({queryKey:["callExport","list"]})):a()},onError:j=>{const C=j?.response?.data?.code;J({title:C&&o(`bulkExport.error.${C}`,{defaultValue:""})?o(`bulkExport.error.${C}`):j?.response?.data?.message??o("bulkExport.error.generic"),tone:"bad"})}}),k=oe({mutationFn:j=>ys.remove(j,i),onSuccess:()=>void l.invalidateQueries({queryKey:["callExport","list"]})}),w=m.useMemo(()=>b?b.rows===0?o("bulkExport.blocked.noRows"):n==="audio"?b.audioBlockedBy==="no_recordings"?o("bulkExport.blocked.noRecordings"):b.audioBlockedBy==="files"?o("bulkExport.blocked.files",{count:b.withRecording,max:b.limits.maxAudioFiles}):b.audioBlockedBy==="bytes"?o("bulkExport.blocked.bytes",{size:wr(b.recordingBytes),max:wr(b.limits.maxAudioBytes)}):null:c==="xlsx"&&!b.xlsxAllowed?o("bulkExport.blocked.xlsx",{count:b.rows,max:b.limits.maxXlsxRows}):null:null,[b,n,c,o]);return t.jsxs(ot,{open:e,onClose:a,title:o(n==="audio"?"bulkExport.titleAudio":"bulkExport.title"),eyebrow:r,maxWidth:560,footer:t.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[t.jsx("button",{className:"cia-btn cia-btn-ghost",onClick:a,children:o("common.cancel",{defaultValue:"Cancelar"})}),t.jsx("button",{className:"cia-btn cia-btn-cta",disabled:!b||!!w||y.isPending,onClick:()=>y.mutate(),children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(je,{className:"size-4 animate-spin"})," ",o("bulkExport.generating")]}):t.jsxs(t.Fragment,{children:[t.jsx(Tn,{className:"size-4"})," ",n==="data"&&b?.syncAllowed?o("bulkExport.download"):o("bulkExport.generate")]})})]}),children:[h.isLoading||!b?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"var(--cia-text-3)",fontSize:13},"aria-live":"polite",children:[t.jsx(je,{className:"size-4 animate-spin"})," ",o("bulkExport.calculating")]}):t.jsxs("div",{style:{display:"grid",gap:6,marginBottom:14},children:[t.jsx("div",{style:{fontSize:20,fontWeight:650,color:"var(--cia-text)"},children:o("bulkExport.rows",{count:b.rows})}),n==="audio"&&t.jsxs("div",{style:{fontSize:13,color:"var(--cia-text-2)"},children:[o("bulkExport.recordings",{count:b.withRecording})," ·"," ",o("bulkExport.size",{size:wr(b.recordingBytes)})]}),b.firstAt&&b.lastAt&&t.jsx("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:o("bulkExport.range",{from:Be(b.firstAt),to:Be(b.lastAt)}
975)})]}),w&&t.jsx("div",{style:{marginBottom:14},children:t.jsx(le,{tone:"warn",children:w})}),n==="data"?t.jsxs("div",{style:{display:"grid",gap:10,marginBottom:8},children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"var(--cia-text-3)"},children:o("bulkExport.format")}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsxs("button",{className:`cia-btn cia-btn-sm ${c==="csv"?"cia-btn-cta":"cia-btn-outline"}`,onClick:()=>d("csv"),children:[t.jsx(_n,{className:"size-4"})," ",o("bulkExport.formatCsv")]}),t.jsxs("button",{className:`cia-btn cia-btn-sm ${c==="xlsx"?"cia-btn-cta":"cia-btn-outline"}`,onClick:()=>d("xlsx"),children:[t.jsx(Eu,{className:"size-4"})," ",o("bulkExport.formatXlsx",{max:b?.limits.maxXlsxRows??5e4})]})]}),t.jsx(mn,{checked:u,onChange:p,label:o("bulkExport.includeTranscript"),description:o("bulkExport.includeTranscriptHint")})]}):t.jsxs("div",{style:{display:"grid",gap:10,marginBottom:8},children:[t.jsx(mn,{checked:f,onChange:x,label:o("bulkExport.subfoldersByDate"),description:o("bulkExport.subfoldersHint")}),t.jsxs("div",{style:{fontSize:12,color:"var(--cia-text-3)",lineHeight:1.5},children:[t.jsx(Ru,{className:"size-3.5",style:{display:"inline",marginRight:6}}),o("bulkExport.zipContents")]})]}),(g.data?.length??0)>0&&t.jsxs("div",{style:{marginTop:18,borderTop:"1px solid var(--cia-border)",paddingTop:14},children:[t.jsx("div",{style:{fontSize:12,fontWeight:600,color:"var(--cia-text-3)",marginBottom:10},children:o("bulkExport.recent")}),t.jsx("div",{style:{display:"grid",gap:10},children:g.data.slice(0,5).map(j=>t.jsx(LI,{job:j,organizationId:i,onRemove:()=>k.mutate(j.id)},j.id))})]})]})}function LI({job:e,organizationId:a,onRemove:n}){const{t:s}=M("calls"),i=u1(e);return t.jsxs("div",{style:{display:"grid",gap:6},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontSize:13,color:"var(--cia-text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.filename??`${e.kind}.${e.format}`}),t.jsx("span",{className:`chip ${e.status==="failed"?"chip-rose":e.status==="ready"?"chip-mint":""}`,children:s(`bulkExport.status.${e.status}`)}),e.status==="ready"&&t.jsx("button",{className:"cia-btn cia-btn-sm cia-btn-outline",onClick:()=>void ys.download(e.id,a),title:s("bulkExport.download"),children:t.jsx(Tn,{className:"size-4"})}),t.jsx("button",{className:"cia-btn cia-btn-sm cia-btn-ghost",onClick:n,title:s("bulkExport.remove"),"aria-label":s("bulkExport.remove"),children:t.jsx(mt,{className:"size-4"})})]}),i&&t.jsx(qu,{value:e.progressPct,indeterminate:e.progressPct<=1,showValue:!0}),e.status==="failed"&&e.errorCode&&t.jsx("div",{style:{fontSize:12,color:"var(--cia-rose-600, #b4232a)"},children:s(`bulkExport.error.${e.errorCode}`,{defaultValue:s("bulkExport.error.unknown")})}),e.status==="ready"&&!!e.missingCount&&t.jsxs("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:[s("bulkExport.missing",{count:e.missingCount})," —"," ",s("bulkExport.missingHint")]}),e.status==="ready"&&e.expiresAt&&t.jsxs("div",{style:{fontSize:11,color:"var(--cia-text-3)"},children:[s("bulkExport.expiresIn",{date:Be(e.expiresAt)})," ·"," ",wr(e.bytes)]})]})}function eu(){return{picked:new Set,allMatching:!1,excluded:new Set}}function bp(e,a){return e.allMatching?!e.excluded.has(a):e.picked.has(a)}function FI(e,a){return e.allMatching?Math.max(0,a-e.excluded.size):e.picked.size}function p1(e,a,n){if(e.allMatching){const i=new Set(e.excluded);return n?i.delete(a):i.add(a),{...e,excluded:i}}const s=new Set(e.picked);return n?s.add(a):s.delete(a),{...e,picked:s}}function h1(e,a,n){let s=e;for(const i of a)s=p1(s,i,n);return s}function OI(e,a,n){return h1(e,a,n)}function $I(e,a){if(a.length===0)return{checked:!1,indeterminate:!1};let n=0;for(const s of a)bp(e,s)&&n++;return{checked:n===a.length,indeterminate:n>0&&n<a.length}}function qI(){return{picked:new Set,allMatching:!0,excluded:new Set}}function BI(e,a){if(!e.allMatching)return{mode:"ids",ids:Array.from(e.picked)};const n=Array.from(e.excluded);return{mode:"filter",filters:a,...n.length?{excludeIds:n}:{}}}function mg(e){const a={};return e.agentId&&e.agentId!=="all"&&(a.agentId=e.agentId),e.q?.trim()&&(a.q=e.q.trim()),e.from&&(a.from=new Date(`${e.from}T00:00:00`).toISOString()),e.to&&(a.to=new Date(`${e.to}T23:59:59.999`).toISOString()),e.direction&&e.direction!=="all"&&(a.direction=e.direction),e.status&&e.status!=="all"&&(a.status=e.status),typeof e.hasRecording=="boolean"&&(a.hasRecording=e.hasRecording),e.campaignId&&(a.campaignId=e.campaignId),e.batchId&&(a.batchId=e.batchId),a}function WI(e){return e==="outbound"?{Icon:ka,color:"var(--cia-cta-500)"}:e==="web"?{Icon:Va,color:"var(--cia-sky-500)"}:{Icon:yn,color:"var(--cia-brand-500)"}}function UI(e){const a=o1(e.clientCountry);return a&&e.clientIp?`${a} · ${e.clientIp}`:a||e.clientIp||"—"}const VI=[10,15,20];function m1({withCost:e=!1}){const{t:a}=M("calls"),{can:n}=tt(),s=xt(H=>H.resolved),i=Os({strict:!1}),[r,o]=m.useState(()=>i.callId??null);m.useEffect(()=>{i.callId&&o(i.callId)},[i.callId]);const[l,c]=m.useState(""),[d,u]=m.useState(""),[p,f]=m.useState(""),[x,h]=m.useState("all"),[b,g]=m.useState(""),[v,y]=m.useState(""),[k,w]=m.useState("all"),[j,C]=m.useState(0),[N,S]=m.useState(10);m.useEffect(()=>{const H=setTimeout(()=>{f(d),C(0)},350);return()=>clearTimeout(H)},[d]);const _=se({queryKey:["admin-orgs-picker"],queryFn:async()=>(await T.get("/admin/organizations")).data,enabled:e}),R=se({queryKey:["agents-filter"],queryFn:async()=>(await T.get("/agents")).data,enabled:!e}),A=(H,fe)=>{const Z=new URLSearchParams;Z.set("limit",String(H)),Z.set("offset",String(fe)),e&&l&&Z.set("organizationId",l),x!=="all"&&Z.set("agentId",x),k!=="all"&&Z.set("medium",k);const ae=p.trim();return ae&&Z.set("q",ae),b&&Z.set("from",new Date(`${b}T00:00:00`).toISOString()),v&&Z.set("to",new Date(`${v}T23:59:59.999`).toISOString()),`/calls?${Z.toString()}`},{data:E,isLoading:I,isFetching:P}=se({queryKey:["calls","history",e?l:"mine",j,N,p,x,k,b,v],queryFn:async()=>(await T.get(A(N,j*N))).data,enabled:!e||!!l,placeholderData:xc}),O=e&&!l,K=E?.items??[],W=E?.total??0,V=m.useMemo(()=>{const H=new Map;for(const fe of K)fe.agentId&&H.set(fe.agentId,fe.agent?.name||fe.agentId);return[...H.entries()]},[K]),U=e?V:(R.data??[]).map(H=>[H.id,H.name]),X=!!(d||x!=="all"||k!=="all"||b||v);function ie(){u(""),h("all"),w("all"),g(""),y(""),C(0)}const de=n("calls.export"),$=k!=="all",[z,D]=m.useState(eu),[F,G]=m.useState(null),[te,B]=m.useState(null),ne=m.useMemo(()=>K.map(H=>H.id),[K]),me=m.useMemo(()=>$I(z,ne),[z,ne]),Ee=FI(z,W);m.useEffect(()=>{D(eu()),G(null)},[p,x,k,b,v,l]);function L(H,fe,Z){if(Z&&F){const ae=ne.indexOf(F),pe=ne.indexOf(H);if(ae>=0&&pe>=0){const ye=ne.slice(Math.min(ae,pe),Math.max(ae,pe)+1);D(qe=>h1(qe,ye,fe)),G(H);return}}D(ae=>p1(ae,H,fe)),G(H)}const re=m.useMemo(()=>BI(z,mg({agentId:x,q:p,from:b,to:v})),[z,x,p,b,v]),ke=8;return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:a(e?"topbar.eyebrowReports":"topbar.eyebrowCalls"),title:a(e?"topbar.titleReports":"topbar.titleCalls"),actions:t.jsxs("div",{className:"flex items-center gap-2",children:[e&&t.jsxs("select",{className:"input h-9 w-56",value:l,onCh
975ange:H=>{c(H.target.value),o(null),C(0)},children:[t.jsx("option",{value:"",children:a("orgPicker.placeholder")}),(_.data?.items||[]).map(H=>t.jsx("option",{value:H.id,children:H.name},H.id))]}),de&&t.jsx(vn,{trigger:t.jsxs("span",{className:"btn btn-outline h-9",title:$?a("bulkExport.mediumNoExportable"):void 0,children:[t.jsx(Tn,{className:"size-4"}),a("bulkExport.menu"),t.jsx(Ut,{className:"size-4"})]}),items:[{key:"data",label:a("bulkExport.data"),icon:Eu,onSelect:()=>B("data"),disabled:W===0||$},{key:"audio",label:a("bulkExport.audio"),icon:Ru,onSelect:()=>B("audio"),disabled:W===0||$}]})]})}),t.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":s,style:{background:"var(--cia-bg)",color:"var(--cia-text)",minWidth:0,display:"flex",flexDirection:"column"},children:t.jsx("div",{style:{width:"100%",padding:24,display:"flex",flexDirection:"column",flex:1,minHeight:0},children:O?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{icon:yc,title:a("needsOrg.title"),desc:a("needsOrg.desc")})}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:16,flexWrap:"wrap"},children:[t.jsx(ph,{value:d,onChange:u,placeholder:a("filters.searchPlaceholder"),width:260}),t.jsxs("select",{className:"input h-9",style:{width:190},value:x,onChange:H=>{h(H.target.value),C(0)},"aria-label":a("filters.agentAria"),children:[t.jsx("option",{value:"all",children:a("filters.allAgents")}),U.map(([H,fe])=>t.jsx("option",{value:H,children:fe},H))]}),t.jsxs("select",{className:"input h-9",style:{width:150},value:k,onChange:H=>{w(H.target.value),C(0)},"aria-label":a("filters.mediumAria"),children:[t.jsx("option",{value:"all",children:a("filters.allMediums")}),KD.map(H=>t.jsx("option",{value:H,children:a(`medium.${H}`)},H))]}),t.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12.5,color:"var(--cia-text-3)"},children:[a("filters.from"),t.jsx("input",{type:"date",className:"input h-9",value:b,max:v||void 0,onChange:H=>{g(H.target.value),C(0)},"aria-label":a("filters.fromAria")})]}),t.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12.5,color:"var(--cia-text-3)"},children:[a("filters.to"),t.jsx("input",{type:"date",className:"input h-9",value:v,min:b||void 0,onChange:H=>{y(H.target.value),C(0)},"aria-label":a("filters.toAria")})]}),X&&t.jsxs("button",{type:"button",className:"cia-btn cia-btn-ghost",onClick:ie,style:{height:36,fontSize:13},children:[t.jsx(nt,{size:14})," ",a("filters.clear")]}),t.jsx("span",{style:{flex:1}}),P&&!I&&t.jsx(je,{className:"animate-spin",size:15,style:{color:"var(--cia-text-3)"},"aria-label":a("filters.updating")})]}),de&&Ee>0&&t.jsxs("div",{className:"cia-card",style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",padding:"10px 14px",marginBottom:12,background:"var(--cia-bg-tint)"},role:"status","aria-live":"polite",children:[t.jsx("strong",{style:{fontSize:13},children:a("selection.count",{count:Ee})}),!z.allMatching&&W>Ee&&t.jsx("button",{className:"cia-btn cia-btn-sm cia-btn-ghost",onClick:()=>D(qI()),children:a("selection.allMatching",{count:W})}),z.allMatching&&t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-3)"},children:a("selection.allSelected",{count:Ee})}),t.jsx("span",{style:{flex:1}}),t.jsxs("button",{className:"cia-btn cia-btn-sm cia-btn-outline",onClick:()=>B("data"),disabled:$,title:$?a("bulkExport.mediumNoExportable"):void 0,children:[t.jsx(Eu,{className:"size-4"})," ",a("bulkExport.data")]}),t.jsxs("button",{className:"cia-btn cia-btn-sm cia-btn-outline",onClick:()=>B("audio"),disabled:$,title:$?a("bulkExport.mediumNoExportable"):void 0,children:[t.jsx(Ru,{className:"size-4"})," ",a("bulkExport.audio")]}),t.jsxs("button",{className:"cia-btn cia-btn-sm cia-btn-ghost",onClick:()=>D(eu()),children:[t.jsx(nt,{className:"size-4"})," ",a("selection.clear")]})]}),t.jsxs("div",{className:"cia-card",style:{overflow:"hidden",padding:0,display:"flex",flexDirection:"column",flex:1,minHeight:0},children:[t.jsx("div",{className:"cia-scroll",style:{flex:1,minHeight:0,overflow:"auto"},children:t.jsxs("table",{style:{width:"100%",minWidth:760,borderCollapse:"collapse",fontSize:13},children:[t.jsx("thead",{children:t.jsxs("tr",{className:"cia-mono",style:{background:"var(--cia-bg-soft)",borderBottom:"1px solid var(--cia-border)",fontSize:10,letterSpacing:"0.06em",color:"var(--cia-text-3)"},children:[de&&t.jsx("th",{style:{padding:"10px 12px",width:34},children:t.jsx(mn,{checked:me.checked,indeterminate:me.indeterminate,onChange:H=>D(fe=>OI(fe,ne,H)),ariaLabel:a("selection.selectPage")})}),t.jsx("th",{style:{padding:"10px 12px",width:28}}),t.jsx("th",{style:{textAlign:"left",padding:"10px 12px",fontWeight:500},children:a("table.date")}),t.jsx("th",{style:{textAlign:"left",padding:"10px 12px",fontWeight:500},children:a("table.agent")}),t.jsx("th",{style:{textAlign:"left",padding:"10px 12px",fontWeight:500},children:a("table.number")}),t.jsx("th",{style:{textAlign:"left",padding:"10px 12px",fontWeight:500},children:a("table.duration")}),t.jsx("th",{style:{textAlign:"left",padding:"10px 12px",fontWeight:500},children:a("table.outcome")}
975),t.jsx("th",{style:{textAlign:"left",padding:"10px 12px",fontWeight:500},children:a("table.sentiment")}),t.jsx("th",{style:{textAlign:"right",padding:"10px 12px",fontWeight:500},children:a(e?"table.cost":"table.usage")}),t.jsx("th",{style:{textAlign:"left",padding:"10px 12px",fontWeight:500},children:a("table.status")})]})}),t.jsx("tbody",{children:I?Array.from({length:N}).map((H,fe)=>t.jsxs("tr",{style:{borderTop:"1px solid var(--cia-border)"},children:[de&&t.jsx("td",{style:{padding:"12px"}}),t.jsx("td",{style:{padding:"12px"}}),Array.from({length:ke}).map((Z,ae)=>t.jsx("td",{style:{padding:"12px"},children:t.jsx(ge,{h:12,w:ae===0?120:ae===ke-1?64:"70%"})},ae))]},fe)):K.length>0?K.map(H=>{const{Icon:fe,color:Z}=WI(H.direction),ae=r===H.id;return t.jsxs("tr",{onClick:()=>o(H.id),style:{borderTop:"1px solid var(--cia-border)",cursor:"pointer",background:ae?"var(--cia-bg-tint)":"transparent"},className:"cia-row-hover",children:[de&&t.jsx("td",{style:{padding:"12px",textAlign:"center"},onClick:pe=>pe.stopPropagation(),children:t.jsx(mn,{checked:bp(z,H.id),onChange:pe=>L(H.id,pe,!1),onClickCapture:pe=>{pe.shiftKey&&L(H.id,!bp(z,H.id),!0)},ariaLabel:a("selection.selectRow")})}),t.jsx("td",{style:{padding:"12px",textAlign:"center"},children:t.jsx(fe,{size:13,style:{color:Z},"aria-hidden":"true"})}),t.jsx("td",{className:"cia-mono",style:{padding:"12px",color:"var(--cia-text-2)",fontSize:12},children:Be(H.startedAt||H.createdAt)}),t.jsx("td",{style:{padding:"12px"},children:H.agent?.name||"—"}),t.jsxs("td",{className:"cia-mono",style:{padding:"12px",fontSize:12,color:"var(--cia-text-2)"},children:[dc(H)&&t.jsx("span",{className:"chip",style:{marginRight:6,fontSize:10},children:a("medium.whatsapp")}),H.direction==="web"?UI(H):As(lv(H))]}),t.jsx("td",{className:"cia-mono",style:{padding:"12px",fontVariantNumeric:"tabular-nums"},children:Ca(H.durationSeconds)}),t.jsx("td",{style:{padding:"12px"},children:t.jsx(rI,{result:H.analysis?.success?.result})}),t.jsx("td",{style:{padding:"12px"},children:t.jsx(oI,{value:H.analysis?.sentiment?.value})}),t.jsx("td",{className:"cia-mono",style:{padding:"12px",textAlign:"right",fontVariantNumeric:"tabular-nums",fontSize:12},children:e?H.costUsd!=null?t.jsxs(t.Fragment,{children:[t.jsxs("span",{style:{fontWeight:600},children:["$",H.costUsd.toFixed(4)]}),H.durationSeconds>0&&t.jsx("div",{style:{fontSize:10,color:"var(--cia-text-3)"},children:a("cell.perMin",{value:(H.costUsd/(H.durationSeconds/60)).toFixed(4)})})]}):t.jsx("span",{style:{color:"var(--cia-text-3)"},children:"—"}):H.billing?t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{fontWeight:600},children:a("cell.minValue",{value:(H.billing.weightedSeconds/60).toFixed(1)})}),H.billing.premium&&t.jsx("div",{style:{fontSize:10,color:"var(--cia-brand-500)"},children:a("cell.premium",{mult:H.billing.multiplier})})]}):t.jsx("span",{style:{color:"var(--cia-text-3)"},children:"—"})}),t.jsx("td",{style:{padding:"12px"},children:t.jsx(No,{call:H})})]},H.id)}):t.jsx("tr",{children:t.jsx("td",{colSpan:ke+1+(de?1:0),children:t.jsx(st,{mini:!0,icon:Mn,title:a(X?"empty.noMatchTitle":"empty.noneTitle"),desc:a(X?"empty.noMatchDesc":"empty.noneDesc")})})})})]})}),(W>0||j>0)&&t.jsx("div",{style:{borderTop:"1px solid var(--cia-border)",padding:"0 14px"},children:t.jsx(Yy,{page:j,pageSize:N,total:W,pageSizeOptions:VI,onPageChange:C,onPageSizeChange:H=>{S(H),C(0)},itemLabel:a("pagination.items")})})]})]})})}),t.jsx(DI,{callId:r,onClose:()=>o(null),withCost:e,orgId:e?l:void 0})]}),de&&t.jsx(II,{open:te!==null,onClose:()=>B(null),kind:te??"data",selection:Ee>0?re:{mode:"filter",filters:mg({agentId:x,q:p,from:b,to:v})},organizationId:e?l:void 0})]})}const ai=25;function KI(e){const a=Math.floor(e/60),n=e%60;return`${a}:${String(n).padStart(2,"0")}`}function fg({llamadas:e,plata:a}){const{t:n}=M("calls"),s=e.total??e.cantidad??0;return t.jsxs("section",{className:"cia-card cia-card-pad",style:{display:"grid",gap:10},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10,flexWrap:"wrap",alignItems:"baseline"},children:[t.jsx("h3",{style:{margin:0,fontSize:14,fontWeight:600},children:n("reportes.llamadas.titulo")}),t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:n("reportes.llamadas.total",{n:s})})]}),s===0?t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)"},children:n("reportes.llamadas.ninguna")}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gap:10,gridTemplateColumns:"repeat(auto-fit,minmax(150px,1fr))",fontSize:13},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("reportes.llamadas.entrantes")}
975),t.jsx("div",{style:{fontVariantNumeric:"tabular-nums"},children:e.entrantes.toLocaleString()})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("reportes.llamadas.salientes")}),t.jsx("div",{style:{fontVariantNumeric:"tabular-nums"},children:e.salientes.toLocaleString()})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("reportes.llamadas.minutos")}),t.jsx("div",{style:{fontVariantNumeric:"tabular-nums"},children:e.minutos.toLocaleString()})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("reportes.llamadas.costoIa")}),t.jsx("div",{style:{fontSize:15},children:a(e.costoIaUsd,e.costoIaEsPiso)})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("reportes.llamadas.estimadoMeta")}),t.jsx("div",{style:{fontSize:15},children:e.estimadoMetaUsd==null?a(null):t.jsxs("span",{style:{fontVariantNumeric:"tabular-nums"},children:[s1(e.estimadoEsPiso)," $",e.estimadoMetaUsd.toFixed(6)]})}),t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("reportes.llamadas.denominador",{n:s})})]})]}),t.jsx("p",{style:{margin:0,fontSize:12,color:"var(--cia-text-3)"},children:n("reportes.llamadas.facturaDirecta")}),e.sinTarifa>0&&t.jsx("p",{style:{margin:0,fontSize:12,color:"var(--cia-warn-ink)"},children:n("reportes.llamadas.sinTarifa",{n:e.sinTarifa})}),e.sinCostear>0&&t.jsx("p",{style:{margin:0,fontSize:12,color:"var(--cia-text-3)"},children:n("reportes.llamadas.sinCostear",{n:e.sinCostear})})]})]})}function HI(){const{t:e}=M("calls"),[a,n]=m.useState(0),[s,i]=m.useState(""),[r,o]=m.useState(""),[l,c]=m.useState(""),[d,u]=m.useState(null),p=se({queryKey:["wa-reportes",a,s,r,l],queryFn:()=>{const g=new URLSearchParams({limit:String(ai),offset:String(a*ai)});return s.trim()&&g.set("q",s.trim()),r&&g.set("from",new Date(`${r}T00:00:00`).toISOString()),l&&g.set("to",new Date(`${l}T23:59:59.999`).toISOString()),T.get(`/admin/whatsapp/conversations?${g}`).then(v=>v.data)}}),f=se({queryKey:["wa-reportes-detalle",d],queryFn:()=>T.get(`/admin/whatsapp/conversations/${d}`).then(g=>g.data),enabled:!!d}),x=se({queryKey:["admin","whatsapp","summary"],queryFn:()=>T.get("/admin/whatsapp/summary").then(g=>g.data)}),h=(g,v=!1)=>g==null?t.jsx("span",{style:{color:"var(--cia-text-3)"},children:e("reportes.sinCotizar")}):t.jsxs("span",{style:{fontVariantNumeric:"tabular-nums"},children:[v?"≥ ":"","$",g.toFixed(6)]});if(d)return t.jsxs("div",{className:"cia-scroll",style:{height:"100%",overflowY:"auto",padding:16},children:[t.jsxs("button",{type:"button",onClick:()=>u(null),style:{display:"inline-flex",alignItems:"center",gap:6,background:"none",border:0,padding:"4px 0",color:"var(--cia-text-2)",cursor:"pointer",fontSize:13,minHeight:32},children:[t.jsx(gn,{size:15,"aria-hidden":!0}),e("reportes.volver")]}),f.isLoading?t.jsx(ge,{h:320}):f.data?t.jsxs("div",{style:{display:"grid",gap:14,marginTop:8},children:[t.jsxs("section",{className:"cia-card cia-card-pad",style:{display:"grid",gap:10},children:[t.jsx("h2",{style:{margin:0,fontSize:16},children:f.data.conversacion.contactName??f.data.conversacion.contactExternalId}),t.jsx("div",{style:{display:"grid",gap:10,gridTemplateColumns:"repeat(auto-fit,minmax(150px,1fr))",fontSize:13},children:[["cliente",f.data.conversacion.orgName??"—"],["agente",f.data.conversacion.agentName??"—"],["estado",e(`reportes.estado.${f.data.conversacion.state}`,{defaultValue:f.data.conversacion.state})],["atiende",e(`reportes.modo.${f.data.conversacion.mode}`,{defaultValue:f.data.conversacion.mode})],["inicio",Be(f.data.conversacion.createdAt)],["ultimo",Be(f.data.conversacion.lastMessageAt)],["cierre",f.data.conversacion.closedAt?Be(f.data.conversacion.closedAt):"—"]].map(([g,v])=>t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:e(`reportes.campo.${g}`)}),t.jsx("div",{children:v})]},g))})]}),t.jsxs("section",{className:"cia-card cia-card-pad",style:{display:"grid",gap:10},children:[t.jsx("h3",{style:{margin:0,fontSize:14,fontWeight:600},children:e("reportes.costo.titulo")}),t.jsxs("div",{style:{display:"grid",gap:10,gridTemplateColumns:"repeat(auto-fit,minmax(150px,1fr))"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:e("reportes.costo.agente")}),t.jsx("div",{style:{fontSize:15},children:h(f.data.costo.agenteUsd)})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:e("reportes.costo.entrega")}),t.jsx("div",{style:{fontSize:15},children:h(f.data.costo.entregaUsd)})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:e("reportes.costo.total")}),t.jsx("div",{style:{fontSize:15},children:t.jsx("strong",{children:h(f.data.costo.totalUsd,f.data.costo.parcial)})})]})]}),f.data.costo.parcial&&t.jsx("p",{style:{margin:0,fontSize:12,color:"var(--cia-warn-ink)"},children:e("reportes.costo.piso",{turnos:f.data.costo.turnosSinCostear,mensajes:f.data.costo.mensajesSinCotizar})})]}),f.data.llamadas&&(f.data.llamadas.cantidad??f.data.llamadas.total??0)>0&&t.jsx(fg,{llamadas:f.data.llamadas,plata:h}),(f.data.llamadasDetalle??[]).length>0&&t.jsxs("section",{className:"cia-card cia-card-pad",style:{display:"grid",gap:10},children:[t.jsx("h3",{style:{margin:0,fontSize:14,fontWeight:600},children:e("reportes.llamadas.desglose")}),t.jsx("div",{className:"cia-scroll-x",style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",fontSize:12.5,borderCollapse:"collapse",minWidth:560},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{textAlign:"left",color:"var(--cia-text-3)"},children:[t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:e("reportes.llamadas.col.cuando")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:e("reportes.llamadas.col.direccion")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500,textAlign:"right"},children:e("reportes.llamadas.col.duracion")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:e("reportes.llamadas.col.cierre")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500,textAlign:"right"},children:e("reportes.llamadas.col.costoIa")}),t.jsx("th",{style:{padding:"3px 0",fontWeight:500,textAlign:"right"},children:e("reportes.llamadas.col.estimado")})]})}),t.jsx("tbody",{children:(f.data.llamadasDetalle??[]).map(g=>t.jsxs("tr",{style:{borderTop:"1px solid var(--cia-border-2)"},children:[t.jsx("td",{style:{padding:"5px 8px 5px 0",color:"var(--cia-text-2)"},children:Be(g.cuando)}),t.jsx("td",{style:{padding:"5px 8px 5px 0"},children:t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5},children:[g.direccion==="outbound"?t.jsx(ka,{size:12,"aria-hidden":!0}):t.jsx(yn,{size:12,"aria-hidden":!0}),e(`reportes.llamadas.dir.${g.direccion}`)]})}),t.jsx("td",{style:{padding:"5px 8px 5px 0",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:KI(g.segundos)}),t.jsx("td",{style:{padding:"5px 8px 5px 0",color:"var(--cia-text-3)"},children:g.motivoDeCierre?e(`format:endReason.${g.motivoDeCierre}`,{defaultValue:g.motivoDeCierre}):"—"}),t.jsx("td",{style:{padding:"5px 8px 5px 0",textAlign:"right"},children:h(g.costoIaUsd)}),t.jsxs("td",{style:{padding:"5px 0",textAlign:"right"},children:[h(g.estimadoMetaUsd),g.motivo&&t.jsxs("div",{style:{fontSize:11,color:"var(--cia-text-4)"},children:[e(`reportes.llamadas.motivo.${g.motivo}`,{defaultValue:g.motivo}),g.pulsos?` · ${e("reportes.llamadas.pulsos",{n:g.pulsos})}`:""]})]})]},g.id))})]})})]}),f.data.fueraDeTurno.length>0&&t.jsxs("section",{className:"cia-card cia-card-pad",style:{display:"grid",gap:8},children:[t.jsxs("div",{children:[t.jsx("strong",{style:{fontSize:13.5},children:e("reportes.sueltos.titulo")}),t.jsx("div",{style:{fontSize:12,color:"var(--cia-text-3)",marginTop:2},children:e("reportes.sueltos.explicacion")})]}),t.jsx("div",{className:"cia-scroll-x",style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",fontSize:12.5,borderCollapse:"collapse",minWidth:460},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{textAlign:"left",color:"var(--cia-text-3)"},children:[t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:e("reportes.sueltos.que")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:e("reportes.sueltos.origenCol")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:e("reportes.col.categoria")}),t.jsx("th",{style:{padding:"3px 0",fontWeight:500,textAlign:"right"},children:e("reportes.col.costo")})]})}),t.jsx("tbody",{children:f.data.fueraDeTurno.map(g=>t.jsxs("tr",{style:{borderTop:"1px solid var(--cia-border-2)"},children:[t.jsxs("td",{style:{padding:"5px 8px 5px 0"},children:[e(`reportes.sueltos.tipo.${g.tipo}`,{defaultValue:g.tipo}),t.jsxs("span",{style:{color:"var(--cia-text-3)"},children:[" · ",Be(g.occurredAt)]})]}),t.jsx("td",{style:{padding:"5px 8px 5px 0",color:"var(--cia-text-2)"},children:e(`reportes.sueltos.origen.${g.origen}`,{defaultValue:g.origen})}),t.jsxs("td",{style:{padding:"5px 8px 5px 0",color:"var(--cia-text-2)"},children:[g.categoria?e(`reportes.categoria.${g.categoria}`,{defaultValue:g.categoria}):"—",g.facturable===!1&&t.jsxs("span",{style:{color:"var(--cia-text-3)"},children:[" · ",e("reportes.sueltos.noCobra")]})]}),t.jsx("td",{style:{padding:"5px 0",textAlign:"right",fontWeight:600},children:h(g.costoUsd)})]},g.id))})]})})]}),f.data.turnos.map((g,v)=>t.jsxs("section",{className:"cia-card cia-card-pad",style:{display:"grid",gap:8},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10,flexWrap:"wrap",alignItems:"baseline"},children:[t.jsxs("strong",{style:{fontSize:13.5},children:[e("reportes.turno",{n:v+1})," · ",Be(g.occurredAt)]}),t.jsx("span",{style:{fontSize:13},children:h(g.desglose.totalUsd,g.desglose.parcial)})]}),t.jsxs("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:[g.model??"—"," · ",e("reportes.tokens",{n:g.tokens.toLocaleStr
975ing()}),g.errorCode&&t.jsxs("span",{style:{color:"var(--cia-bad-500)"},children:[" · ",g.errorCode]})]}),t.jsx("div",{className:"cia-scroll-x",style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",fontSize:12.5,borderCollapse:"collapse",minWidth:460},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{textAlign:"left",color:"var(--cia-text-3)"},children:[t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:e("reportes.col.concepto")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:e("reportes.col.proveedor")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500,textAlign:"right"},children:e("reportes.col.cantidad")}),t.jsx("th",{style:{padding:"3px 0",fontWeight:500,textAlign:"right"},children:e("reportes.col.costo")})]})}),t.jsx("tbody",{children:g.desglose.lineas.map(y=>t.jsxs("tr",{style:{borderTop:"1px solid var(--cia-border-2)"},children:[t.jsx("td",{style:{padding:"5px 8px 5px 0"},children:e(`reportes.concepto.${y.concepto}`)}),t.jsxs("td",{style:{padding:"5px 8px 5px 0",color:"var(--cia-text-2)"},children:[y.proveedor??"—",y.modelo&&t.jsxs("span",{style:{color:"var(--cia-text-3)"},children:[" · ",y.modelo]}),y.variasCategorias?t.jsxs("span",{style:{color:"var(--cia-text-3)"},children:[" · ",e("reportes.categoriaVarias")]}):y.categoria&&t.jsxs("span",{style:{color:"var(--cia-text-3)"},children:[" · ",e(`reportes.categoria.${y.categoria}`,{defaultValue:y.categoria})]})]}),t.jsx("td",{style:{padding:"5px 8px 5px 0",textAlign:"right",fontVariantNumeric:"tabular-nums",color:"var(--cia-text-3)"},children:y.cantidad==null?"—":`${y.cantidad.toLocaleString()} ${e(`reportes.unidad.${y.unidad??"unidades"}`,{count:y.cantidad,defaultValue:y.unidad??""})}`}),t.jsx("td",{style:{padding:"5px 0",textAlign:"right"},children:y.estado==="sin_cotizar"?h(null):h(y.usd)})]},y.concepto))})]})})]},g.id))]}):null]});const b=p.data?.total??0;return t.jsxs("div",{className:"cia-scroll",style:{height:"100%",overflowY:"auto",padding:16,display:"grid",gap:12,alignContent:"start"},children:[t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[t.jsx("input",{className:"cia-input",placeholder:e("reportes.buscar"),value:s,onChange:g=>{i(g.target.value),n(0)},style:{minWidth:200,maxWidth:280,minHeight:34,flex:"0 1 260px"}}),t.jsx("input",{type:"date",className:"cia-input",value:r,onChange:g=>{o(g.target.value),n(0)},style:{minHeight:34,width:170,flex:"0 0 auto"}}),t.jsx("input",{type:"date",className:"cia-input",value:l,onChange:g=>{c(g.target.value),n(0)},style:{minHeight:34,width:170,flex:"0 0 auto"}}),t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:e("reportes.total",{n:b.toLocaleString()})})]}),x.data?.llamadas&&t.jsx(fg,{llamadas:x.data.llamadas,plata:h}),p.isLoading?t.jsx(ge,{h:280}):t.jsx("div",{className:"cia-card cia-scroll-x",style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",fontSize:13,borderCollapse:"collapse",minWidth:820},children:[t.jsx("thead",{children:t.jsx("tr",{style:{textAlign:"left",color:"var(--cia-text-3)",borderBottom:"1px solid var(--cia-border)"},children:["contacto","cliente","agente","estado","tipo","mensajes","turnos","agente$","entrega$","total"].map(g=>t.jsx("th",{style:{padding:"9px 12px",fontWeight:500,textAlign:g.endsWith("$")||g==="total"||g==="mensajes"||g==="turnos"?"right":"left"},children:e(`reportes.col.${g}`)},g))})}),t.jsx("tbody",{children:(p.data?.items??[]).map(g=>t.jsxs("tr",{onClick:()=>u(g.id),style:{borderTop:"1px solid var(--cia-border-2)",cursor:"pointer"},children:[t.jsx("td",{style:{padding:"9px 12px"},children:g.contactName??g.contactExternalId}),t.jsx("td",{style:{padding:"9px 12px",color:"var(--cia-text-2)"},children:g.orgName??"—"}),t.jsx("td",{style:{padding:"9px 12px",color:"var(--cia-text-2)"},children:g.agentName??"—"}),t.jsx("td",{style:{padding:"9px 12px"},children:e(`reportes.estado.${g.state}`,{defaultValue:g.state})}),t.jsx("td",{style:{padding:"9px 12px"},children:g.llamadas>0?t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--cia-brand-500)"},title:e("reportes.tipo.llamadasDetalle",{n:g.llamadas,salientes:g.llamadasSalientes,entrantes:g.llamadas-g.llamadasSalientes}),children:[t.jsx(Ma,{size:13,"aria-hidden":!0}),e("reportes.tipo.llamadas",{n:g.llamadas})]}):t.jsx("span",{style:{color:"var(--cia-text-3)"},children:e("reportes.tipo.chat")})}),t.jsx("td",{style:{padding:"9px 12px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:g.mensajes}),t.jsx("td",{style:{padding:"9px 12px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:g.turnos}),t.jsx("td",{style:{padding:"9px 12px",textAlign:"right"},children:h(g.costoAgenteUsd)}),t.jsx("td",{style:{padding:"9px 12px",textAlign:"right"},children:h(g.costoEntregaUsd)}),t.jsx("td",{style:{padding:"9px 12px",textAlign:"right"},children:t.jsx("strong",{children:h(g.costoTotalUsd,g.parcial)})})]},g.id))})]})}),b>ai&&t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",justifyContent:"flex-end"},children:[t.jsx("button",{type:"button",className:"cia-btn",disabled:a===0,onClick:()=>n(g=>g-1),style:{minHeight:32},children:e("reportes.anterior")}),t.jsxs("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:[a*ai+1,"–",Math.min((a+1)*ai,b)]}),t.jsx("button",{type:"button",className:"cia-btn",disabled:(a+1)*ai>=b,onClick:()=>n(g=>g+1),style:{minHeight:32},children:e("reportes.siguiente")})]})]})}function QI(){const{t:e}=M("calls"),[a,n]=m.useState("voice");return t.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[t.jsx("div",{style:{display:"flex",gap:2,borderBottom:"1px solid var(--cia-border)",padding:"0 16px",background:"var(--cia-bg)",flexShrink:0},children:[["voice",Ma],["whatsapp",Ba]].map(([s,i])=>t.jsxs("button",{type:"button",onClick:()=>n(s),"aria-current":a===s?"page":void 0,style:{display:"inline-flex",alignItems:"center",gap:7,padding:"11px 14px",minHeight:40,background:"none",border:0,borderBottom:`2px solid ${a===s?"var(--cia-primary)":"transparent"}`,color:a===s?"var(--cia-text)":"var(--cia-text-2)",fontSize:13.5,fontWeight:a===s?600:400,cursor:"pointer"},children:[t.jsx(i,{size:15,"aria-hidden":!0}),e(`reportes.producto.${s}`)]}
975,s))}),t.jsx("div",{style:{flex:1,minHeight:0},children:a==="voice"?t.jsx(m1,{withCost:!0}):t.jsx(HI,{})})]})}const GI=2500,ZI=180;function f1(e,a=!0){const n=xe(),[s,i]=m.useState(!1),r=!!e&&e.startsWith("call_")&&a,[o,l]=m.useState(()=>Date.now());m.useEffect(()=>{if(!r||s)return;const x=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(x)},[r,s]);const c=m.useRef(null);m.useEffect(()=>{c.current!==e&&(c.current=e,i(!1))},[e]);const d=se({queryKey:["call-progress",e],enabled:r&&!s,queryFn:async()=>(await T.get(`/calls/${e}`)).data,refetchInterval:x=>{const h=x.state.data;return s||h&&!la(h)?!1:GI},retry:!1});m.useEffect(()=>{if(!r)return;const x=ns(),h=b=>{!b||b.callId&&b.callId!==e||n.invalidateQueries({queryKey:["call-progress",e]})};return x.on("call:ended",h),()=>{x.off("call:ended",h)}},[r,e,n]),m.useEffect(()=>{if(!r)return;const x=setTimeout(()=>i(!0),ZI*1e3);return()=>clearTimeout(x)},[r,e]);const u=d.data??null,p=d.error?.response?.status===403||!!e&&!a;return{phase:e?p?"forbidden":r?u?la(u)?s?"no_signal":zh(u)?"dialing":"connected":X4(u)?"failed":"ended":s?"no_signal":"dialing":"no_signal":"idle",call:u,stalled:!!u&&zr(u,o),outcome:u?Dh(u):null}}const YI=/^\+[1-9]\d{6,15}$/,dl="cia.playground.tracking",XI=300*1e3,JI=()=>typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function eL(){const{t:e}=M("playground"),{t:a}=M("format"),{can:n}=tt(),s=xt(L=>L.resolved),[i,r]=m.useState(""),[o,l]=m.useState(""),[c,d]=m.useState(""),[u,p]=m.useState("+57"),f=m.useRef(!1),[x,h]=m.useState({}),[b,g]=m.useState(null),v=f1(b?.callId??null,n("calls.view"));m.useEffect(()=>{if(b?.callId)try{sessionStorage.setItem(dl,JSON.stringify({callId:b.callId,roomName:b.roomName,at:Date.now()}))}catch{}},[b?.callId,b?.roomName]),m.useEffect(()=>{if(!b)try{const L=sessionStorage.getItem(dl);if(!L)return;const re=JSON.parse(L);if(!re?.callId||!re?.at||Date.now()-re.at>XI){sessionStorage.removeItem(dl);return}g({callId:re.callId,roomName:re.roomName??""})}catch{}},[]),m.useEffect(()=>{if(["ended","failed","no_signal"].includes(v.phase))try{sessionStorage.removeItem(dl)}catch{}},[v.phase]);const y=oe({mutationFn:async()=>{b?.callId&&await T.post(`/calls/${b.callId}/hangup`,{})}}),k=se({queryKey:["phone-numbers"],queryFn:async()=>(await T.get("/phone-numbers")).data}),w=se({queryKey:["org-me"],queryFn:async()=>(await T.get("/organizations/me")).data,staleTime:300*1e3}),j=C_(w.data?.businessProfile?.country)??__(w.data?.businessProfile?.contactPhone)??"+57";m.useEffect(()=>{f.current||p(j)},[j]);const C=se({queryKey:["agents"],queryFn:async()=>(await T.get("/agents")).data}),S=(se({queryKey:["playground-wa-numbers"],queryFn:async()=>{try{return((await T.get("/whatsapp/accounts")).data.items??[]).flatMap(re=>re.numbers??[])}catch(L){if(L?.response?.status===501||L?.response?.status===404)return null;throw L}},retry:!1}).data??[]).filter(L=>L.callingStatus==="enabled"),_=(k.data??[]).filter(L=>L.canOriginate===!0),R=_.find(L=>
975L.rotating===!0),A=_.filter(L=>L.rotating!==!0),E=(C.data??[]).find(L=>L.id===c),I=_.find(L=>L.id===i),{all:P,required:O}=u0(E),K=O.every(L=>(x[L.name]??"").trim()!==""),W=!!E&&P.length>0,V=L=>{r(L),l("")},U=L=>{l(L),r("")},X=!!i||!!o,ie=!!c,de=YI.test(u),$=de,z=n("calls.operate"),D=z&&X&&ie&&$&&K,F=oe({mutationFn:async()=>{const L=Object.fromEntries(Object.entries(x).filter(([,ke])=>ke.trim()!==""));if(o){const{data:ke}=await T.post(`/whatsapp/numbers/${o}/calling/originate`,{destino:u,agentId:c,...Object.keys(L).length>0?{variables:L}:{}});return ke}const{data:re}=await T.post("/calls/originate",{numberId:i,agentId:c,destinationNumber:u,...Object.keys(L).length>0?{variables:L}:{}});return re},onSuccess:L=>g(L),onError:()=>g(null)}),G=(()=>{if(!F.isError)return null;const L=F.error?.response?.status,re=F.error?.response?.data?.message||F.error.message;return L===429?e("call.concurrencyError"):re})(),te=(()=>{const L=b?.callId&&v.call?.durationSeconds?Ca(v.call.durationSeconds):"",re=v.call?.endReason?a(`endReason.${v.call.endReason}`,{defaultValue:""}):"";switch(v.phase){case"connected":return{orbClass:"cia-pg-orb-ok",Icon:dn,title:e("track.connectedTitle"),desc:e("track.connectedDesc"),motivo:""};case"ended":return{orbClass:"cia-pg-orb-ok",Icon:Nt,title:e("track.endedTitle"),desc:L?e("track.endedDesc",{duration:L}):e("track.connectedDesc"),motivo:re};case"failed":return{orbClass:"cia-pg-orb-bad",Icon:cs,title:v.outcome?e(`outcome.${v.outcome}`,{defaultValue:e("track.failedTitle")}):e("track.failedTitle"),desc:e("track.failedTitle"),motivo:re};case"no_signal":return{orbClass:"cia-pg-orb-warn",Icon:vc,title:e("track.noSignalTitle"),desc:e("track.noSignalDesc"),motivo:""};case"forbidden":return{orbClass:"cia-pg-orb-ok",Icon:Nt,title:e("track.sentTitle"),desc:e("track.noViewPermission"),motivo:""};default:return v.stalled?{orbClass:"cia-pg-orb-warn",Icon:Tt,title:e("track.stalledTitle"),desc:e("track.stalledDesc"),motivo:""}:{orbClass:"cia-pg-orb-dial",Icon:ka,title:e("track.ringingTitle"),desc:e("track.ringingDesc"),motivo:""}}})(),B=v.phase==="dialing"||v.phase==="connected",ne=(L,re="bad")=>L?{borderColor:re==="bad"?"var(--cia-bad-500)":"var(--cia-warn-500)"}:void 0,me=m.useRef(null);m.useEffect(()=>{const L=me.current;if(!L)return;if(JI()){L.classList.add("in");return}const re=requestAnimationFrame(()=>L.classList.add("in"));return()=>cancelAnimationFrame(re)},[]);const Ee=[{label:e("stepper.origin"),done:X,active:!X},{label:e("stepper.agent"),done:ie,active:X&&!ie},{label:e("stepper.destination"),done:$&&ie,active:X&&ie&&!$},...W?[{label:e("stepper.data"),done:$&&K,active:X&&ie&&$&&!K}]:[]];return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("topbar.eyebrow"),title:e("topbar.title")}),t.jsx("main",{className:"cia cia-playground flex-1 overflow-y-auto cia-scroll","data-theme":s,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-playground-grid",style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) 360px",gap:22,padding:24,alignItems:"start"},children:[t.jsxs("div",{ref:me,className:"cia-stagger",style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx("div",{className:"cia-stagger-item",style:{"--i":0},children:t.jsx("div",{className:"cia-pg-steps",children:Ee.map((L,re)=>t.jsxs("div",{style:{display:"contents"},children:[t.jsxs("div",{className:"cia-pg-step",children:[t.jsx("span",{className:"cia-pg-step-dot","data-state":L.done?"done":L.active?"active":"idle",children:L.done?t.jsx(Nt,{size:15}):re+1}),t.jsx("span",{className:"cia-pg-step-label","data-state":L.active?"active":void 0,children:L.label})]}),re<Ee.length-1&&t.jsx("span",{className:"cia-pg-step-line","data-filled":L.done?"true":"false"})]},L.label))})}),t.jsxs("section",{className:"cia-card cia-stagger-item",style:{"--i":1,padding:20},children:[t.jsx(ul,{icon:dn,title:e("step1.title"),desc:e("step1.desc")}),k.isLoading?t.jsx(xg,{text:e("step1.loading")}):_.length===0&&S.length===0?t.jsxs("div",{style:{borderRadius:"var(--cia-r)",border:"1px dashed var(--cia-border-2)",padding:16,fontSize:13,color:"var(--cia-text-3)",textAlign:"center"},children:[e("step1.empty")," ",t.jsx("a",{href:"/trunks",style:{color:"var(--cia-brand-500)",fontWeight:500},children:e("step1.emptyLink")})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"cia-pg-chips",children:[A.map(L=>t.jsxs("button",{type:"button",className:"cia-pg-chip cia-mono","data-selected":i===L.id,onClick:()=>V(L.id),children:[t.jsx("span",{className:"cia-pg-chip-dot"}),L.e164,L.label?t.jsxs("span",{style:{fontSize:11.5,opacity:.7,fontFamily:"var(--cia-font, inherit)"},children:["· ",L.label]}):null,L.pool?t.jsxs("span",{title:e("step1.poolDesc"),style:{fontSize:11.5,opacity:.7,fontFamily:"var(--cia-font, inherit)"},children:["· ",e("step1.poolChip")]}):null]},L.id)),S.map(L=>t.jsxs("button",{type:"button",className:"cia-pg-chip cia-mono","data-selected":o===L.id,onClick:()=>U(L.id),title:e("step1.whatsappDesc"),style:{display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(Ba,{size:13,style:{color:"var(--cia-brand-500)"}}),L.displayPhoneNumber,t.jsxs("span",{style:{fontSize:11.5,opacity:.7,fontFamily:"var(--cia-font, inherit)"},children:["· ",e("step1.whatsappChip")]})]},L.id)),R&&t.jsxs("button",{type:"button",className:"cia-pg-chip","data-selected":i===R.id,onClick:()=>V(R.id),title:e("step1.rotatingDesc"),style:{display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(r2,{size:13,style:{color:"var(--cia-brand-500)"}}),e("step1.rotatingChip")]},R.id)]}),R&&i===R.id&&t.jsx("p",{style:{marginTop:10,marginBottom:0,fontSize:12.5,color:"var(--cia-text-3)"},children:e("step1.rotatingDesc")}),o&&t.jsx("p",{style:{marginTop:10,marginBottom:0,fontSize:12.5,color:"var(--cia-text-3)"},children:e("step1.whatsappDesc")})]})]}),t.jsxs("section",{className:"cia-card cia-pg-section cia-stagger-item","data-locked":!X,style:{"--i":2,padding:20},children:[t.jsx(ul,{icon:Ft,title:e("step2.title"),desc:e("step2.desc")}),C.isLoading?t.jsx(xg,{text:e("step2.loading")}):(C.data??[]).length===0?t.jsxs("div",{style:{borderRadius:"var(--cia-r)",border:"1px dashed var(--cia-border-2)",padding:16,fontSize:13,color:"var(--cia-text-3)",textAlign:"center"},children:[e("step2.empty")," ",t.jsx("a",{href:"/agents",style:{color:"var(--cia-brand-500)",fontWeight:500},children:e("step2.emptyLink")})]}):t.jsx("div",{className:"cia-pg-agents cia-scroll",children:(C.data??[]).map(L=>t.jsxs("button",{type:"button",className:"cia-pg-agent","data-selected":c===L.id,disabled:!X,onClick:()=>{d(L.id),h({})},children:[c===L.id&&t.jsx("span",{className:"cia-pg-agent-check",children:t.jsx(Nt,{size:13})}),t.jsx(ss,{id:L.id,accent:L.accent,size:34}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontWeight:600,fontSize:13.5,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:L.name}),t.jsxs("div",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:2,display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{children:to(L.language)}),L.status!=="published"&&t.jsx("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:"var(--cia-r-pill)",background:"color-mix(in oklab, var(--cia-warn-500) 16%, transparent)",color:"var(--cia-warn-ink)",fontWeight:600},children:L.status==="draft"?e("step2.draftBadge"):L.status})]})]})]},L.id))})]}),t.jsxs("section",{className:"cia-card cia-pg-section cia-stagger-item","data-locked":!ie,style:{"--i":3,padding:20},children:[t.jsx(ul,{icon:Xp,title:e("step3.title"),desc:e("step3.desc")}),t.jsxs("div",{className:"cia-pg-dial","data-bad":u.length>3&&!de,children:[t.jsx(Ma,{size:16,style:{color:de?"var(--cia-brand-500)":"var(--cia-text-3)",flex:"none"},"aria-hidden":"true"}),t.jsx("input",{type:"tel",inputMode:"tel",value:u,onChange:L=>{f.current=!0,p(L.target.value)},placeholder:j==="+1"?"+13235550123":`${j}3104441234`,disabled:!ie}),de&&t.jsx(Nt,{size:16,style:{color:"var(--cia-ok-500)",flex:"none"}})]}),u.length>3&&!de&&t.jsx("p",{style:{fontSize:12,color:"var(--cia-bad-500)",marginTop:8},children:e("step3.invalid")})]}),W&&t.jsxs("section",{className:"cia-card cia-pg-section cia-stagger-item","data-locked":!$,style:{"--i":4,padding:20},children:[t.jsx(ul,{icon:yS,title:e("step4.title"),desc:e("step4.desc")}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:P.map(L=>{const re=L.defaultValue===void 0,ke=x[L.name]??"";return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[t.jsx("code",{className:"cia-mono",style:{fontSize:12,color:"var(--cia-cta-500)"},children:`{{${L.name}}}`}),re?t.jsx("span",{style:{fontSize:10,fontWeight:500,color:"var(--cia-warn-ink)"},children:e("step4.required")}
975):t.jsx("span",{style:{fontSize:10,color:"var(--cia-text-3)"},children:e("step4.optional")})]}),t.jsx("input",{className:"input w-full",style:ne(re&&ke.trim()==="","warn"),value:ke,onChange:H=>h(fe=>({...fe,[L.name]:H.target.value})),placeholder:L.defaultValue!==void 0?e("step4.defaultPlaceholder",{value:L.defaultValue}):L.description||e("step4.valuePlaceholder")}),L.description&&L.defaultValue!==void 0&&t.jsx("p",{style:{fontSize:11,color:"var(--cia-text-3)",marginTop:2},children:L.description})]},L.name)})}),!K&&t.jsx("p",{style:{fontSize:12,color:"var(--cia-warn-ink)",marginTop:8},children:e("step4.requiredHint")})]}),t.jsx("button",{onClick:()=>{g(null),F.mutate()},disabled:!D||F.isPending||B,title:z?B?e("guard.inProgress"):void 0:e("common:noPermission"),className:"cia-btn cia-btn-cta cia-btn-lg cia-stagger-item",style:{"--i":5,width:"100%",marginTop:2},children:F.isPending?t.jsxs(t.Fragment,{children:[t.jsx(je,{className:"animate-spin",size:16})," ",e("call.originating")]}):t.jsxs(t.Fragment,{children:[t.jsx(ka,{size:16})," ",e("call.call")]})})]}),t.jsx("aside",{className:"cia-card cia-pg-hero",style:{padding:"32px 26px",display:"flex",flexDirection:"column",alignItems:"center",gap:20,textAlign:"center",background:"var(--cia-bg-soft)"},children:b?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:te.orbClass,children:t.jsx(te.Icon,{size:42,strokeWidth:1.6})}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,maxWidth:320},children:[t.jsx("h2",{style:{margin:0,fontSize:21,fontWeight:600,letterSpacing:"-0.02em"},children:te.title}),t.jsx("p",{style:{margin:0,fontSize:13,lineHeight:1.55,color:"var(--cia-text-3)"},children:te.desc}),te.motivo&&t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)"},children:te.motivo})]}),(v.phase==="dialing"||v.phase==="connected")&&n("calls.operate")&&b.callId&&t.jsxs("button",{type:"button",className:"cia-btn cia-btn-ghost",style:{width:"100%"},disabled:y.isPending,onClick:()=>{y.mutate(void 0,{onSuccess:()=>J({tone:"ok",title:e("hangup.done")}),onError:()=>J({tone:"bad",title:e("hangup.err")})})},children:[t.jsx(Ts,{size:15})," ",e("hangup.cta")]}),n("calls.view")&&t.jsxs("a",{href:b.callId?`/live?call=${b.callId}`:"/live",className:"cia-btn cia-btn-cta",style:{width:"100%"},children:[t.jsx(vi,{size:15})," ",e("success.viewLive")]}),v.phase!=="dialing"&&v.phase!=="connected"&&t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost",style:{width:"100%"},onClick:()=>{g(null),F.reset(),y.reset()},children:e("success.callAgain")})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:F.isPending?"cia-orb-dialing":void 0,children:t.jsx(N5,{icon:F.isPending?ka:Ma})}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,maxWidth:320},children:[t.jsx("h2",{style:{margin:0,fontSize:21,fontWeight:600,letterSpacing:"-0.02em"},children:F.isPending?t.jsxs(t.Fragment,{children:[e("idle.originating"),t.jsxs("span",{className:"cia-pg-dots",children:[t.jsx("span",{children:"."}),t.jsx("span",{children:"."}),t.jsx("span",{children:"."})]})]}):e("idle.title")}),t.jsx("p",{style:{margin:0,fontSize:13,lineHeight:1.55,color:"var(--cia-text-3)"},children:F.isPending?e("idle.connecting"):e("idle.hint")})]}),t.jsxs("div",{className:"cia-pg-sum",children:[t.jsxs("div",{className:"cia-pg-sum-row",children:[t.jsx(dn,{size:15,className:"cia-pg-sum-ico"}),t.jsx("span",{className:"cia-pg-sum-k",children:e("summary.from")}),t.jsx("span",{className:"cia-pg-sum-v cia-mono","data-empty":!I,children:I?I.rotating?e("step1.rotatingChip"):I.e164:e("summary.unset")})]}),t.jsxs("div",{className:"cia-pg-sum-row",children:[t.jsx(Ft,{size:15,className:"cia-pg-sum-ico"}),t.jsx("span",{className:"cia-pg-sum-k",children:e("summary.agent")}),t.jsx("span",{className:"cia-pg-sum-v","data-empty":!E,children:E?E.name:e("summary.unset")})]}),t.jsxs("div",{className:"cia-pg-sum-row",children:[t.jsx(oa,{size:15,className:"cia-pg-sum-ico"}),t.jsx("span",{className:"cia-pg-sum-k",children:e("summary.to")}),t.jsx("span",{className:"cia-pg-sum-v cia-mono","data-empty":!de,children:de?u:e("summary.unsetDial")})]})]}),F.isError&&t.jsx("div",{style:{width:"100%",borderRadius:"var(--cia-r)",padding:14,fontSize:13,textAlign:"left",background:"color-mix(in oklab, var(--cia-bad-500) 10%, transparent)",color:"var(--cia-bad-500)"},children:G})]})})]})})]})}function ul({icon:e,title:a,desc:n}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:3},children:[t.jsx(e,{size:15,style:{color:"var(--cia-text-3)"},"aria-hidden":"true"}),t.jsx("span",{style:{fontWeight:600,fontSize:14},children:a})]}),t.jsx("p",{style:{fontSize:12,color:"var(--cia-text-3)",margin:0},children:n})]})}function xg({text:e}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--cia-text-3)"},children:[t.jsx(je,{className:"animate-spin",size:16})," ",e]})}const gg="https://sdk.mercadopago.com/js/v2";let pl=null;function tL(){return typeof window<"u"&&window.MercadoPago?Promise.resolve():pl||(pl=new Promise((e,a)=>{const n=document.querySelector(`script[src="${gg}"]`);if(n){n.addEventListener("load",()=>e()),n.addEventListener("error",()=>
975a(new Error("No se pudo cargar MercadoPago"))),window.MercadoPago&&e();return}const s=document.createElement("script");s.src=gg,s.async=!0,s.onload=()=>e(),s.onerror=()=>a(new Error("No se pudo cargar MercadoPago")),document.head.appendChild(s)}),pl)}async function aL(e){if(await tL(),!window.MercadoPago)throw new Error("MercadoPago no disponible");return new window.MercadoPago(e,{locale:"es-CO"})}const nL=1e4;function Qc({open:e,onClose:a,title:n,subtitle:s,usdAmount:i,method:r,mode:o="pay",onConfirm:l}){const{t:c}=M("settings"),d=xt(R=>R.resolved),u=o==="pay"&&r.hasCard,[p,f]=m.useState(u?"choose":"form"),[x,h]=m.useState(!1),[b,g]=m.useState(!1),[v,y]=m.useState(!1),[k,w]=m.useState(null),j=m.useRef(null),C=m.useRef("");C.current||(C.current=typeof crypto<"u"&&crypto.randomUUID?.()||`ck_${Date.now()}_${Math.random().toString(36).slice(2)}`);const N=r.trm&&i>0?Math.round(i*r.trm):null,S=o==="save"?nL:Math.max(1,N??(Math.round(i)||1));m.useEffect(()=>{if(!e||p!=="form"||b)return;if(!r.publicKey){w(c("checkout.unavailable"));return}let R=!1;return y(!1),w(null),(async()=>{try{const A=await aL(r.publicKey);if(R)return;const E=A.bricks();j.current=await E.create("cardPayment","cia-card-form",{initialization:{amount:S},customization:{visual:{hidePaymentButton:!1,style:{theme:d==="dark"?"dark":"default",customVariables:{baseColor:"#2B52A1",borderRadiusMedium:"10px",borderRadiusSmall:"8px",formPadding:"0px"}},texts:{formSubmit:c(o==="save"?"checkout.submitSave":"checkout.submitPay")}},paymentMethods:{maxInstallments:1}},callbacks:{onReady:()=>!R&&y(!0),onError:I=>!R&&w(I?.message||c("checkout.loadError")),onSubmit:I=>(async()=>{const P=I?.formData??I,O={token:P?.token,paymentMethodId:P?.payment_method_id,issuerId:P?.issuer_id,installments:P?.installments};h(!0);try{await l(O,C.current),R||g(!0)}catch{C.current=typeof crypto<"u"&&crypto.randomUUID?.()||`ck_${Date.now()}_${Math.random().toString(36).slice(2)}`}finally{R||h(!1)}})()}})}catch(A){R||w(A?.message||c("checkout.loadError"))}})(),()=>{R=!0;try{j.current?.unmount?.()}catch{}j.current=null}},[e,p,b,r.publicKey,S,d,o]);async function _(){h(!0);try{await l(void 0,C.current),g(!0)}catch{C.current=typeof crypto<"u"&&crypto.randomUUID?.()||`ck_${Date.now()}_${Math.random().toString(36).slice(2)}`}finally{h(!1)}}return m.useEffect(()=>{if(!b)return;const R=setTimeout(a,1400);return()=>clearTimeout(R)},[b,a]),t.jsx(ot,{open:e,onClose:x?()=>{}:a,maxWidth:440,eyebrow:c("checkout.eyebrow"),title:n,children:b?t.jsxs("div",{className:"cia-fade-up",style:{display:"flex",flexDirection:"column",alignItems:"center",gap:12,padding:"24px 0 12px"},children:[t.jsx("div",{style:{width:56,height:56,borderRadius:"50%",display:"grid",placeItems:"center",background:"color-mix(in oklab, var(--cia-ok-500) 16%, transparent)"},children:t.jsx(Nt,{size:30,style:{color:"var(--cia-ok-500)"}})}),t.jsx("div",{style:{fontSize:16,fontWeight:700},children:c(o==="save"?"checkout.doneSaved":"checkout.donePaid")}),t.jsx("div",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:c("checkout.doneClose")})]}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[s&&t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)"},children:s}),o==="pay"&&t.jsxs("div",{className:"cia-fade-up",style:{padding:16,borderRadius:"var(--cia-r-lg, 14px)",background:"linear-gradient(135deg, color-mix(in oklab, var(--cia-brand-500) 12%, var(--cia-bg-elev)), var(--cia-bg-elev))",border:"1px solid color-mix(in oklab, var(--cia-brand-500) 24%, var(--cia-border))",display:"flex",alignItems:"flex-end",justifyContent:"space-between",gap:10},children:[t.jsxs("div",{children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:2},children:c("checkout.totalToPay")}),t.jsxs("div",{style:{fontSize:30,fontWeight:800,lineHeight:1,fontVariantNumeric:"tabular-nums"},children:["$",i.toFixed(2)," ",t.jsx("span",{style:{fontSize:13,fontWeight:500,color:"var(--cia-text-3)"},children:c("checkout.usd")})]})]}),N!=null&&t.jsxs("div",{className:"cia-mono",style:{fontSize:11.5,color:"var(--cia-text-3)",textAlign:"right"}
975,children:[c("checkout.copApprox",{cop:N.toLocaleString(Te())}),t.jsx("br",{}),c("checkout.trm",{trm:r.trm.toLocaleString(Te())})]})]}),r.mode==="sandbox"&&t.jsxs("div",{style:{fontSize:11,color:"var(--cia-warn-ink)",display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(yi,{size:12})," ",c("checkout.sandbox")]}),p==="choose"&&u?t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsx("button",{className:"cia-btn cia-btn-cta",style:{width:"100%",justifyContent:"center",height:46},onClick:_,disabled:x,children:x?t.jsx(je,{className:"animate-spin",size:18}):t.jsxs(t.Fragment,{children:[t.jsx($s,{size:17})," ",c("checkout.paySaved",{brand:r.brand||c("checkout.card"),last4:r.last4})]})}),t.jsx("button",{className:"cia-btn cia-btn-outline",style:{width:"100%",justifyContent:"center"},onClick:()=>f("form"),disabled:x,children:c("checkout.useAnother")})]}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[k?t.jsx(le,{tone:"bad",children:k}):v?null:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"var(--cia-text-3)",fontSize:13,padding:"6px 0"},children:[t.jsx(je,{className:"animate-spin",size:15})," ",c("checkout.loadingForm")]}),t.jsx("div",{id:"cia-card-form",style:{minHeight:v?void 0:0}}),u&&t.jsx("button",{className:"cia-btn cia-btn-outline",style:{width:"100%",justifyContent:"center"},onClick:()=>f("choose"),disabled:x,children:c("checkout.backToSaved")})]}),x&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,fontSize:12.5,color:"var(--cia-text-2)"},children:[t.jsx(je,{className:"animate-spin",size:14})," ",c("checkout.processing")]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:7,fontSize:11,color:"var(--cia-text-3)"},children:[t.jsx(ho,{size:13,style:{color:"var(--cia-ok-500)"}}),c("checkout.securitySeal")]})]})})}const yp=["payment-method"];function Gc(){return se({queryKey:yp,queryFn:async()=>(await T.get("/payments/method")).data})}function sL(){const{t:e}=M("settings");Pe(p=>p.user?.role);const{can:a}=tt(),n=a("billing.manage"),s=xe(),{data:i,isLoading:r}=Gc(),[o,l]=m.useState(!1),c=oe({mutationFn:async p=>(await T.post("/payments/setup-card",{cardToken:p})).data,onSuccess:()=>{s.invalidateQueries({queryKey:yp}),J({tone:"ok",title:e("paymentMethod.toasts.saved")}),l(!1)},onError:p=>J({tone:"bad",title:p?.response?.data?.message||e("paymentMethod.toasts.saveFailed")})}),d=oe({mutationFn:async()=>(await T.delete("/payments/method")).data,onSuccess:()=>{s.invalidateQueries({queryKey:yp}),J({tone:"ok",title:e("paymentMethod.toasts.deleted")})},onError:p=>J({tone:"bad",title:p?.response?.data?.message||e("paymentMethod.toasts.deleteFailed")})});if(r)return t.jsx("div",{className:"cia-card",style:{padding:18},children:t.jsx(ge,{w:"40%",h:16})});if(!i?.mpConfigured)return null;const u=i.paymentStatus==="past_due"||i.paymentStatus==="suspended";
975return t.jsxs("div",{className:"cia-card",style:{padding:18,display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("span",{style:{fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",gap:8},children:[t.jsx($s,{size:15,style:{color:"var(--cia-text-3)"}})," ",e("paymentMethod.title")]}),u&&t.jsx(le,{tone:"bad",children:i.paymentStatus==="suspended"?e("paymentMethod.suspended"):e("paymentMethod.pastDue")}),i.hasCard?t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8,fontSize:13.5},children:[t.jsx(ho,{size:16,style:{color:"var(--cia-ok-500)"}}),i.brand||e("paymentMethod.card")," •••• ",i.last4]}),n&&t.jsxs("span",{style:{display:"inline-flex",gap:8},children:[t.jsx("button",{className:"cia-btn cia-btn-outline",style:{fontSize:12.5},onClick:()=>l(!0),children:e("paymentMethod.change")}),i.canRemove!==!1&&t.jsx("button",{className:"cia-btn cia-btn-outline",style:{fontSize:12.5,color:"var(--cia-bad-500)"},onClick:()=>d.mutate(),disabled:d.isPending,title:e("paymentMethod.deleteTitle"),children:t.jsx(mt,{size:14})})]})]}):t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:e("paymentMethod.addPrompt")}),n&&t.jsxs("button",{className:"cia-btn cia-btn-cta",style:{fontSize:13},onClick:()=>l(!0),children:[t.jsx(Fe,{size:15})," ",e("paymentMethod.addCard")]})]}),o&&t.jsx(Qc,{open:!0,mode:"save",onClose:()=>l(!1),title:i.hasCard?e("paymentMethod.changeCardTitle"):e("paymentMethod.addCardTitle"),subtitle:e("paymentMethod.saveSubtitle"),usdAmount:0,method:i,onConfirm:async p=>{await c.mutateAsync(p?.token)}})]})}function iL(){const{t:e}=M("misc"),a=xt(x=>x.resolved),n=xe(),[s,i]=m.useState(!1),{can:r}=tt(),o=r("phoneNumbers.manage"),l=se({queryKey:["phone-numbers"],queryFn:async()=>(await T.get("/phone-numbers")).data}),c=se({queryKey:["agents-min"],queryFn:async()=>(await T.get("/agents")).data}),d=(l.data??[]).filter(x=>!x.rotating),u=c.data??[],p=oe({mutationFn:async x=>T.patch(`/phone-numbers/${x.id}/assign`,{agentId:x.agentId}),onSuccess:()=>n.invalidateQueries({queryKey:["phone-numbers"]}),onError:x=>J({tone:"bad",title:x?.response?.data?.message||e("trunks.toast.assignFail")})}),f=oe({mutationFn:async x=>T.delete(`/phone-numbers/${x}`),onSuccess:()=>{n.invalidateQueries({queryKey:["phone-numbers"]}),J({tone:"ok",title:e("trunks.toast.released")})},onError:x=>J({tone:"bad",title:x?.response?.data?.message||e("trunks.toast.releaseFail")})});return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("trunks.eyebrow"),title:e("trunks.title"),actions:o?t.jsxs("button",{className:"cia-btn cia-btn-primary",onClick:()=>i(!0),children:[t.jsx(Mu,{size:15})," ",e("trunks.buyNumber")]}):void 0}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":a,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{style:{width:"100%",maxWidth:980,padding:24,display:"flex",flexDirection:"column",gap:16},children:[l.isLoading?t.jsx("div",{className:"cia-card",style:{padding:24,color:"var(--cia-text-3)"},children:e("trunks.loading")}):d.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{icon:Mu,title:e("trunks.empty.title"),desc:e("trunks.empty.desc"),action:o?{label:e("trunks.buyNumber"),onClick:()=>i(!0)}:void 0})}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(320px, 1fr))",gap:12},children:d.map(x=>t.jsxs("div",{className:"cia-card cia-fade-up",style:{padding:16,display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx(Yr,{active:!!x.active&&x.canOriginate!==!1,tone:"ok",size:38}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{className:"cia-mono",style:{fontSize:15,fontWeight:600},children:As(x.e164)}),t.jsx("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:x.label||x.country||"CO"})]}),t.jsx("span",{className:"cia-badge",style:{background:x.tenantBillable?"var(--cia-bg-tint)":void 0},children:x.tenantBillable?e("trunks.card.additional"):e("trunks.card.included")})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsxs("select",{className:"input",style:{flex:1,fontSize:13},value:x.agentId||"",disabled:!o,title:o?void 0:e("common:noPermission"),onChange:h=>p.mutate({id:x.id,agentId:h.target.value||null}),children:[t.jsx("option",{value:"",children:e("trunks.card.noAgent")}),u.map(h=>t.jsx("option",{value:h.id,children:h.name},h.id))]}),o&&t.jsx("button",{className:"cia-btn cia-btn-outline cia-btn-icon",style:{width:38,color:"var(--cia-bad-500)"},disabled:f.isPending,onClick:async()=>{await pa({message:e("trunks.card.cancelConfirm",{number:x.e164}),danger:!0})&&f.mutate(x.id)},title:e("trunks.card.cancelTitle"),children:t.jsx(mt,{size:15})})]})]},x.id))}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",margin:0,lineHeight:1.6},children:e("trunks.footnote")})]})}),s&&t.jsx(rL,{onClose:()=>i(!1),onBought:()=>{i(!1),n.invalidateQueries({queryKey:["phone-numbers"]}),n.invalidateQueries({queryKey:["plan-usage"]})}})]})}function rL({onClose:e,onBought:a}){const{t:n}=M("misc"),[s]=m.useState("CO"),[i,r]=m.useState(null),[o,l]=m.useState(!1),c=se({queryKey:["phone-numbers-available",s],queryFn:async()=>(await T.get(`/phone-numbers/available?country=${s}`)).data}),{data:d}=Gc(),u=c.data,p=(u?.freeRemaining??0)>0,f=!!i&&!p&&!!d?.mpConfigured&&(i.proratedUsd??0)>0,x=oe({mutationFn:async h=>(await T.post(`/phone-numbers/${h.id}/buy`,{cardToken:h.card?.token,paymentMethodId:h.card?.paymentMethodId,issuerId:h.card?.issuerId,installments:h.card?.installments,idempotencyKey:h.idempotencyKey})).data,onSuccess:h=>{J({tone:"ok",title:h.requiresCheckout?n("trunks.buy.toastBought"):n("trunks.buy.toastAdded")}),a()},onError:h=>J({tone:"bad",title:h?.response?.data?.message||n("trunks.buy.toastBuyFail")})});return i&&o&&d?t.jsx(Qc,{open:!0,onClose:()=>l(!1),title:n("trunks.buy.checkoutTitle",{number:As(i.e164)}),usdAmount:i.proratedUsd??0,method:d,onConfirm:async(h,b)=>{await x.mutateAsync({id:i.id,card:h,idempotencyKey:b})}}):i?t.jsx(ot,{open:!0,onClose:e,title:n("trunks.buy.confirmTitle"),footer:t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"cia-btn cia-btn-outline",onClick:()=>r(null),children:[t.jsx(du,{size:14})," ",n("trunks.buy.back")]}),t.jsx("button",{className:"cia-btn cia-btn-primary",disabled:x.isPending,onClick:()=>f?l(!0):x.mutate({id:i.id,card:void 0}),children:x.isPending?t.jsx(je,{className:"animate-spin",size:15}):n(p?"trunks.buy.addIncluded":f?"trunks.buy.continuePay":"trunks.buy.buy")})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{className:"cia-card",style:{padding:16,display:"flex",alignItems:"center",gap:12},children:[t.jsx(Yr,{active:!0,tone:"brand",size:38}),t.jsxs("div",{children:[t.jsx("div",{className:"cia-mono",style:{fontSize:16,fontWeight:600},children:As(i.e164)}),t.jsxs("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:[n("trunks.buy.colombia")," · ",i.country]})]})]}),p?t.jsxs(le,{tone:"ok",children:[t.jsx("strong",{children:n("trunks.buy.includedTitle")})," ",n("trunks.buy.includedRest",{n:u?.freeRemaining})]}):t.jsxs(le,{tone:"info",children:[t.jsxs("strong",{children:["$",i.sellPriceUsd,n("trunks.buy.perMonth")]})," ",n("trunks.buy.proratedPre")," ",t.jsxs("strong",{children:["$",i.proratedUsd]})," ",n("trunks.buy.proratedPost")]}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",margin:0},children:n(f?"trunks.buy.securePay":"trunks.buy.availableOnConfirm")})]})}):t.jsx(ot,{open:!0,onClose:e,title:n("trunks.buyNumber"),maxWidth:520,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{className:"cia-eyebrow",children:n("trunks.buy.country")}),t.jsxs("span",{className:"cia-badge",children:["🇨🇴 ",n("trunks.buy.colombia")]})]}),p&&t.jsx(le,{tone:"ok",children:n("trunks.buy.freeBannerStep1",{n:u?.freeRemaining})}),c.isLoading?t.jsx("div",{style:{padding:20,color:"var(--cia-text-3)",fontSize:13},children:n("trunks.buy.loadingNumbers")}):(u?.items.length??0)===0?t.jsx(st,{mini:!0,icon:Mu,title:n("trunks.buy.emptyTitle"),desc:n("trunks.buy.emptyDesc")}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,maxHeight:360,overflowY:"auto"},className:"cia-scroll",children:u.items.map(h=>t.jsxs("button",{type:"button",onClick:()=>r(h),className:"cia-card",style:{padding:14,display:"flex",alignItems:"center",gap:12,cursor:"pointer",textAlign:"left",width:"100%"},children:[t.jsx(Yr,{active:!0,tone:"ok",size:34}),t.jsxs("div",{style:{flex:1},children:[t.jsx("div",{className:"cia-mono",style:{fontSize:15,fontWeight:600},children:As(h.e164)}),t.jsx("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:n("trunks.buy.colombia")})]}),t.jsxs("div",{style:{textAlign:"right"},children:[t.jsx("div",{className:"cia-mono",style:{fontSize:13,fontWeight:600},children:p?n("trunks.buy.included"):`$${h.sellPriceUsd}${n("trunks.buy.perMonthShort")}`}),!p&&t.jsxs("div",{style:{fontSize:10.5,color:"var(--cia-text-3)"},children:["≈ $",h.proratedUsd," ",n("trunks.buy.thisCycle")]})]}),t.jsx(Nt,{size:16,style:{color:"var(--cia-text-4)"}})]}
975,h.id))})]})})}function oL({open:e,onClose:a,onSave:n,saving:s,initial:i,error:r}){const{t:o}=M("misc"),l=Kc(Vc.agendamiento),[c,d]=m.useState(""),[u,p]=m.useState(""),[f,x]=m.useState(""),[h,b]=m.useState(""),[g,v]=m.useState(null);if(m.useEffect(()=>{e&&(d(i?.label??""),p(""),x(i?.baseUrl??""),b(i?.apiKeyExpiresAt?i.apiKeyExpiresAt.slice(0,10):""),v(null))},[e,i]),!e)return null;const y=!!i;function k(){const w=c.trim();if(w.length<2){v(o("calendar.modal.errLabel"));return}if(!y&&u.trim().length<8){v(o("calendar.modal.errKey"));return}const j=f.trim();if(j&&!/^https:\/\//i.test(j)){v(o("calendar.modal.errBaseUrl"));return}n({...y?{}:{provider:"calcom",authMode:"api_key"},label:w,...u.trim()?{apiKey:u.trim()}:{},...j||y?{baseUrl:j}:{},...h||y?{apiKeyExpiresAt:h}:{}})}return t.jsx(ot,{open:e,onClose:a,eyebrow:o("calendar.modal.eyebrow"),title:o(y?"calendar.modal.titleEdit":"calendar.modal.titleNew"),maxWidth:560,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-ghost h-9",onClick:a,disabled:s,children:o("calendar.modal.cancel")}),t.jsx("button",{className:"btn btn-primary h-9 px-4",onClick:k,disabled:s,children:o(y?"calendar.modal.save":"calendar.modal.connect")})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsx("p",{className:"text-xs text-ink-mute",children:t.jsx(wa,{i18nKey:"misc:calendar.modal.intro",components:{guia:t.jsx("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"underline"})}})}),(g||r)&&t.jsx(le,{tone:"bad",children:g||r}),t.jsxs("label",{className:"flex flex-col gap-1.5",children:[t.jsx("span",{className:"text-xs font-medium",children:o("calendar.modal.labelName")}),t.jsx("input",{className:"input",value:c,onChange:w=>d(w.target.value),placeholder:o("calendar.modal.placeholderName"),maxLength:120}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:o("calendar.modal.hintName")})]}),t.jsxs("label",{className:"flex flex-col gap-1.5",children:[t.jsx("span",{className:"text-xs font-medium",children:o("calendar.modal.labelKey")}),t.jsx("input",{className:"input font-mono",type:"password",autoComplete:"off",value:u,onChange:w=>p(w.target.value),placeholder:o(y?"calendar.modal.placeholderKeyEdit":"calendar.modal.placeholderKey"),maxLength:400}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:o(y?"calendar.modal.hintKeyEdit":"calendar.modal.hintKey")})]}),t.jsx(le,{tone:"warn",children:o("calendar.modal.expiryWarning")}),t.jsxs("label",{className:"flex flex-col gap-1.5",children:[t.jsx("span",{className:"text-xs font-medium",children:o("calendar.modal.labelExpiry")}),t.jsx("input",{className:"input",type:"date",value:h,onChange:w=>b(w.target.value)}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:o("calendar.modal.hintExpiry")})]}),t.jsxs("details",{children:[t.jsx("summary",{className:"text-xs text-ink-mute cursor-pointer",children:o("calendar.modal.advanced")}),t.jsxs("label",{className:"flex flex-col gap-1.5 mt-3",children:[t.jsx("span",{className:"text-xs font-medium",children:o("calendar.modal.labelBaseUrl")}),t.jsx("input",{className:"input font-mono",value:f,onChange:w=>x(w.target.value),placeholder:"https://calendario.miempresa.com/api/v2",maxLength:300}),t.jsx("span",{className:"text-[11px] text-ink-mute",children:o("calendar.modal.hintBaseUrl")})]})]}),t.jsxs("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-brand-600 hover:underline inline-flex items-center gap-1 w-fit",children:[o("calendar.modal.guideLink"),t.jsx(Ja,{className:"size-3"})]})]})})}const lL={active:"chip-mint",unverified:"chip-amber",error:"chip-rose",revoked:"chip-rose",disabled:"chip"};function cL(){const{t:e}=M("misc"),a=xe(),{can:n}=tt(),s=n("integrations.manage"),[i,r]=m.useState(!1),[o,l]=m.useState(null),[c,d]=m.useState(null),[u,p]=m.useState(null),f=["calendar-connections"],{data:x,isLoading:h,error:b}=se({queryKey:f,queryFn:async()=>{try{return(await T.get("/scheduling/connections")).data}catch(j){const C=j?.response?.status;if(C===501||C===404)return null;throw j}}}),g=oe({mutationFn:async j=>(await T.post("/scheduling/connections",j)).data,onSuccess:()=>{a.invalidateQueries({queryKey:f}),r(!1),J({tone:"ok",title:e("calendar.flashConnected")})},onError:j=>d(hl(j))}),v=oe({mutationFn:async j=>(await T.patch(`/scheduling/connections/${j.id}`,j.body)).data,onSuccess:()=>{a.invalidateQueries({queryKey:f}),r(!1),l(null)},onError:j=>d(hl(j))}),y=oe({mutationFn:async j=>({id:j,r:(await T.post(`/scheduling/connections/${j}/test`)).data}),onSuccess:({id:j,r:C})=>{a.invalidateQueries({queryKey:f}),p({id:j,r:C}),C.ok||J({tone:"bad",title:e("calendar.flashTestFailed")})},onError:j=>J({tone:"bad",title:hl(j)})}),k=oe({mutationFn:async j=>(await T.delete(`/scheduling/connections/${j}`)).data,onSuccess:()=>{a.invalidateQueries({queryKey:f}),J({tone:"ok",title:e("calendar.flashDeleted")})},onError:j=>J({tone:"bad",title:hl(j)})});if(!h&&x===null)return null;const w=x??[];return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-sm font-semibold",children:e("calendar.title")}),t.jsx("p",{className:"text-sm text-ink-mute max-w-xl mt-1",children:e("calendar.desc")})]}),s&&t.jsxs("button",{className:"btn btn-primary h-9 px-4 shrink-0",onClick:()=>{l(null),d(null),r(!0)},children:[t.jsx(Fe,{className:"size-4"}),e("calendar.connect")]})]}),h?t.jsx("div",{className:"cia-card",style:{padding:16},children:t.jsx(ge,{w:"60%",h:14})}):b?t.jsx(le,{tone:"bad",children:e("calendar.loadError")}):w.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{icon:Zn,title:e("calendar.emptyTitle"),desc:e("calendar.emptyDesc"),action:s?{label:e("calendar.connect"),onClick:()=>{l(null),d(null),r(!0)}}:void 0,mini:!0})}):t.jsx("div",{className:"flex flex-col gap-3",children:w.map(j=>t.jsxs("div",{className:"cia-card",style:{padding:16},children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"font-medium text-sm",children:j.label}),t.jsx("span",{className:lL[j.status]??"chip",children:e(`calendar.status.${j.status}`,{defaultValue:j.status})}),j.statusReason&&t.jsx("span",{className:"text-[11px] text-ink-mute",children:e(`calendar.reason.${j.statusReason}`,{defaultValue:j.statusReason})})]}),t.jsxs("div",{className:"text-xs text-ink-mute mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[j.apiKeyLastFour&&t.jsxs("span",{className:"font-mono",children:["····",
975j.apiKeyLastFour]}),t.jsx("span",{children:e("calendar.eventTypes",{count:j.eventTypesCount})}),j.lastOkAt&&t.jsx("span",{children:e("calendar.lastOk",{when:Be(j.lastOkAt)})})]})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[t.jsxs("button",{className:"btn btn-outline h-8",onClick:()=>y.mutate(j.id),disabled:y.isPending,title:e("calendar.test"),children:[y.isPending&&y.variables===j.id?t.jsx(je,{className:"size-4 animate-spin"}):t.jsx(c2,{className:"size-4"}),e("calendar.test")]}),s&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-ghost cia-btn-icon",onClick:()=>{l(j),d(null),r(!0)},"aria-label":e("calendar.edit"),title:e("calendar.edit"),children:t.jsx(qt,{className:"size-4"})}),t.jsx("button",{className:"btn btn-ghost cia-btn-icon",onClick:()=>k.mutate(j.id),disabled:k.isPending,"aria-label":e("calendar.delete"),title:e("calendar.delete"),children:t.jsx(mt,{className:"size-4"})})]})]})]}),typeof j.apiKeyExpiresInDays=="number"&&j.apiKeyExpiresInDays<=14&&t.jsx("div",{className:"mt-3",children:t.jsx(le,{tone:j.apiKeyExpiresInDays<=0?"bad":"warn",children:j.apiKeyExpiresInDays<=0?e("calendar.keyExpired"):e("calendar.keyExpiring",{days:j.apiKeyExpiresInDays})})}),u?.id===j.id&&t.jsx(dL,{r:u.r})]},j.id))}),t.jsx(oL,{open:i,onClose:()=>{r(!1),l(null)},onSave:j=>o?v.mutate({id:o.id,body:j}):g.mutate(j),saving:g.isPending||v.isPending,initial:o,error:c})]})}function dL({r:e}){const{t:a}=M("misc");return t.jsxs("div",{className:"mt-3 flex flex-col gap-2 border-t border-paper-line pt-3",children:[e.ok?t.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-mint-600",children:[t.jsx(Nt,{className:"size-4"}),a("calendar.testOk")]}):t.jsx(le,{tone:"bad",children:a(`calendar.reason.${e.statusReason??"unknown"}`,{defaultValue:e.detalle||a("calendar.testFailedGeneric")})}),e.calendarioConectadoSano===!1&&t.jsx(le,{tone:"bad",children:a("calendar.calendarDisconnected")}),e.horario&&t.jsxs("div",{className:"text-xs",children:[t.jsx("span",{className:"text-ink-mute",children:a("calendar.scheduleWindow",{nombre:e.horario.nombre||a("calendar.scheduleUnnamed"),abre:e.horario.abre,cierra:e.horario.cierra,tz:e.horario.timeZone||"—"})}),e.horario.problemas.map(n=>t.jsx("div",{className:"mt-1",children:t.jsx(le,{tone:"warn",children:a(`calendar.scheduleProblem.${n}`,{defaultValue:n,abre:e.horario.abre,cierra:e.horario.cierra})})},n))]}),e.eventTypes.map(n=>t.jsxs("div",{className:"text-xs flex flex-col gap-1",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"font-medium",children:n.title}),n.lengthInMinutes&&t.jsx("span",{className:"text-ink-mute",children:a("calendar.minutes",{n:n.lengthInMinutes})}),n.exigeCorreo&&t.jsx("span",{className:"chip chip-amber",children:a("calendar.requiresEmail")}),!!n.minimumBookingNotice&&t.jsxs("span",{className:"text-ink-mute inline-flex items-center gap-1",children:[t.jsx(Qa,{className:"size-3"}),a("calendar.notice",{n:n.minimumBookingNotice})]})]}),n.problemas.map(s=>t.jsxs("div",{className:"flex items-start gap-1.5 text-rose-700",children:[t.jsx(Tt,{className:"size-3.5 mt-0.5 shrink-0"}),t.jsx("span",{children:a(`calendar.problem.${s}`,{defaultValue:s})})]},s)),n.camposObligatoriosSinCubrir.length>0&&t.jsxs("div",{className:"flex items-start gap-1.5 text-rose-700",children:[t.jsx(Tt,{className:"size-3.5 mt-0.5 shrink-0"}),t.jsx("span",{children:a("calendar.requiredFields",{fields:n.camposObligatoriosSinCubrir.join(", ")})})]})]},n.id))]})}function hl(e){const a=e?.response?.data?.message;return Array.isArray(a)?a.join(" · "):a||he.t("misc:errors.generic")}function uL(){const{t:e}=M("misc"),a=xt(s=>s.resolved),{can:n}=tt();return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("integraciones.eyebrow"),title:e("integraciones.title")}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":a,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-fade-up flex flex-col gap-8",style:{width:"100%",maxWidth:960,padding:24},children:[n("integrations.view")&&t.jsx(cL,{}),n("webhooks.view")&&t.jsx(K0,{})]})})]})}function So({eyebrow:e,title:a,icon:n,description:s,features:i}){const{t:r}=M("layout"),o=xt(l=>l.resolved);return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e,title:a}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":o,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:"100%",padding:24},children:t.jsxs("div",{className:"cia-card cia-fade-up",style:{maxWidth:460,width:"100%",padding:"40px 32px",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",gap:18},children:[t.jsxs("div",{style:{position:"relative",width:72,height:72,borderRadius:"var(--cia-r-lg)",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",background:"linear-gradient(135deg, var(--cia-brand-500), var(--cia-cta-500))",boxShadow:"0 8px 24px -8px color-mix(in oklab, var(--cia-cta-500) 55%, transparent)"},children:[t.jsx(n,{size:32,strokeWidth:1.6,"aria-hidden":"true"}),t.jsx("span",{style:{position:"absolute",bottom:-6,right:-6,width:26,height:26,borderRadius:"50%",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--cia-warn-500)"},children:t.jsx(OS,{size:14,"aria-hidden":"true"})})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx("span",{className:"cia-soon-tag",style:{alignSelf:"center"},children:r("comingSoon.tag")}),t.jsx("h2",{style:{margin:0,fontSize:22,fontWeight:600,letterSpacing:"-0.02em"},children:a}),t.jsx("p",{style:{margin:0,fontSize:13.5,lineHeight:1.6,color:"var(--cia-text-3)"},children:s})]}),i&&i.length>0&&t.jsx("ul",{style:{listStyle:"none",margin:"4px 0 0",padding:0,width:"100%",display:"flex",flexDirection:"column",gap:8,textAlign:"left"},children:i.map(l=>
975t.jsxs("li",{style:{display:"flex",alignItems:"flex-start",gap:9,fontSize:13,color:"var(--cia-text-2)"},children:[t.jsx("span",{style:{flex:"none",width:18,height:18,marginTop:1,borderRadius:"50%",background:"color-mix(in oklab, var(--cia-ok-500) 18%, transparent)",color:"var(--cia-ok-600)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:t.jsx(ct,{size:11,strokeWidth:2.5,"aria-hidden":"true"})}),t.jsx("span",{children:l})]},l))})]})})})]})}const pL={confirmed:"chip-mint",pending:"chip-amber",unknown:"chip-amber",rescheduled:"chip",cancelled:"chip",failed:"chip-rose",no_show:"chip-rose",completed:"chip-mint"},hL={voice:dn,campaign:kc,portal:iy,provider:Zn};function mL(){const{t:e}=M("appointments"),a=xt(p=>p.resolved),[n,s]=m.useState("live"),[i,r]=m.useState([]),o=i[i.length-1],{data:l,isLoading:c,error:d}=se({queryKey:["appointments",n,o??""],queryFn:async()=>{try{const p=new URLSearchParams({scope:n});return o&&p.set("cursor",o),(await T.get(`/appointments?${p.toString()}`)).data}catch(p){const f=p?.response?.status;if(f===501||f===404)return null;throw p}}});if(!c&&l===null)return t.jsx(So,{eyebrow:e("eyebrow"),title:e("title"),icon:Zn,description:e("soon.desc"),features:[e("soon.f1"),e("soon.f2"),e("soon.f3")]});const u=l?.items??[];return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("eyebrow"),title:e("title")}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":a,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-fade-up",style:{width:"100%",maxWidth:1100,padding:24},children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-4 flex-wrap",children:[t.jsx("p",{className:"text-sm text-ink-mute max-w-2xl",children:e("desc")}),t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:["live","all"].map(p=>t.jsx("button",{className:`btn h-8 ${n===p?"btn-primary":"btn-outline"}`,onClick:()=>{s(p),r([])},children:e(`scope.${p}`)},p))})]}),c?t.jsx("div",{className:"cia-card",style:{padding:16},children:t.jsx(ge,{w:"55%",h:14})}):d?t.jsx(le,{tone:"bad",children:e("loadError")}):u.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{icon:Zn,title:e(n==="live"?"emptyLiveTitle":"emptyTitle"),desc:e("emptyDesc"),mini:!0})}):t.jsx("div",{className:"flex flex-col gap-2",children:u.map(p=>{const f=hL[p.createdVia]??Zn;return t.jsx("div",{className:"cia-card",style:{padding:14},children:t.jsx("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx(f,{className:"size-4 text-ink-mute shrink-0"}),t.jsx("span",{className:"font-medium text-sm",children:p.startAt?Be(p.startAt):e("noStart")}),t.jsx("span",{className:pL[p.status]??"chip",children:e(`status.${p.status}`,{defaultValue:p.status})}),p.rescheduleCount>0&&t.jsxs("span",{className:"text-[11px] text-ink-mute inline-flex items-center gap-1",children:[t.jsx(n2,{className:"size-3"}),e("movedTimes",{count:p.rescheduleCount})]})]}),t.jsxs("div",{className:"text-xs text-ink-mute mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[t.jsx("span",{children:p.attendeeName||e("noName")}),p.attendeeEmail?t.jsx("span",{children:p.attendeeEmail}):t.jsx("span",{children:p.attendeePhone?e("byPhone",{phone:p.attendeePhone}):e("noContact")}),p.durationMinutes?t.jsx("span",{children:e("minutes",{n:p.durationMinutes})}):null,t.jsx("span",{children:p.timeZone}),p.connectionLabel&&t.jsx("span",{children:p.connectionLabel}),t.jsx("span",{children:e(`via.${p.createdVia}`,{defaultValue:p.createdVia})})]}),p.cancelReason&&t.jsx("div",{className:"text-[11px] text-ink-mute mt-1",children:e("cancelReason",{reason:p.cancelReason})})]})})},p.id)})}),(l?.nextCursor||i.length>0)&&t.jsxs("div",{className:"flex items-center justify-between gap-2 mt-4",children:[t.jsx("button",{className:"btn btn-outline h-8",disabled:i.length===0,onClick:()=>r(p=>p.slice(0,-1)),children:e("prev")}),t.jsx("button",{className:"btn btn-outline h-8",disabled:!l?.nextCursor,onClick:()=>l?.nextCursor&&r(p=>[...p,l.nextCursor]),children:e("next")})]})]})})]})}function fL(){const{t:e}=M("misc"),a=xt(n=>n.resolved);return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("secrets.eyebrow"),title:e("secrets.title")}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":a,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsx("div",{className:"cia-fade-up",style:{width:"100%",maxWidth:760,padding:24},children:t.jsx(UP,{})})})]})}const x1=["meetings","list"],Bi={list:e=>[...x1,e],detail:e=>["meetings","detail",e],segments:(e,a)=>["meetings","segments",e,a],analytics:e=>["meetings","analytics",e]};
975function g1(e){return!!e&&iM.includes(e)}function xL(e){return!!e?.some(a=>g1(a.status))}function gL(e){return se({queryKey:Bi.list(e),queryFn:async()=>{const a=new URLSearchParams;a.set("page",String(e.page+1)),a.set("limit",String(e.limit)),e.search&&a.set("search",e.search),e.status&&e.status!=="all"&&a.set("status",e.status),e.platform&&e.platform!=="all"&&a.set("platform",e.platform);try{const{data:n}=await T.get(`/meetings?${a.toString()}`);return{available:!0,items:n.items,total:n.total}}catch(n){const s=n?.response?.status;if(s===501||s===404)return{available:!1,items:[],total:0};throw n}},placeholderData:xc,refetchInterval:a=>xL(a.state.data?.items)?5e3:!1})}function N9(e){return se({queryKey:Bi.detail(e??""),queryFn:async()=>(await T.get(`/meetings/${e}`)).data,enabled:!!e,refetchInterval:a=>g1(a.state.data?.meeting.status)?5e3:!1})}function S9(e,a){return se({queryKey:Bi.segments(e??"",a),queryFn:async()=>(await T.get(`/meetings/${e}/segments?offset=0&limit=${a}`)).data,enabled:!!e,placeholderData:xc})}async function C9(e){const{data:a}=await T.get(`/meetings/${e}/recording-url`);return a.url}async function _9(e){const{data:a}=await T.get(`/meetings/${e}/video-url`);return a.url}function E9(e,a=!0){return se({queryKey:Bi.analytics(e),queryFn:async()=>{const{data:n}=await T.get(`/meetings/${e}/analytics`);return n},enabled:a,staleTime:10*6e4})}function Co(e){e.invalidateQueries({queryKey:x1})}function A9(){const e=xe();return oe({mutationFn:async a=>{const n=new FormData;return n.append("file",a.file),a.title&&n.append("title",a.title),(await T.post("/meetings/upload",n,{timeout:18e4,onUploadProgress:s=>{s.total&&a.onProgress?.(Math.round(s.loaded/s.total*100))}})).data},onSuccess:()=>Co(e)})}function R9(){const e=xe();return oe({mutationFn:async a=>(await T.post("/meetings/invite",a)).data,onSuccess:()=>Co(e)})}function bL(){const e=xe();return oe({mutationFn:async a=>(await T.post(`/meetings/${a}/cancel`)).data,onSuccess:(a,n)=>{Co(e),e.invalidateQueries({queryKey:Bi.detail(n)})}})}const T9=new Set(["capture_needs_signin","capture_bad_link","bot_not_admitted"]);function M9(){const e=xe();return oe({mutationFn:async a=>(await T.post(`/meetings/${a}/retry`)).data,onSuccess:(a,n)=>{Co(e),e.invalidateQueries({queryKey:Bi.detail(n)})}})}function P9(){const e=xe();return oe({mutationFn:async a=>(await T.delete(`/meetings/${a}`)).data,onSuccess:()=>Co(e)})}const yL={meet:j2,zoom:k2,teams:XS,upload:Zp};function z9(e){return yL[e]??Zp}const vL={scheduled:"neutral",capturing:"info",processing:"info",ready:"success",failed:"danger",blocked_by_optout:"warning",cancelled:"neutral",purged:"neutral"};function jL(e){return vL[e]??"neutral"}const wL=["scheduled","capturing","processing"];function kL(e){return wL.includes(e)}function NL({status:e}){const{t:a}=M("meetings");return t.jsx(at,{label:a(`pipeline.status.${e}`,{defaultValue:e}),tone:jL(e),spinning:kL(e)})}const b1=6;function tu(e){const a=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${a}-${n}-${s}`}function SL(e,a=new Date){const n=tu(a),s=new Date(a.getTime()+1440*60*1e3),i=tu(s),r=new Map,o=e.map(l=>({e:l,t:l.startsAt?Date.parse(l.startsAt):NaN})).filter(l=>Number.isFinite(l.t)).sort((l,c)=>l.t-c.t);for(const{e:l,t:c}of o){const d=new Date(c),u=tu(d);let p=r.get(u);p||(p={dayKey:u,labelKind:u===n?"today":u===i?"tomorrow":"date",date:new Date(d.getFullYear(),d.getMonth(),d.getDate()),items:[]},r.set(u,p)),p.items.push(l)}return[...r.values()]}function CL(e,a){const n=e.reduce((o,l)=>o+l.items.length,0);if(a)return{groups:e,hiddenCount:0};const s=[];let i=0;for(const o of e){if(o.labelKind==="today"||o.labelKind==="tomorrow"||i<b1){s.push(o),i+=o.items.length;continue}break}const r=Math.max(0,n-i);return r<=1?{groups:e,hiddenCount:0}:{groups:s,hiddenCount:r}}function _L(e){return e.filter(a=>!!a.joinUrl).length}function EL(e){return e.toLocaleDateString(Te(),{weekday:"long",day:"numeric",month:"short"})}const bg={google:"Google Calendar",microsoft:"Microsoft Calendar (Outlook)"};function ur(e){const a=e.meeting?.status;return a==="ready"?{key:"calendar.chip.recorded",tone:"ok"}:a==="processing"?{key:"calendar.chip.processing",tone:"brand"}:a==="capturing"?{key:"calendar.chip.recording",tone:"brand"}:a==="scheduled"?{key:"calendar.chip.botScheduled",tone:"brand"}:a==="failed"?{key:"calendar.chip.failed",tone:"bad"}:AL(e)?{key:"calendar.inProgress",tone:"ok"}:null}function AL(e){if(!e.startsAt)return!1;const a=Date.parse(e.startsAt);if(!Number.isFinite(a)||a>Date.now())return!1;const n=e.endsAt?Date.parse(e.endsAt):NaN;return Number.isFinite(n)?n>Date.now():!0}function yg({email:e}){const{t:a}=M("meetings"),[n,s]=m.useState(!1),i=async()=>{try{await navigator.clipboard.writeText(e),s(!0),window.setTimeout(()=>s(!1),2e3)}catch{J({tone:"bad",title:a("calendar.mailbox.copyError")})}};return t.jsxs("div",{className:"cia-card",style:{padding:16,display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx(Kr,{size:16,"aria-hidden":!0,style:{color:"var(--cia-text-3)",flex:"none"}}),t.jsx("div",{style:{fontSize:13.5,fontWeight:600},children:a("calendar.mailbox.title")})]}),t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)",lineHeight:1.6},children:a("calendar.mailbox.desc")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx("code",{className:"cia-mono",style:{padding:"6px 10px",borderRadius:"var(--cia-r-sm)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-tint)",fontSize:12.5,userSelect:"all"},children:e}),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",onClick:()=>void i(),children:[n?t.jsx(ct,{size:14}):t.jsx(bn,{size:14}),a(n?"calendar.mailbox.copied":"calendar.mailbox.copy")]})]}),t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:a("calendar.mailbox.hint")})]})}function RL(){const{t:e}=M("meetings"),[a,n]=m.useState(!1),[s,i]=m.useState(!1),r=se({queryKey:["meetings","admin-consent-url"],queryFn:async()=>(await T.get("/integrations/calendar/microsoft/admin-consent-url")).data,enabled:a,staleTime:10*6e4}),o=async()=>
975{if(r.data?.url)try{await navigator.clipboard.writeText(r.data.url),i(!0),window.setTimeout(()=>i(!1),2e3)}catch{J({tone:"bad",title:e("calendar.adminConsent.copyError")})}};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("button",{type:"button",onClick:()=>n(l=>!l),"aria-expanded":a,style:{alignSelf:"flex-start",background:"none",border:0,padding:0,cursor:"pointer",fontSize:12,color:"var(--cia-brand-500)",textDecoration:"underline"},children:e("calendar.adminConsent.toggle")}),a&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:"var(--cia-r)",background:"var(--cia-bg-tint)",border:"1px solid var(--cia-border)"},children:[t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-2)",lineHeight:1.6},children:e("calendar.adminConsent.desc")}),r.isLoading&&t.jsx(ge,{w:"100%",h:32}),r.data?.url&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx("code",{className:"cia-mono cia-scroll cia-scroll-x",style:{flex:1,minWidth:200,padding:"6px 10px",borderRadius:"var(--cia-r-sm)",border:"1px solid var(--cia-border)",background:"var(--cia-bg)",fontSize:11,whiteSpace:"nowrap"},children:r.data.url}),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",onClick:()=>void o(),children:[s?t.jsx(ct,{size:14}):t.jsx(bn,{size:14}),e(s?"calendar.mailbox.copied":"calendar.mailbox.copy")]})]}),r.isError&&t.jsx(le,{tone:"warn",children:e("calendar.adminConsent.unavailable")})]})]})}function vg(){const{t:e}=M("meetings"),a=rt(C=>C.isActive()),n=Pe(C=>C.user),s=xe(),i=m.useRef(null),[r,o]=m.useState(null),[l,c]=m.useState(null),d=se({queryKey:["meetings","preferences"],retry:!1,queryFn:async()=>(await T.get("/meetings/preferences")).data}),u=lt(n,"meetings.operate"),p=d.data?.botName??"",f=r??p,x=r!==null&&r.trim()!==p,h=d.data?.summaryEmail??"",b=l??h,g=l!==null&&l.trim()!==h,v=d.data?.summaryToAttendees??!1,y=oe({mutationFn:async C=>(await T.patch("/meetings/preferences",C)).data,onSuccess:C=>{s.setQueryData(["meetings","preferences"],C),o(null),c(null),J({tone:"ok",title:e("identity.toastSaved")})},onError:C=>J({tone:"bad",title:C?.response?.data?.message??e("calendar.toastError")})}),k=oe({mutationFn:async C=>{const N=new FormData;return N.append("file",C),(await T.post("/meetings/preferences/avatar",N)).data},onSuccess:C=>{s.setQueryData(["meetings","preferences"],C),J({tone:"ok",title:e("identity.toastPhotoSaved")})},onError:C=>{const N=C?.response?.data?.message;
975J({tone:"bad",title:(Array.isArray(N)?N[0]:N)??e("calendar.toastError")})}}),w=oe({mutationFn:async()=>(await T.delete("/meetings/preferences/avatar")).data,onSuccess:C=>{s.setQueryData(["meetings","preferences"],C),J({tone:"ok",title:e("identity.toastPhotoRemoved")})},onError:C=>{const N=C?.response?.data?.message;J({tone:"bad",title:(Array.isArray(N)?N[0]:N)??e("calendar.toastError")})}});if(d.isError)return null;if(d.isLoading)return t.jsx(ge,{h:88});const j=d.data;return j?t.jsxs("div",{className:"cia-card",style:{padding:16,display:"flex",flexDirection:"column",gap:12},children:[a&&t.jsx(le,{tone:"info",title:e("calendar.impersonation.title"),children:e("calendar.impersonation.desc")}),t.jsxs("fieldset",{disabled:a,style:{all:"unset",display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[t.jsx("div",{style:{width:44,height:44,borderRadius:"50%",overflow:"hidden",flex:"none",display:"grid",placeItems:"center",background:"var(--cia-surface-2)",border:"1px solid var(--cia-border)"},children:j.avatarUrl?t.jsx("img",{src:j.avatarUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):t.jsx(Ft,{size:20,"aria-hidden":!0,style:{color:"var(--cia-text-3)"}})}),t.jsxs("div",{style:{flex:1,minWidth:200},children:[t.jsx("div",{style:{fontSize:13.5,fontWeight:600,color:"var(--cia-text)"},children:e("identity.title")}),t.jsx("p",{style:{margin:"2px 0 0",fontSize:12,color:"var(--cia-text-3)",lineHeight:1.5},children:e("identity.subtitle")})]})]}),u&&t.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:10,flexWrap:"wrap"},children:[t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:5,flex:1,minWidth:220},children:[t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-2)",fontWeight:500},children:e("identity.nameLabel")}),t.jsx("input",{className:"cia-input",maxLength:80,value:f,placeholder:j.defaultBotName,onChange:C=>o(C.target.value)})]}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-primary cia-btn-sm",disabled:!x&&!g||y.isPending,onClick:()=>y.mutate({botName:f.trim()||null,...g?{summaryEmail:b.trim()||null}:{}}),children:e("identity.save")}),t.jsx("input",{ref:i,type:"file",accept:"image/jpeg",style:{display:"none"},onChange:C=>{const N=C.target.files?.[0];N&&k.mutate(N),C.target.value=""}}),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",disabled:k.isPending,onClick:()=>i.current?.click(),children:[t.jsx(qS,{size:14,"aria-hidden":!0})," ",e("identity.uploadPhoto")]}),j.avatarUrl&&t.jsxs("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",disabled:w.isPending,onClick:()=>w.mutate(),children:[t.jsx(mt,{size:14,"aria-hidden":!0})," ",e("identity.removePhoto")]}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-4)",flexBasis:"100%"},children:e("identity.photoHint")}),j.summaryEmailEnabled&&t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:5,flexBasis:"100%"},children:[t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-2)",fontWeight:500},children:e("identity.summaryEmailLabel")}),t.jsx("input",{className:"cia-input",type:"email",maxLength:180,value:b,placeholder:j.accountEmail??"",onChange:C=>c(C.target.value)}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-4)"},children:e("identity.summaryEmailHint",{email:j.deliversTo??"—"})}),t.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:8,marginTop:8,cursor:"pointer"},children:[t.jsx("input",{type:"checkbox",checked:v,onChange:C=>y.mutate({summaryToAttendees:C.target.checked}),style:{marginTop:2,width:15,height:15,accentColor:"var(--cia-brand-500)"}}),t.jsxs("span",{children:[t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-2)",fontWeight:500},children:e("identity.toAttendeesLabel")}),t.jsx("span",{style:{display:"block",fontSize:11.5,color:"var(--cia-text-4)",lineHeight:1.5},children:e("identity.toAttendeesHint")})]})]})]})]})]})]}):null}function TL(){const{t:e}=M("meetings"),a=Pe(E=>E.user),n=xe(),[s,i]=m.useState(!0),[r,o]=m.useState(!1),[l,c]=m.useState("upcoming"),d=gL({page:0,limit:5,status:"all",platform:"all"}),u=bL(),f=se({queryKey:["meetings","preferences"],queryFn:async()=>(await T.get("/meetings/preferences")).data,staleTime:6e4}).data?.assistantEmail??null;m.useEffect(()=>{const E=new URLSearchParams(window.location.search),I=E.get("calendar");if(!I)return;J(I==="connected"?{tone:"ok",title:e("calendar.toastConnected")}:I==="adminconsent"?{tone:"ok",title:e("calendar.adminConsent.approved"),duration:1e4}:I==="adminconsent_error"?{tone:"bad",title:e("calendar.adminConsent.approvedError"),duration:1e4}:I==="noscope"?{tone:"warn",title:e("calendar.toastNoScope"),duration:1e4}:{tone:"bad",title:e("calendar.toastError")}),E.delete("calendar");const P=E.toString();window.history.replaceState(null,"",`${window.location.pathname}${P?`?${P}`:""}`)},[e]);const x=se({queryKey:["calendar","identities"],queryFn:async()=>{const{data:E}=await T.get("/integrations/calendar");return E},retry:!1}),h=x.data?.identities??[],b=h.some(E=>E.status==="active"),g=se({queryKey:["calendar","events"],enabled:b,retry:!1,queryFn:async()=>{const{data:E}=await T.get("/integrations/calendar/events");return E.items}}),v=oe({mutationFn:async E=>{const{data:I}=await T.get(`/integrations/calendar/${E}/start`);return I.url},onSuccess:E=>{window.location.href=E},onError:E=>{J({tone:"bad",title:E?.response?.data?.message??e("calendar.toastError")})}}),y=oe({mutationFn:async E=>T.delete(`/integrations/calendar/${E}`),onSuccess:()=>{J({tone:"ok",title:e("calendar.toastDisconnected")}),n.invalidateQueries({queryKey:["calendar"]})}}),k=oe({mutationFn:async E=>T.patch(`/integrations/calendar/${E.provider}/rules`,{autoJoinMode:E.autoJoinMode}),onSuccess:()=>{J({tone:"ok",title:e("calendar.toastRulesSaved")}),n.invalidateQueries({queryKey:["calendar"]})},onError:E=>J({tone:"bad",title:E?.response?.data?.message??e("calendar.toastError")})}),w=oe({mutationFn:async E=>{const{data:I}=await T.post("/meetings/invite",{joinUrl:E.joinUrl,...E.title?{title:E.title}:{},calendarEventId:E.id,...E.startsAt?{startAt:E.startsAt}:{}});return I},onSuccess:()=>{J({tone:"ok",title:e("calendar.toastBotInvited")}),n.invalidateQueries({queryKey:["calendar","events"]})},onError:E=>J({tone:"bad",title:E?.response?.data?.message??e("calendar.toastError")})}),j=g.data??[],C=_L(j),N=s?j.filter(E=>!!E.joinUrl):j,S=SL(N),{groups:_,hiddenCount:R}=CL(S,r);if(x.isLoading)return t.jsx(ge,{h:96});if(x.isError)return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(vg,{}),f&&t.jsx(yg,{email:f}),t.jsx(le,{tone:"info",title:e("calendar.unavailableTitle"),children:e("calendar.unavailableDesc")})]});const A=["google","microsoft"].filter(E=>x.data?.providers?.[E]);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(vg,{}),f&&t.jsx(yg,{email:f}),t.jsxs("div",{children:[t.jsx("h3",{style:{margin:0,fontSize:15,fontWeight:600,color:"var(--cia-text)"},children:e("calendar.title")}),t.jsx("p",{style:{margin:"4px 0 0",fontSize:13,color:"var(--cia-text-3)",lineHeight:1.6},children:e("calendar.subtitle")})]}),A.map(E=>{const I=h.find(O=>O.provider===E),P=I?.status==="active";return t.jsxs("div",{className:"cia-card",style:{padding:16,display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[t.jsx(Ps,{size:18,"aria-hidden":!0,style:{color:"var(--cia-text-3)",flex:"none"}}),t.jsxs("div",{style:{flex:1,minWidth:200},children:[t.jsx("div",{style:{fontSize:13.5,fontWeight:600,color:"var(--cia-text)"},children:bg[E]}),P?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12.5,color:"var(--cia-text-3)"},children:[t.jsx(Yr,{active:!0,tone:"ok",size:10}),t.jsx("span",{children:e("calendar.connectedAs",{email:I?.email??""})})]}):I?.status==="error"?t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12.5,color:"var(--cia-text-3)"},children:[t.jsx(Yr,{active:!0,tone:"bad",size:10}),t.jsx("span",{children:e("calendar.expired")})]}):t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:e("calendar.notConnected")})]}),lt(a,"meetings.operate")&&(P?t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",onClick:()=>y.mutate(E),disabled:y.isPending,children:[t.jsx(wi,{size:14,"aria-hidden":!0})," ",e("calendar.disconnect")]}):t.jsxs("button",{type:"button",className:"cia-btn cia-btn-primary",onClick:()=>v.mutate(E),disabled:v.isPending,children:[t.jsx(t2,{size:14,"aria-hidden":!0})," ",e("calendar.connect",{provider:bg[E]})]})),E==="microsoft"&&!P&&t.jsx("div",{style:{flexBasis:"100%",marginTop:4},children:t.jsx(RL,{})}),P&&lt(a,"meetings.operate")&&t.jsxs("div",{style:{flexBasis:"100%",display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",marginTop:4},children:[t.jsx("span",{style:{fontSize:12.5,color:"var(--cia-text-3)"},children:e("calendar.autoJoin.label")}
975),t.jsx(Yn,{ariaLabel:e("calendar.autoJoin.label"),value:I?.autoJoinMode??"none",onChange:O=>k.mutate({provider:E,autoJoinMode:O}),options:[{value:"none",label:e("calendar.autoJoin.none")},{value:"all",label:e("calendar.autoJoin.all")},{value:"organizer_only",label:e("calendar.autoJoin.organizerOnly")}]}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-4)",flexBasis:"100%"},children:e("calendar.autoJoin.hint")})]})]},E)}),b&&t.jsxs("div",{className:"cia-card",style:{padding:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,flexWrap:"wrap"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,flexWrap:"wrap"},children:[t.jsx("div",{style:{fontSize:13.5,fontWeight:600,color:"var(--cia-text)"},children:e("calendar.agendaTitle")}),l==="upcoming"&&j.length>0&&t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-4)"},children:e("calendar.upcomingCount",{total:j.length,withLink:C})})]}),t.jsx(Yn,{ariaLabel:e("calendar.agendaTitle"),value:l,onChange:E=>c(E),options:[{value:"upcoming",label:e("calendar.viewUpcoming")},{value:"recorded",label:e("calendar.viewRecorded")}]})]}),l==="upcoming"&&t.jsx("p",{style:{margin:"2px 0 8px",fontSize:11.5,color:"var(--cia-text-4)"},children:e("calendar.upcomingHint")}),l==="upcoming"&&j.length>C&&t.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,marginBottom:10,cursor:"pointer",fontSize:12,color:"var(--cia-text-3)"},children:[t.jsx("input",{type:"checkbox",checked:s,onChange:E=>i(E.target.checked),style:{width:14,height:14,accentColor:"var(--cia-brand-500)"}}),e("calendar.onlyWithLink",{count:j.length-C})]}),l==="recorded"?d.isLoading?t.jsx(ge,{h:72}):d.data?.items?.length?t.jsxs("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:6},children:[d.data.items.map(E=>t.jsxs("li",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",padding:"8px 10px",border:"1px solid var(--cia-border)",borderRadius:10},children:[t.jsxs("div",{style:{flex:1,minWidth:220},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600,color:"var(--cia-text)"},children:E.title||e("library.untitled")}),t.jsx(NL,{status:E.status})]}),t.jsxs("div",{className:"cia-mono",style:{fontSize:11.5,color:"var(--cia-text-3)"},children:[E.startedAt?Be(E.startedAt):Be(E.createdAt),E.durationSeconds?` · ${Ca(E.durationSeconds)}`:"",` · ${e(`library.platform.${E.platform}`)}`]})]}),t.jsxs("a",{className:"cia-btn cia-btn-outline cia-btn-sm",style:{fontSize:12,textDecoration:"none"},href:`/meetings/${E.id}`,children:[t.jsx(Ja,{size:13,"aria-hidden":!0})," ",e("calendar.openMeeting")]})]},E.id)),t.jsx("li",{style:{listStyle:"none"},children:t.jsx("a",{className:"cia-btn cia-btn-ghost cia-btn-sm",style:{textDecoration:"none"},href:"/meetings",children:e("calendar.seeAllMeetings")})})]}):t.jsx(st,{mini:!0,icon:Ta,title:e("calendar.recordedEmptyTitle"),desc:e("calendar.recordedEmptyDesc")}):g.isLoading?t.jsx(ge,{h:72}):g.isError?t.jsx(le,{tone:"warn",title:e("calendar.eventsErrorTitle"),children:g.error?.response?.data?.message??e("calendar.toastError")}):!g.data||g.data.length===0?t.jsx(st,{mini:!0,icon:Ps,title:e("calendar.upcomingEmptyTitle"),desc:e("calendar.upcomingEmptyDesc")}):t.jsxs(t.Fragment,{children:[_.map(E=>t.jsxs("div",{style:{marginBottom:12},children:[t.jsxs("div",{style:{fontSize:11,fontWeight:700,letterSpacing:".5px",textTransform:"uppercase",color:"var(--cia-text-4)",padding:"2px 0 6px"},children:[E.labelKind==="today"?e("calendar.day.today"):E.labelKind==="tomorrow"?e("calendar.day.tomorrow"):EL(E.date),t.jsxs("span",{style:{fontWeight:400,textTransform:"none",letterSpacing:0},children:[" · ",e("calendar.day.count",{count:E.items.length})]})]}),t.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:6},children:E.items.map(I=>t.jsxs("li",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",padding:"8px 10px",border:"1px solid var(--cia-border)",borderRadius:10},children:[t.jsxs("div",{style:{flex:1,minWidth:220},children:[t.jsxs("div",{style:{fontSize:13,fontWeight:600,color:"var(--cia-text)",display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[I.title||e("calendar.untitledEvent"),ur(I)&&t.jsx("span",{style:{fontSize:10.5,fontWeight:700,letterSpacing:".4px",textTransform:"uppercase",color:`var(--cia-${ur(I).tone}-500)`,background:`color-mix(in oklab, var(--cia-${ur(I).tone}-500) 12%, transparent)`,border:`1px solid color-mix(in oklab, var(--cia-${ur(I).tone}-500) 25%, transparent)`,borderRadius:999,padding:"1px 7px"},children:e(ur(I).key)})]}),t.jsxs("div",{className:"cia-mono",style:{fontSize:11.5,color:"var(--cia-text-3)"},children:[I.startsAt?Be(I.startsAt):"—",I.platform?` · ${e(`library.platform.${I.platform}`)}`:""]})]}),I.meeting&&["scheduled","capturing"].includes(I.meeting.status)?lt(a,"meetings.operate")&&t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",style:{fontSize:12},disabled:u.isPending,onClick:()=>u.mutate(I.meeting.id,{onSuccess:()=>{J({tone:"ok",title:e("calendar.toastBotRemoved")}),n.invalidateQueries({queryKey:["calendar","events"]})},onError:()=>J({tone:"bad",title:e("calendar.toastError")})}),children:[t.jsx(Hb,{size:13,"aria-hidden":!0})," ",e("calendar.removeBot")]}
975):I.meeting&&I.meeting.status!=="cancelled"?t.jsxs("a",{className:"cia-btn cia-btn-outline cia-btn-sm",style:{fontSize:12,textDecoration:"none"},href:`/meetings/${I.meeting.id}`,children:[t.jsx(Ja,{size:13,"aria-hidden":!0})," ",e("calendar.openMeeting")]}):I.joinUrl?lt(a,"meetings.operate")&&t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",style:{fontSize:12},onClick:()=>w.mutate(I),disabled:w.isPending,children:[t.jsx(Ja,{size:13,"aria-hidden":!0})," ",e("calendar.inviteBot")]}):t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-4)"},children:e("calendar.noVideoLink")})]},`${I.provider}:${I.id}`))})]},E.dayKey)),R>0&&t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{marginTop:2},onClick:()=>o(!0),children:e("calendar.showMore",{count:R})}),r&&j.length>b1&&t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{marginTop:2},onClick:()=>o(!1),children:e("calendar.showLess")})]})]})]})}const ML=[{key:"openai",label:"OpenAI"},{key:"anthropic",label:"Anthropic"},{key:"deepgram",label:"Deepgram"},{key:"elevenlabs",label:"ElevenLabs"},{key:"cartesia",label:"Cartesia"},{key:"google",label:"Google"}];function PL(){const{t:e}=M("settings"),a=xe(),{data:n,isLoading:s,error:i}=se({queryKey:["admin-ai-credentials"],queryFn:async()=>(await T.get("/admin/ai-credentials")).data});return t.jsxs("div",{className:"card p-5",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute",children:e("aiKeys.eyebrow")}),t.jsx("span",{className:"chip chip-brand !h-4 !text-[10px]",children:e("aiKeys.global")})]}),t.jsx("h3",{className:"text-lg font-semibold mt-1",children:e("aiKeys.title")}),t.jsx("p",{className:"text-sm text-ink-mute mt-1",children:e("aiKeys.desc")}),t.jsx("div",{className:"mt-5 flex flex-col gap-3",children:i?t.jsxs("div",{className:"flex items-center gap-2 text-sm text-rose-600",children:[t.jsx(Sc,{className:"size-4"}),e("aiKeys.loadError")]}):s?t.jsx("div",{className:"text-sm text-ink-mute",children:e("aiKeys.loading")}):ML.map(r=>t.jsx(zL,{providerKey:r.key,label:r.label,hint:e(`aiKeys.hints.${r.ke
975y}`),status:n?.[r.key],onChanged:()=>a.invalidateQueries({queryKey:["admin-ai-credentials"]})},r.key))})]})}function zL({providerKey:e,label:a,hint:n,status:s,onChanged:i}){const{t:r}=M("settings"),[o,l]=m.useState(!1),[c,d]=m.useState(""),[u,p]=m.useState(null),f=oe({mutationFn:async()=>{await T.put(`/admin/ai-credentials/${e}`,{apiKey:c})},onSuccess:()=>{l(!1),d(""),p(null),i()},onError:h=>{p(h?.response?.data?.message||r("aiKeys.saveError"))}}),x=oe({mutationFn:async()=>{await T.delete(`/admin/ai-credentials/${e}`)},onSuccess:i});return t.jsxs("div",{className:"rounded-xl border border-paper-line p-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("div",{className:"size-9 rounded-lg bg-brand-50 grid place-items-center",children:t.jsx(Ka,{className:"size-4 text-brand-700"})}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-medium text-sm flex items-center gap-2",children:[a,s?.configured&&t.jsxs("span",{className:"chip chip-mint !h-5 !text-[10px]",children:[t.jsx(ct,{className:"size-3"}),"····",s.lastFour]})]}),t.jsx("div",{className:"text-xs text-ink-mute",children:n})]})]}),!o&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{className:"btn btn-outline h-8",onClick:()=>l(!0),children:s?.configured?r("aiKeys.replace"):r("aiKeys.configure")}),s?.configured&&t.jsx("button",{className:"btn btn-outline h-8",disabled:x.isPending,onClick:()=>x.mutate(),title:r("aiKeys.deleteTitle"),children:x.isPending?t.jsx(je,{className:"size-3.5 animate-spin"}):t.jsx(mt,{className:"size-3.5"})})]})]}),o&&t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("input",{type:"password",className:"input font-mono text-[13px]",placeholder:r("aiKeys.keyPlaceholder",{provider:a}),value:c,onChange:h=>d(h.target.value),autoFocus:!0}),u&&t.jsx("div",{className:"text-xs text-rose-600",children:u}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("button",{className:"btn btn-primary h-8",disabled:!c||f.isPending,onClick:()=>f.mutate(),children:[f.isPending?t.jsx(je,{className:"size-3.5 animate-spin"}):t.jsx(ct,{className:"size-3.5"}),r("aiKeys.validateSave")]}),t.jsx("button",{className:"btn btn-outline h-8",onClick:()=>{l(!1),d(""),p(null)},children:r("aiKeys.cancel")})]}),t.jsx("p",{className:"text-[11px] text-ink-mute",children:r("aiKeys.validationNote",{provider:a})})]})]})}function DL(e){return e.role==="custom"&&e.customRoleId?`custom:${e.customRoleId}`:e.role}function y1(e){return e.startsWith("custom:")?{role:"custom",customRoleId:e.slice(7)}:{role:e}}function IL({adminOrgId:e}){const{can:a}=tt(),n=a("team.manage"),{t:s}=M("settings"),i=xe(),r=Pe(j=>j.user),[o,l]=m.useState(!1),[c,d]=m.useState(null),u=e?`/admin/organizations/${e}/users`:"/users",p=e?["admin-org-users",e]:["org-users"],{data:f,isLoading:x}=se({queryKey:p,queryFn:async()=>(await T.get(u)).data}),{data:h}=se({queryKey:["org-roles"],queryFn:async()=>(await T.get("/roles")).data,enabled:!e,staleTime:6e4}),b=h?.custom??[],g=j=>b.find(C=>C.id===j)?.name,v=j=>e?`/admin/users/${j}`:`/users/${j}`,y=j=>e?`/admin/users/${j}/reset-password`:`/users/${j}/reset-password`,k=oe({mutationFn:async({id:j,patch:C})=>(await T.patch(v(j),C)).data,onSuccess:()=>i.invalidateQueries({queryKey:p})}),w=oe({mutationFn:async j=>(await T.post(y(j))).data,onSuccess:j=>d({email:j.email,password:j.password,title:s("users.oneTime.passwordReset")})});return t.jsxs("div",{className:"card p-5",children:[t.jsxs("div",{className:"flex items-start justify-between",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute",children:s("users.eyebrow")}),t.jsx("h3",{className:"text-lg font-semibold mt-1",children:s("users.title")})]}),n&&t.jsxs("button",{className:"cia-btn cia-btn-cta",style:{gap:7,flex:"none"},onClick:()=>l(!0),children:[t.jsx(Fe,{size:15,"aria-hidden":!0}),s("users.newUser")]})]}),x?t.jsx("div",{className:"py-8 text-center text-sm text-ink-mute",children:s("users.loading")}):f?.length?t.jsx("div",{className:"mt-4 overflow-x-auto",children:t.jsxs("table",{className:"w-full text-sm",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"text-[10px] font-mono tracking-wider text-ink-mute border-b border-paper-line",children:[t.jsx("th",{className:"text-left py-2.5 pr-3",children:s("users.columns.user")}),t.jsx("th",{className:"text-left py-2.5 pr-3",children:s("users.columns.role")}),t.jsx("th",{className:"text-left py-2.5 pr-3",children:s("users.columns.status")}),t.jsx("th",{className:"text-left py-2.5 pr-3",children:s("users.columns.lastAccess")}),t.jsx("th",{className:"text-right py-2.5",children:s("users.columns.actions")})]})}),t.jsx("tbody",{children:f.map(j=>{const C=j.id===r?.id;return t.jsxs("tr",{className:"border-b border-paper-line/60",children:[t.jsxs("td",{className:"py-3 pr-3",children:[t.jsx("div",{className:"font-medium",children:j.name}),t.jsx("div",{className:"text-[11px] text-ink-mute",children:j.email})]}),t.jsx("td",{className:"py-3 pr-3",children:C?t.jsxs("span",{className:"chip chip-brand !text-[10px] inline-flex items-center gap-1",children:[t.jsx(ho,{className:"size-3"}),j.role==="custom"?g(j.customRoleId)??s("users.roles.custom"):s(`users.roles.${j.role}`,{defaultValue:j.role})]}):t.jsxs("select",{className:"input h-8 w-36 text-[13px]",value:DL(j),disabled:k.isPending||!n,title:n?void 0:s("common:noPermission"),onChange:N=>k.mutate({id:j.id,patch:y1(N.target.value)}),children:[t.jsx("option",{value:"admin",children:s("users.roles.admin")}),t.jsx("option",{value:"operator",children:s("users.roles.operator")}),t.jsx("option",{value:"viewer",children:s("users.roles.viewer")}),b.length>0&&t.jsx("optgroup",{label:s("users.roles.customGroup"),children:b.map(N=>t.jsx("option",{value:`custom:${N.id}`,children:N.name},N.id))})]})}),t.jsx("td",{className:"py-3 pr-3",children:j.active?t.jsx("span",{className:"chip chip-mint !text-[10px]",children:s("users.status.active")}):t.jsx("span",{className:"chip chip-rose !text-[10px]",children:s("users.status.inactive")})}),t.jsx("td",{className:"py-3 pr-3 text-[12px] text-ink-mute font-mono",children:j.lastLoginAt?new Date(j.lastLoginAt).toLocaleStr
975ing(Te()):s("users.never")}),t.jsx("td",{className:"py-3 text-right",children:t.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[n&&t.jsx("button",{className:"btn btn-outline h-8 !px-2.5",title:s("users.resetTitle"),disabled:w.isPending,onClick:async()=>{await pa({message:s("users.resetConfirm",{email:j.email})})&&w.mutate(j.id)},children:t.jsx(Ka,{className:"size-3.5"})}),n&&!C&&t.jsx("button",{className:"btn btn-outline h-8 !px-2.5",title:j.active?s("users.deactivateTitle"):s("users.activateTitle"),disabled:k.isPending,onClick:()=>k.mutate({id:j.id,patch:{active:!j.active}}),children:j.active?t.jsx(mo,{className:"size-3.5 text-rose-500"}):t.jsx(nh,{className:"size-3.5 text-mint-600"})})]})})]},j.id)})})]})}):t.jsx("div",{className:"py-8 text-center text-sm text-ink-mute",children:s("users.empty")}),o&&t.jsx(LL,{createUrl:u,customRoles:b,onClose:()=>l(!1),onCreated:j=>{l(!1),i.invalidateQueries({queryKey:p}),j&&d({...j,title:s("users.oneTime.userCreated")})}}),c&&t.jsx(FL,{creds:c,onClose:()=>d(null)})]})}function LL({createUrl:e,customRoles:a=[],onClose:n,onCreated:s}){const{t:i}=M("settings"),[r,o]=m.useState(""),[l,c]=m.useState(""),[d,u]=m.useState("viewer"),[p,f]=m.useState(null),x=oe({mutationFn:async()=>(await T.post(e,{name:r,email:l,...y1(d)})).data,onSuccess:b=>s(b.generatedPassword?{email:b.user.email,password:b.generatedPassword}:null),onError:b=>f(b?.response?.data?.message||i("users.create.error"))}),h=r.trim().length>=2&&/\S+@\S+\.\S+/.test(l);return t.jsx(v1,{title:i("users.create.title"),onClose:n,children:t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-ink-mute",children:i("users.create.name")}),t.jsx("input",{className:"input w-full mt-1",value:r,onChange:b=>o(b.target.value),placeholder:i("users.create.namePlaceholder"),autoFocus:!0})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-ink-mute",children:i("users.create.email")}),t.jsx("input",{className:"input w-full mt-1",type:"email",value:l,onChange:b=>c(b.target.value),placeholder:i("users.create.emailPlaceholder")})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-ink-mute",children:i("users.create.role")}),t.jsxs("select",{className:"input w-full mt-1",value:d,onChange:b=>u(b.target.value),children:[t.jsx("option",{value:"viewer",children:i("users.create.roleViewer")}),t.jsx("option",{value:"operator",children:i("users.create.roleOperator")}),t.jsx("option",{value:"admin",children:i("users.create.roleAdmin")}),a.length>0&&t.jsx("optgroup",{label:i("users.roles.customGroup"),children:a.map(b=>t.jsx("option",{value:`custom:${b.id}`,children:b.name},b.id))})]})]}),t.jsx("p",{className:"text-[11px] text-ink-mute",children:i("users.create.passwordNote")}),p&&t.jsx("p",{className:"text-[12px] text-rose-600",children:p}),t.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[t.jsx("button",{className:"btn btn-outline",onClick:n,children:i("users.create.cancel")}),t.jsxs("button",{className:"cia-btn cia-btn-cta",style:{gap:7},disabled:!h||x.isPending,onClick:()=>{f(null),x.mutate()},children:[x.isPending?t.jsx(je,{className:"size-4 animate-spin"}):t.jsx(Fe,{className:"size-4"}),i("users.create.create")]})]})]})})}function FL({creds:e,onClose:a}){const{t:n}=M("settings"),[s,i]=m.useState(!1);return t.jsx(v1,{title:e.title,onClose:a,children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("p",{className:"text-sm text-ink-soft",children:n("users.oneTime.copyNow")}),t.jsxs("div",{className:"rounded-xl border border-amber-300 bg-amber-50 p-4 space-y-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute",children:n("users.oneTime.email")}),t.jsx("div",{className:"font-mono text-sm",children:e.email})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute",children:n("users.oneTime.password")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("code",{className:"font-mono text-sm bg-white rounded-lg px-2 py-1 border border-amber-200 select-all",children:e.password}),t.jsx("button",{className:"btn btn-outline h-8 !px-2.5",onClick:()=>{navigator.clipboard.writeText(e.password),i(!0),setTimeout(()=>i(!1),1500)},children:s?t.jsx(ct,{className:"size-3.5 text-mint-600"}):t.jsx(bn,{className:"size-3.5"})})]})]})]}),t.jsx("div",{className:"flex justify-end",children:t.jsx("button",{className:"cia-btn cia-btn-cta",style:{gap:7},onClick:a,children:n("users.oneTime.done")})})]})})}function v1({title:e,onClose:a,children:n}){const{t:s}=M("settings");return t.jsx("div",{className:"fixed inset-0 z-50 bg-black/30 backdrop-blur-[2px] grid place-items-center p-4",onMouseDown:i=>{i.target===i.currentTarget&&a()},children:t.jsxs("div",{className:"card w-full max-w-md p-5 shadow-xl",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsx("h3",{className:"text-base font-semibold",children:e}),t.jsx("button",{className:"p-1.5 rounded-lg hover:bg-paper-line/40",onClick:a,"aria-label":s("receipt.close"),children:t.jsx(nt,{className:"size-4 text-ink-mute"})})]}),n]})})}const OL=["view","operate","manage","use"];function $L(){const{can:e}=tt(),a=e("team.manage"),{t:n}=M("settings"),s=xe(),[i,r]=m.useState(null),{data:o}=se({queryKey:["roles-catalog"],queryFn:async()=>(await T.get("/roles/catalog")).data,staleTime:5*6e4}),{data:l,isLoading:c}=se({queryKey:["org-roles"],queryFn:async()=>(await T.get("/roles")).data}),d=oe({mutationFn:async p=>(await T.delete(`/roles/${p}`)).data,onSuccess:()=>{s.invalidateQueries({queryKey:["org-roles"]}),J({tone:"ok",title:n("roles.deleted")})},onError:p=>{const f=p?.response?.data?.message;J({tone:"bad",title:Array.isArray(f)?f.join(" · "):f||n("roles.deleteError")})}}),u=oe({mutationFn:async p=>(await T.delete(`/roles/system/${p}`)).data,onSuccess:()=>{s.invalidateQueries({queryKey:["org-roles"]}),J({tone:"ok",title:n("roles.restored")})},onError:p=>{const f=p?.response?.data?.message;J({tone:"bad",title:Array.isArray(f)?f.join(" · "):f||n("roles.saveError")})}});return t.jsxs("div",{className:"card p-5",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] font-mono tracking-wider text-ink-mute",children:n("roles.eyebrow")}),t.jsx("h2",{className:"text-[15px] font-semibold mt-0.5",children:n("roles.title")}),t.jsx("p",{className:"text-[12.5px] text-ink-mute mt-1 max-w-[60ch]",children:n("roles.desc")})]}),a&&t.jsxs("button",{className:"cia-btn cia-btn-cta",style:{gap:7,flex:"none"},onClick:()=>r({kind:"new"}),children:[t.jsx(Fe,{size:15,"aria-hidden":!0}),n("roles.create")]})]}),c?t.jsx("div",{className:"py-8 grid place-items-center text-ink-mute",children:t.jsx(je,{className:"size-5 animate-spin"})}):t.jsx("div",{className:"mt-4 overflow-x-auto cia-scroll-x",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"text-[10.5px] uppercase tracking-wider text-ink-mute border-b border-paper-line",children:[t.jsx("th",{className:"text-left py-2.5 pr-3",children:n("roles.columns.name")}
975),t.jsx("th",{className:"text-left py-2.5 pr-3",children:n("roles.columns.permissions")}),t.jsx("th",{className:"text-left py-2.5 pr-3",children:n("roles.columns.users")}),t.jsx("th",{className:"py-2.5 text-right",children:n("roles.columns.actions")})]})}),t.jsxs("tbody",{children:[(l?.system??[]).map(p=>t.jsxs("tr",{className:"border-b border-paper-line/60",children:[t.jsxs("td",{className:"py-3 pr-3",children:[t.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium",children:[t.jsx(Cc,{className:"size-3.5 text-ink-mute"}),n(`users.roles.${p.role}`,{defaultValue:p.role})]}),t.jsx("span",{className:"chip !text-[10px] ml-2",children:n("roles.systemBadge")}),p.edited&&t.jsx("span",{className:"chip chip-brand !text-[10px] ml-1.5",children:n("roles.editedBadge")})]}),t.jsx("td",{className:"py-3 pr-3 text-ink-mute",children:n("roles.permissionsCount",{count:p.permissions.length})}),t.jsx("td",{className:"py-3 pr-3 text-ink-mute",children:"—"}),t.jsx("td",{className:"py-3 text-right",children:p.editable&&a?t.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[p.edited&&t.jsx("button",{className:"btn btn-outline h-8 !px-2.5 !text-[11px]",title:n("roles.restore"),disabled:u.isPending,onClick:async()=>{await pa({message:n("roles.restoreConfirm")})&&u.mutate(p.role)},children:t.jsx(po,{className:"size-3.5"})}),t.jsx("button",{className:"btn btn-outline h-8 !px-2.5",title:n("roles.edit"),onClick:()=>r({kind:"system",role:p}),children:t.jsx(qt,{className:"size-3.5"})})]}):t.jsx("span",{className:"text-[11px] text-ink-mute",children:n("roles.adminFull")})})]},p.role)),(l?.custom??[]).map(p=>t.jsxs("tr",{className:"border-b border-paper-line/60",children:[t.jsxs("td",{className:"py-3 pr-3",children:[t.jsx("div",{className:"font-medium",children:p.name}),p.description&&t.jsx("div",{className:"text-[11px] text-ink-mute",children:p.description})]}),t.jsx("td",{className:"py-3 pr-3 text-ink-mute",children:n("roles.permissionsCount",{count:p.permissions.length})}),t.jsx("td",{className:"py-3 pr-3 font-mono",children:p.users}),t.jsx("td",{className:"py-3 text-right",children:a&&t.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[t.jsx("button",{className:"btn btn-outline h-8 !px-2.5",title:n("roles.edit"),onClick:()=>r({kind:"custom",role:p}),children:t.jsx(qt,{className:"size-3.5"})}),t.jsx("button",{className:"p-1.5 rounded-lg text-ink-mute hover:text-rose-500 hover:bg-rose-50 transition-colors",title:n("roles.delete"),disabled:d.isPending,onClick:async()=>{await pa({message:n("roles.deleteConfirm",{name:p.name}),danger:!0})&&d.mutate(p.id)},children:t.jsx(mt,{className:"size-4"})})]})})]},p.id)),(l?.custom??[]).length===0&&t.jsx("tr",{children:t.jsx("td",{colSpan:4,className:"py-6 text-center text-[12.5px] text-ink-mute",children:n("roles.empty")})})]})]})}),i&&o&&t.jsx(qL,{catalog:o,editing:i,onClose:()=>r(null),onSaved:()=>{r(null),s.invalidateQueries({queryKey:["org-roles"]})}})]})}function qL({catalog:e,editing:a,onClose:n,onSaved:s}){const{t:i}=M("settings"),r=a.kind==="system",o=a.kind==="custom"?a.role:null,l=a.kind==="system"?a.role:null,[c,d]=m.useState(o?.name??""),[u,p]=m.useState(o?.description??""),[f,x]=m.useState(new Set(o?.permissions??l?.permissions??[])),[h,b]=m.useState(null),g=m.useMemo(()=>OL.filter(j=>e.modules.some(C=>C.actions.includes(j))),[e]),v=j=>{x(C=>{const N=new Set(C);return N.has(j)?N.delete(j):N.add(j),N})},y=oe({mutationFn:async()=>{if(r&&l)return(await T.patch(`/roles/system/${l.role}`,{permissions:[...f]})).data;const j={name:c.trim(),description:u.trim()||void 0,permissions:[...f]};return o?(await T.patch(`/roles/${o.id}`,j)).data:(await T.post("/roles",j)).data},onSuccess:()=>{J({tone:"ok",title:i(r||o?"roles.updated":"roles.created")}),s()},onError:j=>{const C=j?.response?.data?.message;b(Array.isArray(C)?C.join(" · "):C||i("roles.saveError"))}}),k=(r||c.trim().length>=2)&&f.size>0,w=r?i("roles.editSystemTitle",{name:i(`users.roles.${l.role}`,{defaultValue:l.role})}):o?i("roles.editTitle",{name:o.name}):i("roles.createTitle");return t.jsx(ot,{open:!0,onClose:n,eyebrow:i("roles.eyebrow"),title:w,maxWidth:680,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"cia-btn cia-btn-outline",onClick:n,disabled:y.isPending,children:i("roles.form.cancel")}),t.jsxs("button",{className:"cia-btn cia-btn-cta",style:{gap:7},disabled:!k||y.isPending,onClick:()=>{b(null),y.mutate()},children:[y.isPending?t.jsx(je,{size:14,className:"animate-spin","aria-hidden":!0}):t.jsx(Cc,{size:14,"aria-hidden":!0}),i(r||o?"roles.form.save":"roles.form.create")]})]}),children:t.jsxs("div",{className:"space-y-3",children:[r?t.jsx("p",{className:"text-[12px] text-ink-mute",children:i("roles.form.systemHint")}):t.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-ink-mute",children:i("roles.form.name")}),t.jsx("input",{className:"input w-full mt-1",value:c,onChange:j=>d(j.target.value),placeholder:i("roles.form.namePlaceholder"),maxLength:60,autoFocus:!0})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-ink-mute",children:i("roles.form.description")}),t.jsx("input",{className:"input w-full mt-1",value:u,onChange:j=>p(j.target.value),placeholder:i("roles.form.descriptionPlaceholder"),maxLength:200})]})]}),t.jsx("div",{className:"overflow-x-auto cia-scroll-x border border-paper-line rounded-xl",children:t.jsxs("table",{className:"w-full text-[12.5px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-ink-mute border-b border-paper-line",children:[t.jsx("th",{className:"text-left py-2 px-3",children:i("roles.form.module")}),g.map(j=>t.jsx("th",{className:"py-2 px-2 text-center w-24",children:i(`roles.actions.${j}`)},j))]})}),t.jsx("tbody",{children:e.modules.map(j=>t.jsxs("tr",{className:"border-b border-paper-line/50 last:border-0",children:[t.jsx("td",{className:"py-2 px-3 font-medium whitespace-nowrap",children:i(`roles.modules.${j.key}`,{defaultValue:j.key})}),g.map(C=>{const N=`${j.key}.${C}`,S=j.actions.includes(C);return t.jsx("td",{className:"py-2 px-2 text-center",children:S?t.jsx("input",{type:"checkbox",className:"size-4 accent-[var(--cia-brand-500)] curs
975or-pointer",checked:f.has(N),onChange:()=>v(N),"aria-label":`${i(`roles.modules.${j.key}`,{defaultValue:j.key})} — ${i(`roles.actions.${C}`)}`}):t.jsx("span",{className:"text-ink-mute/40",children:"·"})},C)})]},j.key))})]})}),t.jsx("p",{className:"text-[11px] text-ink-mute",children:i("roles.form.hint")}),h&&t.jsx("p",{className:"text-[12px] text-rose-600",children:h})]})})}function BL(){const{can:e}=tt(),a=e("organization.manage"),{t:n}=M("settings"),s=xe(),{data:i}=se({queryKey:["org","me"],queryFn:async()=>(await T.get("/organizations/me")).data}),r=i?.branding?.liveAlerts??{},[o,l]=m.useState(null),[c,d]=m.useState(null),[u,p]=m.useState(null),f=o??r.enabled!==!1,x=c??r.positive??"chime",h=u??r.negative??"alert",b=o!==null||c!==null||u!==null,g=oe({mutationFn:async()=>(await T.patch("/organizations/me/alert-settings",{enabled:f,positive:x,negative:h})).data,onSuccess:()=>{s.invalidateQueries({queryKey:["org"]}),l(null),d(null),p(null),J({title:n("alerts.toasts.saved"),tone:"ok"})},onError:()=>J({title:n("alerts.toasts.saveFailed"),tone:"bad"})});return t.jsxs("section",{className:"card card-pad flex flex-col gap-4",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(Gp,{className:"size-4 text-brand-600 mt-0.5 shrink-0"}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"text-sm font-medium text-ink",children:n("alerts.title")}),t.jsx("p",{className:"text-xs text-ink-mute mt-0.5",children:t.jsx(wa,{t:n,i18nKey:"alerts.desc",components:{b0:t.jsx("strong",{})}})})]}),t.jsxs("label",{className:"flex items-center gap-2 text-xs shrink-0",children:[t.jsx("input",{type:"checkbox",checked:f,onChange:v=>l(v.target.checked)}),n("alerts.soundOn")]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[t.jsx(jg,{label:n("alerts.positive"),value:x,onChange:d,disabled:!f}),t.jsx(jg,{label:n("alerts.negative"),value:h,onChange:p,disabled:!f})]}),t.jsx("div",{children:t.jsxs("button",{className:"btn btn-primary h-9 px-4 flex items-center gap-2 text-sm",onClick:()=>g.mutate(),disabled:!b||g.isPending||!a,title:a?void 0:n("common:noPermission"),children:[g.isPending?t.jsx(je,{className:"size-4 animate-spin"}):t.jsx(ly,{className:"size-4"}),n("alerts.save")]})})]})}function jg({label:e,value:a,onChange:n,disabled:s}){const{t:i}=M("settings");return t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{className:"text-[11px] font-medium text-ink-mute uppercase tracking-wide",children:e}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("select",{className:"select flex-1",value:a,onChange:r=>n(r.target.value),disabled:s,children:Dv.map(r=>t.jsx("option",{value:r.id,children:r.label},r.id))}),t.jsx("button",{type:"button",className:"btn btn-ghost h-9 px-2",onClick:()=>Iv(a),disabled:s||a==="none",title:i("alerts.listen"),"aria-label":i("alerts.listenAria",{label:e}),children:t.jsx(rn,{className:"size-4"})})]})]})}function vp(e){return{plan_initial:"Suscripción de plan",plan_change:"Cambio de plan",did:"Número telefónico",channel:"Canal adicional",overage_cycle:"Renovación + consumo"}[e]||e}function j1(e){return{approved:"Pagado",rejected:"Rechazado",pending:"Pendiente",in_process:"En proceso",refunded:"Devuelto"}[e]||e}function jp(e){return e==="approved"?"ok":e==="rejected"?"bad":e==="in_process"||e==="pending"?"warn":"muted"}function w1(e){return e?{cc_rejected_insufficient_amount:"Fondos insuficientes",cc_rejected_bad_filled_card_number:"Número de tarjeta incorrecto",cc_rejected_bad_filled_date:"Fecha de vencimiento incorrecta",cc_rejected_bad_filled_security_code:"Código de seguridad (CVV) incorrecto",cc_rejected_bad_filled_other:"Datos de la tarjeta incorrectos",cc_rejected_high_risk:"Rechazada por seguridad (riesgo)",cc_rejected_call_for_authorize:"El banco pide autorizar el pago",cc_rejected_card_disabled:"Tarjeta inhabilitada — contactá al banco",cc_rejected_duplicated_payment:"Pago duplicado",cc_rejected_max_attempts:"Demasiados intentos — probá más tarde",cc_rejected_card_error:"Error con la tarjeta",cc_rejected_blacklist:"Rechazada por seguridad",cc_rejected_other_reason:"Rechazada por el banco",cc_amount_rate_limit_exceeded:"Superó el límite de monto permitido",rejected_by_bank:"Rechazada por el banco",rejected_insufficient_data:"Faltan datos para procesar",payer_email_forbidden:"El comprador no puede ser la cuenta del negocio",invali
975d_users_involved:"Comprador y vendedor no pueden ser la misma cuenta"}[e]||e.replace(/^cc_rejected_/,"").replace(/_/g," "):null}const wg=e=>`$${(Number(e)||0).toFixed(2)}`,WL=e=>e!=null?`COP ${Number(e).toLocaleString(Te())}`:"—",kg=e=>e?new Date(e).toLocaleString(Te(),{dateStyle:"long",timeStyle:"short"}):"—";function UL(e){const a=e.breakdown;if(!a)return[{label:vp(e.kind),usd:Number(e.usdAmount)||0}];const n=[];return a.planUsd&&n.push({label:`${he.t("settings:receipt.concepts.plan")}${a.planCode?` ${a.planCode}`:""}`,usd:a.planUsd}),a.overageUsd&&n.push({label:he.t("settings:receipt.concepts.overage"),usd:a.overageUsd}),a.didsUsd&&n.push({label:he.t("settings:receipt.concepts.dids"),usd:a.didsUsd}),a.channelsUsd&&n.push({label:he.t("settings:receipt.concepts.channels"),usd:a.channelsUsd}),a.creditAppliedUsd&&n.push({label:he.t("settings:receipt.concepts.credit"),usd:-Math.abs(a.creditAppliedUsd)}),n.length===0&&n.push({label:vp(e.kind),usd:Number(e.usdAmount)||0}),n}function VL({payment:e,onClose:a}){const{t:n}=M("settings"),s=jp(e.status),i=s==="ok"?"var(--cia-ok-500)":s==="bad"?"var(--cia-bad-500)":"var(--cia-warn-ink)",r=s==="ok"?Nt:s==="bad"?cs:Qa,o=e.status==="rejected"?w1(e.mpStatusDetail):null,l=UL(e),c=e.id.replace(/^pay_/,"").toUpperCase().slice(0,10);return t.jsx(ot,{open:!0,onClose:a,maxWidth:520,eyebrow:n("receipt.eyebrow"),title:n("receipt.title",{no:c}),children:t.jsxs("div",{id:"cia-receipt",style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:17,fontWeight:800,letterSpacing:.2},children:"Enlassa AI"}),t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("receipt.tagline")})]}),t.jsxs("span",{className:"cia-badge",style:{display:"inline-flex",alignItems:"center",gap:6,color:i,borderColor:"currentColor"},children:[t.jsx(r,{size:14})," ",j1(e.status)]})]}),t.jsx("div",{style:{height:1,background:"var(--cia-border)"}}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,fontSize:12.5},children:[(e.organizationName||e.organizationId)&&t.jsx(ni,{label:n("receipt.client"),value:e.organizationName||e.organizationId}),t.jsx(ni,{label:n("receipt.receipt"),value:`#${c}`,mono:!0}),t.jsx(ni,{label:n("receipt.issued"),value:kg(e.createdAt)}),t.jsx(ni,{label:e.status==="approved"?n("receipt.paidOn"):n("receipt.statusAt"),value:kg(e.paidAt??e.createdAt)}),e.mpPaymentId&&t.jsx(ni,{label:n("receipt.paymentRef"),value:e.mpPaymentId,mono:!0}),e.trm?t.jsx(ni,{label:n("receipt.trmApplied"),value:n("receipt.trmValue",{trm:Number(e.trm).toLocaleString(Te())})}):null]}),o&&t.jsxs("div",{style:{padding:"10px 12px",borderRadius:10,background:"color-mix(in oklab, var(--cia-bad-500) 10%, transparent)",color:"var(--cia-bad-500)",fontSize:12.5},children:[t.jsx("strong",{children:n("receipt.rejectReason")})," ",o]}),t.jsx("div",{className:"cia-card",style:{padding:0,overflow:"hidden"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12.5},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{background:"var(--cia-bg-soft)"},children:[t.jsx("th",{style:{textAlign:"left",padding:"8px 14px",fontSize:11,color:"var(--cia-text-3)",textTransform:"uppercase",letterSpacing:.4},children:n("receipt.concept")}),t.jsx("th",{style:{textAlign:"right",padding:"8px 14px",fontSize:11,color:"var(--cia-text-3)",textTransform:"uppercase",letterSpacing:.4},children:n("receipt.amount")})]})}),t.jsx("tbody",{children:l.map((d,u)=>t.jsxs("tr",{style:{borderTop:"1px solid var(--cia-border)"},children:[t.jsx("td",{style:{padding:"9px 14px"},children:d.label}),t.jsxs("td",{style:{padding:"9px 14px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[wg(d.usd)," USD"]})]},u))}),t.jsx("tfoot",{children:t.jsxs("tr",{style:{borderTop:"2px solid var(--cia-border)"},children:[t.jsx("td",{style:{padding:"11px 14px",fontWeight:700},children:n("receipt.total")}),t.jsxs("td",{style:{padding:"11px 14px",textAlign:"right",fontWeight:800,fontVariantNumeric:"tabular-nums"},children:[wg(e.usdAmount)," USD",t.jsx("div",{style:{fontSize:11,fontWeight:400,color:"var(--cia-text-3)"},children:WL(e.copAmount)})]})]})})]})}),t.jsx("p",{style:{fontSize:10.5,color:"var(--cia-text-3)",margin:0,lineHeight:1.5},children:n("receipt.footer")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[t.jsx("button",{className:"cia-btn cia-btn-outline",onClick:a,children:n("receipt.close")}),t.jsxs("button",{className:"cia-btn cia-btn-cta",onClick:()=>window.print(),children:[t.jsx(a2,{size:15})," ",n("receipt.printPdf")]})]})]})})}function ni({label:e,value:a,mono:n}){return t.jsxs("div",{children:[t.jsx("div",{className:"cia-eyebrow",style:{marginBottom:1},children:e}),t.jsx("div",{className:n?"cia-mono":void 0,style:{fontSize:12.5,color:"var(--cia-text)",wordBreak:"break-word"},children:a})]})}const ba=e=>
975e.toLocaleString(Te()),Ng=e=>new Date(e).toLocaleDateString(Te(),{day:"numeric",month:"short"});function KL(){const{t:e}=M("settings");Pe(p=>p.user?.role);const{can:a}=tt(),n=a("billing.manage"),[s,i]=m.useState(null),r=se({queryKey:["plan-usage"],queryFn:async()=>(await T.get("/organizations/me/plan-usage")).data}),o=se({queryKey:["me-plans"],queryFn:async()=>(await T.get("/organizations/me/plans")).data}),l=r.data,c=l?.plan??null,d=c?.code??null,u=o.data??[];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(sL,{}),r.isLoading?t.jsx("div",{className:"cia-card",style:{padding:22},children:t.jsx(ge,{w:"45%",h:22})}):c&&l?t.jsx(HL,{data:l}):t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{icon:$s,title:e("billing.notConfigured.title"),desc:e("billing.notConfigured.desc")})}),c&&l&&t.jsxs("div",{className:"cia-billing-2col",children:[t.jsx(GL,{canManage:n}),t.jsx(ZL,{data:l,canEdit:n})]}),t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:12,marginBottom:10},children:[t.jsx("span",{className:"cia-eyebrow",children:e("billing.plans.available")}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:e("billing.plans.note")})]}),o.isLoading?t.jsx("div",{className:"cia-billing-plans",children:[0,1,2].map(p=>t.jsx("div",{className:"cia-card",style:{padding:16},children:t.jsx(ge,{w:"50%",h:18})},p))}):t.jsx("div",{className:"cia-billing-plans",children:u.map(p=>{const f=p.code===d;return t.jsxs("div",{className:"cia-card cia-fade-up",style:{padding:16,position:"relative",display:"flex",flexDirection:"column",gap:9,border:`1.5px solid ${f?"var(--cia-brand-500)":"var(--cia-border)"}`,background:f?"var(--cia-bg-tint)":"var(--cia-bg-elev)"},children:[f&&t.jsx("span",{className:"cia-badge cia-badge-success",style:{position:"absolute",top:11,right:11},children:e("billing.plans.current")}),t.jsxs("div",{children:[t.jsx("h4",{style:{margin:0,fontSize:15,fontWeight:600},children:p.name}),t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:4,marginTop:5},children:[t.jsxs("span",{style:{fontSize:23,fontWeight:700,fontVariantNumeric:"tabular-nums"},children:["$",p.priceUsd.toLocaleString(Te())]}),t.jsx("span",{style:{fontSize:12,color:"var(--cia-text-3)"},children:e("billing.plans.perMonth")})]})]}),t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:e("billing.plans.perEffectiveMinute",{price:`$${(p.includedMinutes>0?p.priceUsd/p.includedMinutes:0).toFixed(3)}`})}),t.jsx("div",{style:{height:1,background:"var(--cia-border)",margin:"2px 0"}}),t.jsx(QL,{plan:p}),t.jsx("button",{className:`cia-btn ${f?"cia-btn-outline":"cia-btn-cta"}`,style:{width:"100%",justifyContent:"center",marginTop:"auto",fontSize:13},disabled:f||!n,onClick:()=>i(p),title:n?void 0:e("billing.plans.adminOnlyTitle"),children:f?e("billing.plans.currentPlan"):e("billing.plans.changeTo",{name:p.name})})]},p.code)})}),!n&&t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:9},children:e("billing.plans.adminOnlyNote")})]}),t.jsx(YL,{canView:n}),s&&t.jsx(XL,{plan:s,onClose:()=>i(null)})]})}function HL({data:e}){const{t:a}=M("settings"),n=e.plan,s=e.usage,i=s.includedMinutes>0?s.usedMinutes/s.includedMinutes:0,r=Math.round(i*100),o=s.overageMinutes>0,l=!o&&r>=80,c=Math.max(0,s.includedMinutes-s.usedMinutes),d=e.nextBillUsd??n.priceUsd;return t.jsxs("div",{className:"cia-card cia-fade-up",style:{padding:22,display:"flex",flexWrap:"wrap",alignItems:"center",gap:24},children:[t.jsx(E5,{value:i,label:a("billing.current.gaugeLabel"),size:118}),t.jsxs("div",{style:{flex:1,minWidth:220,display:"flex",flexDirection:"column",gap:9},children:[t.jsxs("div",{children:[t.jsx("span",{className:"cia-eyebrow",children:a("billing.current.yourPlan")}),t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:12,flexWrap:"wrap",marginTop:2},children:[t.jsx("span",{style:{fontSize:22,fontWeight:700,lineHeight:1.1},children:n.name}),t.jsxs("span",{style:{fontSize:18,fontWeight:700,fontVariantNumeric:"tabular-nums"},children:["$",ba(n.priceUsd),t.jsx("span",{style:{fontSize:12,fontWeight:400,color:"var(--cia-text-3)"},children:a("billing.current.perMonth")})]})]}),t.jsx("span",{className:"cia-mono",style:{fontSize:11.5,color:"var(--cia-text-3)"},children:a("billing.current.cycle",{start:Ng(s.cycleStart),end:Ng(s.cycleEnd)})})]}),t.jsx(Ic,{value:i,variant:o?"over":l?"warn":"ok",height:10}),t.jsxs("div",{className:"cia-mono",style:{fontSize:12.5,color:"var(--cia-text-2)",fontVariantNumeric:"tabular-nums"},children:[a("billing.current.minutes",{used:ba(s.usedMinutes),included:ba(s.includedMinutes)}),t.jsx("span",{style:{color:o?"var(--cia-bad-500)":"var(--cia-text-3)",marginLeft:8},children:o?a("billing.current.overage",{mins:ba(s.overageMinutes)}):a("billing.current.remaining",{mins:ba(c),pct:r})})]}),e.usageByProduct&&e.usageByProduct.meetingPlanMinutes>0?t.jsxs("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:[a("billing.current.byProduct",{voice:ba(e.usageByProduct.voiceMinutes),meetings:ba(e.usageByProduct.meetingPlanMinutes),meetingMinutes:ba(e.meetings?.minutes??0)}),e.meetings?.planMinutesPerMinute?t.jsxs(t.Fragment,{children:[" · ",a("billing.current.meetingConversion",{ratio:e.meetings.planMinutesPerMinute.toFixed(2)})]}):null]}):t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:a("billing.current.oneBalance")})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,minWidth:150},children:[t.jsx(Sg,{label:a("billing.current.projectionMonth"),value:a("billing.current.minutesValue",{value:ba(s.projectedMinutes)})}),t.jsx(Sg,{label:a("billing.current.nextBill"),value:`$${d.toFixed(2)}`,sub:a("billing.current.planPlusExtras")})]})]})}function Sg({label:e,value:a,sub:n}){return t.jsxs("div",{children:[t.jsx("div",{className:"cia-eyebrow",children:e}),t.jsx("div",{style:{fontSize:18,fontWeight:700,fontVariantNumeric:"tabular-nums",lineHeight:1.15},children:a}),n&&t.jsx("div",{style:{fontSize:11,color:"var(--cia-text-3)"},children:n})]})}function QL({plan:e}){const{t:a}=M("settings"),n=r=>r==null?a("billing.features.unlimited"):ba(r),s=e.code!=="starter",i=[{text:a("billing.features.minutesPerMonth",{value:ba(e.includedMinutes)}),on:!0},{text:a("billing.features.overage",{rate:Number(e.overageRatePerMin).toFixed(2)}),on:!0},...e.meetingRatePerMin!=null?[{text:a("billing.features.meetings",{rate:Number(e.meetingRatePerMin).toFixed(2),hours:ba(Math.round((e.meetingMinutesEquivalent??0)/60))}),on:!0}]:[],{text:a("billing.features.portalUsers",{value:n(e.maxUsers)}),on:!0},{text:a("billing.features.concurrentCalls",{value:ba(e.maxConcurrentCalls)}),on:!0},{text:a("billing.features.numbersIncluded",{count:e.includedDids}),on:!0},{text:a("billing.features.webhooks",{value:n(e.maxWebhookEndpoints)}),on:!0},{text:a("billing.features.dataPoints",{count:e.maxDataPoints}),on:!0},{text:e.rolloverPct>0?a("billing.features.rollover",{pct:e.rolloverPct}):a("billing.features.noRollover"),on:e.rolloverPct>0},{text:a("billing.features.unlimitedAgents"),on:!0},{text:a("billing.features.allModelsVoices"),on:!0},{text:a("billing.features.recordingTranscription"),on:!0},{text:a("billing.features.liveSentiment"),on:s}];return t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:5,fontSize:12,color:"var(--cia-text-2)"},children:i.map(r=>
975t.jsxs("span",{style:{display:"inline-flex",alignItems:"flex-start",gap:7,opacity:r.on?1:.45},children:[r.on?t.jsx(ct,{size:13,style:{color:"var(--cia-ok-500)",flex:"none",marginTop:1}}):t.jsx(th,{size:13,style:{color:"var(--cia-text-3)",flex:"none",marginTop:1}}),r.text]},r.text))})}function GL({canManage:e}){const{t:a}=M("settings"),n=xe(),[s,i]=m.useState(1),[r,o]=m.useState(null),{data:l,isLoading:c}=se({queryKey:["channels"],queryFn:async()=>(await T.get("/organizations/me/channels")).data,staleTime:15e3,refetchInterval:2e4}),{data:d}=Gc(),u=oe({mutationFn:async b=>(await T.post("/organizations/me/channels/buy",{qty:s,cardToken:b.card?.token,paymentMethodId:b.card?.paymentMethodId,issuerId:b.card?.issuerId,installments:b.card?.installments,idempotencyKey:b.idempotencyKey})).data,onSuccess:()=>{n.invalidateQueries({queryKey:["channels"]}),n.invalidateQueries({queryKey:["plan-usage"]}),n.invalidateQueries({queryKey:["payments"]}),J({tone:"ok",title:a("billing.channels.toasts.added",{count:s})}),i(1),o(null)},onError:b=>J({tone:"bad",title:b?.response?.data?.message||a("billing.channels.toasts.buyFailed")})}),p=oe({mutationFn:async b=>(await T.post("/organizations/me/channels/release",{qty:b})).data,onSuccess:()=>{n.invalidateQueries({queryKey:["channels"]}),n.invalidateQueries({queryKey:["plan-usage"]}),J({tone:"ok",title:a("billing.channels.toasts.released")})},onError:b=>J({tone:"bad",title:b?.response?.data?.message||a("billing.channels.toasts.releaseFailed")})});async function f(){try{const b=(await T.get("/organizations/me/channels-quote",{params:{qty:s}})).data;b.proratedUsd>0&&b.paymentsEnabled?o({usd:b.proratedUsd}):await u.mutateAsync({})}catch(b){J({tone:"bad",title:b?.response?.data?.message||a("billing.channels.toasts.quoteFailed")})}}if(c||!l)return t.jsxs("div",{className:"cia-card",style:{padding:18,dis
975play:"flex",flexDirection:"column",gap:12},children:[t.jsx(ge,{w:"45%",h:16}),t.jsx(ge,{w:"100%",h:8})]});const x=l.total>0?Math.min(1,l.inUse/l.total):0,h=l.pricePerChannelUsd;return t.jsxs("div",{className:"cia-card",style:{padding:18,display:"flex",flexDirection:"column",gap:11},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[t.jsxs("span",{style:{fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",gap:8},children:[t.jsx(vi,{size:15,style:{color:"var(--cia-text-3)"}})," ",a("billing.channels.title")]}),t.jsx("span",{className:"cia-mono",style:{fontSize:12.5,color:"var(--cia-text-2)",fontVariantNumeric:"tabular-nums"},children:a("billing.channels.inUse",{inUse:l.inUse,total:l.total})})]}),t.jsx(Ic,{value:x,variant:"ok",height:8}),t.jsxs("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:[a("billing.channels.included",{count:l.base}),l.purchased>0?a("billing.channels.additional",{count:l.purchased}):""]}),e&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{height:1,background:"var(--cia-border)",margin:"2px 0"}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12.5,fontWeight:600},children:a("billing.channels.addChannels")}),t.jsx("div",{style:{fontSize:11,color:"var(--cia-text-3)"},children:a("billing.channels.eachChannel")})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("button",{className:"cia-btn cia-btn-outline cia-btn-icon",style:{width:30,height:30},onClick:()=>i(b=>Math.max(1,b-1)),"aria-label":a("billing.channels.less"),disabled:s<=1,children:t.jsx(th,{size:13})}),t.jsx("span",{className:"cia-mono",style:{fontSize:15,fontWeight:600,minWidth:22,textAlign:"center"},children:s}),t.jsx("button",{className:"cia-btn cia-btn-outline cia-btn-icon",style:{width:30,height:30},onClick:()=>i(b=>Math.min(50,b+1)),"aria-label":a("billing.channels.more"),disabled:s>=50,children:t.jsx(Fe,{size:13})})]})]}),t.jsx("button",{className:"cia-btn cia-btn-cta",style:{width:"100%",justifyContent:"center",fontSize:13},onClick:f,disabled:u.isPending,children:u.isPending?t.jsx(je,{className:"animate-spin",size:15}):a("billing.channels.addCta",{qty:s,total:(h*s).toFixed(2)})}),t.jsx("div",{style:{fontSize:10.5,color:"var(--cia-text-3)"},children:a("billing.channels.prorationNote")}),l.purchased>0&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,borderTop:"1px solid var(--cia-border)",paddingTop:9},children:[t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:a("billing.channels.billing",{count:l.purchased})}),t.jsx("button",{className:"cia-btn cia-btn-outline",style:{fontSize:12,color:"var(--cia-bad-500)"},onClick:()=>p.mutate(1),disabled:p.isPending,title:a("billing.channels.cancelTitle"),children:p.isPending?t.jsx(je,{className:"animate-spin",size:14}):a("billing.channels.cancelOne")})]})]}),r&&d&&t.jsx(Qc,{open:!0,onClose:()=>o(null),title:a("billing.channels.checkoutTitle",{count:s}),usdAmount:r.usd,method:d,onConfirm:async(b,g)=>{await u.mutateAsync({card:b,idempotencyKey:g})}})]})}function ZL({data:e,canEdit:a}){const{t:n}=M("settings"),s=xe(),[i,r]=m.useState(null),o=oe({mutationFn:async p=>(await T.patch("/organizations/me/spend-cap",{capUsd:p})).data,onSuccess:()=>{s.invalidateQueries({queryKey:["plan-usage"]}),r(null),J({tone:"ok",title:n("billing.spendCap.toasts.updated")})},onError:p=>{const f=p?.response?.data?.message;J({tone:"bad",title:Array.isArray(f)?f.join(" · "):f||n("billing.spendCap.toasts.saveFailed")})}}),l=e.overageSpendCapUsd,c=i!==null?i:l!=null?String(l):"",d=e.enforcementMode==="hard";function u(){const p=c.trim();if(p===""){o.mutate(null);return}const f=parseFloat(p);if(isNaN(f)||f<0){J({tone:"bad",title:n("billing.spendCap.toasts.invalid")});return}o.mutate(f)}
975return t.jsxs("div",{className:"cia-card",style:{padding:18,display:"flex",flexDirection:"column",gap:11},children:[t.jsxs("span",{style:{fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",gap:8},children:[t.jsx(_c,{size:15,style:{color:"var(--cia-text-3)"}})," ",n("billing.spendCap.title")]}),t.jsxs("div",{style:{fontSize:11.5,color:"var(--cia-text-3)",lineHeight:1.5},children:[n("billing.spendCap.descBase"),d?` ${n("billing.spendCap.descHard")}`:` ${n("billing.spendCap.descSoft")}`," ",n("billing.spendCap.descEmpty")]}),t.jsx("div",{style:{flex:1}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("input",{className:"input cia-mono",style:{maxWidth:130,fontSize:13},type:"number",step:"1",min:"0",placeholder:n("billing.spendCap.placeholder"),value:c,disabled:!a,onChange:p=>r(p.target.value)}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("billing.spendCap.perCycle")}),a&&t.jsx("button",{className:"cia-btn cia-btn-primary",style:{fontSize:13,marginLeft:"auto"},onClick:u,disabled:o.isPending||i===null,children:o.isPending?t.jsx(je,{className:"animate-spin",size:15}):n("billing.spendCap.save")})]})]})}function YL({canView:e}){const{t:a}=M("settings"),[n,s]=m.useState(null),{data:i,isLoading:r}=se({queryKey:["payments"],queryFn:async()=>(await T.get("/payments")).data,enabled:e});if(!e)return null;const o=i??[],l=c=>jp(c)==="ok"?"var(--cia-ok-500)":jp(c)==="bad"?"var(--cia-bad-500)":"var(--cia-text-3)";
975return t.jsxs("div",{className:"cia-card",style:{padding:18,display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("span",{style:{fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",gap:8},children:[t.jsx(oy,{size:15,style:{color:"var(--cia-text-3)"}})," ",a("billing.invoices.title"),o.length>0&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-text-3)",fontWeight:400},children:a("billing.invoices.hint")})]}),r?t.jsx(ge,{w:"100%",h:14}):o.length===0?t.jsx("p",{style:{fontSize:12,color:"var(--cia-text-3)",margin:0},children:a("billing.invoices.empty")}):t.jsx("div",{style:{display:"flex",flexDirection:"column"},children:o.map(c=>{const d=c.status==="rejected"?w1(c.mpStatusDetail):null;return t.jsxs("button",{type:"button",onClick:()=>s(c),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,fontSize:12.5,padding:"8px 4px",background:"transparent",border:"none",borderBottom:"1px solid var(--cia-border)",textAlign:"left",cursor:"pointer",width:"100%"},className:"cia-row-hover",children:[t.jsxs("span",{style:{minWidth:0},children:[t.jsxs("span",{style:{color:"var(--cia-text-2)"},children:[new Date(c.createdAt).toLocaleDateString(Te(),{day:"numeric",month:"short",year:"numeric"})," · ",vp(c.kind)]}),d&&t.jsx("span",{style:{display:"block",fontSize:11,color:"var(--cia-bad-500)"},children:d})]}),t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:10,flex:"none"},children:[t.jsxs("span",{className:"cia-mono",children:["$",Number(c.usdAmount).toFixed(2),c.copAmount?` · COP ${Number(c.copAmount).toLocaleString(Te())}`:""]}),t.jsx("span",{style:{color:l(c.status),fontWeight:600,minWidth:64,textAlign:"right"},children:j1(c.status)})]})]},c.id)})}),n&&t.jsx(VL,{payment:n,onClose:()=>s(null)})]})}function XL({plan:e,onClose:a}){const{t:n}=M("settings"),s=xe(),{data:i}=Gc(),[r,o]=m.useState(!1),l=se({queryKey:["plan-quote",e.code],queryFn:async()=>(await T.get("/organizations/me/plan-quote",{params:{code:e.code}})).data}),c=oe({mutationFn:async f=>(await T.patch("/organizations/me/plan",{code:e.code,cardToken:f.card?.token,paymentMethodId:f.card?.paymentMethodId,issuerId:f.card?.issuerId,installments:f.card?.installments,idempotencyKey:f.idempotencyKey})).data,onSuccess:()=>{["plan-usage","me-plans","channels","payments"].forEach(f=>s.invalidateQueries({queryKey:[f]})),s.invalidateQueries({queryKey:["org","me"]}),J({tone:"ok",title:n("billing.changePlan.toastChanged",{name:e.name})}),a()},onError:f=>J({tone:"bad",title:f?.response?.data?.message||n("billing.changePlan.toastFailed")})}),d=l.data,u=!!d&&d.usdToCharge>0&&d.paymentsEnabled;async function p(){d&&(u?o(!0):await c.mutateAsync({}))}return r&&d&&i?t.jsx(Qc,{open:!0,onClose:()=>o(!1),title:n("billing.changePlan.checkoutTitle",{name:e.name}),usdAmount:d.usdToCharge,method:i,onConfirm:async(f,x)=>{await c.mutateAsync({card:f,idempotencyKey:x})}}):t.jsx(ot,{open:!0,onClose:a,maxWidth:460,eyebrow:n("billing.changePlan.eyebrow"),title:n("billing.changePlan.title",{name:e.name}),footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"cia-btn cia-btn-outline",onClick:a,disabled:c.isPending,children:n("billing.changePlan.cancel")}),t.jsx("button",{className:"cia-btn cia-btn-cta",onClick:p,disabled:c.isPending||l.isLoading,children:c.isPending?t.jsx(je,{className:"animate-spin",size:15}):n(u?"billing.changePlan.continueToPayment":"billing.changePlan.confirmChange")})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsxs("div",{className:"cia-card",style:{padding:16,display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[t.jsx("span",{style:{fontSize:16,fontWeight:600},children:e.name}),t.jsxs("span",{className:"cia-mono",style:{fontSize:15,fontWeight:600},children:["$",e.priceUsd.toLocaleString(Te()),n("billing.plans.perMonth")]})]}),[n("billing.features.minutesPerMonth",{value:ba(e.includedMinutes)}),n("billing.features.numbersIncluded",{count:e.includedDids}),n("billing.features.channelsCount",{count:e.maxConcurrentCalls})].map(f=>t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:7,fontSize:12.5,color:"var(--cia-text-2)"},children:[t.jsx(ct,{size:13,style:{color:"var(--cia-ok-500)"}})," ",f]},f))]}),l.isLoading?t.jsx(ge,{w:"60%",h:14}):d?d.usdToCharge>0?t.jsx(le,{tone:"info",children:d.kind==="upgrade"?t.jsx(wa,{t:n,i18nKey:"billing.changePlan.bannerUpgrade",values:{amount:d.usdToCharge.toFixed(2)},components:{b0:t.jsx("strong",{})}}):t.jsxs(t.Fragment,{children:[t.jsx(wa,{t:n,i18nKey:"billing.changePlan.bannerAdvance",values:{amount:d.usdToCharge.toFixed(2)},components:{b0:t.jsx("strong",{})}}),d.paymentsEnabled?"":` ${n("billing.changePlan.bannerAdvanceSoon")}`]})}):d.creditToAddUsd>0?t.jsx(le,{tone:"ok",children:t.jsx(wa,{t:n,i18nKey:"billing.changePlan.bannerDowngrade",values:{amount:d.creditToAddUsd.toFixed(2)},components:{b0:t.jsx("strong",{})}})}):t.jsx(le,{tone:"info",children:n("billing.changePlan.bannerSame")}):null,t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",margin:0},children:n("billing.changePlan.noTax")})]})})}const au=50,JL="Soporte Enlassa AI",pr={textAlign:"left",padding:"12px 14px",fontWeight:500},si={padding:"12px 14px"};function e6(){const{t:e}=M("settings"),a=[{value:"",label:e("audit.filters.all")},{value:"agents.",label:e("audit.filters.agents")},{value:"calls.",label:e("audit.filters.calls")},{value:"user.",label:e("audit.filters.users")},{value:"webhook-endpoints.",label:e("audit.filters.integrations")},{value:"secrets.",label:e("audit.filters.secrets")},{value:"phone-numbers.",label:e("audit.filters.numbers")},{value:"auth.",label:e("audit.filters.sessions")},{value:"organizations.",label:e("audit.filters.organization")},{value:"whatsapp.",label:e("audit.filters.whatsapp")}],n={"auth.login":e("audit.actions.authLogin"),"auth.login_failed":e("audit.actions.authLoginFailed"),"auth.logout":e("audit.actions.authLogout"),"user.create":e("audit.actions.userCreate"),"user.update":e("audit.actions.userUpdate"),"user.reset_password":e("audit.actions.userResetPassword"),"agents.create":e("audit.actions.agentsCreate"),"agents.update":e("audit.actions.agentsUpdate"),"agents.delete":e("audit.actions.agentsDelete"),"calls.originate":e("audit.actions.callsOriginate"),"calls.hangup":e("audit.actions.callsHangup"),"calls.transfer":e("audit.actions.callsTransfer"),"webhook-endpoints.create":e("audit.actions.webhookCreate"),"webhook-endpoints.update":e("audit.actions.webhookUpdate"),"webhook-endpoints.test":e("audit.actions.webhookTest"),"webhook-endpoints.rotate-secret":e("audit.actions.webhookRotateSecret"),"secrets.create":e("audit.actions.secretsCreate"),"secrets.delete":e("audit.actions.secretsDelete"),"secrets.rotate":e("audit.actions.secretsRotate"),"organizations.spend-cap":e("audit.actions.orgSpendCap"),"calls.recording":e("audit.actions.callsRecording"),"web-agent.session":e("audit.actions.webAgentSession"),"webhook-endpoints.delete":e("audit.actions.webhookDelete"),"imp.write":e("audit.actions.impWrite"),"whatsapp.account.connected":e("audit.actions.waAccountConnected"),"whatsapp.account.disconnected":e("audit.actions.waAccountDisconnected"),"whatsapp.account.verified":e("audit.actions.waAccountVerified"),"whatsapp.alerts.updated":e("audit.actions.waAlertsUpdated"),"whatsapp.conversation_exported":e("audit.actions.waConversationExported"),"whatsapp.conversation_content_deleted":e("audit.actions.waConversationContentDeleted")},[s,i]=m.useState(""),[r,o]=m.useState(""),[l,c]=m.useState(!1),[d,u]=m.useState(0),[p,f]=m.useState(null),{data:x}=se({queryKey:["org-users"],queryFn:async()=>(await T.get("/users")).data}),{data:h,isLoading:b,error:g}=se({queryKey:["tenant-audit",s,r,l,d],queryFn:async()=>{const k=new URLSearchParams;return s&&k.set("action",s),r&&k.set("actorUserId",r),l&&k.set("imp","true"),k.set("limit",String(au)),k.set("offset",String(d*au)),(await T.get(`/audit?${k.toString()}`)).data}}),v=g?.response?.status===403,y=Math.max(1,Math.ceil((h?.total??0)/au));return t.jsxs("div",{children:[t.jsxs("div",{className:"cia-card",style:{padding:16,marginBottom:16,display:"flex",flexWrap:"wrap",alignItems:"center",gap:12},children:[t.jsx(Qr,{size:16,style:{color:"var(--cia-text-3)"}}),t.jsx("select",{className:"input h-9 w-56",value:s,onChange:k=>{i(k.target.value),u(0)},children:a.map(k=>t.jsx("option",{value:k.value,children:k.label},k.value))}),t.jsxs("select",{className:"input h-9 w-56",value:r,onChange:k=>{o(k.target.value),u(0)},children:[t.jsx("option",{value:"",children:e("audit.allUsers")}),(x??[]).map(k=>t.jsx("option",{value:k.id,children:k.email},k.id))]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[t.jsx("input",{type:"checkbox",checked:l,onChange:k=>{c(k.target.checked),u(0)}}),e("audit.onlySupport")]}),t.jsx("div",{style:{flex:1}}),t.jsx("div",{style:{fontSize:13,color:"var(--cia-text-3)"},children:e("audit.events",{count:h?.total??0})})]}),g?t.jsxs("div",{className:"cia-card",style:{padding:24,display:"flex",alignItems:"center",gap:12,fontSize:13,color:"var(--cia-bad-500)"},children:[t.jsx(Sc,{size:20}),e(v?"audit.forbidden":"audit.loadFailed")]}):b?t.jsx("div",{className:"cia-card",style:{padding:16,display:"flex",flexDirection:"column",gap:14},children:Array.from({length:8}).map((k,w)=>t.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center"},children:[t.jsx(ge,{w:140,h:12}),t.jsx(ge,{w:"30%",h:12}),t.jsx(ge,{w:120,h:12,style:{marginLeft:"auto"}})]},w))}):h?.items.length?t.jsxs("div",{className:"cia-card",style:{overflow:"hidden",padding:0},children:[t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[t.jsx("thead",{children:t.jsxs("tr",{className:"cia-mono",style:{borderBottom:"1px solid var(--cia-border)",fontSize:10,letterSpacing:"0.06em",color:"var(--cia-text-3)"},children:[t.jsx("th",{style:pr,children:e("audit.columns.when")}),t.jsx("th",{style:pr,children:e("audit.columns.user")}),t.jsx("th",{style:pr,children:e("audit.columns.action")}),t.jsx("th",{style:pr,children:e("audit.columns.detail")}),t.jsx("th",{style:{...pr,textAlign:"right"}})]})}),t.jsx("tbody",{children:h.items.map(k=>{const w=k.actorEmail===JL,j=k.metadata?.path||k.targetId||"—",C=k.action==="auth.login_failed"?"chip chip-rose":w?"chip chip-amber":"chip chip-brand";return t.jsxs(m.Fragment,{children:[t.jsxs("tr",{className:"cia-row-hover",style:{borderTop:"1px solid var(--cia-border)"},children:[t.jsx("td",{className:"cia-mono",style:{...si,fontSize:12,color:"var(--cia-text-2)",whiteSpace:"nowrap"}
975,children:new Date(k.createdAt).toLocaleString(Te())}),t.jsx("td",{style:si,children:w?t.jsxs("span",{className:"chip chip-amber",style:{fontSize:10,display:"inline-flex",alignItems:"center",gap:4},children:[t.jsx(qs,{size:12})," ",e("audit.support")]}):t.jsx("div",{style:{fontWeight:500,fontSize:13},children:k.actorEmail})}),t.jsx("td",{style:si,children:t.jsx("span",{className:C,style:{fontSize:10},children:n[k.action]||k.action})}),t.jsx("td",{className:"cia-mono",style:{...si,fontSize:12,color:"var(--cia-text-3)",maxWidth:320},children:t.jsx("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:j,children:j})}),t.jsx("td",{style:{...si,textAlign:"right"},children:k.metadata&&t.jsx("button",{style:{fontSize:11,color:"var(--cia-brand-500)",background:"none",border:0,cursor:"pointer"},onClick:()=>f(p===k.id?null:k.id),children:p===k.id?e("audit.hide"):e("audit.showDetail")})})]}),p===k.id&&k.metadata&&t.jsx("tr",{style:{borderTop:"1px solid var(--cia-border)",background:"var(--cia-bg-soft)"},children:t.jsx("td",{colSpan:5,style:si,children:t.jsx("pre",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-2)",whiteSpace:"pre-wrap",wordBreak:"break-all",background:"var(--cia-bg-elev)",borderRadius:"var(--cia-r-sm)",padding:12,border:"1px solid var(--cia-border)",margin:0},children:JSON.stringify(k.metadata,null,2)})})})]},k.id)})})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:12,borderTop:"1px solid var(--cia-border)",fontSize:13},children:[t.jsxs("button",{className:"cia-btn cia-btn-outline cia-btn-sm",disabled:d===0,onClick:()=>u(k=>Math.max(0,k-1)),children:[t.jsx(gn,{size:14})," ",e("audit.prev")]}),t.jsx("span",{className:"cia-mono",style:{color:"var(--cia-text-3)",fontSize:12},children:e("audit.page",{page:d+1,total:y})}),t.jsxs("button",{className:"cia-btn cia-btn-outline cia-btn-sm",disabled:d+1>=y,onClick:()=>u(k=>k+1),children:[e("audit.next")," ",t.jsx(ca,{size:14})]})]})]}):t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{mini:!0,icon:Qr,title:e("audit.emptyTitle"),desc:e("audit.emptyDesc")})})]})}function t6(e,a){const n=(e||a||"?").trim(),s=n.split(/\s+/).filter(Boolean);return s.length>=2?(s[0][0]+s[1][0]).toUpperCase():n.slice(0,2).toUpperCase()}const a6=e=>e?new Date(e).toLocaleDateString(Te(),{day:"numeric",month:"long",year:"numeric"}):"—",n6=e=>e?new Date(e).toLocaleString(Te(),{dateStyle:"medium",timeStyle:"short"}):"—";function s6(e,a=160){return new Promise((n,s)=>{const i=new FileReader;i.onerror=()=>s(new Error("No se pudo leer la imagen")),i.onload=()=>{const r=new Image;r.onerror=()=>s(new Error("Imagen inválida")),r.onload=()=>{const o=document.createElement("canvas");o.width=a,o.height=a;const l=o.getContext("2d");if(!l)return s(new Error("Canvas no disponible"));const c=Math.min(r.width,r.height),d=(r.width-c)/2,u=(r.height-c)/2;l.drawImage(r,d,u,c,c,0,0,a,a),n(o.toDataURL("image/jpeg",.82))},r.src=i.result},i.readAsDataURL(e)})}function i6(){const{t:e}=M("settings"),a=dt(),n=xe(),s=Pe(v=>v.user),i=Pe(v=>v.setUser),r=Pe(v=>v.logout),[o,l]=m.useState(!1),c=m.useRef(null),{data:d,isLoading:u}=se({queryKey:["auth-profile"],queryFn:async()=>(await T.get("/auth/profile")).data}),p=oe({mutationFn:async v=>(await T.patch("/auth/me",{avatar:v})).data,onSuccess:()=>{n.invalidateQueries({queryKey:["auth-profile"]}),J({tone:"ok",title:e("profile.toasts.photoUpdated")})},onError:v=>J({tone:"bad",title:v?.response?.data?.message||e("profile.toasts.photoUpdateFailed")})});async function f(v){const y=v.target.files?.[0];if(v.target.value="",!!y){if(!y.type.startsWith("image/")){J({tone:"bad",title:e("profile.toasts.pickImage")});return}if(y.size>8*1024*1024){J({tone:"bad",title:e("profile.toasts.imageTooLarge")});return}try{const k=await s6(y);p.mutate(k)}catch{J({tone:"bad",title:e("profile.toasts.imageProcessFailed")})}}}const x=d?.name??s?.name,h=d?.email??s?.email,b=d?.role??s?.role,g=d?.avatar??null;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16,maxWidth:640},children:[t.jsxs("div",{children:[t.jsx("span",{className:"cia-eyebrow",children:e("profile.eyebrow")}),t.jsx("h2",{style:{margin:"2px 0 0",fontSize:20,fontWeight:600},children:e("profile.heading")})]}),t.jsxs("div",{className:"cia-card",style:{padding:20,display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14},children:[t.jsxs("div",{style:{position:"relative",flex:"none"},children:[t.jsx("div",{style:{width:56,height:56,borderRadius:"50%",overflow:"hidden",display:"grid",placeItems:"center",fontSize:19,fontWeight:700,color:"#fff",background:"linear-gradient(135deg, var(--cia-brand-500), var(--cia-cta-500))"},children:g?t.jsx("img",{src:g,alt:e("profile.avatarAlt"),style:{width:"100%",height:"100%",objectFit:"cover"}}):t6(x,h)}),t.jsx("button",{onClick:()=>c.current?.click(),disabled:p.isPending,title:e("profile.changePhoto"),style:{position:"absolute",right:-2,bottom:-2,width:22,height:22,borderRadius:"50%",display:"grid",placeItems:"center",cursor:"pointer",background:"var(--cia-bg-elev)",border:"1px solid var(--cia-border-2)",color:"var(--cia-text-2)",padding:0},children:p.isPending?t.jsx(je,{className:"animate-spin",size:11}):t.jsx(vS,{size:12})}),t.jsx("input",{ref:c,type:"file",accept:"image/*",hidden:!0,onChange:f})]}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:17,fontWeight:700,lineHeight:1.2},children:x||"—"}),t.jsxs("div",{style:{fontSize:13,color:"var(--cia-text-3)",display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(Kr,{size:13})," ",h]}),g&&t.jsx("button",{onClick:()=>p.mutate(""),style:{fontSize:11,color:"var(--cia-text-3)",background:"none",border:"none",cursor:"pointer",padding:"2px 0"},children:e("profile.removePhoto")})]}),!o&&t.jsxs("button",{className:"cia-btn cia-btn-outline",style:{fontSize:13,flex:"none"},onClick:()=>l(!0),children:[t.jsx(qt,{size:14})," ",e("profile.edit")]})]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 18px",fontSize:12.5,color:"var(--cia-text-2)"},children:[t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(Cc,{size:14,style:{color:"var(--cia-text-3)"}})," ",t.jsx("span",{className:"cia-badge",children:e(`profile.roles.${b}`,{defaultValue:b})})]}),u?t.jsx(ge,{w:160,h:14}):t.jsxs(t.Fragment,{children:[t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(Ps,{size:14,style:{color:"var(--cia-text-3)"}})," ",e("profile.memberSince",{date:a6(d?.createdAt)})]}),t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx(Qa,{size:14,style:{color:"var(--cia-text-3)"}})," ",e("profile.lastAccess",{value:d?.lastLoginAt?n6(d.lastLoginAt):e("profile.never")})]})]})]}),o&&t.jsx(r6,{onClose:()=>l(!1),onSaved:v=>{v&&i({...s,name:v.name,email:v.email}),n.invalidateQueries({queryKey:["auth-profile"]}),l(!1)}})]}),t.jsx(l6,{}),t.jsx(o6,{}),t.jsxs("div",{className:"cia-card",style:{padding:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:13.5,fontWeight:600},children:e("profile.session.title")}),t.jsx("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:e("profile.session.desc")})]}),t.jsxs("button",{onClick:()=>{r(),a({to:"/login"})},className:"cia-btn cia-btn-outline",style:{color:"var(--cia-bad-500)",borderColor:"color-mix(in oklab, var(--cia-bad-500) 40%, var(--cia-border-2))",flex:"none"},children:[t.jsx(eh,{size:16})," ",e("profile.session.logout")]})]}),t.jsx("div",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)"},children:"Enlassa AI v1.0"})]})}function r6({onClose:e,onSaved:a}){const{t:n}=M("settings"),s=Pe(y=>y.user),[i,r]=m.useState(s?.name||""),[o,l]=m.useState(s?.email||""),[c,d]=m.useState(!1),[u,p]=m.useState(""),[f,x]=m.useState(""),h=!!o.trim()&&o.trim()!==s?.email,b=h||c&&!!f,g=oe({mutationFn:async()=>{const y={};return i.trim()&&i.trim()!==s?.name&&(y.name=i.trim()),h&&(y.email=o.trim()),c&&f&&(y.newPassword=f),b&&(y.currentPassword=u),(await T.patch("/auth/me",y)).data},onSuccess:y=>{J({tone:"ok",title:n("editProfile.toasts.updated")}),a(y)},onError:y=>{const k=y?.response?.data?.message;J({tone:"bad",title:Array.isArray(k)?k.join(" · "):k||n("editProfile.toasts.updateFailed")})}});function v(){if(b&&!u){J({tone:"bad",title:n("editProfile.toasts.needCurrent")});return}if(c&&f&&f.length<8){J({tone:"bad",title:n("editProfile.toasts.passwordTooShort")});return}g.mutate()}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,borderTop:"1px solid var(--cia-border)",paddingTop:14},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[t.jsx("span",{className:"cia-eyebrow",children:n("editProfile.name")}),t.jsx("input",{className:"input",value:i,onChange:y=>r(y.target.value),style:{fontSize:13.5}})]}),t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[t.jsx("span",{className:"cia-eyebrow",children:n("editProfile.email")}),t.jsx("input",{className:"input",type:"email",value:o,onChange:y=>l(y.target.value),style:{fontSize:13.5}})]})]}),c?t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4,maxWidth:320},children:[t.jsx("span",{className:"cia-eyebrow",children:n("editProfile.newPassword")}),t.jsx("input",{className:"input",type:"password",value:f,onChange:y=>x(y.target.value),placeholder:n("editProfile.newPasswordPlaceholder"),style:{fontSize:13.5}})]}):t.jsx("button",{className:"cia-btn cia-btn-outline",style:{alignSelf:"flex-start",fontSize:12.5},onClick:()=>d(!0),children:n("editProfile.changePassword")}),b&&t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4,maxWidth:320},children:[t.jsx("span",{className:"cia-eyebrow",children:n("editProfile.currentPassword")}),t.jsx("input",{className:"input",type:"password",value:u,onChange:y=>p(y.target.value),placeholder:n("editProfile.currentPasswordPlaceholder"),style:{fontSize:13.5}})]}),t.jsx(le,{tone:"info",children:n("editProfile.reloginNotice")}),t.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[t.jsxs("button",{className:"cia-btn cia-btn-outline",onClick:e,disabled:g.isPending,children:[t.jsx(nt,{size:14})," ",n("editProfile.cancel")]}),t.jsx("button",{className:"cia-btn cia-btn-cta",onClick:v,disabled:g.isPending,children:g.isPending?t.jsx(je,{className:"animate-spin",size:15}):t.jsxs(t.Fragment,{children:[t.jsx(ct,{size:15})," ",n("editProfile.save")]})})]})]})}function o6(){const{t:e}=M("settings"),{t:a}=M("common"),n=xe();Pe(u=>u.user?.role);const{can:s}=tt(),i=s("organization.manage"),r=se({queryKey:["org","me"],queryFn:async()=>(await T.get("/organizations/me")).data}),o=r.data?.businessProfile,l=o?.language==="en"?"en":"es",c=oe({mutationFn:async u=>(await T.patch("/organizations/me/profile",{language:u})).data,onSuccess:()=>{J({tone:"ok",title:e("preferences.toasts.languageUpdated")}),n.invalidateQueries({queryKey:["org","me"]})},onError:u=>J({tone:"bad",title:u?.response?.data?.message||e("preferences.toasts.languageFailed")})});if(!r.data)return null;const d=(u,p)=>t.jsx("button",{type:"button","aria-pressed":l===u,disabled:!i||c.isPending,onClick:()=>{i&&u!==l&&c.mutate(u)},className:"cia-btn",style:{minHeight:36,padding:"0 16px",borderRadius:"var(--cia-r)",border:`1.5px solid ${l===u?"var(--cia-brand-500)":"var(--cia-border-2)"}`,background:l===u?"var(--cia-bg-tint)":"var(--cia-bg-elev)",color:l===u?"var(--cia-brand-500)":"var(--cia-text-2)",fontWeight:l===u?600:500,cursor:i?"pointer":"not-allowed"},children:p});return t.jsxs("div",{className:"cia-card",style:{padding:20,display:"flex",flexDirection:"column",gap:16},children:[t.jsx("span",{className:"cia-eyebrow",children:e("preferences.eyebrow")}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx("div",{style:{fontSize:13.5,fontWeight:600},children:e("preferences.language")}),t.jsxs("div",{className:"cia-row",style:{gap:8},children:[d("es",a("spanish")),d("en",a("english"))]}),t.jsxs("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:[e("preferences.languageDesc"),!i&&` ${e("preferences.adminOnly")}`]})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("div",{style:{fontSize:13.5,fontWeight:600},children:e("preferences.country")}),t.jsx("div",{style:{fontSize:14,color:"var(--cia-text-2)"},children:o?.country?e(`preferences.countries.${o.country}`,{defaultValue:o.country}):"—"}),t.jsx("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:e("preferences.countryDesc")})]})]})}function l6(){const{t:e}=M("settings"),a=xe();Pe(x=>x.user?.role);const{can:n}=tt(),s=n("organization.manage"),[i,r]=m.useState(!1),[o,l]=m.useState(""),c=se({queryKey:["org","me"],queryFn:async()=>(await T.get("/organizations/me")).data}),d=oe({mutationFn:async x=>(await T.patch("/organizations/me/name",{name:x})).data,onSuccess:()=>{a.invalidateQueries({queryKey:["org","me"]}),r(!1),J({tone:"ok",title:e("org.renamed")})},onError:x=>{const h=x?.response?.data?.message;J({tone:"bad",title:Array.isArray(h)?h.join(" · "):h||e("org.renameError")})}});if(!c.data)return null;const u=c.data.plan==="trial"?e("org.trialPlan"):c.data.plan?c.data.plan.charAt(0).toUpperCase()+c.data.plan.slice(1):"—",p=o.trim(),f=p.length>=2&&p!==c.data.name&&!d.isPending;return t.jsxs("div",{className:"cia-card",style:{padding:20,display:"flex",flexDirection:"column",gap:12},children:[t.jsx("span",{className:"cia-eyebrow",children:e("org.eyebrow")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:10,flex:"none",display:"grid",placeItems:"center",background:"var(--cia-bg-tint)",color:"var(--cia-brand-500)"},children:t.jsx(yc,{size:20})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[i?t.jsxs("form",{style:{display:"flex",alignItems:"center",gap:6},onSubmit:x=>{x.preventDefault(),f&&d.mutate(p)},children:[t.jsx("input",{className:"input",style:{flex:1,minWidth:0,fontSize:14,height:34,boxSizing:"border-box"},value:o,onChange:x=>l(x.target.value),maxLength:120,autoFocus:!0,"aria-label":e("org.renameLabel")}),t.jsx("button",{type:"submit",className:"cia-btn cia-btn-cta",style:{height:34,paddingInline:10},disabled:!f,title:e("org.renameSave"),children:d.isPending?t.jsx(je,{size:14,className:"animate-spin","aria-hidden":!0}):t.jsx(ct,{size:14,"aria-hidden":!0})}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-outline",style:{height:34,paddingInline:10},onClick:()=>r(!1),disabled:d.isPending,title:e("org.renameCancel"),children:t.jsx(nt,{size:14,"aria-hidden":!0})})]}):t.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,maxWidth:"100%"},children:[t.jsx("span",{style:{fontSize:16,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.data.name}),s&&t.jsx("button",{type:"button",onClick:()=>{l(c.data.name),r(!0)},title:e("org.renameLabel"),"aria-label":e("org.renameLabel"),style:{display:"grid",placeItems:"center",width:26,height:26,borderRadius:7,border:"1px solid var(--cia-border)",background:"transparent",color:"var(--cia-text-3)",cursor:"pointer",flex:"none"},children:t.jsx(qt,{size:12,"aria-hidden":!0})})]}),t.jsxs("div",{style:{fontSize:12.5,color:"var(--cia-text-3)",display:"inline-flex",alignItems:"center",gap:6},children:[t.jsx($s,{size:13})," ",e("org.plan",{name:u})]})]})]})]})}function c6(){const{t:e}=M("settings"),a=xt(u=>u.resolved),n=Pe(u=>u.user),s=n?.role==="admin"||n?.role==="superadmin",i=Os({strict:!1}),{can:r}=tt(),o=[{id:"profile",label:e("nav.profile"),icon:my},...r("billing.view")?[{id:"billing",label:e("nav.billing"),icon:$s}]:[],...r("meetings.view")?[{id:"meetings",label:e("nav.meetings"),icon:Ps}]:[],...s||r("team.manage")?[{id:"team",label:e("nav.team"),icon:Bs}]:[],...s||r("team.manage")?[{id:"roles",label:e("nav.roles"),icon:Cc}]:[],...s||r("audit.view")?[{id:"audit",label:e("nav.audit"),icon:Qr}]:[]],l=o.some(u=>u.id===i.s)?i.s:"profile",[c,d]=m.useState(l);return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("topbar.eyebrow"),title:e(
975"topbar.title")}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":a,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-settings",children:[t.jsx("nav",{className:"cia-settings-nav",children:o.map(u=>{const p=u.icon;return t.jsxs("button",{type:"button",className:"cia-settings-link","data-active":c===u.id,onClick:()=>d(u.id),children:[t.jsx(p,{size:15})," ",u.label]},u.id)})}),t.jsxs("div",{className:"cia-settings-body",children:[c==="profile"&&t.jsx(i6,{}),c==="billing"&&t.jsx(KL,{}),c==="meetings"&&r("meetings.view")&&t.jsx(TL,{}),c==="team"&&(s||r("team.manage"))&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[n?.role==="superadmin"&&t.jsx(PL,{}),t.jsx(IL,{}),t.jsx(BL,{})]}),c==="roles"&&(s||r("team.manage"))&&t.jsx($L,{}),c==="audit"&&(s||r("audit.view"))&&t.jsx(e6,{})]})]})})]})}function xn(e,a){const n=e?.response?.data?.message;return typeof n=="string"&&n.trim()?n:Array.isArray(n)&&typeof n[0]=="string"&&n[0].trim()?n[0]:a}function k1(e){const a=e?.response?.status;return typeof a=="number"?a:null}async function N1(){try{return(await T.get("/flows")).data}catch(e){const a=k1(e);if(a===501||a===404)return null;throw e}}async function d6(e){try{return{disponible:!0,corrida:(await T.get(`/flows/por-conversacion/${encodeURIComponent(e)}`)).data?.corrida??null}}catch(a){const n=k1(a);if(n===501||n===404||n===403)return{disponible:!1};throw a}}function S1(e,a,n={}){return se({queryKey:Qe.porConversacion(e??"",a),queryFn:()=>d6(e),enabled:!!e&&(n.enabled??!0),staleTime:3e4,placeholderData:(s,i)=>i?.queryKey[2]===(e??"")?s:void 0})}function C1(e={}){return se({queryKey:Qe.lista(),queryFn:N1,enabled:e.enabled??!0})}function D9(e){return se({queryKey:Qe.detalle(e),queryFn:async()=>(await T.get(`/flows/${e}`)).data})}function I9(){return se({queryKey:Qe.plantillas(),queryFn:async()=>(await T.get("/flows/plantillas")).data,staleTime:10*6e4})}function L9(e,a={}){return se({queryKey:Qe.corridasDeConFiltros(e,{...a}),queryFn:async()=>(await T.get(`/flows/${e}/runs`,{params:a})).data})}function F9(e={}){return se({queryKey:Qe.corridasGlobalesConFiltros({...e}),queryFn:async()=>(await T.get("/flows/corridas",{params:e})).data})}function O9(e){return se({queryKey:Qe.corrida(e??""),enabled:!!e,queryFn:async()=>(await T.get(`/flows/runs/${e}`)).data})}function $9(e){return se({queryKey:Qe.versiones(e),queryFn:async()=>(await T.get(`/flows/${e}/versions`)).data})}function q9(e,a){return se({queryKey:Qe.version(e,a??""),enabled:!!a,queryFn:async()=>(await T.get(`/flows/${e}/versions/${a}`)).data})}function B9(e,a={}){return se({queryKey:Qe.metricas(e,{...a}),queryFn:async()=>(await T.get(`/flows/${e}/metrics`,{params:a})).data})}function W9(e,a,n){return se({queryKey:Qe.diagnostico(e,n),enabled:!!a,queryFn:async()=>(await T.post("/flows/diagnostico",{grafo:a,flowId:e})).data,staleTime:1/0})}async function u6(e){return(await T.get(`/flows/${e}/export`)).data}function U9(){return se({queryKey:Qe.ajustesDeLaPlataforma(),queryFn:async()=>(await T.get("/admin/platform-settings/flows")).data})}function na(e,a){for(const n of a)e.invalidateQueries({queryKey:[...n]})}function ln(e,a){e.setQueryData(Qe.detalle(a.id),a)}function p6(){const e=xe();return oe({mutationFn:async a=>(await T.post("/flows",a)).data,onSuccess:a=>{ln(e,a),na(e,aa.crear())}})}function h6(e){const a=xe();return oe({mutationFn:async n=>(await T.patch(`/flows/${e}`,n)).data,onSuccess:n=>{ln(a,n),na(a,aa.editar(e))}})}function V9(e){const a=xe();return oe({mutationFn:async n=>(await T.patch(`/flows/${e}/draft`,{draft:n})).data,onSuccess:n=>{ln(a,n),na(a,aa.guardarBorrador(e))}})}function K9(e){const a=xe();return oe({mutationFn:async()=>(await T.post(`/flows/${e}/publish`)).data,onSuccess:()=>na(a,aa.publicar(e))})}function H9(e){const a=xe();return oe({mutationFn:async n=>(await T.patch(`/flows/${e}/enabled`,{enabled:n})).data,onSuccess:n=>{ln(a,n),na(a,aa.encender(e))}})}function m6(){const e=xe();return oe({mutationFn:async a=>(await T.delete(`/flows/${a}`)).data,onSuccess:(a,n)=>{e.removeQueries({queryKey:[...Qe.detalle(n)]}),na(e,aa.eliminar())}})}function f6(){const e=xe();return oe({mutationFn:async a=>(await T.post(`/flows/${a.flowId}/duplicate`,a.name?{name:a.name}:{})).data,onSuccess:a=>{ln(e,a),na(e,aa.duplicar())}})}function x6(){const e=xe();return oe({mutationFn:async a=>(await T.post("/flows/import",a)).data,onSuccess:a=>{ln(e,a),na(e,aa.importar())}})}function Q9(){const e=xe();return oe({mutationFn:async a=>(await T.post(`/flows/desde-plantilla/${encodeURIComponent(a.clave)}`,a.name?{name:a.name}:{})).data,onSuccess:a=>{ln(e,a),na(e,aa.desdePlantilla())}})}function G9(e){const a=xe();return oe({mutationFn:async n=>(await T.post(`/flows/${e}/triggers`,n)).data,onSuccess:n=>{ln(a,n),na(a,aa.disparador(e))}})}function Z9(e){const a=xe();return oe({mutationFn:async n=>(await T.patch(`/flows/${e}/triggers/${n.triggerId}`,n.cambios)).data,onSuccess:n=>{ln(a,n),na(a,aa.disparador(e))}})}function Y9(e){const a=xe();return oe({mutationFn:async n=>(await T.delete(`/flows/${e}/triggers/${n}`)).data,onSuccess:n=>{ln(a,n),na(a,aa.disparador(e))}})}function g6(e){const a=xe();return oe({mutationFn:async n=>(await T.post(`/flows/${e}/start`,n)).data,onSuccess:()=>na(a,aa.lanzar(e))})}function b6(){const e=xe();return oe({mutationFn:async a=>(await T.post(`/flows/runs/${a}/cancel`)).data,onSuccess:(a,n)=>na(e,aa.cancelarCorrida(n))})}function X9(e){const a=xe();return oe({mutationFn:async n=>(await T.post(`/flows/${e}/versions/${n}/restore`)).data,onSuccess:n=>{ln(a,n),na(a,aa.restaurarVersion(e))}})}function J9(){const e=xe();return oe({mutationFn:async a=>(await T.patch("/admin/platform-settings/flows",a)).data,onSuccess:()=>na(e,aa.ajustesDeLaPlataforma())})}function eW(){return oe({mutationFn:async e=>(await T.post("/admin/platform-settings/flows/cancelar-vivas",{organizationId:e})).data})}const _1=120,y6=400;async function v6(e,a,n){try{const s=await u6(e),i=hS(a);ao(new Blob([JSON.stringify(s,null,2)],{type:"application/json"}),i),J({tone:"ok",title:n("flows.modulo.archivo.descargado"),desc:i})}catch(s){J({tone:"bad",title:n("flows.modulo.archivo.noSeDescargo"),desc:xn(s,n("flows.modulo.errorGenerico"))})}}function j6({abierto:e,onCerrar:a,onCreado:n}){const{t:s}=M("misc"),i=p6(),[r,o]=m.useState(""),[l,c]=m.useState(null);m.useEffect(()=>{e&&(o(""),c(null))},[e]);const d=()=>{const u=r.trim();u&&i.mutate({name:u},{onSuccess:p=>n(p),onError:p=>c(xn(p,s("flows.modulo.errorGenerico")))})};return t.jsx(ot,{open:e,onClose:a,title:s("flows.modulo.nuevo.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{variant:"ghost",onClick:a,children:s("flows.modulo.cancelar")}
975),t.jsx(Ie,{variant:"primary",loading:i.isPending,disabled:!r.trim(),disabledReason:r.trim()?void 0:s("flows.modulo.nuevo.faltaNombre"),onClick:d,children:s("flows.modulo.nuevo.crear")})]}),children:t.jsx("form",{onSubmit:u=>{u.preventDefault(),d()},children:t.jsx(Lc,{label:s("flows.modulo.nuevo.nombre"),description:s("flows.modulo.nuevo.ayuda"),placeholder:s("flows.modulo.nuevo.placeholder"),value:r,onChange:o,maxLength:_1,required:!0,autoFocus:!0,error:l??void 0})})})}function w6({abierto:e,onCerrar:a,onImportado:n}){const{t:s}=M("misc"),i=x6(),[r,o]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(null);m.useEffect(()=>{e&&(o(null),c(null),u(null))},[e]);const p=async f=>{if(o(f),c(null),f.size>pS){u(s("flows.modulo.importar.muyGrande"));return}const x=mS(await f.text());if(!x.ok){u(s(`flows.modulo.importar.${x.motivo}`));return}u(null),c(x.datos)};return t.jsxs(ot,{open:e,onClose:a,title:s("flows.modulo.importar.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{variant:"ghost",onClick:a,children:s("flows.modulo.cancelar")}),t.jsx(Ie,{variant:"primary",loading:i.isPending,disabled:!l,disabledReason:l?void 0:s("flows.modulo.importar.eligeArchivo"),onClick:()=>{l&&i.mutate(l,{onSuccess:f=>n(f),onError:f=>u(xn(f,s("flows.modulo.errorGenerico")))})},children:s("flows.modulo.importar.importar")})]}),children:[t.jsx("p",{className:"cia-flujo-modal-texto",children:s("flows.modulo.importar.explicacion")}),t.jsx(ev,{accept:".json,application/json",file:r,onFile:f=>void p(f),onClear:()=>{o(null),c(null),u(null)},error:d,hint:s("flows.modulo.importar.pista")}),l?t.jsx(le,{tone:"info",variant:"compact",children:s("flows.modulo.importar.listo",{nombre:l.name,count:l.draft?.nodos?.length??0})}):null]})}function tW({abierto:e,onCerrar:a,flujo:n}){const{t:s}=M("misc"),i=h6(n.id),[r,o]=m.useState(n.name),[l,c]=m.useState(n.description??""),[d,u]=m.useState(null);m.useEffect(()=>{e&&(o(n.name),c(n.description??""),u(null))},[e,n.name,n.description]);const p=r.trim()!==n.name||l.trim()!==(n.description??""),f=r.trim()?p?void 0:s("flows.modulo.datos.sinCambios"):s("flows.modulo.nuevo.faltaNombre");return t.jsx(ot,{open:e,onClose:a,title:s("flows.modulo.datos.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{variant:"ghost",onClick:a,children:s("flows.modulo.cancelar")}),t.jsx(Ie,{variant:"primary",loading:i.isPending,disabled:!!f,disabledReason:f,onClick:()=>i.mutate({name:r.trim(),description:l.trim()||null},{onSuccess:a,onError:x=>u(xn(x,s("flows.modulo.errorGenerico")))}),children:s("flows.modulo.guardar")})]}),children:t.jsxs("div",{className:"cia-flujo-modal-campos",children:[t.jsx(Lc,{label:s("flows.modulo.datos.nombre"),value:r,onChange:o,maxLength:_1,required:!0}),t.jsx(yv,{label:s("flows.modulo.datos.descripcion"),description:s("flows.modulo.datos.descripcionAyuda"),value:l,onChange:c,maxLength:y6,counter:!0,rows:3,autoGrow:!0}),d?t.jsx(le,{tone:"bad",children:d}):null]})})}function k6(){const{t:e}=M("misc"),a=xt(j=>j.resolved),n=Pe(j=>j.user),s=dt(),i=lt(n,"workflows.manage"),[r,o]=m.useState(null),l=f6(),c=m6(),{data:d,isLoading:u,isError:p,isFetching:f,refetch:x}=se({queryKey:Qe.lista(),queryFn:N1}),h=j=>void s({to:"/workflows/$flowId",params:{flowId:j}}),b=j=>t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("workflows.eyebrow"),title:e("workflows.title"),titleAs:"div"}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":a,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsx("div",{className:"cia-flujos-pagina",children:j})})]});if(u)return b(t.jsxs("div",{"aria-busy":"true",className:"cia-flujos-esqueleto",children:[t.jsx(ge,{w:220,h:40,r:10}),t.jsx(ge,{h:44,r:10}),t.jsx(ge,{h:220,r:14})]}));if(d===null)return t.jsx(So,{eyebrow:e("workflows.eyebrow"),title:e("workflows.title"),icon:en,description:e("workflows.desc")});const g=(j,C)=>t.jsx(Jy,{title:e("workflows.title"),subtitle:e("flows.modulo.lista.subtitulo"),icon:en,actions:j?t.jsxs("div",{className:"cia-flujos-acciones",children:[t.jsxs(et,{to:"/workflows/plantillas",className:"cia-btn cia-button cia-btn-ghost","data-size":"md",children:[t.jsx("span",{className:"cia-btn-glyph","aria-hidden":"true",children:t.jsx(bi,{})}),e("flows.modulo.lista.plantillas")]}),t.jsxs(et,{to:"/workflows/corridas",className:"cia-btn cia-button cia-btn-ghost","data-size":"md",children:[t.jsx("span",{className:"cia-btn-glyph","aria-hidden":"true",children:t.jsx(Hp,{})}),e("flows.modulo.lista.corridas")]}),i?t.jsx(Ie,{variant:"outline",icon:t.jsx(b2,{}),onClick:()=>o("importar"),children:e("flows.modulo.lista.importar")}):null,i&&!C?t.jsx(Ie,{variant:"cta",icon:t.jsx(Fe,{}),onClick:()=>o("nuevo"),children:e("flows.modulo.lista.nuevo")}):null]}):void 0});if(p&&!d)return b(t.jsxs(t.Fragment,{children:[g(!1,!1),t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:e("flows.modulo.reintentar"),icon:Na,loading:f,onClick:()=>void x()},children:e("workflows.loadError")})]}));const v=(d?.items??[]).map(j=>({...j})),y=j=>{const C=[{key:"ver",items:[{key:"abrir",label:e("flows.modulo.lista.abrir"),icon:Ja,onSelect:()=>h(j.id)},{key:"exportar",label:e("flows.modulo.menu.exportar"),icon:Tn,onSelect:()=>void v6(j.id,j.name,e)}]}];return i&&(C[0].items.push({key:"duplicar",label:e("flows.modulo.menu.duplicar"),icon:bn,onSelect:()=>l.mutate({flowId:j.id},{onSuccess:N=>J({tone:"ok",title:e("flows.modulo.menu.duplicado",{nombre:N.name}),desc:e("flows.modulo.menu.duplicadoDesc")}),onError:N=>J({tone:"bad",title:xn(N,e("flows.modulo.errorGenerico"))})})}),C.push({key:"peligro",items:[{key:"eliminar",label:e("flows.modulo.menu.eliminar"),icon:mt,danger:!0,disabled:j.corridasVivas>0,disabledReason:j.corridasVivas>0?e("flows.modulo.menu.motivos.hayCorridasVivas",{count:j.corridasVivas}):void 0,onSelect:()=>void pa({danger:!0,title:e("flows.modulo.eliminar.titulo",{nombre:j.name}),message:e("flows.modulo.eliminar.mensaje"),confirmLabel:e("flows.modulo.eliminar.confirmar"),onConfirm:async()=>{try{await c.mutateAsync(j.id)}catch(N){throw J({tone:"bad",title:xn(N,e("flows.modulo.errorGenerico"))}),N}}})}]})),C},k=[{key:"name",header:e("flows.modulo.lista.columnas.nombre"),render:(j,C)=>t.jsxs("div",{className:"cia-flujos-nombre",children:[t.jsx(et,{to:"/workflows/$flowId",params:{flowId:C.id},className:"cia-flujos-enlace",children:C.name}),C.description?t.jsx("span",{className:"cia-flujos-desc",children:C.description}):null]})},{key:"estado",header:e("flows.modulo.lista.columnas.estado"),render:(j,C)=>{const N=cS(C),S=dS[N];return t.jsx(at,{tone:S.tono,icon:S.conIcono?void 0:!1,label:e(`flows.modulo.estado.${N}`)})}},{key:"canalDeEntrada",header:e("flows.modulo.lista.columnas.canal"),render:(j,C)=>t.jsx("span",{className:"cia-flujos-dato",children:e(`flows.modulo.canal.${C.canalDeEntrada}`,{defaultValue:C.canalDeEntrada})})}
975,{key:"corridasVivas",header:e("flows.modulo.lista.columnas.enCurso"),align:"right",render:(j,C)=>t.jsx("span",{className:"cia-flujos-numero","data-cero":C.corridasVivas===0?"1":void 0,children:C.corridasVivas})},{key:"updatedAt",header:e("flows.modulo.lista.columnas.actualizado"),render:(j,C)=>t.jsx("span",{className:"cia-flujos-dato",children:ts(C.updatedAt)})},{key:"acciones",header:t.jsx("span",{className:"cia-sr-only",children:e("flows.modulo.lista.columnas.acciones")}),align:"right",width:"56px",render:(j,C)=>t.jsx(vn,{iconTrigger:{icon:t.jsx(zi,{}),label:e("flows.modulo.lista.accionesDe",{nombre:C.name}),size:"sm"},groups:y(C),"aria-label":e("flows.modulo.lista.accionesDe",{nombre:C.name})})}],w=v.length===0;return b(t.jsxs(t.Fragment,{children:[g(!0,w),p?t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:e("flows.modulo.reintentar"),icon:Na,loading:f,onClick:()=>void x()},children:e("workflows.loadError")}):null,w?t.jsx(st,{icon:en,title:e("flows.modulo.lista.vacioTitulo"),desc:e("flows.modulo.lista.vacioDesc"),action:i?{label:e("flows.modulo.lista.vacioCrear"),onClick:()=>o("nuevo"),variant:"cta"}:void 0,secondaryAction:{label:e("flows.modulo.lista.vacioPlantillas"),onClick:()=>void s({to:"/workflows/plantillas"})}}):t.jsx(hh,{columns:k,rows:v,rowKey:"id",dividers:!0}),t.jsx(j6,{abierto:r==="nuevo",onCerrar:()=>o(null),onCreado:j=>h(j.id)}),t.jsx(w6,{abierto:r==="importar",onCerrar:()=>o(null),onImportado:j=>{j.idsRegenerados>0&&J({tone:"info",title:e("flows.modulo.importar.idsRegenerados",{count:j.idsRegenerados})}),h(j.id)}})]}))}const Cg="facebook.com";function N6(e){let a;try{a=new URL(e)}catch{return!1}return a.protocol!=="https:"?!1:a.hostname===Cg||a.hostname.endsWith("."+Cg)}const S6=2e4,C6=10*6e4;let hr=null;function _6(e){return hr||(hr=new Promise((a,n)=>{const s=window;if(s.FB){a();return}s.fbAsyncInit=()=>{window.FB?.init({appId:e,autoLogAppEvents:!1,xfbml:!1,version:"v25.0",fedCM:!1}),a()};const i=document.createElement("script");i.src="https://connect.facebook.net/en_US/sdk.js",i.async=!0,i.defer=!0,i.crossOrigin="anonymous",i.onerror=()=>{hr=null,n(new Error("sdk_no_cargo"))},document.head.appendChild(i)}),hr)}function E6(e,a={}){const n=a.modo??"cloud_api";if(n==="coexistencia"&&!e.coexistencia)return Promise.reject(new Error("coexistencia_no_disponible"));if(!e.disponible||!e.appId||!e.configId)return Promise.reject(new Error("no_disponible"));const s=A6(e,n);return new Promise((i,r)=>{let o=null,l=null,c=null,d=!1,u=null;const p=Date.now(),f=[],x=A=>f.push(`${A} +${Date.now()-p}ms`),h=new Map,b=new Set,g=12,v=(A,E)=>{h.size<g&&!h.has(A)&&h.set(A,E)},y=A=>{b.size<g&&b.add(A)},k=()=>{const A=[...h.entries()].map(([I,P])=>`${P?"✓":"✗"}${I}`).join(" "),E=[...b].join(",");return`orígenes: ${A||"ninguno"} · eventos: ${E||"ninguno"}`},w=()=>`modo=${n} · config_id=${String(s.config_id??"?")} · extras=${JSON.stringify(s.extras??null)}`,j=(A,E)=>{d||(d=!0,window.removeEventListener("message",S),clearTimeout(_),u&&clearTimeout(u),console.info(`[conexión de WhatsApp] ${E?`terminó por «${E}»`:"completó"} (${w()}). Señales: ${f.length?f.join(" · "):"ninguna"} — ${k()}`+(l?` · número adjunto: ${l}`:"")),A())},C=()=>{u||(u=setTimeout(()=>j(()=>r(new Error("tiempo_agotado")),"tiempo_agotado"),S6))},N=()=>{const A=c;A&&j(()=>i({wabaId:o,phoneNumberId:l,codigo:A}))};function S(A){if(!N6(A.origin)){v(A.origin,!1);return}v(A.origin,!0);try{const E=typeof A.data=="string"?JSON.parse(A.data):A.data;if(E?.type!=="WA_EMBEDDED_SIGNUP")return;y(typeof E?.event=="string"?E.event:"(sin evento)");{const I=E?.data?.waba_id;typeof I=="string"&&I&&(o=I,x("identificador de la cuenta"),N());const P=E?.data?.phone_number_id;typeof P=="string"&&P&&(l=P)}E?.event==="CANCEL"&&j(()=>r(new Error("cancelado")),"CANCEL de Meta")}catch{}}const _=setTimeout(()=>j(()=>r(new Error("cancelado")),"techo del popup"),C6);window.addEventListener("message",S);const R=window.FB;if(!R){j(()=>r(new Error("sdk_no_cargo")),"sdk_no_cargo");return}R.login(A=>{const E=A?.authResponse?.code;if(typeof E=="string"&&E){c=E,x("codigo canjeable"),C(),N();return}j(()=>r(new Error(o?"sin_codigo":"cancelado")),o?"sin_codigo":"cancelado")},s)})}function A6(e,a){const n={response_type:"code",override_default_response_type:!0};switch(a){case"cloud_api":return{config_id:e.configId,...n,extras:{setup:{}}};case"coexistencia":{const s=e.coexistencia;return s?{config_id:s.configId??e.configId,...n,extras:{setup:{},[s.extrasKey]:s.featureType,...s.sessionInfoVersion?{sessionInfoVersion:s.sessionInfoVersion}:{},...s.extrasVersion?{version:s.extrasVersion}:{}}}:{config_id:e.configId,...n,extras:{setup:{}}}}}}const _g="numeros";function R6(e){const a=["numeros"];return e.llamadasDisponibles&&a.push("llamadas"),a.push("atencion"),e.puedeAdministrar&&a.push("avisos"),e.puedeVerIntegraciones&&a.push("integraciones"),a}function E1(e){for(const a of e??[]){const n=a.numbers?.[0]?.id;if(n)return n}return null}function T6(e,a){if(typeof e!="string")return _g;const n=e;return a.includes(n)?n:_g}function M6(e){const a=e.trim(),n=/[.!?](\s+)/.exec(a);if(!n)return{primera:a,resto:""};const s=n.index+1;return{primera:a.slice(0,s),resto:a.slice(s).trim()}}function P6(e){const a=String(e??"").trim().toUpperCase();if(!a)return null;if(a==="TIER_UNLIMITED"||a==="UNLIMITED")return"ilimitado";const n=/^TIER_(\d{1,6})(K|M)?$/.exec(a);if(!n)return null;const s=Number(n[1]);if(!Number.isFinite(s)||s<=0)return null;const i=n[2]==="M"?1e6:n[2]==="K"?1e3:1;return s*i}const z6=new Set(["motivoDesconexion"]);function D6(e){const a=String(e??"").trim();if(!a)return null;const n=a.indexOf(":"),s=(n<0?a:a.slice(0,n)).trim(),i=n<0?"":a.slice(n+1).trim().toLowerCase(),r=/^[a-z0-9_]{1,64}$/.test(s)&&!z6.has(s)?s:"rechazo_desconocido",o=/^[a-z0-9_]{1,60}$/.test(i)?i:null;return{code:r,motivo:o}}const I6=14,A1=864e5;function L6(e,a){if(!e)return null;const n=Date.parse(e);
975return Number.isFinite(n)?Math.ceil((n-a)/A1):null}function F6(e,a){if(!e||!e.consultadoEl)return{tipo:"desconocida"};if(!e.venceEl)return{tipo:"no_vence"};const n=L6(e.venceEl,a);return n===null?{tipo:"desconocida"}:{tipo:"vence",venceEl:e.venceEl,dias:n,porVencer:n<=I6,vencida:n<=0}}const O6=new Set(["enabled"]);function $6(e,a,n){const s=e.filter(p=>p.status==="active"),i=s.flatMap(p=>p.numbers.filter(f=>f.status==="active")),r=i.length>0,o=[];o.push({id:"conectar",hecho:r,motivo:r?null:s.length>0?"registrando":null});const l=i.filter(p=>!p.agentId);o.push(r?l.length===0?{id:"agente",hecho:!0,motivo:null}:{id:"agente",hecho:!1,motivo:"numeros_sin_agente",faltan:l.length,numeroId:l[0].id}:{id:"agente",hecho:!1,motivo:"falta_conectar"});const c=s.find(p=>p.elegibilidad?.puedeEnviarPlantillas===!1),d=s.some(p=>p.elegibilidad?.puedeEnviarPlantillas===!0);o.push(s.length===0?{id:"verificar",hecho:!1,motivo:"falta_conectar"}:c?{id:"verificar",hecho:!1,motivo:"con_problema",problema:c.elegibilidad?.problemas?.[0]}:d?{id:"verificar",hecho:!0,motivo:null}:{id:"verificar",hecho:!1,motivo:"sin_datos"}),o.push(s.length===0?{id:"plantilla",hecho:!1,motivo:"falta_conectar"}:a==null?{id:"plantilla",hecho:!1,motivo:"sin_datos"}:a.some(p=>p.usable)?{id:"plantilla",hecho:!0,motivo:null}:{id:"plantilla",hecho:!1,motivo:null});const u=i.filter(p=>!p.isOnBizApp);if(n&&u.length>0){const p=u.some(f=>O6.has(String(f.callingStatus??"")));o.push({id:"llamadas",hecho:p,motivo:null,opcional:!0})}return o}function Eg(e){const a=e.filter(n=>!n.opcional);return a.length>0&&a.every(n=>n.hecho)}function q6(e,a){return(e?["cloud_api","coexistencia"]:["cloud_api"]).map(s=>{const i=a!==null&&s!==a;return{modo:s,deshabilitada:i,motivo:i?a==="coexistencia"?"reconexion_celular":"reconexion_nube":null}})}const B6=7;function W6(e,a){if(!e.coexistence||e.status==="disconnected")return!1;const n=Date.parse(e.createdAt);return Number.isFinite(n)?a-n<=B6*A1:!1}function U6({cuentas:e,llamadasDisponibles:a,puedeAdministrar:n,onConectar:s,guia:i,onIrAPestana:r}){const{t:o}=M("misc"),l=dt(),{data:c,isLoading:d}=se({queryKey:["whatsapp","templates"],enabled:e.length>0,queryFn:async()=>{try{return(await T.get("/whatsapp/templates")).data}catch(h){const b=h?.response?.status;if(b===501||b===404||b===403)return null;throw h}},staleTime:6e4}),u=$6(e,c?c.items:null,a);if(d){const h=u.filter(b=>b.id!=="plantilla");return Eg(h)?null:t.jsx(ge,{h:228,r:14})}if(Eg(u))return null;function p(h){if(!h)return;const b=document.getElementById(`wa-agente-${h}`);if(!b)return;const g=window.matchMedia("(prefers-reduced-motion: reduce)").matches;b.scrollIntoView({block:"center",behavior:g?"auto":"smooth"}),b.focus({preventScroll:!0})}function f(h,b){h.preventDefault(),b()}function x(h){const b=h.motivo==="falta_conectar"?o("whatsapp.puestaEnMarcha.faltaConectar"):null;switch(h.id){case"conectar":return{id:h.id,label:o("whatsapp.puestaEnMarcha.pasos.conectar.label"),description:h.motivo==="registrando"?o("whatsapp.puestaEnMarcha.pasos.conectar.registrando"):o("whatsapp.puestaEnMarcha.pasos.conectar.desc"),done:h.hecho,action:!h.hecho&&h.motivo!=="registrando"&&s?{label:o("whatsapp.modulo.conectar"),onClick:()=>s()}:void 0};case"agente":return{id:h.id,label:o("whatsapp.puestaEnMarcha.pasos.agente.label"),description:b??(h.motivo==="numeros_sin_agente"?o("whatsapp.puestaEnMarcha.pasos.agente.faltan",{count:h.faltan??1}):o("whatsapp.puestaEnMarcha.pasos.agente.desc")),done:h.hecho,action:h.motivo==="numeros_sin_agente"&&n?{label:o("whatsapp.puestaEnMarcha.pasos.agente.accion"),onClick:()=>p(h.numeroId)}:void 0};case"verificar":return{id:h.id,label:o("whatsapp.puestaEnMarcha.pasos.verificar.label"),description:b??(h.motivo==="con_problema"?o("whatsapp.puestaEnMarcha.pasos.verificar.conProblema"):h.motivo==="sin_datos"?o("whatsapp.puestaEnMarcha.pasos.verificar.sinDatos"):o("whatsapp.puestaEnMarcha.pasos.verificar.desc")),done:h.hecho,action:!h.hecho&&!b?{label:o("whatsapp.puestaEnMarcha.pasos.verificar.accion"),href:i,external:!0}:void 0};case"plantilla":return{id:h.id,label:o("whatsapp.puestaEnMarcha.pasos.plantilla.label"),description:b??(h.motivo==="sin_datos"?o("whatsapp.puestaEnMarcha.pasos.plantilla.sinDatos"):o("whatsapp.puestaEnMarcha.pasos.plantilla.desc")),done:h.hecho,action:!h.hecho&&!b&&h.motivo!=="sin_datos"&&n?{label:o("whatsapp.puestaEnMarcha.pasos.plantilla.accion"),href:"/whatsapp/plantillas/nueva",onClick:g=>f(g,()=>void l({to:"/whatsapp/plantillas/nueva"}))}:void 0};case"llamadas":return{id:h.id,label:o("whatsapp.puestaEnMarcha.pasos.llamadas.label"),description:o("whatsapp.puestaEnMarcha.pasos.llamadas.desc"),done:h.hecho,optional:h.opcional,action:h.hecho?void 0:{label:o("whatsapp.puestaEnMarcha.pasos.llamadas.accion"),href:"/whatsapp?tab=llamadas",onClick:g=>f(g,()=>r("llamadas"))}}}}return t.jsx(fE,{title:o("whatsapp.puestaEnMarcha.titulo"),doneLabel:o("whatsapp.puestaEnMarcha.listo"),items:u.map(x)})}const Pt="flows.bandeja";function V6(e,a){const n=new Date(e),s=new Date(a);return n.getFullYear()===s.getFullYear()&&n.getMonth()===s.getMonth()&&n.getDate()===s.getDate()}function K6(e){return`flows.eventos.${e.replace(/\./g,"_")}`}
975function H6(e,a=Date.now()){if(!e)return null;const n=e.flowName.trim(),s=n?{clave:`${Pt}.ficha.titulo`,params:{nombre:n}}:{clave:`${Pt}.ficha.tituloSinNombre`},i=e.esperando,r=i?.hasta??null,o=l=>{if(!r)return{clave:l};const c=V6(r,a);return{clave:c?`${l}Hasta`:`${l}HastaEl`,hastaIso:r,mismoDia:c}};return e.atascada?{titulo:s,detalle:o(`${Pt}.ficha.atascada`),tono:"aviso"}:i?i.tipo==="respuesta"?{titulo:s,detalle:o(`${Pt}.ficha.esperaRespuesta`),tono:"info"}:i.tipo==="tiempo"?{titulo:s,detalle:o(`${Pt}.ficha.esperaTiempo`),tono:"info"}:i.tipo==="agente"?{titulo:s,detalle:{clave:`${Pt}.ficha.esperaAgente`},tono:"info"}:i.evento?{titulo:s,detalle:{...o(`${Pt}.ficha.esperaEvento`),params:{evento:i.evento}},tono:"info"}:{titulo:s,detalle:o(`${Pt}.ficha.esperaEventoSinNombre`),tono:"info"}:{titulo:s,detalle:{clave:`${Pt}.ficha.avanzando`},tono:"info"}}function Q6(e){const a=e.filter(n=>n.publicado&&n.enabled&&n.lanzableAMano===!0);return{lanzables:a,fuera:e.length-a.length}}function Vh(e){const a=e?.response;return{status:typeof a?.status=="number"?a.status:null,code:typeof a?.data?.code=="string"?a.data.code:null}}function G6(e){const{status:a,code:n}=Vh(e);return a===409&&n==="ya_hay_corrida"?`${Pt}.lanzar.rechazo.yaHayCorrida`:a===400&&n==="flujo_sin_lanzador_manual"?`${Pt}.lanzar.rechazo.sinLanzadorManual`:a===404?`${Pt}.lanzar.rechazo.noExiste`:a===403?`${Pt}.lanzar.rechazo.sinPermiso`:a===501?`${Pt}.lanzar.rechazo.noDisponible`:null}function Z6(e){return Vh(e).status===404}function Y6(e){return e.atiende!=="flujo"?null:!e.flowId||!e.flujo?{clave:`${Pt}.numero.aviso.flujoNoEsta`}:e.flujo.publicado?e.flujo.encendido?null:{clave:`${Pt}.numero.aviso.apagado`,params:{nombre:e.flujo.nombre}}:{clave:`${Pt}.numero.aviso.sinPublicar`,params:{nombre:e.flujo.nombre}}}function X6(e,a){return e.filter(n=>n.publicado||n.id===a)}function J6(e){const{status:a,code:n}=Vh(e);return n==="flujo_sin_publicar"?`${Pt}.numero.rechazo.sinPublicar`:n==="flujos_no_disponibles"?`${Pt}.numero.rechazo.noDisponibles`:n==="flujo_requerido"?`${Pt}.numero.rechazo.elegi`:a===404?`${Pt}.numero.rechazo.noExiste`:a===403?`${Pt}.numero.rechazo.sinPermiso`:null}function R1(e){return[e.state,e.mode??"",e.assigneeUserId??"",e.lastMessageAt??""].join("|")}function eF({numero:e,puedeAdministrar:a,agenteNombre:n}){const{t:s}=M("misc"),i=xe(),r=dt(),o=m.useId(),l=Pe(I=>I.user),c=lt(l,"workflows.view"),d=C1({enabled:c}),u=e.atiende==="flujo"?"flujo":"asistente",[p,f]=m.useState(null),[x,h]=m.useState(null),b=p??u,g=e.displayPhoneNumber||e.id,v=oe({mutationFn:async I=>(await T.patch(`/whatsapp/numbers/${e.id}/atencion`,{atiende:I.atiende,flowId:I.flowId})).data,onMutate:()=>h(null),onSuccess:(I,P)=>{f(null),i.invalidateQueries({queryKey:["whatsapp","accounts"]});const O=P.flowId?(d.data?.items??[]).find(W=>W.id===P.flowId)?.name??null:null,K=P.anterior;J({tone:"ok",title:P.deshacer?s("whatsapp.numero.deshecho"):s("whatsapp.numero.guardado"),desc:P.atiende==="flujo"?O?s("flows.bandeja.numero.guardadoFlujo",{phone:g,nombre:O}):s("flows.bandeja.numero.guardadoFlujoSinNombre",{phone:g}):s("flows.bandeja.numero.guardadoAsistente",{phone:g}),action:P.deshacer||!K?void 0:{label:s("whatsapp.numero.deshacer"),onClick:()=>v.mutate({...K,deshacer:!0})}})},onError:I=>{f(null);const P=J6(I);h(P?s(P):xn(I,s("flows.bandeja.numero.rechazo.generico")))}}),y={atiende:u,flowId:u==="flujo"?e.flowId??null:null},k=c&&d.data===null;if(u==="asistente"&&(!c||k))return null;if(u==="asistente"&&d.isPending)return t.jsxs("div",{className:"cia-wa-numero-atencion","aria-busy":"true",children:[t.jsx(ge,{h:12,w:120}),t.jsx(ge,{h:64,r:10})]});const w=Y6(e),j=d.data?.items??[],C=X6(j,u==="flujo"?e.flowId??null:null),N=v.isPending,S=c?k?s("flows.bandeja.numero.motivo.noDisponible"):N?s("flows.bandeja.numero.motivo.guardando"):void 0:s("flows.bandeja.numero.motivo.sinPermiso"),_=[{value:"asistente",title:s("flows.bandeja.numero.asistente"),description:n?s("flows.bandeja.numero.asistenteDesc",{nombre:n}):s("flows.bandeja.numero.asistenteDescSinAgente"),icon:t.jsx(Ft,{}),...N?{disabled:!0,disabledReason:s("flows.bandeja.numero.motivo.guardando")}:{}},{value:"flujo",title:s("flows.bandeja.numero.flujo"),description:s("flows.bandeja.numero.flujoDesc"),icon:t.jsx(en,{}),...S?{disabled:!0,disabledReason:S}:{}}],R=I=>
975{if(h(null),I===u)return f(null);if(I==="asistente")return v.mutate({atiende:"asistente",flowId:null,anterior:y});f("flujo")},A=N?s("flows.bandeja.numero.motivo.guardando"):d.isPending?s("flows.bandeja.numero.motivo.cargandoFlujos"):d.isError&&!d.data?s("flows.bandeja.numero.motivo.falloFlujos"):C.length===0?s("flows.bandeja.numero.motivo.sinPublicados"):void 0,E=u==="flujo"?e.flujo?s("flows.bandeja.numero.leeFlujo",{nombre:e.flujo.nombre}):s("flows.bandeja.numero.leeFlujoSinNombre"):s("flows.bandeja.numero.leeAsistente");return t.jsxs("div",{className:"cia-wa-numero-atencion",children:[t.jsx("span",{className:"cia-wa-numero-rotulo",id:o,children:s("flows.bandeja.numero.rotulo")}),a?t.jsx(uv,{className:"cia-wa-atiende-opciones",value:b,onChange:R,options:_,ariaLabelledBy:o}):t.jsx("span",{className:"cia-wa-numero-valor","aria-labelledby":o,children:E}),b==="flujo"?t.jsxs("div",{className:"cia-wa-atiende-flujo",children:[a&&c?t.jsxs(t.Fragment,{children:[t.jsx(hn,{id:`wa-atiende-flujo-${e.id}`,label:s("flows.bandeja.numero.campoFlujo"),value:u==="flujo"?e.flowId??"":"",placeholder:s("flows.bandeja.numero.placeholder"),options:C.map(I=>({value:I.id,label:I.enabled?I.name:s("flows.bandeja.numero.opcionApagada",{nombre:I.name})})),disabled:!!A,disabledReason:A,onChange:I=>{I&&I!==e.flowId&&v.mutate({atiende:"flujo",flowId:I,anterior:y})}}),d.isError&&!d.data?t.jsx(Ie,{variant:"ghost",size:"sm",icon:t.jsx(Na,{}),onClick:()=>void d.refetch(),children:s("flows.modulo.reintentar")}):null,p==="flujo"&&u==="asistente"?t.jsx("p",{className:"cia-wa-atiende-pendiente","aria-live":"polite",children:s("flows.bandeja.numero.sinGuardar")}):null]}):null,t.jsx("p",{className:"cia-wa-atiende-explicacion",children:s("flows.bandeja.numero.explicacion",{asistente:s("flows.nodos.agente"),persona:s("flows.nodos.asignar"),fin:s("flows.nodos.fin")})})]}):null,w?t.jsx(le,{tone:"warn",variant:"compact",action:e.flowId&&c?{label:s("flows.bandeja.numero.abrirFlujo"),icon:nn,onClick:()=>void r({to:"/workflows/$flowId",params:{flowId:e.flowId}})}:void 0,children:s(w.clave,w.params)}):null,x?t.jsx(le,{tone:"bad",children:x}):null]})}const tF={GREEN:{tone:"success"},YELLOW:{tone:"warning",icon:Tt},RED:{tone:"danger",icon:ry}};function aF({numero:e,llamadasDisponibles:a,puedeAdministrar:n,agentes:s,motivoSinAgentes:i,onReintentarAgentes:r,guardando:o,error:l,onElegirAgente:c}){const{t:d}=M("misc"),u=dt(),p=e.displayPhoneNumber||e.id,f=P6(e.messagingTier),x=f==="ilimitado"?d("whatsapp.numero.sinLimite"):typeof f=="number"?d("whatsapp.numero.limiteDiario",{n:new Intl.NumberFormat(Te()).format(f)}):d("whatsapp.numero.limiteSinConfirmar"),h=e.qualityRating?tF[e.qualityRating]:void 0,b=s??[],g=e.agentId?b.find(j=>j.id===e.agentId)??null:null,v=[...b.map(j=>({value:j.id,label:j.name})),...e.agentId&&!g?[{value:e.agentId,label:d(s?"whatsapp.numero.agenteNoListado":"whatsapp.numero.cargandoAgentes")}]:[]],y=o?d("whatsapp.numero.guardandoAgente"):s===void 0?i??d("whatsapp.numero.cargandoAgentes"):void 0,k=e.status==="pending"?M6(e.registro?.errorCode?d(`whatsapp.errors.${e.registro.errorCode}`,{defaultValue:d("whatsapp.numero.registroPendiente")}):d("whatsapp.numero.registroPendiente")):null,w=e.status==="pending"&&e.registro?.proximoIntentoEl?d("whatsapp.numero.proximoIntento",{when:Be(e.registro.proximoIntentoEl)}):null;return t.jsxs("li",{className:"cia-wa-numero",children:[t.jsx("div",{className:"cia-wa-numero-id",children:t.jsx(Ws,{icon:e.isOnBizApp?ji:Ma,title:t.jsx("span",{className:"cia-mono",children:p}),subtitle:e.verifiedName||void 0,meta:e.sincronizadoEl?d("whatsapp.numero.actualizado",{when:ts(e.sincronizadoEl)}):void 0,tooltip:e.sincronizadoEl?Be(e.sincronizadoEl):void 0})}),t.jsxs("div",{className:"cia-wa-numero-hechos",children:[e.status==="pending"?t.jsx(at,{tone:"warning",pulse:!0,label:d("whatsapp.numero.registrando")}):e.status==="disconnected"?t.jsx(at,{tone:"neutral",icon:wi,label:d("whatsapp.numero.desconectado")}):null,t.jsx(at,{tone:h?.tone??"neutral",icon:h?.icon,label:d(h?`whatsapp.numero.calidad.${e.qualityRating}
975`:"whatsapp.numero.calidad.sinDatos")}),t.jsx("span",{className:"cia-wa-numero-dato",children:x}),a&&t.jsx(sF,{numero:e})]}),t.jsxs("div",{className:"cia-wa-numero-agente",children:[t.jsx("span",{className:"cia-wa-numero-rotulo","aria-hidden":"true",children:d("whatsapp.numero.agente")}),n?t.jsxs(t.Fragment,{children:[t.jsx(hn,{id:`wa-agente-${e.id}`,value:e.agentId??"",placeholder:d("whatsapp.numero.sinAgente"),options:v,ariaLabel:d("whatsapp.table.agentFor",{phone:p}),disabled:!!y,disabledReason:y,onChange:j=>c(j||null)}),s===void 0&&r?t.jsx(Ie,{variant:"ghost",size:"sm",icon:t.jsx(Na,{}),onClick:r,children:d("whatsapp.numero.reintentarAgentes")}):null]}):t.jsx("span",{className:"cia-wa-numero-valor",children:g?d("whatsapp.numero.atiende",{name:g.name}):e.agentId?d("whatsapp.numero.conAgente"):d("whatsapp.numero.sinAgente")})]}),t.jsx(eF,{numero:e,puedeAdministrar:n,agenteNombre:g?.name??null}),k?t.jsxs("div",{className:"cia-wa-numero-nota",children:[t.jsx(Tt,{className:"cia-wa-numero-nota-icono","aria-hidden":"true"}),t.jsxs("div",{className:"cia-wa-numero-nota-texto",children:[t.jsx("p",{className:"cia-wa-numero-nota-que",children:k.primera}),k.resto?t.jsx("p",{className:"cia-wa-numero-nota-como",children:k.resto}):null,w?t.jsx("p",{className:"cia-wa-numero-nota-cuando",children:w}):null]})]}):null,l?t.jsx("div",{className:"cia-wa-numero-error",children:t.jsx(le,{tone:"bad",actionPlacement:"end",action:l.agentId?{label:d("whatsapp.numero.abrirElAgente"),icon:nn,onClick:()=>void u({to:"/agents/$agentId",params:{agentId:l.agentId}})}:void 0,children:l.texto})}):null]})}const nF={enabled:{tone:"success",icon:dn},enabling:{tone:"warning",pulse:!0},disabling:{tone:"warning",pulse:!0},failed:{tone:"danger"}};function sF({numero:e}){const{t:a}=M("misc"),n=String(e.callingStatus??""),s=nF[n];return s?t.jsx(et,{to:"/whatsapp",search:{tab:"llamadas"},className:"cia-wa-pill-enlace","aria-label":a("whatsapp.numero.llamadasIr",{estado:a(`whatsapp.numero.llamadas.${n}`),phone:e.displayPhoneNumber||e.id}),children:t.jsx(at,{tone:s.tone,pulse:s.pulse,icon:s.icon,label:a(`whatsapp.numero.llamadas.${n}`)})}):null}const iF={active:{tone:"success"},pending:{tone:"warning",pulse:!0},unknown:{tone:"warning",pulse:!0},failed:{tone:"danger"},disconnected:{tone:"neutral",icon:wi}},Ag=6e4;function rF({cuenta:e,llamadasDisponibles:a,puedeAdministrar:n,motivoSinReconexion:s,agentes:i,motivoSinAgentes:r,onReintentarAgentes:o,guardandoAgente:l,errorDeAgente:c,onElegirAgente:d,onReconectar:u,onDesconectar:p,desconectando:f,ahora:x}){const{t:h}=M("misc"),b=xe(),g=m.useId(),v=e.businessName||h("whatsapp.account.unnamed"),y=e.status==="active",[k,w]=m.useState(0);m.useEffect(()=>{if(!k)return;const U=k-Date.now();if(U<=0){w(0);return}const X=window.setTimeout(()=>w(0),U);return()=>window.clearTimeout(X)},[k]);const j=oe({mutationFn:async()=>(await T.post(`/whatsapp/accounts/${e.id}/verificar`)).data,onSuccess:U=>{if(w(Date.now()+Ag),b.invalidateQueries({queryKey:["whatsapp","accounts"]}),!U.ok){J({tone:"warn",title:h("whatsapp.cuenta.sinRespuesta")});return}const X=U.fueraDelPlan??0;J({tone:X>0?"warn":"ok",title:U.numeros>0?h("whatsapp.cuenta.actualizada",{count:U.numeros}):h("whatsapp.cuenta.actualizadaSinNumeros"),desc:X>0?h("whatsapp.cuenta.fueraDelPlan",{count:X}):void 0,duration:X>0?0:void 0})},onError:U=>{const X=U?.response?.status;if(X===429){w(Date.now()+Ag);const de=U?.response?.data?.message;J({tone:"warn",title:typeof de=="string"&&de?de:h("whatsapp.cuenta.actualizadaHaceUnMomento")});return}const ie=U?.response?.data?.message;J({tone:"bad",title:typeof ie=="string"&&ie?ie:h("whatsapp.cuenta.errorAlActualizar"),action:X===409&&n&&!s?{label:h("whatsapp.cuenta.reconectar"),onClick:()=>u(e)}:void 0})}}),C=F6(e.credencial,x),N=C.tipo==="vence"&&C.porVencer&&e.status!=="disconnected",S=e.errorCode&&!y?D6(e.errorCode):null;let _=null;if(S)if(S.code==="cuenta_desconectada"){const U=S.motivo?h(`whatsapp.errors.motivoDesconexion.${S.motivo}`,{defaultValue:""}):"";_=[h("whatsapp.errors.cuenta_desconectada"),U].filter(Boolean).join(" ")}
975else _=h(`whatsapp.errors.${S.code}`,{defaultValue:h("whatsapp.errors.rechazo_desconocido")});const R=k>0,A=[{key:"actualizar",label:h("whatsapp.cuenta.actualizarEstado"),description:h("whatsapp.cuenta.actualizarEstadoDesc"),icon:Di,onSelect:()=>j.mutate(),disabled:!y||R||j.isPending,disabledReason:y?j.isPending?h("whatsapp.cuenta.actualizando"):R?h("whatsapp.cuenta.actualizadaHaceUnMomento"):void 0:h("whatsapp.cuenta.actualizarSoloActiva")}];n&&A.push({key:"reconectar",label:h(N?"whatsapp.cuenta.renovarCredencial":"whatsapp.cuenta.reconectar"),description:h("whatsapp.cuenta.reconectarDesc"),icon:Ka,onSelect:()=>u(e),disabled:!!s,disabledReason:s});const E=[{key:"estado",items:A}];n&&e.status!=="disconnected"&&E.push({key:"peligro",items:[{key:"desconectar",label:h("whatsapp.cuenta.desconectar"),icon:wi,danger:!0,onSelect:()=>p(e),disabled:f,disabledReason:f?h("whatsapp.cuenta.desconectando"):void 0}]});const I=iF[e.status]??{tone:"neutral"},P=[h("whatsapp.account.since",{date:kn(e.createdAt)}),N?null:C.tipo==="vence"?C.vencida?h("whatsapp.cuenta.credencialVencio",{date:kn(C.venceEl)}):h("whatsapp.cuenta.credencialVence",{date:kn(C.venceEl)}):C.tipo==="no_vence"?h("whatsapp.cuenta.credencialNoVence"):null].filter(Boolean).join(" · "),O=W6(e,x),K=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"cia-wa-cuenta-meta-linea",children:P}),O?t.jsxs("span",{className:"cia-wa-cuenta-historial",children:[t.jsx(Mi,{"aria-hidden":"true"}),h("whatsapp.coexistence.sinHistorial")]}):null]}),W=n&&!s,V=[];if(_&&V.push({id:"error",tone:e.status==="unknown"?"warn":"bad",icon:e.status==="unknown"?void 0:wi,text:_,action:W&&(e.status==="disconnected"||e.status==="failed")?{label:h("whatsapp.cuenta.reconectar"),onClick:()=>u(e)}:void 0}),e.elegibilidad?.puedeEnviarPlantillas===!1)for(const U of e.elegibilidad.problemas)V.push({id:`elegibilidad-${U}`,tone:"warn",icon:Sc,text:h(`whatsapp.elegibilidad.${U}`,{defaultValue:U}),detail:e.elegibilidad.consultadoEl?h("whatsapp.cuenta.consultadoEl",{date:Be(e.elegibilidad.consultadoEl)}):void 0});return N&&C.tipo==="vence"&&V.push({id:"credencial",tone:C.vencida?"bad":"warn",icon:Ka,text:C.vencida?h("whatsapp.cuenta.credencialVencidaAviso",{date:kn(C.venceEl)}):h("whatsapp.cuenta.credencialPorVencerAviso",{date:kn(C.venceEl)}),action:W?{label:h("whatsapp.cuenta.renovar"),onClick:()=>u(e)}:void 0}),t.jsxs("article",{className:"cia-card cia-wa-cuenta","aria-labelledby":g,children:[t.jsxs("header",{className:"cia-wa-cuenta-cabecera",children:[t.jsx("div",{className:"cia-wa-cuenta-identidad",children:t.jsx(Ws,{size:"lg",icon:yc,title:t.jsx("h2",{id:g,className:"cia-wa-cuenta-nombre",children:v}),subtitle:t.jsxs("span",{className:"cia-wa-cuenta-id",children:[t.jsx("span",{className:"cia-mono",children:e.wabaId}),t.jsx(kl,{value:e.wabaId,size:"sm",label:h("whatsapp.cuenta.copiarId"),copiedLabel:h("whatsapp.cuenta.idCopiado")})]}),meta:K,tooltip:Be(e.createdAt)})}),t.jsxs("div",{className:"cia-wa-cuenta-estado",children:[j.isPending?t.jsx(at,{tone:"info",spinning:!0,label:h("whatsapp.cuenta.actualizando")}):null,t.jsx(at,{tone:I.tone,pulse:I.pulse,icon:I.icon,label:h(`whatsapp.status.${e.status}`,{defaultValue:e.status})}),e.coexistence?t.jsx(at,{tone:"neutral",icon:ji,label:h("whatsapp.coexistence.label")}):null,N&&C.tipo==="vence"?t.jsx(at,{tone:C.vencida?"danger":"warning",label:C.vencida?h("whatsapp.cuenta.vencida"):h("whatsapp.cuenta.venceEn",{count:Math.max(1,C.dias)})}):null,t.jsx(vn,{iconTrigger:{icon:t.jsx(zi,{}),label:h("whatsapp.cuenta.opciones",{nombre:v})},"aria-label":h("whatsapp.cuenta.opciones",{nombre:v}),groups:E,minWidth:260})]})]}),t.jsx(k_,{title:h("whatsapp.cuenta.queNecesita"),items:V}),t.jsxs("section",{className:"cia-wa-cuenta-numeros","aria-label":h("whatsapp.cuenta.numerosDe",{nombre:v}),children:[t.jsx("h3",{className:"cia-wa-cuenta-subtitulo",children:h("whatsapp.cuenta.numeros")}),e.numbers.length===0?t.jsx("p",{className:"cia-wa-cuenta-vacio",children:h("whatsapp.cuenta.sinNumeros")}):t.jsx("ul",{className:"cia-wa-numeros",children:e.numbers.map(U=>t.jsx(aF,{numero:U,llamadasDisponibles:a,puedeAdministrar:n,agentes:i,motivoSinAgentes:r,onReintentarAgentes:o,guardando:l(U.id),error:c[U.id]??null,onElegirAgente:X=>d(U.id,X,U.agentId)},U.id))})]})]})}function oF({cuentas:e,llamadasDisponibles:a,puedeAdministrar:n,onConectar:s,motivoSinConexion:i,motivoSinReconexion:r,onReconectar:o,onDesconectar:l,desconectando:c,agentes:d,motivoSinAgentes:u,onReintentarAgentes:p,guardandoAgente:f,errorDeAgente:x,onElegirAgente:h,guia:b,onIrAPestana:g}){const{t:v}=M("misc"),[y]=m.useState(()=>Date.now());return e.length===0?t.jsxs("div",{className:"cia-wa-hub-bloques",children:[t.jsxs("div",{className:"cia-card",children:[t.jsx(st,{icon:Ba,title:v("whatsapp.empty.title"),desc:v("whatsapp.empty.description"),action:s?{label:v("whatsapp.modulo.conectar"),icon:Fe,onClick:s,variant:"cta"}:void 0,secondaryAction:{label:v("whatsapp.modulo.verGuia"),icon:ua,onClick:()=>window.open(b,"_blank","noopener,noreferrer")}}),n&&!s&&i?t.jsx("p",{className:"cia-wa-hub-motivo",role:"status",children:i}):null]}),t.jsxs(Rs,{title:v("whatsapp.vacio.queNecesitas"),className:"cia-card cia-wa-hub-lectura",children:[t.jsx(Zt,{label:v("whatsapp.vacio.numero"),children:v("whatsapp.vacio.numeroDesc")}),t.jsx(Zt,{label:v("whatsapp.vacio.meta"),children:v("whatsapp.vacio.metaDesc")}),t.jsx(Zt,{label:v("whatsapp.vacio.negocio"),children:v("whatsapp.vacio.negocioDesc")})]})]}):t.jsxs("div",{className:"cia-wa-hub-bloques",children:[t.jsx(U6,{cuentas:e,llamadasDisponibles:a,puedeAdministrar:n,onConectar:s,guia:b,onIrAPestana:g}),e.map(k=>t.jsx(rF,{cuenta:k,llamadasDisponibles:a,puedeAdministrar:n,motivoSinReconexion:r(k),agentes:d,motivoSinAgentes:u,onReintentarAgentes:p,guardandoAgente:f,errorDeAgente:x,onElegirAgente:h,onReconectar:o,onDesconectar:l,desconectando:c,ahora:y},k.id))]})}function lF({abierto:e,onCerrar:a,cfg:n,onConectar:s,modoInicial:i=null,conectando:r=!1}){const{t:o}=M("misc"),l=m.useId(),c=m.useId(),[d,u]=m.useState(i),[p,f]=m.useState(!1);m.useEffect(()=>{e&&(u(i),f(!1))},[e,i]);const x=!!n?.coexistencia,h=d==="coexistencia",b={cloud_api:{titulo:o("whatsapp.conexion.nube.titulo"),desc:o("whatsapp.conexion.nube.desc"),icon:t.jsx(ji,{})},coexistencia:{titulo:o("whatsapp.conexion.celular.titulo"),desc:o("whatsapp.conexion.celular.desc"),icon:t.jsx(o2,{})}},g=q6(x,i).map(w=>({value:w.modo,title:b[w.modo].titulo,description:b[w.modo].desc,icon:b[w.modo].icon,disabled:w.deshabilitada,disabledReason:w.motivo?o(`whatsapp.conexion.motivo.${w.motivo}`):void 0})),v=()=>{f(!1),a()},y=()=>
975{if(!d||d==="coexistencia"&&!p)return;const w=d;f(!1),a(),s(w)},k=d?h&&!p?o("whatsapp.conexion.marcaElAcuse"):r?o("whatsapp.conexion.enCurso"):void 0:o("whatsapp.conexion.elegiPrimero");return t.jsx(ot,{open:e,onClose:v,title:o("whatsapp.conexion.titulo"),maxWidth:560,footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{variant:"ghost",onClick:v,children:o("whatsapp.modulo.cancelar")}),t.jsx(Ie,{variant:"cta",disabled:!!k,disabledReason:k,onClick:y,children:o(h?"whatsapp.coexistence.modalCta":"whatsapp.conexion.continuar")})]}),children:t.jsxs("div",{className:"cia-wa-conexion",children:[t.jsx("p",{id:l,className:"cia-wa-conexion-intro",children:o("whatsapp.conexion.intro")}),t.jsx(uv,{className:"cia-wa-conexion-opciones",ariaLabelledBy:l,value:d,options:g,onChange:w=>{u(w),w!=="coexistencia"&&f(!1)}}),h?t.jsxs("section",{className:"cia-wa-conexion-acuse","aria-labelledby":c,children:[t.jsx("h3",{id:c,className:"cia-wa-conexion-acuse-titulo",children:o("whatsapp.coexistence.modalTitle")}),t.jsx(le,{tone:"info",title:o("whatsapp.coexistence.requisitoTitle"),children:o("whatsapp.coexistence.requisito")}),t.jsx(le,{tone:"warn",title:o("whatsapp.coexistence.avisoTitle"),children:o("whatsapp.coexistence.aviso")}),t.jsx("p",{className:"cia-wa-conexion-parrafo",children:o("whatsapp.coexistence.detalle")}),t.jsx("p",{className:"cia-wa-conexion-parrafo",children:o("whatsapp.coexistence.historial")}),t.jsx(mn,{checked:p,onChange:f,label:o("whatsapp.coexistence.acuse")})]}):null]})})}async function Kh({queryKey:e}){const a=String(e[2]??"");try{return(await T.get(`/whatsapp/numbers/${a}/calling`)).data}catch(n){const s=n?.response?.status;if(s===501||s===404)return null;throw n}}const cF={enabling:{tone:"warning",pulse:!0},disabling:{tone:"warning",pulse:!0},enabled:{tone:"success",icon:dn},failed:{tone:"danger"}},dF={sin_agente:{tone:"warning",icon:mo},agente_con_transferencia:{tone:"warning",icon:uo},estado_desconocido:{tone:"warning",icon:vc},plataforma_sin_sip:{tone:"neutral",icon:Au},plataforma_sin_cidrs:{tone:"neutral",icon:Au}},uF=/^[A-Za-z0-9_]{1,64}$/;function pF({numero:e,puedeAdministrar:a,onAviso:n}){const{t:s}=M("misc"),{t:i}=M("common"),r=xe(),o=e.displayPhoneNumber??e.id,l=m.useId(),[c,d]=m.useState(!1),{data:u,isLoading:p,isError:f,isFetching:x,refetch:h}=se({queryKey:["whatsapp","calling",e.id],queryFn:Kh,refetchInterval:E=>BD(E.state.data?.callingStatus)}),b=()=>{r.invalidateQueries({queryKey:["whatsapp","calling",e.id]}),r.invalidateQueries({queryKey:["whatsapp","accounts"]})},g=E=>{const I=E?.response?.data,P=Array.isArray(I?.message)?I.message.join(" · "):typeof I?.message=="string"&&I.message?I.message:s("whatsapp.calling.falloGenerico"),O=typeof I?.code=="string"&&I.code?I.code:null;n({tono:"bad",texto:O?s(`whatsapp.errors.${O}`,{defaultValue:P}):P}),b()},v=(E,I)=>{if(b(),E.ok){n({tono:"ok",texto:I});return}const P=E.callingErrorCode?s(`whatsapp.errors.${E.callingErrorCode}`,{defaultValue:s("whatsapp.calling.falloDesconocido")}):s("whatsapp.calling.falloDesconocido");n({tono:E.callingStatus==="failed"?"bad":"warn",texto:P})},y=oe({mutationFn:async()=>(await T.post(`/whatsapp/numbers/${e.id}/calling`)).data,onSuccess:E=>v(E,s("whatsapp.calling.pedidoDeActivacion",{phone:o})),onError:g}),k=oe({mutationFn:async()=>(await T.delete(`/whatsapp/numbers/${e.id}/calling`)).data,onSuccess:E=>v(E,s("whatsapp.calling.apagadas",{phone:o})),onError:g}),w=E=>t.jsx(Nl,{className:"cia-wa-llamada-fila",icon:e.isOnBizApp?ji:dn,title:t.jsx("span",{className:"cia-mono",children:o}),description:e.verifiedName||void 0,...E});if(p)return t.jsx("div",{className:"cia-wa-llamada",children:w({control:t.jsx(ge,{w:40,h:22,r:11})})});if(u===null)return t.jsx("div",{className:"cia-wa-llamada",children:w({control:t.jsx("span",{className:"cia-wa-llamada-sin-dato","aria-hidden":"true",children:"—"}),foot:s("whatsapp.pestanaLlamadas.noDisponible")})});if(f||u===void 0)return t.jsx("div",{className:"cia-wa-llamada",children:w({control:E=>t.jsx(Ie,{id:E.controlId,"aria-describedby":E.descId,size:"sm",variant:"outline",icon:t.jsx(Na,{}),loading:x,onClick:()=>void h(),children:s("whatsapp.calling.reintentar")}
975),foot:s("whatsapp.calling.noSePudoLeer")})});const j=$D(u,a),C=j.bloqueo==="sin_agente"||j.bloqueo==="agente_con_transferencia"||j.bloqueo==="estado_desconocido"?s(`whatsapp.calling.bloqueo.${j.bloqueo}`):cg(j.bloqueo)?s("whatsapp.calling.bloqueo.plataforma"):null,N=j.bloqueo==="sin_permiso"?i("noPermission"):j.bloqueo==="coexistencia"?s("whatsapp.calling.noDisponibleCoexistenciaHint"):j.bloqueo==="transicion"?s("whatsapp.pestanaLlamadas.motivo.transicion"):C??void 0,S=j.chip?cF[j.chip]:null,_=!j.chip&&j.bloqueo?dF[j.bloqueo]:void 0,R=j.bloqueo==="coexistencia"?t.jsx(at,{tone:"neutral",icon:ji,label:s("whatsapp.calling.noDisponibleCoexistencia")}):S?t.jsx(at,{tone:S.tone,pulse:S.pulse,icon:S.icon,label:s(`whatsapp.calling.status.${j.chip}`)}):_&&j.bloqueo==="sin_agente"?t.jsx(et,{to:"/whatsapp",search:{tab:"numeros"},className:"cia-wa-pill-enlace","aria-label":s("whatsapp.pestanaLlamadas.irAsignarAgente",{phone:o}),children:t.jsx(at,{tone:_.tone,icon:_.icon,label:s("whatsapp.pestanaLlamadas.bloqueoCorto.sin_agente")})}):_&&j.bloqueo?t.jsx(at,{tone:_.tone,icon:_.icon,label:s(`whatsapp.pestanaLlamadas.bloqueoCorto.${cg(j.bloqueo)?"plataforma":j.bloqueo}`)}):null,A=j.chip==="failed"&&u.callingErrorCode?s(`whatsapp.errors.${u.callingErrorCode}`,{defaultValue:s("whatsapp.calling.falloDesconocido")}):void 0;return t.jsxs("div",{className:"cia-wa-llamada",children:[w({status:R,foot:A,disabled:j.deshabilitado,disabledReason:j.deshabilitado?N:void 0,control:t.jsx(vt,{checked:j.encendido,label:s("whatsapp.calling.switchLabel",{phone:o}),onChange:E=>(E?y:k).mutateAsync().then(()=>{},()=>{})})}),t.jsx(hF,{estado:u,id:l,abierto:c,onAlternar:()=>d(E=>!E)})]})}function hF({estado:e,id:a,abierto:n,onAlternar:s}){const{t:i}=M("misc"),r=e.ajustes??null;if(!(!!e.callingSyncedAt||!!(r&&(r.iconoVisible||r.permisoDeDevolucion||r.restricciones.length>0))))return null;const l=r?.iconoVisible==="DEFAULT"?i("whatsapp.pestanaLlamadas.proveedor.icono.visible"):r?.iconoVisible==="DISABLE_ALL"?i("whatsapp.pestanaLlamadas.proveedor.icono.oculto"):r?.iconoVisible?i("whatsapp.pestanaLlamadas.proveedor.otroValor",{valor:r.iconoVisible}):null,c=r?.permisoDeDevolucion==="ENABLED"?i("whatsapp.pestanaLlamadas.proveedor.devolucion.permitida"):r?.permisoDeDevolucion==="DISABLED"?i("whatsapp.pestanaLlamadas.proveedor.devolucion.noPermitida"):r?.permisoDeDevolucion?i("whatsapp.pestanaLlamadas.proveedor.otroValor",{valor:r.permisoDeDevolucion}):null,d=(r?.restricciones??[]).map(u=>uF.test(u)?i(`whatsapp.pestanaLlamadas.proveedor.restriccion.${u}`,{defaultValue:i("whatsapp.pestanaLlamadas.proveedor.restriccionDesconocida",{code:u})}):i("whatsapp.pestanaLlamadas.proveedor.restriccionDesconocida",{code:u}));return t.jsxs("div",{className:"cia-wa-llamada-detalle",children:[t.jsx(Ie,{size:"sm",variant:"ghost",icon:t.jsx(Ut,{className:"cia-wa-llamada-chevron","data-abierto":n?"":void 0}),"aria-expanded":n,"aria-controls":a,onClick:s,children:i("whatsapp.pestanaLlamadas.proveedor.titulo")}),t.jsx(pv,{open:n,id:a,children:t.jsxs("div",{className:"cia-wa-llamada-datos",children:[l?t.jsx(Zt,{label:i("whatsapp.pestanaLlamadas.proveedor.icono.rotulo"),children:l}):null,c?t.jsx(Zt,{label:i("whatsapp.pestanaLlamadas.proveedor.devolucion.rotulo"),children:c}):null,r?t.jsx(Zt,{label:i("whatsapp.pestanaLlamadas.proveedor.restricciones"),children:d.length?d.join(" · "):i("whatsapp.pestanaLlamadas.proveedor.sinRestricciones")}):null,t.jsx(Zt,{label:i("whatsapp.pestanaLlamadas.proveedor.leido"),children:e.callingSyncedAt?Be(e.callingSyncedAt):i("whatsapp.pestanaLlamadas.proveedor.nuncaLeido")})]})})]})}function mF({cuentas:e,puedeAdministrar:a,onAviso:n}){const{t:s}=M("misc"),i=Kc(Vc.whatsappLlamadas),r=e.flatMap(u=>u.numbers.filter(p=>p.status==="active")),o=E1(e),{data:l,isLoading:c}=se({queryKey:["whatsapp","calling",o??""],enabled:o!==null,queryFn:Kh}),d=l?.ajustes?.horario??null;return t.jsxs("div",{className:"cia-wa-pestana",children:[t.jsxs(le,{tone:"info",title:s("whatsapp.calling.avisoTitulo"),children:[t.jsx("span",{className:"cia-wa-aviso-linea",children:s("whatsapp.calling.avisoPropagacion")}),t.jsx("span",{className:"cia-wa-aviso-linea",children:s("whatsapp.calling.avisoSinTransferencia")}),t.jsxs("a",{className:"cia-wa-enlace",href:i,target:"_blank",rel:"noopener noreferrer",children:[s("whatsapp.pestanaLlamadas.leerLaGuia"),t.jsx("span",{className:"cia-sr-only",children:s("whatsapp.modulo.abreEnOtraPestana")})]})]}),t.jsx(as,{title:s("whatsapp.pestanaLlamadas.porNumero.titulo"),description:s("whatsapp.pestanaLlamadas.porNumero.desc"),icon:dn,children:r.length===0?t.jsx(st,{mini:!0,icon:Ts,title:s("whatsapp.pestanaLlamadas.porNumero.vacioTitulo"),desc:s("whatsapp.pestanaLlamadas.porNumero.vacioDesc")}):r.map(u=>t.jsx(pF,{numero:u,puedeAdministrar:a,onAviso:n},u.id))}),t.jsxs(as,{title:s("whatsapp.pestanaLlamadas.horario.titulo"),icon:Qa,children:[t.jsx("p",{className:"cia-wa-lectura",children:s("whatsapp.pestanaLlamadas.horario.mismoQueLaVoz")}),d?t.jsx(gF,{horario:d}):c?t.jsxs("div",{className:"cia-wa-horario","aria-hidden":"true",children:[t.jsx(ge,{w:"min(280px, 100%)",h:14}),t.jsx(ge,{w:180,h:14})]}):null]})]})}const wp=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"];function Rg(e){const a=/^\d{4}$/.test(e)?e:"";return a?a==="2359"?"24:00":`${a.slice(0,2)}:${a.slice(2)}`:e}function nu(e,a){return new Intl.DateTimeFormat(a,{weekday:"long",timeZone:"UTC"}).format(new Date(Date.UTC(2024,0,1+e)))}function fF(e){const a=new Map(e.map(s=>[s.dia,s])),n=[];
975return wp.forEach((s,i)=>{const r=a.get(s);if(!r)return;const o=n[n.length-1];o&&o.hasta===i-1&&o.abre===r.abre&&o.cierra===r.cierra?o.hasta=i:n.push({desde:i,hasta:i,abre:r.abre,cierra:r.cierra})}),n}function xF(e,a){try{const s=new Intl.DateTimeFormat(a,{timeZone:e,timeZoneName:"longGeneric"}).formatToParts(new Date).find(i=>i.type==="timeZoneName")?.value;if(s)return s}catch{}return e}function gF({horario:e}){const{t:a}=M("misc"),n=Te(),s=fF(e.semanal),i=new Set(e.semanal.map(c=>c.dia)),r=wp.filter(c=>!i.has(c)).length,o=(c,d)=>c==="0000"&&d==="2359"?a("whatsapp.pestanaLlamadas.horario.todoElDia"):a("whatsapp.pestanaLlamadas.horario.franja",{abre:Rg(c),cierra:Rg(d)}),l=c=>c.desde===0&&c.hasta===wp.length-1?a("whatsapp.pestanaLlamadas.horario.todosLosDias"):c.desde===c.hasta?nu(c.desde,n):a("whatsapp.pestanaLlamadas.horario.rango",{desde:nu(c.desde,n),hasta:nu(c.hasta,n)});return t.jsxs("div",{className:"cia-wa-horario",children:[s.map(c=>t.jsx(Zt,{inline:!0,label:t.jsx("span",{className:"cia-wa-horario-dias",children:l(c)}),children:t.jsx("span",{className:"cia-wa-horario-franja",children:o(c.abre,c.cierra)})},`${c.desde}-${c.hasta}`)),r>0?t.jsx(Zt,{inline:!0,label:a("whatsapp.pestanaLlamadas.horario.restoDeLosDias"),children:a("whatsapp.pestanaLlamadas.horario.noSeAtiende")}):null,e.feriados.length>0?t.jsx(Zt,{inline:!0,label:a("whatsapp.pestanaLlamadas.horario.diasEspeciales"),children:e.feriados.map(c=>kn(`${c.fecha}T12:00:00Z`)).join(" · ")}):null,t.jsx(Zt,{inline:!0,label:a("whatsapp.pestanaLlamadas.horario.zona"),children:t.jsx(Ra,{label:e.timezone,children:t.jsx("span",{className:"cia-wa-horario-zona",children:xF(e.timezone,n)})})})]})}const bF=40,yF=["azul","naranja","verde","ambar","rojo","gris"];function vF(e){return!e||e.hilos<=0?null:Math.round(e.sinEtiqueta/e.hilos*100)}function jF(e,a){const n=new Set(a.map(s=>s.id));return e.filter(s=>!n.has(s.id))}function wF({puedeGestionarTipificaciones:e,puedeEditarRespuestas:a}){return t.jsxs("div",{className:"cia-wa-pestana",children:[t.jsx(kF,{puede:e}),t.jsx(_F,{puede:a})]})}function Ir(e,a){const n=e?.response?.data?.message;return Array.isArray(n)?n.join(" · "):typeof n=="string"&&n?n:a}function T1(){return t.jsx("ul",{className:"cia-wa-atencion-lista","aria-hidden":"true",children:[0,1,2].map(e=>t.jsxs("li",{className:"cia-wa-atencion-item",children:[t.jsx(ge,{w:`${48-e*8}%`,h:14}),t.jsx(ge,{w:96,h:12})]},e))})}function kF({puede:e}){const{t:a}=M("misc"),n=xe(),[s,i]=m.useState(null),[r,o]=m.useState(null),[l,c]=m.useState(null),d=se({queryKey:["wa-etiquetas-catalogo"],queryFn:async()=>(await T.get("/whatsapp/etiquetas")).data.items,staleTime:5*6e4}),u=()=>{n.invalidateQueries({queryKey:["wa-etiquetas-catalogo"]}),n.invalidateQueries({queryKey:["wa-etiquetas-resumen"]}),n.invalidateQueries({queryKey:["wa-conversations"]})},p=oe({mutationFn:async v=>(await T.post("/whatsapp/etiquetas",{nombre:v.nombre,color:v.color})).data,onSuccess:(v,y)=>{i(null),u(),J({tone:"ok",title:a("whatsapp.pestanaAtencion.tipificaciones.creada",{nombre:y.nombre})})},onError:v=>o(Ir(v,a("whatsapp.etiquetas.falloGenerico")))}),f=oe({mutationFn:async v=>(await T.patch(`/whatsapp/etiquetas/${v.id}`,{nombre:v.nombre,color:v.color})).data,onSuccess:()=>{i(null),u(),J({tone:"ok",title:a("whatsapp.pestanaAtencion.tipificaciones.guardada")})},onError:v=>o(Ir(v,a("whatsapp.etiquetas.falloGenerico")))}),x=oe({mutationFn:async v=>(await T.delete(`/whatsapp/etiquetas/${v}`)).data,onSuccess:()=>{c(null),u(),J({tone:"ok",title:a("whatsapp.pestanaAtencion.tipificaciones.borrada")})},onError:v=>c(Ir(v,a("whatsapp.etiquetas.falloGenerico")))});async function h(v){v.usos>0&&!await pa({title:a("whatsapp.pestanaAtencion.tipificaciones.borrarTitulo",{nombre:v.nombre}),message:a("whatsapp.etiquetas.confirmarBorrado",{nombre:v.nombre,n:v.usos}),confirmLabel:a("whatsapp.pestanaAtencion.borrar"),cancelLabel:a("whatsapp.pestanaAtencion.cancelar"),danger:!0})||x.mutate(v.id)}const b=v=>{o(null),i(v)},g=d.data??[];return t.jsxs(as,{title:a("whatsapp.pestanaAtencion.tipificaciones.titulo"),description:a("whatsapp.pestanaAtencion.tipificaciones.desc"),icon:Pu,aside:e&&g.length>0?t.jsx(Ie,{size:"sm",variant:"outline",icon:t.jsx(Fe,{}),onClick:()=>b({modo:"nueva"}),children:a("whatsapp.pestanaAtencion.tipificaciones.nueva")}):void 0,footer:e?void 0:a("whatsapp.pestanaAtencion.tipificaciones.soloLectura"),children:[d.isLoading?t.jsx(T1,{}):d.isError?t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:a("whatsapp.pestanaAtencion.reintentar"),icon:Na,loading:d.isFetching,onClick:()=>void d.refetch()},children:a("whatsapp.pestanaAtencion.tipificaciones.errorAlLeer")}):g.length===0?t.jsx(st,{mini:!0,icon:Pu,title:a("whatsapp.pestanaAtencion.tipificaciones.vacioTitulo"),desc:a(e?"whatsapp.pestanaAtencion.tipificaciones.vacioPuede":"whatsapp.etiquetas.vacioSoloMira"),action:e?{label:a("whatsapp.pestanaAtencion.tipificaciones.crearLaPrimera"),icon:Fe,onClick:()=>b({modo:"nueva"})}:void 0}):t.jsxs("div",{className:"cia-wa-pila",children:[l?t.jsx(le,{tone:"bad",children:l}):null,t.jsx("ul",{className:"cia-wa-atencion-lista",children:g.map(v=>{const y=[{key:"editar",items:[{key:"editar",label:a("whatsapp.pestanaAtencion.tipificaciones.editar"),icon:qt,onSelect:()=>b({modo:"editar",etiqueta:v})}]},{key:"peligro",items:[{key:"borrar",label:a("whatsapp.pestanaAtencion.borrar"),icon:mt,danger:!0,disabled:x.isPending,disabledReason:x.isPending?a("whatsapp.pestanaAtencion.borrando"):void 0,onSelect:()=>void h(v)}]}];return t.jsxs("li",{className:"cia-wa-atencion-item",children:[t.jsx("span",{className:"cia-wa-atencion-principal",children:t.jsx(ps,{label:v.nombre,tone:v.color})}),t.jsx("span",{className:"cia-wa-atencion-uso",children:a("whatsapp.pestanaAtencion.tipificaciones.usadaEn",{count:v.usos})}),e?t.jsx("span",{className:"cia-wa-atencion-menu",children:t.jsx(vn,{iconTrigger:{icon:t.jsx(zi,{}),label:a("whatsapp.pestanaAtencion.tipificaciones.opciones",{nombre:v.nombre})},groups:y,minWidth:220})}):null]},v.id)})})]}),s?t.jsx(NF,{editor:s,guardando:p.isPending||f.isPending,error:r,onCerrar:()=>i(null),onGuardar:v=>{if(o(null),s.modo==="nueva"){p.mutate(v);return}const y=s.etiqueta;f.mutate({id:y.id,nombre:v.nombre!==y.nombre?v.nombre:void 0,color:v.color!==(y.color??"gris")?v.color:void 0})}}):null]})}function NF({editor:e,guardando:a,error:n,onCerrar:s,onGuardar:i}){const{t:r}=M("misc"),o=e.modo==="editar"?e.etiqueta:null,[l,c]=m.useState(o?.nombre??""),[d,u]=m.useState(o?.color??"gris"),p=l.trim(),f=o===null||p!==o.nombre||d!==(o.color??"gris"),x=p?f?void 0:r("whatsapp.pestanaAtencion.sinCambios"):r("whatsapp.pestanaAtencion.tipificaciones.faltaNombre"),h=yF.map(b=>({value:b,label:r(`whatsapp.etiquetas.color.${b}`)}));return t.jsx(ot,{open:!0,onClose:s,title:r(o?"whatsapp.pestanaAtencion.tipificaciones.editarTitulo":"whatsapp.pestanaAtencion.tipificaciones.nuevaTitulo"),maxWidth:460,footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{variant:"ghost",onClick:s,children:r("whatsapp.pestanaAtencion.cancelar")}
975),t.jsx(Ie,{variant:"primary",loading:a,disabled:!f||!p,disabledReason:a?void 0:x,onClick:()=>i({nombre:p,color:d}),children:r(o?"whatsapp.etiquetas.guardar":"whatsapp.etiquetas.crear")})]}),children:t.jsxs("form",{className:"cia-wa-atencion-form",onSubmit:b=>{b.preventDefault(),f&&p&&!a&&i({nombre:p,color:d})},children:[t.jsx(Lc,{label:r("whatsapp.etiquetas.nombre"),value:l,onChange:c,placeholder:r("whatsapp.etiquetas.placeholder"),maxLength:bF,counter:!0,required:!0,autoFocus:!0,description:o?r("whatsapp.pestanaAtencion.tipificaciones.renombrarConserva",{count:o.usos}):void 0}),t.jsx(hn,{label:r("whatsapp.etiquetas.nombreDelColor"),value:d,onChange:b=>u(b),options:h}),t.jsxs("div",{className:"cia-wa-atencion-vista",children:[t.jsx("span",{className:"cia-wa-atencion-vista-rotulo",children:r("whatsapp.pestanaAtencion.tipificaciones.asiSeVe")}),t.jsx(ps,{label:p||r("whatsapp.etiquetas.placeholder"),tone:d})]}),n?t.jsx(le,{tone:"bad",children:n}):null]})})}const SF=40,CF=4096;function _F({puede:e}){const{t:a}=M("misc"),n=xe(),[s,i]=m.useState(null),[r,o]=m.useState(null),[l,c]=m.useState(null),d=se({queryKey:["wa-snippets"],queryFn:async()=>(await T.get("/whatsapp/snippets")).data.items,staleTime:5*6e4}),u=()=>void n.invalidateQueries({queryKey:["wa-snippets"]}),p=y=>o({campo:y?.response?.status===409?"atajo":null,texto:Ir(y,a("whatsapp.pestanaAtencion.respuestas.falloGenerico"))}),f=oe({mutationFn:async y=>(await T.post("/whatsapp/snippets",y)).data,onSuccess:()=>{i(null),u(),J({tone:"ok",title:a("whatsapp.pestanaAtencion.respuestas.creada")})},onError:p}),x=oe({mutationFn:async y=>(await T.patch(`/whatsapp/snippets/${y.id}`,{atajo:y.atajo,texto:y.texto})).data,onSuccess:()=>{i(null),u(),J({tone:"ok",title:a("whatsapp.pestanaAtencion.respuestas.guardada")})},onError:p}),h=oe({mutationFn:async y=>(await T.delete(`/whatsapp/snippets/${y}`)).data,onSuccess:()=>{c(null),u(),J({tone:"ok",title:a("whatsapp.pestanaAtencion.respuestas.borrada")})},onError:y=>c(Ir(y,a("whatsapp.pestanaAtencion.respuestas.falloGenerico")))});async function b(y){await pa({title:a("whatsapp.pestanaAtencion.respuestas.borrarTitulo",{atajo:y.atajo}),message:a("whatsapp.pestanaAtencion.respuestas.borrarCuerpo"),confirmLabel:a("whatsapp.pestanaAtencion.borrar"),cancelLabel:a("whatsapp.pestanaAtencion.cancelar"),danger:!0})&&h.mutate(y.id)}const g=y=>{o(null),i(y)},v=d.data??[];return t.jsxs(as,{title:a("whatsapp.pestanaAtencion.respuestas.titulo"),description:a("whatsapp.pestanaAtencion.respuestas.desc"),icon:ef,aside:e&&v.length>0?t.jsx(Ie,{size:"sm",variant:"outline",icon:t.jsx(Fe,{}),onClick:()=>g({modo:"nueva"}),children:a("whatsapp.pestanaAtencion.respuestas.nueva")}):void 0,footer:e?void 0:a("whatsapp.pestanaAtencion.respuestas.soloLectura"),children:[d.isLoading?t.jsx(T1,{}):d.isError?t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:a("whatsapp.pestanaAtencion.reintentar"),icon:Na,loading:d.isFetching,onClick:()=>void d.refetch()},children:a("whatsapp.pestanaAtencion.respuestas.errorAlLeer")}):v.length===0?t.jsx(st,{mini:!0,icon:ef,title:a("whatsapp.pestanaAtencion.respuestas.vacioTitulo"),desc:a("whatsapp.pestanaAtencion.respuestas.vacioDesc"),action:e?{label:a("whatsapp.pestanaAtencion.respuestas.crearLaPrimera"),icon:Fe,onClick:()=>g({modo:"nueva"})}:void 0}):t.jsxs("div",{className:"cia-wa-pila",children:[l?t.jsx(le,{tone:"bad",children:l}):null,t.jsx("ul",{className:"cia-wa-atencion-lista",children:v.map(y=>{const k=[{key:"editar",items:[{key:"editar",label:a("whatsapp.pestanaAtencion.respuestas.editar"),icon:qt,onSelect:()=>g({modo:"editar",respuesta:y})}]},{key:"peligro",items:[{key:"borrar",label:a("whatsapp.pestanaAtencion.borrar"),icon:mt,danger:!0,disabled:h.isPending,disabledReason:h.isPending?a("whatsapp.pestanaAtencion.borrando"):void 0,onSelect:()=>void b(y)}]}];return t.jsxs("li",{className:"cia-wa-atencion-item",children:[t.jsxs("span",{className:"cia-wa-atencion-principal cia-wa-respuesta",children:[t.jsxs("span",{className:"cia-mono cia-wa-respuesta-atajo",children:["/",y.atajo]}),t.jsx("span",{className:"cia-wa-respuesta-texto",title:y.texto,children:y.texto})]}),t.jsx("span",{className:"cia-wa-atencion-uso",children:a("whatsapp.pestanaAtencion.respuestas.usos",{count:y.usos})}),e?t.jsx("span",{className:"cia-wa-atencion-menu",children:t.jsx(vn,{iconTrigger:{icon:t.jsx(zi,{}),label:a("whatsapp.pestanaAtencion.respuestas.opciones",{atajo:y.atajo})},groups:k,minWidth:220})}):null]},y.id)})})]}),s?t.jsx(EF,{editor:s,guardando:f.isPending||x.isPending,error:r,onCerrar:()=>i(null),onGuardar:y=>{if(o(null),s.modo==="nueva"){f.mutate(y);return}const k=s.respuesta;x.mutate({id:k.id,atajo:y.atajo!==k.atajo?y.atajo:void 0,texto:y.texto!==k.texto?y.texto:void 0})}}):null]})}function EF({editor:e,guardando:a,error:n,onCerrar:s,onGuardar:i}){const{t:r}=M("misc"),o=e.modo==="editar"?e.respuesta:null,[l,c]=m.useState(o?.atajo??""),[d,u]=m.useState(o?.texto??""),p=l.trim(),f=d.trim(),x=o===null||p!==o.atajo||f!==o.texto,h=p?f?x?void 0:r("whatsapp.pestanaAtencion.sinCambios"):r("whatsapp.pestanaAtencion.respuestas.faltaTexto"):r("whatsapp.pestanaAtencion.respuestas.faltaAtajo"),b=!!(p&&f&&x);return t.jsx(ot,{open:!0,onClose:s,title:r(o?"whatsapp.pestanaAtencion.respuestas.editarTitulo":"whatsapp.pestanaAtencion.respuestas.nuevaTitulo"),maxWidth:560,footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{variant:"ghost",onClick:s,children:r("whatsapp.pestanaAtencion.cancelar")}
975),t.jsx(Ie,{variant:"primary",loading:a,disabled:!b,disabledReason:a?void 0:h,onClick:()=>i({atajo:p,texto:f}),children:r(o?"whatsapp.pestanaAtencion.guardar":"whatsapp.pestanaAtencion.respuestas.crear")})]}),children:t.jsxs("div",{className:"cia-wa-atencion-form",children:[t.jsx(Lc,{label:r("whatsapp.pestanaAtencion.respuestas.atajo"),description:r("whatsapp.pestanaAtencion.respuestas.atajoAyuda"),value:l,onChange:c,placeholder:r("whatsapp.pestanaAtencion.respuestas.atajoEjemplo"),maxLength:SF,counter:!0,mono:!0,required:!0,autoFocus:!0,error:n?.campo==="atajo"?n.texto:void 0}),t.jsx(yv,{label:r("whatsapp.pestanaAtencion.respuestas.texto"),value:d,onChange:u,placeholder:r("whatsapp.pestanaAtencion.respuestas.textoEjemplo"),maxLength:CF,counter:!0,required:!0,rows:4,autoGrow:!0}),n&&n.campo===null?t.jsx(le,{tone:"bad",children:n.texto}):null]})})}const Tg=[15,30,60],Hh=["cuentaDesconectada","credencialPorVencer","plantilla","calidad"];function AF(e,a){const n={};for(const i of Hh)e[i]!==a[i]&&(n[i]=a[i]);const s={};return e.traspasoSinAtender.activo!==a.traspasoSinAtender.activo&&(s.activo=a.traspasoSinAtender.activo),e.traspasoSinAtender.minutos!==a.traspasoSinAtender.minutos&&(s.minutos=a.traspasoSinAtender.minutos),Object.keys(s).length&&(n.traspasoSinAtender=s),Object.keys(n).length?n:null}function RF(e){return e?Hh.filter(a=>a in e).length+Object.keys(e.traspasoSinAtender??{}).length:0}function TF(e,a){return{...e,...Object.fromEntries(Hh.filter(n=>n in a).map(n=>[n,a[n]])),traspasoSinAtender:{...e.traspasoSinAtender,...a.traspasoSinAtender??{}}}}const Mg=["whatsapp","ajustes","avisos"];function MF({puedeAdministrar:e}){const{t:a}=M("misc"),{t:n}=M("common"),{can:s}=tt(),i=xe(),[r,o]=m.useState({}),[l,c]=m.useState("dirty"),[d,u]=m.useState(null),{data:p,isLoading:f,isError:x,isFetching:h,refetch:b}=se({queryKey:Mg,queryFn:async()=>{try{return(await T.get("/whatsapp/ajustes/avisos")).data}catch(O){const K=O?.response?.status;if(K===501||K===404)return null;throw O}}}),g=p?.avisos??null,v=g?TF(g,r):null,y=g&&v?AF(g,v):null,k=y!==null;m.useEffect(()=>{if(l!=="saved")return;const O=window.setTimeout(()=>c("dirty"),1400);return()=>window.clearTimeout(O)},[l]);const w=oe({mutationFn:async O=>(await T.patch("/whatsapp/ajustes/avisos",O)).data,onMutate:()=>{u(null),c("saving")},onSuccess:O=>{i.setQueryData(Mg,O),o({}),c("saved")},onError:O=>{const K=O?.response?.data?.message;u(Array.isArray(K)?K.join(" · "):typeof K=="string"&&K?K:a("whatsapp.pestanaAvisos.errorAlGuardar")),c("error")}}),j=Ik({shouldBlockFn:()=>k,enableBeforeUnload:()=>k,withResolver:!0}),C=(O,K)=>{l!=="saving"&&c("dirty"),o(W=>({...W,[O]:K}))},N=O=>{l!=="saving"&&c("dirty"),o(K=>({...K,traspasoSinAtender:{...K.traspasoSinAtender??{},...O}}))};if(f)return t.jsxs("div",{className:"cia-wa-pestana","aria-busy":"true",children:[t.jsx(ge,{w:220,h:18}),t.jsx(ge,{h:340,r:14}),t.jsx(ge,{w:160,h:18}),t.jsx(ge,{h:96,r:14})]});if(p===null)return t.jsx("div",{className:"cia-wa-pestana",children:t.jsx(le,{tone:"info",children:a("whatsapp.pestanaAvisos.noDisponible")})});if(x||!p||!v)return t.jsx("div",{className:"cia-wa-pestana",children:t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:a("whatsapp.pestanaAvisos.reintentar"),icon:Na,loading:h,onClick:()=>void b()},children:a("whatsapp.pestanaAvisos.errorAlLeer")})});const S=!e,_=S?n("noPermission"):void 0,R=v.traspasoSinAtender,A=Tg.map(O=>({value:String(O),label:a("whatsapp.pestanaAvisos.minutos",{count:O})})),E=p.destinatarios.some(O=>O.email===null),I=(O,K)=>t.jsx(Nl,{icon:K,title:a(`whatsapp.pestanaAvisos.eventos.${O}.titulo`),description:a(`whatsapp.pestanaAvisos.eventos.${O}.desc`),disabled:S,disabledReason:_,control:t.jsx(vt,{checked:v[O],onChange:W=>C(O,W)})},O),P=s("webhooks.view")||s("integrations.view");return t.jsxs("div",{className:"cia-wa-pestana",children:[t.jsxs(as,{title:a("whatsapp.pestanaAvisos.titulo"),description:a("whatsapp.pestanaAvisos.desc"),icon:Gp,footer:P?t.jsxs("span",{children:[a("whatsapp.pestanaAvisos.tambienPorWebhooks")," ",t.jsx(et,{to:"/whatsapp",search:{tab:"integraciones"},className:"cia-wa-enlace",children:a("whatsapp.pestanaAvisos.irAIntegraciones")})]}):a("whatsapp.pestanaAvisos.tambienPorWebhooks"),children:[I("cuentaDesconectada",wi),I("credencialPorVencer",Ka),I("plantilla",bi),I("calidad",co),t.jsx(Nl,{icon:Au,title:a("whatsapp.pestanaAvisos.eventos.traspaso.titulo"),description:a("whatsapp.pestanaAvisos.eventos.traspaso.desc"),disabled:S,disabledReason:_,control:t.jsx(vt,{checked:R.activo,onChange:O=>N({activo:O})})}),t.jsx(Nl,{dependent:!0,title:a("whatsapp.pestanaAvisos.eventos.traspaso.despues"),description:R.activo?a("whatsapp.pestanaAvisos.eventos.traspaso.plazo",{count:R.minutos}):a("whatsapp.pestanaAvisos.eventos.traspaso.encendeloPrimero"),disabled:S||!R.activo,disabledReason:S?_:R.activo?void 0:a("whatsapp.pestanaAvisos.eventos.traspaso.encendeloPrimero"),control:t.jsx(hn,{value:String(R.minutos),options:A,onChange:O=>{const K=Number(O);Tg.includes(K)&&N({minutos:K})}})})]}),t.jsx(as,{title:a("whatsapp.pestanaAvisos.destinatarios.titulo"),description:a("whatsapp.pestanaAvisos.destinatarios.desc"),icon:Bs,aside:s("team.view")?t.jsx(et,{to:"/settings",search:{s:"team"},className:"cia-btn cia-button cia-btn-outline cia-btn-sm","data-size":"sm",children:a("whatsapp.pestanaAvisos.destinatarios.irAEquipo")}):void 0,footer:E?a("whatsapp.pestanaAvisos.destinatarios.sinCorreos"):void 0,children:p.destinatarios.length===0?t.jsx(le,{tone:"warn",children:a("whatsapp.pestanaAvisos.destinatarios.nadie")}):t.jsx("ul",{className:"cia-wa-destinatarios",children:p.destinatarios.map((O,K)=>t.jsxs("li",{className:"cia-wa-destinatario",children:[t.jsx("span",{className:"cia-wa-destinatario-nombre",children:O.nombre}),O.email?t.jsx("span",{className:"cia-wa-destinatario-correo",children:O.email}):null]},`${O.email??O.nombre}-${K}`))})}),e?t.jsx(uE,{visible:k||l==="saving"||l==="saved"||l==="error",state:k&&l==="saved"?"dirty":l,message:l==="error"&&d?d:k?a("whatsapp.pestanaAvisos.cambiados",{count:RF(y)}):void 0,onSave:()=>y?w.mutateAsync(y).then(()=>{},()=>{}):void 0,onDiscard:()=>{o({}),u(null),c("dirty")}}):null,j.status==="blocked"?t.jsx(ot,{open:!0,onClose:j.reset,title:a("whatsapp.pestanaAvisos.salir.titulo"),maxWidth:440,footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{variant:"ghost",onClick:j.reset,children:a("whatsapp.pestanaAvisos.salir.quedarme")}),t.jsx(Ie,{variant:"danger",onClick:j.proceed,children:a("whatsapp.pestanaAvisos.salir.salir")})]}),children:t.jsx("p",{className:"cia-wa-lectura",children:a("whatsapp.pestanaAvisos.salir.desc")})}):null]})}const PF=Wh.filter(e=>e.value.startsWith("whatsapp."));function zF(e,a){return e.filter(n=>!n.revokedAt&&(!n.expiresAt||Date.parse(n.expiresAt)>a)&&n.scopes.some(s=>s.startsWith("whatsapp.")))}function DF(e,a){return a.filter(n=>n.agentId===null&&n.enabled&&n.events.includes(e)).length}function IF({puedeVerWebhooks:e,puedeVerClaves:a}){const{t:n}=M("misc"),[s]=m.useState(()=>Date.now()),i=se({queryKey:["webhook-endpoints","org"],enabled:e,queryFn:async()=>(await T.get("/webhook-endpoints",{params:{agentId:"__org__"}})).data}),r=se({queryKey:["api-keys"],enabled:a,queryFn:async()=>(await T.get("/api-keys")).data.items}),o=r.data?zF(r.data,s):[],l=o.map(d=>d.lastUsedAt).filter(d=>!!d).sort(),c=l.length?l[l.length-1]:null;return t.jsxs("div",{className:"cia-wa-pestana",children:[t.jsx(as,{title:n("whatsapp.pestanaIntegraciones.eventos.titulo"),description:n("whatsapp.pestanaIntegraciones.eventos.desc"),icon:Ec,aside:e?t.jsx(et,{to:"/integraciones",className:"cia-btn cia-button cia-btn-outline cia-btn-sm","data-size":"sm",children:n("whatsapp.pestanaIntegraciones.eventos.administrar")}):void 0,footer:n(e?"whatsapp.pestanaIntegraciones.eventos.soloOrganizacion":"whatsapp.pestanaIntegraciones.eventos.sinPermiso"),children:t.jsxs("div",{className:"cia-wa-pila",children:[e&&i.isError?t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:n("whatsapp.pestanaIntegraciones.reintentar"),icon:Na,loading:i.isFetching,onClick:()=>void i.refetch()},children:n("whatsapp.pestanaIntegraciones.eventos.errorAlLeer")}):null,t.jsx("ul",{className:"cia-wa-eventos",children:PF.map(d=>{const u=i.data?DF(d.value,i.data):null;return t.jsxs("li",{className:"cia-wa-evento",children:[t.jsxs("div",{className:"cia-wa-evento-texto",children:[t.jsx("span",{className:"cia-wa-evento-titulo",children:n(`whatsapp.pestanaIntegraciones.eventos.rotulo.${d.key}`)}),t.jsx("span",{className:"cia-wa-evento-desc",children:n(`webhookModal.event.${d.key}.hint`)}),t.jsx("code",{className:"cia-mono cia-wa-evento-id",children:d.value})]}),e?i.isLoading?t.jsx(ge,{w:110,h:14}):u===null?null:t.jsx("span",{className:"cia-wa-evento-conteo","data-vacio":u===0?"":void 0,children:u>0?n("whatsapp.pestanaIntegraciones.eventos.suscritos",{count:u}):n("whatsapp.pestanaIntegraciones.eventos.ninguno")}):null]},d.value)})})]})}),a?t.jsx(as,{title:n("whatsapp.pestanaIntegraciones.claves.titulo"),description:n("whatsapp.pestanaIntegraciones.claves.desc"),icon:Ka,footer:n("whatsapp.pestanaIntegraciones.claves.sinPantalla"),children:r.isLoading?t.jsxs("div",{className:"cia-wa-claves","aria-hidden":"true",children:[t.jsx(ge,{w:"min(320px, 100%)",h:16}),t.jsx(ge,{w:200,h:14})]}):r.isError?t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:n("whatsapp.pestanaIntegraciones.reintentar"),icon:Na,loading:r.isFetching,onClick:()=>void r.refetch()},children:n("whatsapp.pestanaIntegraciones.claves.errorAlLeer")}):t.jsxs("div",{className:"cia-wa-claves",children:[t.jsxs("p",{className:"cia-wa-claves-resumen",children:[o.length>0?n("whatsapp.pestanaIntegraciones.claves.conPermiso",{count:o.length}):n("whatsapp.pestanaIntegraciones.claves.ninguna"),o.length>0?t.jsxs(t.Fragment,{children:[" · ",c?n("whatsapp.pestanaIntegraciones.claves.ultimoUso",{when:ts(c)}):n("whatsapp.pestanaIntegraciones.claves.nuncaUsadas")]}):null]}),o.length>0?t.jsx("ul",{className:"cia-wa-claves-lista",children:o.map(d=>t.jsxs("li",{className:"cia-wa-clave",children:[t.jsx("span",{className:"cia-wa-clave-nombre",children:d.name}),t.jsxs("code",{className:"cia-mono cia-wa-clave-prefijo",children:[d.keyPrefix,"…"]}),t.jsxs("span",{className:"cia-wa-clave-meta",children:[d.scopes.filter(u=>u.startsWith("whatsapp.")).join(" · ")," · ",d.lastUsedAt?n("whatsapp.pestanaIntegraciones.claves.usadaHace",{when:ts(d.lastUsedAt)}):n("whatsapp.pestanaIntegraciones.claves.nuncaUsada")]})]},d.id))}):null]})}):null]})}const LF={numeros:Ma,llamadas:dn,atencion:YS,avisos:Gp,integraciones:Ec};function FF(){const{t:e}=M("misc"),{t:a}=M("agentsRoutes"),n=xt(H=>H.resolved),s=Pe(H=>H.user),i=xe(),r=dt(),o=Os({strict:!1}),l=lt(s,"whatsapp.manage"),c=lt(s,"whatsapp.operate"),d=lt(s,"webhooks.view"),u=lt(s,"integrations.view"),[p,f]=m.useState(null),[x,h]=m.useState({}),[b,g]=m.useState({abierto:!1,modoInicial:null}),v=Kc(Vc.whatsapp),{data:y,isLoading:k,isError:w,refetch:j,isFetching:C}=se({queryKey:["whatsapp","accounts"],queryFn:async()=>{try{return(await T.get("/whatsapp/accounts")).data}catch(H){const fe=H?.response?.status;if(fe===501||fe===404)return null;throw H}}}),{data:N}=se({queryKey:["whatsapp","signup-config"],enabled:l&&y!==null&&y!==void 0,queryFn:async()=>{try{return(await T.get("/whatsapp/signup-config")).data}catch{return{disponible:!1,appId:null,configId:null}}}}),S=lt(s,"agents.view"),_=se({queryKey:["agents"],enabled:S,queryFn:async()=>(await T.get("/agents")).data}),R=S?_.isError&&!_.data?e("whatsapp.numero.errorAgentes"):void 0:e("whatsapp.numero.sinPermisoAgentes"),A=oe({mutationFn:async H=>(await T.patch(`/whatsapp/numbers/${H.numberId}/agent`,{agentId:H.agentId})).data,onSuccess:(H,fe)=>{h(({[fe.numberId]:pe,...ye})=>ye),i.invalidateQueries({queryKey:["whatsapp","accounts"]}),i.invalidateQueries({queryKey:["whatsapp","calling",fe.numberId]});const Z=(y?.items??[]).flatMap(pe=>pe.numbers).find(pe=>
975pe.id===fe.numberId)?.displayPhoneNumber??fe.numberId,ae=fe.agentId?(_.data??[]).find(pe=>pe.id===fe.agentId)?.name:null;J({tone:"ok",title:fe.deshacer?e("whatsapp.numero.deshecho"):e("whatsapp.numero.guardado"),desc:fe.agentId?ae?e("whatsapp.numero.agenteGuardado",{phone:Z,name:ae}):e("whatsapp.numero.agenteGuardadoSinNombre",{phone:Z}):e("whatsapp.numero.quedoSinAgente",{phone:Z}),action:fe.deshacer?void 0:{label:e("whatsapp.numero.deshacer"),onClick:()=>{A.mutate({numberId:fe.numberId,agentId:fe.anterior,anterior:fe.agentId,deshacer:!0})}}})},onError:(H,fe)=>{const Z=H?.response?.data,pe=(Array.isArray(Z?.issues)?Z.issues:[]).map(qe=>{const ut=a(`audit.code.${qe.code}`,{defaultValue:qe.message,...qe.params??{}});return ut.includes("{{")?qe.message:ut}).filter(Boolean),ye=Z?.code==="agent_audit_blocked"?e("whatsapp.numero.auditorRechazo"):typeof Z?.message=="string"&&Z.message?Z.message:typeof Z?.code=="string"&&Z.code?e(`whatsapp.errors.${Z.code}`,{defaultValue:e("whatsapp.table.agentFailed")}):e("whatsapp.table.agentFailed");h(qe=>({...qe,[fe.numberId]:{texto:[ye,...pe].join(" · "),agentId:fe.agentId}}))}}),E=oe({mutationFn:async(H="cloud_api")=>{if(!N?.disponible||!N.appId)throw new Error("no_disponible");await _6(N.appId);const fe=await E6(N,{modo:H});return(await T.post("/whatsapp/connect",{wabaId:fe.wabaId,codigo:fe.codigo,coexistence:H==="coexistencia"})).data},onSuccess:H=>{if(i.invalidateQueries({queryKey:["whatsapp","accounts"]}),H.ok){f({tono:"ok",texto:H.actualizada?e("whatsapp.reconnected"):e("whatsapp.connected"),aLaBandeja:!H.actualizada});return}if(H.status==="unknown"){f({tono:"warn",texto:e("whatsapp.pendingConfirm")});return}f({tono:"bad",texto:e(`whatsapp.errors.${H.code??"rechazo_desconocido"}`,{defaultValue:e("whatsapp.errors.rechazo_desconocido")})})},onError:H=>{const fe=H?.message??"";if(fe==="cancelado"){f(null);return}const Z=H?.response?.data?.message;if(typeof Z=="string"&&Z){f({tono:"bad",texto:Z});return}f({tono:"bad",texto:e(fe==="no_disponible"?"whatsapp.signupUnavailable":fe==="tiempo_agotado"?"whatsapp.signupTimeout":fe==="coexistencia_no_disponible"?"whatsapp.signupCoexistenciaNoDisponible":fe==="sin_codigo"?"whatsapp.signupSinCodigo":"whatsapp.signupFailed")})}}),I=oe({mutationFn:async H=>(await T.delete(`/whatsapp/accounts/${H}`)).data,onSuccess:()=>{i.invalidateQueries({queryKey:["whatsapp","accounts"]}),f({tono:"ok",texto:e("whatsapp.disconnected")})},onError:H=>{const fe=H?.response?.data?.message;f({tono:"bad",texto:typeof fe=="string"&&fe?fe:e("whatsapp.cuenta.errorAlDesconectar")})}});async function P(H){const fe=H.businessName||e("whatsapp.account.unnamed"),Z=H.numbers.length,ae=H.numbers.map(ye=>ye.displayPhoneNumber||ye.id).join(", ");await pa({title:e("whatsapp.cuenta.desconectarTitulo",{nombre:fe}),message:Z>0?e("whatsapp.cuenta.desconectarAlcance",{count:Z,telefonos:ae}):e("whatsapp.cuenta.desconectarSinNumeros"),confirmLabel:Z>0?e("whatsapp.cuenta.desconectarN",{count:Z}):e("whatsapp.cuenta.desconectar"),cancelLabel:e("whatsapp.modulo.cancelar"),danger:!0})&&I.mutate(H.id)}const O=E1(y?.items),{data:K,isLoading:W,isError:V,isFetching:U,refetch:X}=se({queryKey:["whatsapp","calling",O??""],enabled:O!==null,queryFn:Kh}),ie=O!==null&&!W&&K!==null&&K!==void 0,de=O!==null&&V&&K===void 0,$=o.tab==="llamadas"&&O!==null&&(W||de),z=R6({puedeAdministrar:l,llamadasDisponibles:ie,puedeVerIntegraciones:d||u}),D=$?"llamadas":T6(o.tab,z),F=!k&&y!==null&&y!==void 0;m.useEffect(()=>{!F||$||o.tab!==void 0&&o.tab!==D&&r({to:"/whatsapp",search:H=>({...H,tab:D}),replace:!0})},[F,$,o.tab,D,r]);function G(H,fe){f(null),r({to:"/whatsapp",search:Z=>({...Z,tab:H}),replace:fe==="teclado"})}const te=N===void 0?e("whatsapp.modulo.preparando"):N.disponible?E.isPending?e("whatsapp.conexion.enCurso"):void 0:e("whatsapp.signupUnavailable");function B(){if(!te){if(N?.coexistencia){g({abierto:!0,modoInicial:null});return}E.mutate("cloud_api")}}function ne(H){if(te)return te;if(H.coexistence&&!N?.coexistencia)return e("whatsapp.signupCoexistenciaNoDisponible")}function me(H){if(!ne(H)){if(H.coexistence){g({abierto:!0,modoInicial:"coexistencia"});return}E.mutate("cloud_api")}}const Ee=(H,fe={})=>t.jsx(Jy,{title:e("whatsapp.title"),subtitle:e("whatsapp.modulo.subtitulo"),icon:Ba,spacing:fe.conPestanas?"tabs":"default",actions:H?t.jsxs("div",{className:"cia-wa-hub-acciones",children:[t.jsxs(et,{to:"/whatsapp/plantillas",className:"cia-btn cia-button cia-btn-ghost cia-wa-hub-solo-ancho","data-size":"md",children:[t.jsx("span",{className:"cia-btn-glyph","aria-hidden":"true",children:t.jsx(bi,{})}),e("whatsapp.modulo.irAPlantillas")]}),fe.sinCuentas?null:t.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"cia-btn cia-button cia-btn-outline","data-size":"md",children:[t.jsx("span",{className:"cia-btn-glyph","aria-hidden":"true",children:t.jsx(ua,{})}),e("whatsapp.modulo.verGuia"),t.jsx("span",{className:"cia-sr-only",children:e("whatsapp.modulo.abreEnOtraPestana")})]}),l&&!fe.sinCuentas?t.jsx(Ie,{variant:fe.ctaActivo?"cta":"outline",icon:t.jsx(Fe,{}),loading:E.isPending,disabled:!!te&&!E.isPending,disabledReason:E.isPending?void 0:te,onClick:B,children:e("whatsapp.modulo.conectar")}
975):null]}):void 0});if(k)return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("whatsapp.eyebrow"),title:e("whatsapp.title"),titleAs:"div"}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":n,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-wa-hub","aria-busy":"true",children:[t.jsxs("div",{className:"cia-wa-hub-esqueleto-cabecera",children:[t.jsx(ge,{w:40,h:40,r:10}),t.jsxs("div",{className:"cia-wa-hub-esqueleto-textos",children:[t.jsx(ge,{w:96,h:10}),t.jsx(ge,{w:160,h:22}),t.jsx(ge,{w:"min(420px, 100%)",h:14})]})]}),t.jsx(ge,{h:36}),t.jsx(ge,{h:228,r:14}),t.jsx(ge,{h:260,r:14})]})})]});if(y===null)return t.jsx(So,{eyebrow:e("whatsapp.eyebrow"),title:e("whatsapp.title"),icon:Ba,description:e("whatsapp.description"),features:[e("whatsapp.f1"),e("whatsapp.f2"),e("whatsapp.f3")]});if(w&&!y)return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("whatsapp.eyebrow"),title:e("whatsapp.title"),titleAs:"div"}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":n,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-wa-hub",children:[Ee(!1),t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:e("whatsapp.modulo.reintentar"),icon:Na,loading:C,onClick:()=>void j()},children:e("whatsapp.loadError")})]})})]});const L=y?.items??[],re=L.reduce((H,fe)=>H+fe.numbers.length,0),ke=z.map(H=>({id:H,label:e(`whatsapp.modulo.pestanas.${H}`),icon:LF[H],count:H==="numeros"&&re>0?re:void 0,panelId:`wa-panel-${H}`}));return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("whatsapp.eyebrow"),title:e("whatsapp.title"),titleAs:"div"}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":n,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsxs("div",{className:"cia-wa-hub",children:[t.jsxs("div",{className:"cia-wa-hub-cabecera",children:[Ee(!0,{sinCuentas:L.length===0,ctaActivo:D==="numeros",conPestanas:!0}),t.jsx(Fi,{items:ke,active:D,onChange:(H,fe)=>G(H,fe)})]}),w?t.jsx(le,{tone:"bad",actionPlacement:"end",action:{label:e("whatsapp.modulo.reintentar"),icon:Na,loading:C,onClick:()=>void j()},children:e("whatsapp.loadError")}):null,de?t.jsx(le,{tone:"warn",actionPlacement:"end",action:{label:e("whatsapp.modulo.reintentar"),icon:Na,loading:U,onClick:()=>void X()},children:e("whatsapp.modulo.sondaDeLlamadasFallo")}):null,p?t.jsx(le,{tone:p.tono,actionPlacement:"end",action:p.aLaBandeja?{label:e("whatsapp.modulo.irALaBandeja"),onClick:()=>void r({to:"/whatsapp/bandeja"})}:void 0,children:p.texto}):null,t.jsxs("div",{role:"tabpanel",id:`wa-panel-${D}`,"aria-label":e(`whatsapp.modulo.pestanas.${D}`),children:[D==="numeros"&&t.jsx(oF,{cuentas:L,llamadasDisponibles:ie,puedeAdministrar:l,onConectar:l&&!te?B:void 0,motivoSinConexion:te,motivoSinReconexion:ne,onReconectar:me,onDesconectar:H=>void P(H),desconectando:I.isPending,agentes:_.data,motivoSinAgentes:R,onReintentarAgentes:S&&_.isError?()=>void _.refetch():void 0,guardandoAgente:H=>A.isPending&&A.variables?.numberId===H,errorDeAgente:x,onElegirAgente:(H,fe,Z)=>A.mutate({numberId:H,agentId:fe,anterior:Z}),guia:v,onIrAPestana:G}),D==="llamadas"&&ie&&t.jsx(mF,{cuentas:L,puedeAdministrar:l,onAviso:f}),D==="llamadas"&&!ie&&!de&&t.jsx(ge,{h:260,r:14}),D==="atencion"&&t.jsx(wF,{puedeGestionarTipificaciones:l,puedeEditarRespuestas:c}),D==="avisos"&&t.jsx(MF,{puedeAdministrar:l}),D==="integraciones"&&t.jsx(IF,{puedeVerWebhooks:d,puedeVerClaves:u})]})]})}),t.jsx(lF,{abierto:b.abierto,onCerrar:()=>g({abierto:!1,modoInicial:null}),cfg:N,modoInicial:b.modoInicial,conectando:E.isPending,onConectar:H=>E.mutate(H)})]})}function OF(e){if(!e.startsWith("/"))return null;const a=e.slice(1);return/\s/.test(a)?null:a.toLowerCase()}function $F({borrador:e,respuestas:a,onElegir:n,onBorrar:s,onGuardarBorrador:i}){const{t:r}=M("misc"),[o,l]=m.useState(0),c=m.useRef(null),d=OF(e),u=m.useMemo(()=>{if(d===null)return[];const p=d.trim(),f=x=>!p||x.atajo.includes(p)||x.texto.toLowerCase().includes(p);return a.filter(f).slice(0,8)},[d,a]);return m.useEffect(()=>l(0),[d]),m.useEffect(()=>{if(d===null)return;const p=f=>{u.length&&(f.key==="ArrowDown"?(f.preventDefault(),l(x=>(x+1)%u.length)):f.key==="ArrowUp"?(f.preventDefault(),l(x=>(x-1+u.length)%u.length)):(f.key==="Enter"||f.key==="Tab")&&(f.preventDefault(),f.stopPropagation(),n(u[o])))};return document.addEventListener("keydown",p,!0),()=>document.removeEventListener("keydown",p,!0)},[d,u,o,n]),d===null?null:t.jsx(Or,{trigger:t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:1,height:1}}),open:!0,onOpenChange:()=>{},disabled:!0,autoFocus:!1,ariaLabel:r("whatsapp.inbox.snippets.titulo"),width:340,children:t.jsx("div",{ref:c,role:"listbox","aria-label":r("whatsapp.inbox.snippets.titulo"),style:{display:"flex",flexDirection:"column",gap:2,maxHeight:280,overflowY:"auto"},children:u.length?u.map((p,f)=>
975t.jsxs("div",{className:"cia-snippet-fila","data-marcado":f===o?"1":void 0,role:"option","aria-selected":f===o,children:[t.jsxs("button",{type:"button",className:"cia-snippet-elegir",onClick:()=>n(p),children:[t.jsxs("span",{className:"cia-snippet-atajo",children:["/",p.atajo]}),t.jsx("span",{className:"cia-snippet-texto",children:p.texto})]}),s?t.jsx(Lt,{icon:t.jsx(mt,{}),size:"sm",label:r("whatsapp.inbox.snippets.borrar"),onClick:()=>s(p)}):null]},p.id)):t.jsxs("div",{className:"cia-snippet-vacio",children:[t.jsx("span",{children:r("whatsapp.inbox.snippets.sinResultados")}),i?t.jsx(Ie,{size:"sm",variant:"outline",onClick:i,children:r("whatsapp.inbox.snippets.crear")}):null]})})})}const M1=[{id:"todas",clave:"whatsapp.inbox.zonas.todas",icono:Tp,conteo:"todas"},{id:"sin_leer",clave:"whatsapp.inbox.zonas.sinLeer",icono:ZS,conteo:"sinLeer"},{id:"importantes",clave:"whatsapp.inbox.zonas.importantes",icono:Ii,conteo:"importantes"},{id:"mias",clave:"whatsapp.inbox.zonas.mias",icono:En,conteo:"mias"},{id:"sin_asignar",clave:"whatsapp.inbox.zonas.sinAsignar",icono:mo,conteo:"sin_asignar"},{id:"de_la_ia",clave:"whatsapp.inbox.zonas.deLaIa",icono:Ft,conteo:"de_la_ia"},{id:"pospuestas",clave:"whatsapp.inbox.zonas.pospuestas",icono:Qa,conteo:"pospuestas"},{id:"cerradas",clave:"whatsapp.inbox.zonas.cerradas",icono:bc,conteo:"cerradas"}];function qF(e){return typeof e=="string"&&M1.some(a=>a.id===e)}function BF(e,a){const n=e?.[a.conteo];return typeof n=="number"&&Number.isInteger(n)&&n>=0?n:null}function WF(e){switch(e){case"todas":return{incluirCerradas:"true"};case"sin_leer":return{soloSinLeer:"true"};case"importantes":return{soloImportantes:"true"};case"cerradas":return{estado:"closed"};case"mias":case"sin_asignar":case"de_la_ia":case"pospuestas":return{zona:e};default:{const a=e;throw new Error(`zona sin parámetros: ${String(a)}`)}}}const UF=80;function VF(e){const a={},n=(e.buscar??"").trim().slice(0,UF).trim();return n&&(a.buscar=n),e.etiqueta&&(a.etiqueta=e.etiqueta),e.linea&&(a.linea=e.linea),a}function KF(e){return(e.etiqueta?1:0)+(e.linea?1:0)}function HF(e){const a=new Set,n=[];for(const s of e??[])for(const i of s.numbers??[])!i?.id||a.has(i.id)||(a.add(i.id),n.push({id:i.id,numero:(i.displayPhoneNumber??"").trim()||i.id,nombre:(i.verifiedName??"").trim()||null,status:typeof i.status=="string"?i.status:null}));return n}function QF(e){return(e??[]).filter(a=>a.status==="active")}function GF(e){return(e?.length??0)>1}function ZF({zona:e,onZona:a,conteos:n,buscar:s,onBuscar:i,etiqueta:r,onEtiqueta:o,linea:l,onLinea:c,etiquetas:d,lineas:u,onReintentarEtiquetas:p,buscarRef:f,conIconos:x=!1}){const{t:h}=M("misc"),b=m.useRef(null),g=f??b,v=M1.map(N=>({id:N.id,label:h(N.clave),count:BF(n,N),icon:x?N.icono:void 0})),y=GF(u),k=KF({etiqueta:r,linea:l}),w=[],j=s.trim();if(j&&w.push({key:"buscar",label:h("whatsapp.inbox.filtrosBandeja.chip.buscar"),value:j,onRemove:()=>i("")}),r){const N=d?.find(S=>S.id===r);w.push({key:"etiqueta",label:h("whatsapp.inbox.filtrosBandeja.chip.etiqueta"),value:N?N.nombre:h(d===void 0?"whatsapp.inbox.filtrosBandeja.cargando":d===null?"whatsapp.inbox.filtrosBandeja.nombreNoDisponible":"whatsapp.inbox.filtrosBandeja.etiquetaDesconocida"),tone:N?N.color??"gris":void 0,onRemove:()=>o(null)})}if(l){const N=u?.find(S=>S.id===l);w.push({key:"linea",label:h("whatsapp.inbox.filtrosBandeja.chip.linea"),value:N?N.numero:h(u===void 0?"whatsapp.inbox.filtrosBandeja.cargando":u===null?"whatsapp.inbox.filtrosBandeja.nombreNoDisponible":"whatsapp.inbox.filtrosBandeja.lineaDesconocida"),onRemove:()=>c(null)})}const C=t.jsxs(nd,{activeCount:k,onClear:()=>{o(null),c(null)},triggerText:h("whatsapp.inbox.filtrosBandeja.boton"),placement:"bottom-start",children:[t.jsx(nd.Section,{title:h("whatsapp.inbox.filtrosBandeja.etiqueta"),children:t.jsx(YF,{etiquetas:d,elegida:r,onElegir:o,onReintentar:p})}),y&&u?t.jsx(nd.Section,{title:h("whatsapp.inbox.filtrosBandeja.linea"),children:t.jsx(hn,{value:l??"",onChange:N=>c(N||null),ariaLabel:h("whatsapp.inbox.filtrosBandeja.linea"),placeholder:h("whatsapp.inbox.filtrosBandeja.todasLasLineas"),options:[...u.map(N=>({value:N.id,label:N.nombre?`${N.numero} · ${N.nombre}`:N.numero})),...l&&!u.some(N=>N.id===l)?[{value:l,label:h("whatsapp.inbox.filtrosBandeja.lineaDesconocida")}]:[]]})}):null]});return t.jsxs("div",{className:"cia-wafil",children:[t.jsx(ph,{size:"sm",width:"100%",value:s,onChange:i,inputRef:g,placeholder:h("whatsapp.inbox.filtrosBandeja.buscarPlaceholder"),"aria-label":h("whatsapp.inbox.buscarPlaceholder")}
975),t.jsx(sE,{layout:"wrap",items:v,value:e,onChange:N=>{qF(N)&&a(N)},ariaLabel:h("whatsapp.inbox.zonas.label")}),t.jsxs("div",{className:"cia-wafil-fila",children:[C,t.jsx(cE,{filters:w,onClearAll:w.length>1?()=>{i(""),o(null),c(null)}:void 0,focusAfterClearRef:g})]})]})}const su={borderRadius:"var(--cia-r-pill)"};function YF({etiquetas:e,elegida:a,onElegir:n,onReintentar:s}){const{t:i}=M("misc");return e===void 0?t.jsxs("div",{className:"cia-wafil-etiquetas",role:"status","aria-label":i("whatsapp.inbox.filtrosBandeja.etiquetasCargando"),children:[t.jsx(ge,{w:72,h:24,style:su}),t.jsx(ge,{w:96,h:24,style:su}),t.jsx(ge,{w:60,h:24,style:su})]}):e===null?t.jsxs("div",{className:"cia-wafil-aviso",role:"alert",children:[t.jsx("p",{className:"cia-wafil-nota",children:i("whatsapp.inbox.filtrosBandeja.etiquetasError")}),s?t.jsx(Ie,{size:"sm",variant:"outline",onClick:s,children:i("whatsapp.inbox.filtrosBandeja.reintentar")}):null]}):e.length===0?t.jsx("p",{className:"cia-wafil-nota",children:i("whatsapp.inbox.filtrosBandeja.sinEtiquetas")}):t.jsx("div",{className:"cia-wafil-etiquetas",role:"group","aria-label":i("whatsapp.inbox.filtrosBandeja.etiquetasAria"),children:e.map(r=>t.jsx(ps,{label:r.nombre,tone:r.color,active:a===r.id,onClick:()=>n(a===r.id?null:r.id)},r.id))})}function XF(e=!0){const a=se({queryKey:["wa-etiquetas-catalogo"],queryFn:async()=>(await T.get("/whatsapp/etiquetas")).data.items,staleTime:3e5,enabled:e});return{etiquetas:a.data??(a.isError?null:void 0),reintentar:()=>void a.refetch()}}function P1(e=!0){const a=se({queryKey:["whatsapp","accounts"],queryFn:async()=>{try{return(await T.get("/whatsapp/accounts")).data}catch(n){if(n?.response?.status===501||n?.response?.status===404)return null;throw n}},select:n=>HF(n?.items),staleTime:6e4,enabled:e});return a.data??(a.isError?null:void 0)}const JF=/\{\{\s*(\d+)\s*\}\}/g;function eO(e,a){const n=[];let s=0;for(const i of String(e??"").matchAll(JF)){const r=i.index??0;r>s&&n.push({tipo:"texto",v:e.slice(s,r)});const o=Number(i[1]),l=a?.[o-1],c=typeof l=="string"&&l.trim()?l:null;n.push({tipo:"hueco",n:o,valor:c}),s=r+i[0].length}return s<(e??"").length&&n.push({tipo:"texto",v:e.slice(s)}),n}function tO(e,a){const n=a?.[e-1];return typeof n=="string"&&n.trim()?n:null}function iu({texto:e,valores:a,ejemplos:n}){const{t:s}=M("misc");return t.jsx(t.Fragment,{children:eO(e,a).map((i,r)=>{if(i.tipo==="texto")return t.jsx("span",{children:i.v},r);const o=i.valor?null:tO(i.n,n);return t.jsx("span",{className:"cia-plantilla-hueco","data-lleno":i.valor?"1":void 0,"data-ejemplo":o?"1":void 0,title:o?s("whatsapp.plantilla.vistaPrevia.ejemploDe",{n:i.n}):s("whatsapp.plantilla.vistaPrevia.hueco",{n:i.n}),children:i.valor??o??s("whatsapp.plantilla.vistaPrevia.valorN",{n:i.n})},r)})})}function aO({componentes:e,valores:a,ejemplos:n}){const{t:s}=M("misc"),i=(e.encabezado??"").trim(),r=(e.pie??"").trim(),o=(e.botones??[]).filter(l=>(l??"").trim());return t.jsxs("div",{className:"cia-plantilla-previa","aria-label":s("whatsapp.plantilla.vistaPrevia.titulo"),children:[t.jsxs("div",{className:"cia-plantilla-globo",children:[i?t.jsx("div",{className:"cia-plantilla-encabezado",children:t.jsx(iu,{texto:i,valores:a,ejemplos:n})}):null,t.jsx("div",{className:"cia-plantilla-cuerpo",children:t.jsx(iu,{texto:e.cuerpo??"",valores:a,ejemplos:n})}),r?t.jsx("div",{className:"cia-plantilla-pie",children:t.jsx(iu,{texto:r,valores:a,ejemplos:n})}):null]}),o.length>0?t.jsx("div",{className:"cia-plantilla-botones",children:o.map((l,c)=>t.jsx("span",{className:"cia-plantilla-boton",children:l},`${l}-${c}`))}):null]})}function nO(e){const a=e.approvedBody??e.submittedBody??"",n=new Set;for(const s of a.matchAll(/\{\{\s*(\d+)\s*\}\}/g))n.add(Number(s[1]));return[...n].sort((s,i)=>s-i)}function sO({abierto:e,onCerrar:a,destino:n,onEnviada:s}){const{t:i}=M("misc"),r=dt(),{can:o}=tt(),[l,c]=m.useState(""),[d,u]=m.useState([]),[p,f]=m.useState(""),[x,h]=m.useState(""),[b,g]=m.useState(null),[v,y]=m.useState("");m.useEffect(()=>{e&&(y(`inbox-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`),g(null))},[e]);const k=se({queryKey:["whatsapp","templates"],queryFn:async()=>(await T.get("/whatsapp/templates")).data,enabled:e,staleTime:6e4}),w=P1(e&&n.tipo==="nuevo"),j=m.useMemo(()=>QF(w),[w]),C=j.find(P=>P.id===p)??null,N=Array.isArray(w)&&j.length===0,S=m.useMemo(()=>(k.data?.items??[]).filter(P=>P.usable),[k.data]),_=S.find(P=>P.id===l)??null,R=_?nO(_):[],A=R.some((P,O)=>!(d[O]??"").trim()),E=n.tipo==="nuevo"&&(!C||x.trim().length<7),I=oe({mutationFn:async()=>{const P={templateId:l,parametros:R.map((O,K)=>d[K]??""),clientToken:v};return n.tipo==="hilo"?P.conversationId=n.conversationId:(P.waNumberId=p,P.telefono=x.replace(/[^0-9]/g,"")),(await T.post("/whatsapp/conversations/plantilla",P)).data},onSuccess:P=>{s(P.conversationId),a()},onError:P=>g(P?.response?.data?.message??i("whatsapp.enviarPlantilla.errorGenerico"))});return e?t.jsx(ot,{open:!0,onClose:a,title:i("whatsapp.enviarPlantilla.titulo"),maxWidth:560,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-3)",lineHeight:1.6},children:n.tipo==="hilo"?i("whatsapp.enviarPlantilla.introHilo",{contacto:n.contacto}):i("whatsapp.enviarPlantilla.introNuevo")}),b?t.jsx(le,{tone:"bad",children:b}):null,n.tipo==="nuevo"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx(hn,{label:i("whatsapp.enviarPlantilla.desde"),value:C?p:"",onCh
975ange:f,placeholder:i("whatsapp.enviarPlantilla.elegirNumero"),disabled:N,options:j.map(P=>({value:P.id,label:Xv(P.nombre,P.numero)??P.numero}))}),N?t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-warn-ink)",lineHeight:1.5},children:(w??[]).length>0?i("whatsapp.enviarPlantilla.ningunaLineaActiva"):i("whatsapp.enviarPlantilla.sinLineas")}):null]}),t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600},children:i("whatsapp.enviarPlantilla.para")}),t.jsx("input",{className:"cia-input",value:x,onChange:P=>h(P.target.value),placeholder:"573001112233",inputMode:"tel"}),t.jsx("span",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:i("whatsapp.enviarPlantilla.telefonoAyuda")})]})]}):null,t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx(hn,{label:i("whatsapp.enviarPlantilla.plantilla"),value:l,onChange:P=>{c(P),u([])},placeholder:i("whatsapp.enviarPlantilla.elegirPlantilla"),options:S.map(P=>({value:P.id,label:`${P.name} · ${P.language}`}))}),!k.isLoading&&S.length===0?(k.data?.items??[]).length>0?t.jsx(st,{mini:!0,icon:bi,title:i("whatsapp.enviarPlantilla.vacio.ningunaAprobadaTitulo"),desc:i("whatsapp.enviarPlantilla.vacio.ningunaAprobadaDesc"),action:{label:i("whatsapp.enviarPlantilla.administrar"),icon:nn,onClick:()=>{a();const P=rS(k.data?.items??[]);r({to:"/whatsapp/plantillas",search:P?{estado:P}:{}})}}}):t.jsx(st,{mini:!0,icon:bi,title:i("whatsapp.enviarPlantilla.vacio.ningunaCreadaTitulo"),desc:o("whatsapp.manage")?i("whatsapp.enviarPlantilla.vacio.ningunaCreadaDesc"):i("whatsapp.enviarPlantilla.vacio.ningunaCreadaSinPermiso"),action:o("whatsapp.manage")?{label:i("whatsapp.enviarPlantilla.vacio.crear"),icon:Fe,onClick:()=>{a(),r({to:"/whatsapp/plantillas/nueva",search:{}})}}:void 0}):S.length>0?t.jsxs(et,{to:"/whatsapp/plantillas",className:"cia-ficha-enlace",onClick:a,children:[i("whatsapp.enviarPlantilla.administrar"),t.jsx(nn,{"aria-hidden":"true"})]}):null]}),R.map((P,O)=>t.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.jsx("span",{style:{fontSize:13,fontWeight:600},children:`{{${P}}}`}),t.jsx("input",{className:"cia-input",value:d[O]??"",onChange:K=>{const W=[...d];W[O]=K.target.value,u(W)},maxLength:1024})]},P)),_?t.jsxs("div",{style:{padding:"12px 14px",borderRadius:10,background:"var(--cia-bg-soft)",border:"1px solid var(--cia-border)"},children:[t.jsx("div",{style:{fontSize:11.5,fontWeight:600,color:"var(--cia-text-3)",marginBottom:6},children:i("whatsapp.enviarPlantilla.previa")}),t.jsx(aO,{componentes:_.aprobado??_.enviado,valores:R.map((P,O)=>d[O]??"")}),_.approvedBody===null?t.jsx("div",{style:{fontSize:11,color:"var(--cia-warn-ink)",marginTop:8},children:i("whatsapp.enviarPlantilla.sinCuerpoAprobado")}):null]}):null,t.jsxs("div",{className:"cia-row",style:{justifyContent:"flex-end",gap:8},children:[t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost",onClick:a,children:i("whatsapp.enviarPlantilla.cancelar")}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta",disabled:!_||A||E||I.isPending,onClick:()=>{g(null),I.mutate()},children:I.isPending?i("whatsapp.enviarPlantilla.enviando"):i("whatsapp.enviarPlantilla.enviar")})]})]})}):null}const iO=120,Pg=20,rO=600*1e3,kp=new Map,zg=new Map,Np=(e,a)=>`${e}:${a}`;function z1(e,a){const n=kp.get(Np(e,a));return n?n.vence<=Date.now()?(kp.delete(Np(e,a)),null):n.valor:null}async function D1(e,a){const n=[...a.ids].slice(0,Pg),s=[...a.ids].slice(Pg);a.ids=new Set(s),a.timer=null;let i={};try{i=(await T.post(`/whatsapp/conversations/${e}/media/urls`,{messageIds:n})).data??{}}catch{i={}}const r=Date.now();for(const o of n){const l=i[o]??null;l&&kp.set(Np(e,o),{valor:l,vence:r+rO});const c=a.esperas.get(o)??[];a.esperas.delete(o);for(const d of c)d(l)}a.ids.size&&D1(e,a)}function kr(e,a){const n=z1(e,a);if(n)return Promise.resolve(n);let s=zg.get(e);s||(s={ids:new Set,esperas:new Map,timer:null},zg.set(e,s)),s.ids.add(a);const i=new Promise(r=>{const o=s.esperas.get(a)??[];o.push(r),s.esperas.set(a,o)});return s.timer||(s.timer=setTimeout(()=>void D1(e,s),iO)),i}function Qh(e){const a=e?.mediaStatus;return a==="ready"?"listo":a==="pending"?"descargando":a==="unavailable"?"no_dis
975ponible":"ninguno"}function _o(e){if(!e)return null;if(e.esNotaDeVoz===!0)return"nota_de_voz";switch(e.type){case"image":return"imagen";case"sticker":return"sticker";case"video":return"video";case"audio":return"audio";case"document":return"documento"}const a=(e.mediaMimeType??"").toLowerCase();return a.startsWith("image/")?"imagen":a.startsWith("audio/")?"audio":a.startsWith("video/")?"video":a?"documento":null}const I1=/[‪-‮⁦-⁩‎‏؜]/g;function ru(e){const a=(e?.mediaFilename??"").replace(I1,"").trim();if(a)return a.slice(0,80);const n=_o(e);return n==="imagen"?"Imagen":n==="video"?"Video":n==="nota_de_voz"?"Nota de voz":n==="audio"?"Audio":n==="sticker"?"Sticker":"Archivo"}function oO(e){const a=(e?.mediaFilename??"").replace(I1,"").trim(),n=a.lastIndexOf("."),s=n>0?a.slice(n+1):"";if(/^[A-Za-z0-9]{1,4}$/.test(s))return s.toUpperCase();const i=_o(e);return i==="imagen"?"IMG":i==="video"?"VID":i==="audio"||i==="nota_de_voz"?"AUD":i==="sticker"?"STK":i==="documento"?"DOC":"FILE"}function Dg(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"";if(e<1024)return`${e} B`;const a=e/1024;if(a<1024)return`${a<10?a.toFixed(1):Math.round(a)} kB`;const n=a/1024;return`${n<10?n.toFixed(1):Math.round(n)} MB`}function lO(e){if(Qh(e)!=="listo")return!1;const a=_o(e);return a==="imagen"||a==="sticker"||a==="audio"||a==="nota_de_voz"||a==="video"}const cO=["👍","❤️","😂","😮","🙏"];function dO({conversationId:e,mensaje:a,onVer:n,reacciones:s,onIrACitado:i}){const{t:r}=M("misc"),[o,l]=m.useState(()=>z1(e,a.id)),[c,d]=m.useState(!1),[u,p]=m.useState(!1),f=m.useRef(null),x=Qh(a),h=_o(a),b=async()=>{if(o)return o;d(!0),p(!1);try{const N=await kr(e,a.id);if(!N)throw new Error("sin url");return l(N),N}catch{return p(!0),null}finally{d(!1)}},g=m.useCallback(N=>{if(!N){f.current?.disconnect(),f.current=null;return}if(o||typeof IntersectionObserver>"u")return;const S=new IntersectionObserver(_=>{_.some(R=>R.isIntersecting)&&(S.disconnect(),kr(e,a.id).then(R=>R?l(R):p(!0)))},{rootMargin:"200px"});f.current=S,S.observe(N)},[e,a.id,o]),v=N=>{const S=document.createElement("a");S.href=N.urlDescarga,S.download=N.filename,S.rel="noopener",document.body.appendChild(S),S.click(),S.remove()},y=async()=>{p(!1);const N=await kr(e,a.id);N?v(N):p(!0)},k=N=>t.jsx(Lt,{icon:t.jsx(Tn,{size:14}),label:r("whatsapp.inbox.media.descargarArchivo",{nombre:ru(a)}),size:"sm",variant:N,onClick:()=>void y()}),w=async()=>{if(n&&(h==="imagen"||h==="sticker"||h==="video")){n(a.id);return}const N=await b();N&&(N.url===N.urlDescarga?v(N):window.open(N.url,"_blank","noopener,noreferrer"))},j=(a.text??"").trim(),C=a.textoAparte?"":a.opciones?j.split(`
976`)[0].trim():j;return t.jsxs("div",{className:"cia-msg-cuerpo",children:[a.replyTo?t.jsx("button",{type:"button",className:"cia-msg-cita",disabled:!a.replyTo.id||!i,onClick:a.replyTo.id&&i?()=>i(a.replyTo.id):void 0,children:a.replyTo.resumen||r("whatsapp.inbox.cita.yaNoEsta")}):null,x!=="ninguno"?t.jsxs("div",{className:"cia-msg-adjunto","data-clase":h??"archivo","data-estado":x,children:[x==="descargando"?t.jsx("span",{className:"cia-msg-adjunto-estado",children:r("whatsapp.inbox.media.descargando")}):x==="no_disponible"?t.jsx("span",{className:"cia-msg-adjunto-estado","data-tono":"warn",children:r(`whatsapp.mediaErrors.${a.mediaError??"descarga_fallida"}`,{defaultValue:r("whatsapp.inbox.media.noDisponible")})}):h==="audio"||h==="nota_de_voz"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"cia-msg-adjunto-fila",children:[t.jsx($_,{className:"cia-msg-audio",resolveSrc:async()=>{const N=await kr(e,a.id);if(!N)throw new Error("sin url");return N.url},playLabel:r("whatsapp.inbox.media.reproducir"),pauseLabel:r("whatsapp.inbox.media.pausar"),errorLabel:r("whatsapp.inbox.media.noSePudoAbrir"),speedLabel:r("whatsapp.inbox.media.velocidad")}),k("ghost")]}),t.jsx(pO,{mensaje:a})]}):h==="video"?t.jsx("span",{ref:g,style:{display:"block",minHeight:o?void 0:150},children:o?t.jsxs("span",{className:"cia-msg-adjunto-marco",children:[t.jsx("video",{className:"cia-msg-video",src:o.url,controls:!0,preload:"metadata"}),t.jsx("span",{className:"cia-msg-adjunto-bajar",children:k("overlay")})]}):u?t.jsx("span",{className:"cia-msg-adjunto-estado","data-tono":"warn",children:r("whatsapp.inbox.media.noSePudoAbrir")}):t.jsx("span",{className:"cia-msg-adjunto-cargando","aria-hidden":!0})}):h==="imagen"||h==="sticker"?t.jsxs("span",{className:"cia-msg-adjunto-marco",children:[t.jsx("button",{type:"button",className:"cia-msg-adjunto-visual","data-clase":h,onClick:w,"aria-label":r("whatsapp.inbox.media.ver"),ref:g,children:o?t.jsx("img",{src:o.url,alt:a.text?.trim()||ru(a),loading:"lazy",decoding:"async"}):u?t.jsx("span",{className:"cia-msg-adjunto-estado","data-tono":"warn",children:r("whatsapp.inbox.media.noSePudoAbrir")}):t.jsx("span",{className:"cia-msg-adjunto-cargando","aria-hidden":!0})}),o?t.jsx("span",{className:"cia-msg-adjunto-bajar",children:k("overlay")}):null]}):t.jsxs("button",{type:"button",className:"cia-msg-adjunto-abrir","data-ext":oO(a),onClick:w,disabled:c,
976children:[t.jsx("span",{className:"cia-msg-adjunto-nombre",children:ru(a)}),Dg(a.mediaSizeBytes)?t.jsx("span",{className:"cia-msg-adjunto-peso",children:Dg(a.mediaSizeBytes)}):null,t.jsx("span",{className:"cia-msg-adjunto-accion",children:c?r("whatsapp.inbox.media.abriendo"):lO(a)?r("whatsapp.inbox.media.ver"):r("whatsapp.inbox.media.descargar")})]}),u?t.jsx("span",{className:"cia-msg-adjunto-estado","data-tono":"warn",children:r("whatsapp.inbox.media.noSePudoAbrir")}):null]}):null,a.opciones?t.jsxs("div",{className:"cia-msg-opciones","data-clase":a.opciones.clase,children:[a.opciones.titulos.map((N,S)=>t.jsx("span",{className:"cia-msg-opcion",children:N},`${N}-${S}`)),a.opciones.url?t.jsx("span",{className:"cia-msg-opcion-destino",title:a.opciones.url,children:a.opciones.url}):null]}):null,a.eleccion?t.jsxs("div",{className:"cia-msg-eleccion",children:[t.jsx("span",{className:"cia-msg-eleccion-titulo",children:a.eleccion.titulo}),a.eleccion.descripcion?t.jsx("span",{className:"cia-msg-eleccion-desc",children:a.eleccion.descripcion}):null]}):null,a.ubicacion?t.jsxs("a",{className:"cia-msg-ubicacion",href:`https://www.openstreetmap.org/?mlat=${a.ubicacion.lat}&mlon=${a.ubicacion.lng}#map=16/${a.ubicacion.lat}/${a.ubicacion.lng}`,target:"_blank",rel:"noopener noreferrer",children:[t.jsx("span",{className:"cia-msg-ubicacion-nombre",children:a.ubicacion.nombre??r("whatsapp.inbox.location.compartida")}),a.ubicacion.direccion?t.jsx("span",{className:"cia-msg-ubicacion-dir",children:a.ubicacion.direccion}):null]}):null,a.contactos?.length?t.jsx("div",{className:"cia-msg-contactos",children:a.contactos.map((N,S)=>t.jsxs("div",{className:"cia-msg-contacto",children:[t.jsx("span",{className:"cia-msg-contacto-nombre",children:N.nombre}),N.telefonos.map(_=>t.jsx("span",{className:"cia-msg-contacto-tel",children:_},_))]},`${N.nombre}-${S}`))}):null,C?t.jsx("span",{className:"cia-msg-texto",children:C}):null,!C&&x==="ninguno"&&!a.ubicacion&&!a.contactos?.length?t.jsx("span",{className:"cia-msg-texto",children:r("whatsapp.inbox.noText")}):null,s&&s.length>0?t.jsx("span",{className:"cia-msg-reacciones",children:s.map(N=>t.jsxs("span",{className:"cia-msg-reaccion","data-propia":N.propia||void 0,children:[t.jsx("span",{"aria-hidden":!0,children:N.emoji}),N.cuantas>1?t.jsx("span",{className:"cia-msg-reaccion-n",children:N.cuantas}):null]},N.emoji))}):null]})}function uO({onResponder:e,onReaccionar:a,reacciones:n}){const{t:s}=M("misc");return!e&&!a?null:t.jsxs("span",{className:"cia-msg-acciones",children:[e?t.jsx("button",{type:"button",className:"cia-msg-accion",onClick:e,title:s("whatsapp.inbox.responder"),"aria-label":s("whatsapp.inbox.responder"),children:t.jsx(Yb,{size:13,"aria-hidden":!0})}):null,a?cO.map(i=>{const r=n?.some(o=>o.emoji===i&&o.propia)??!1;return t.jsx("button",{type:"button",className:"cia-msg-accion","data-puesta":r||void 0,onClick:()=>a(r?"":i),title:s(r?"whatsapp.inbox.quitarReaccion":"whatsapp.inbox.reaccionar"),"aria-label":s(r?"whatsapp.inbox.quitarReaccion":"whatsapp.inbox.reaccionar"),"aria-pressed":r,children:t.jsx("span",{"aria-hidden":!0,children:i})},i)}):null]})}function pO({mensaje:e}){const{t:a}=M("misc"),n=e.transcriptStatus??null,s=(e.transcript??"").trim();if(!n&&!s)return null;if(s)return t.jsx("p",{className:"cia-msg-transcript",lang:e.transcriptLang??void 0,children:s});const i=n==="pending"?"transcribiendo":n==="unavailable"?"sinVoz":"noSePudoTranscribir";return t.jsx("p",{className:"cia-msg-transcript","data-estado":n??void 0,children:a(`whatsapp.inbox.media.${i}`)})}function hO({tarjeta:e,occurredAt:a}){const{t:n}=M("misc"),s=dt(),i=e.quienInicio==="persona"?yn:ka,r={status:e.enCurso?"connected":"completed",endReason:e.resultado,endedAt:e.enCurso?null:a,durationSeconds:e.durationSeconds};return t.jsx("div",{className:"cia-msg-llamada",role:"group","aria-label":n(`whatsapp.inbox.llamada.${e.quienInicio}`),children:t.jsxs("div",{className:"cia-msg-llamada-card",children:[t.jsxs("div",{className:"cia-msg-llamada-fila",children:[t.jsx(i,{size:15,"aria-hidden":!0,className:"cia-msg-llamada-icono","data-quien":e.quienInicio}),t.jsx("strong",{className:"cia-msg-llamada-quien",children:n(`whatsapp.inbox.llamada.${e.quienInicio}`)}),t.jsx("span",{className:"cia-msg-llamada-fecha",children:Be(a)}),t.jsx("span",{className:"cia-msg-llamada-spacer"}),e.enCurso||e.resultado?t.jsx(No,{call:r}):null]}),t.jsx("div",{className:"cia-msg-llamada-datos",children:t.jsxs("span",{children:[n("whatsapp.inbox.llamada.duracion")," ",t.jsx("strong",{className:"cia-msg-llamada-duracion",children:e.enCurso?n("whatsapp.inbox.llamada.enCurso"):e.durationSeconds===null?"—":e.conecto?Ca(e.durationSeconds):n("whatsapp.inbox.llamada.noConecto")})]})}),t.jsx("span",{className:"cia-msg-llamada-nota",children:n("whatsapp.inbox.llamada.loHabladoNoEstaAca")}),e.callId?t.jsxs("button",{type:"button",className:"cia-msg-llamada-ver",onClick:()=>s({to:"/history",search:{callId:e.callId}}),children:[t.jsx(Ja,{size:13,"aria-hidden":!0}),n("whatsapp.inbox.llamada.verDetalle")]}):t.jsx("span",{className:"cia-msg-llamada-nota",children:n("whatsapp.inbox.llamada.sinDetalle")})]})})}const mO=["audio/webm","audio/ogg","audio/mpeg","audio/mp4","audio/aac","audio/wav","audio/x-wav","audio/amr","audio/3gpp"],fO=["audio/webm;codecs=opus","audio/webm","audio/mp4"];function xO(e){return String(e??"").split(";")[0].trim().toLowerCase()}function gO(e){for(const a of fO)if(e(a)&&mO.includes(xO(a)))return a;return null}const L1=300;function bO(e){return e>=L1}function Ig(e){const a=Math.max(0,Math.floor(e));return`${Math.floor(a/60)}:${String(a%60).padStart(2,"0")}`}function yO({deshabilitado:e,onMandar:a,labels:n}){const[s,i]=m.useState("quieto"),[r,o]=m.useState(0),[l,c]=m.useState(null),[d,u]=m.useState(null),p=m.useRef(null),f=m.useRef([]),x=m.useRef([]),[h]=m.useState(()=>typeof MediaRecorder>"u"?null:gO(j=>
976{try{return MediaRecorder.isTypeSupported(j)}catch{return!1}})),b=()=>{for(const j of f.current)try{j.stop()}catch{}f.current=[]},g=m.useRef(null);g.current=d,m.useEffect(()=>()=>{try{p.current?.stop()}catch{}b(),g.current&&URL.revokeObjectURL(g.current.url)},[]);const v=()=>{try{p.current?.stop()}catch{b(),i("quieto")}};m.useEffect(()=>{if(s!=="grabando")return;const j=setInterval(()=>{o(C=>{const N=C+1;return bO(N)&&v(),N})},1e3);return()=>clearInterval(j)},[s]);const y=async()=>{if(c(null),!!h)try{const j=await navigator.mediaDevices.getUserMedia({audio:!0});f.current=j.getTracks(),x.current=[];const C=new MediaRecorder(j,{mimeType:h});C.ondataavailable=N=>{N.data?.size&&x.current.push(N.data)},C.onstop=()=>{b();const N=new Blob(x.current,{type:h});if(!N.size){c(n.sinPermiso),i("quieto");return}u({blob:N,url:URL.createObjectURL(N),mime:h}),i("listo")},p.current=C,C.start(1e3),o(0),i("grabando")}catch{b(),c(n.sinPermiso),i("quieto")}},k=()=>{d&&URL.revokeObjectURL(d.url),u(null),o(0),i("quieto"),c(null)},w=async()=>{if(!d)return;if(i("mandando"),await a(d.blob,d.mime)){k();return}i("listo")};return h?s==="listo"||s==="mandando"?t.jsxs("span",{className:"cia-nota-de-voz","data-estado":s,children:[t.jsx("audio",{src:d?.url,controls:!0,preload:"metadata"}),t.jsx(Lt,{icon:t.jsx(mt,{}),variant:"outline",label:n.descartar,onClick:k,disabled:s==="mandando"}),t.jsx(Lt,{icon:t.jsx(Gr,{}),variant:"primary",label:n.mandar,onClick:w,loading:s==="mandando"})]}):t.jsxs("span",{className:"cia-nota-de-voz","data-estado":s,children:[t.jsx(Lt,{icon:s==="grabando"?t.jsx(ah,{}):t.jsx(Ta,{}),variant:"outline",tone:s==="grabando"?"bad":"default",active:s==="grabando",label:s==="grabando"?n.parar:n.grabar,onClick:s==="grabando"?v:y,disabled:e}),s==="grabando"?t.jsxs("span",{className:"cia-nota-de-voz-reloj","aria-live":"polite",children:[Ig(r)," / ",Ig(L1)]}):null,l&&s!=="grabando"?t.jsx("span",{className:"cia-nota-de-voz-error",children:l}):null]}):null}function vO({conversationId:e,medios:a,inicial:n,onCerrar:s}){const{t:i}=M("misc"),[r,o]=m.useState(()=>Math.max(0,a.findIndex(h=>h.id===n))),[l,c]=m.useState(null),[d,u]=m.useState(!1),p=a[r],f=m.useCallback(h=>{o(b=>{const g=b+h;return g<0||g>=a.length?b:g})},[a.length]);if(m.useEffect(()=>{let h=!0;if(c(null),u(!1),!!p)return kr(e,p.id).then(b=>{h&&(b?c(b):u(!0))}),()=>{h=!1}},[e,p]),!p)return null;const x=a.length>1;return t.jsx(rE,{open:!0,onClose:s,ariaLabel:i("whatsapp.inbox.visor.titulo"),onPrev:x?()=>f(-1):void 0,onNext:x?()=>f(1):void 0,prevDisabled:r===0,nextDisabled:r===a.length-1,prevLabel:i("whatsapp.inbox.visor.anterior"),nextLabel:i("whatsapp.inbox.visor.siguiente"),toolbar:t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"cia-visor-quien",children:[t.jsx("strong",{children:p.autor}),t.jsx("span",{children:p.fecha}),x?t.jsx("span",{className:"cia-visor-cuenta",children:i("whatsapp.inbox.visor.deTotal",{n:r+1,total:a.length})}):null]}),t.jsx("span",{className:"cia-visor-spacer"}),l?t.jsx("span",{className:"cia-visor-acciones",children:t.jsxs("a",{className:"cia-btn cia-btn-sm",href:l.urlDescarga,download:l.filename,"aria-label":i("whatsapp.inbox.media.descargarArchivo",{nombre:l.filename}),children:[t.jsx(Tn,{size:15,"aria-hidden":!0}),t.jsx("span",{children:i("whatsapp.inbox.media.descargar")})]})}):null]}),children:t.jsx("div",{className:"cia-visor-medio",children:d?t.jsx("p",{className:"cia-visor-error",children:i("whatsapp.inbox.media.noSePudoAbrir")}):l?p.clase==="video"?t.jsx("video",{src:l.url,controls:!0,autoPlay:!0,playsInline:!0}):t.jsx("img",{src:l.url,alt:p.autor}):t.jsx("span",{className:"cia-visor-cargando","aria-hidden":!0})})})}function jO({conversationId:e,contactExternalId:a,llamadas:n,puedeLlamar:s,puedeVerLlamadas:i,puedeOperar:r,estadoEn:o}){const{t:l}=M("misc"),c=xe(),[d,u]=m.useState(!1),[p,f]=m.useState(""),[x,h]=m.useState(null),[b,g]=m.useState(!1),[v,y]=m.useState(null),k=n?.habilitadas===!0,w=se({queryKey:["wa-permiso-de-llamada",n?.waNumberId,a],enabled:k&&!!n?.waNumberId,staleTime:6e4,retry:!1,queryFn:async()=>(await T.get(`whatsapp/numbers/${n.waNumberId}/calling/permission`,{params:{contacto:a}})).data}),j=f1(v,i),C=j.phase==="dialing"||j.phase==="connected";m.useEffect(()=>{v&&(C||j.phase==="forbidden"||(y(null),c.invalidateQueries({queryKey:["wa-messages",e]}),c.invalidateQueries({queryKey:["wa-conversations"]})))},[v,C,j.phase,e,c]);const N=oe({mutationFn:async()=>(h(null),(await T.post(`whatsapp/numbers/${n.waNumberId}/calling/originate`,{destino:a,contactoExternalId:a})).data),onSuccess:E=>{g(!1),y(E.callId??null)},onError:E=>h(E?.response?.data?.message??l("whatsapp.calling.action.failed"))}),S=oe({mutationFn:async()=>{h(null),await T.post(`whatsapp/conversations/${e}/calling/permission-request`,{texto:p.trim()})},onSuccess:()=>{u(!1),f(""),g(!0),c.invalidateQueries({queryKey:["wa-messages",e]}),c.invalidateQueries({queryKey:["wa-conversations"]}),w.refetch()},onError:E=>h(E?.response?.data?.message??l("whatsapp.calling.action.failed"))}),_=XD(n,w.data,w.isLoading);if(_.clase==="nada"&&_.motivo==="sin_llamadas")return null;const R=JD(w.data?.venceEn),A=t.jsxs(t.Fragment,{children:[_.clase==="nada"&&_.motivo==="no_autoriza"?t.jsx(at,{tone:"neutral",label:l("whatsapp.calling.action.notAllowed"),icon:!1,truncate:!0}):null,_.clase==="nada"&&_.motivo==="no_se_sabe"?t.jsx(at,{tone:"neutral",label:l("whatsapp.calling.action.unknown"),icon:!1,truncate:!0}):null,v&&j.phase!=="forbidden"?t.jsx(No,{call:j.call??void 0,status:j.call?void 0:"dialing"}):null,v&&j.stalled?t.jsx(at,{tone:"warning",label:l("whatsapp.calling.action.live.stalled")}):null,v&&j.phase==="forbidden"?t.jsx(at,{tone:"neutral",label:l("whatsapp.calling.action.live.started"),icon:!1}):null,b&&_.clase!=="llamar"?t.jsx(at,{tone:"neutral",label:l("whatsapp.calling.action.requestSent"),icon:!1}):null,x?t.jsx("span",{className:"cia-inbox-error",role:"alert",children:x}):null]});return t.jsxs(t.Fragment,{children:[_.clase==="llamar"&&s?t.jsx(Lt,{icon:t.jsx(ka,{}),label:[l("whatsapp.calling.action.call"),R!==null?l("whatsapp.calling.action.expiresIn",{days:R}
976):null].filter(Boolean).join(" · "),onClick:()=>N.mutate(),disabled:N.isPending||C,loading:N.isPending,tooltipPosition:"bottom"}):null,_.clase==="pedir_permiso"&&r?t.jsx(Lt,{icon:t.jsx(Ma,{}),label:l("whatsapp.calling.action.askPermission"),onClick:()=>u(!0),disabled:S.isPending,tooltipPosition:"bottom"}):null,o?Ti.createPortal(A,o):A,t.jsxs(ot,{open:d,onClose:()=>u(!1),title:l("whatsapp.calling.action.askTitle"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{onClick:()=>u(!1),children:l("whatsapp.calling.action.askCancel")}),t.jsx(Ie,{variant:"primary",onClick:()=>S.mutate(),loading:S.isPending,disabled:p.trim().length===0,disabledReason:l("whatsapp.calling.action.askVacia"),children:l("whatsapp.calling.action.askSend")})]}),children:[t.jsx("p",{className:"cia-muted",children:l("whatsapp.calling.action.askQuota")}),t.jsx("textarea",{className:"cia-input",rows:3,maxLength:1024,value:p,placeholder:l("whatsapp.calling.action.askPlaceholder"),onChange:E=>f(E.target.value)}),w.data?.solicitudesRestantes!==null&&w.data?.solicitudesRestantes!==void 0?t.jsx("p",{className:"cia-muted",children:l("whatsapp.calling.action.askRemaining",{count:w.data.solicitudesRestantes})}):null,x?t.jsx("p",{className:"cia-inbox-error",children:x}):null]})]})}function wO({conversationId:e,esSuperadmin:a}){const{t:n}=M("misc"),[s,i]=m.useState(!1),[r,o]=m.useState(null),l=se({queryKey:["wa-costo-conversacion",e],queryFn:()=>T.get(`/whatsapp/conversations/${e}/costo`,{_sesionReal:!0}).then(d=>d.data),enabled:a&&s});if(!a)return null;const c=(d,u)=>d==null?t.jsx("span",{style:{color:"var(--cia-text-3)"},children:n("costoConversacion.sinCotizar")}):t.jsxs("span",{style:{fontVariantNumeric:"tabular-nums"},children:[u?"≥ ":"","$",d.toFixed(6)]});return t.jsx(mh,{title:n("costoConversacion.titulo"),icon:jc,open:s,onToggle:()=>i(d=>!d),children:t.jsx("div",{style:{display:"grid",gap:10},children:s&&(l.isLoading?t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-3)"},children:n("costoConversacion.cargando")}):l.isError?t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-3)"},children:n("costoConversacion.error")}):l.data?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gap:8,gridTemplateColumns:"repeat(auto-fit,minmax(190px,1fr))"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("costoConversacion.agente")}),t.jsx("div",{style:{fontSize:15},children:c(l.data.total.totalUsd,l.data.total.parcial)}),t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("costoConversacion.enTurnos",{n:l.data.turnos.length})})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("costoConversacion.entrega")}),t.jsx("div",{style:{fontSize:15},children:c(l.data.entrega.totalUsd,l.data.entrega.parcial)}),(l.data.entrega.sinCotizar??0)>0&&t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-warn-ink)"},children:n("costoConversacion.sinCotizarN",{n:l.data.entrega.sinCotizar,total:l.data.entrega.mensajes??0})})]})]}),t.jsxs("div",{style:{borderTop:"1px solid var(--cia-border-2)",paddingTop:8,display:"flex",justifyContent:"space-between",alignItems:"baseline",fontSize:13.5},children:[t.jsx("span",{style:{color:"var(--cia-text-2)"},children:n("costoConversacion.granTotal")}),t.jsx("strong",{children:c(l.data.granTotal.totalUsd,l.data.granTotal.parcial)})]}),l.data.llamadas&&l.data.llamadas.cantidad>0&&t.jsxs("div",{style:{borderTop:"1px solid var(--cia-border-2)",paddingTop:8,display:"grid",gap:6},children:[t.jsx("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:n("costoConversacion.llamadas.titulo",{n:l.data.llamadas.cantidad,min:l.data.llamadas.minutos})}),t.jsxs("div",{style:{display:"grid",gap:8,gridTemplateColumns:"repeat(auto-fit,minmax(190px,1fr))"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("costoConversacion.llamadas.costoIa")}),t.jsx("div",{style:{fontSize:14},children:c(l.data.llamadas.costoIaUsd,l.data.llamadas.costoIaEsPiso)})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("costoConversacion.llamadas.estimadoMeta")}),t.jsx("div",{style:{fontSize:14},children:l.data.llamadas.estimadoMetaUsd==null?c(null):t.jsxs("span",{style:{fontVariantNumeric:"tabular-nums"},children:[s1(l.data.llamadas.estimadoEsPiso)," $",l.data.llamadas.estimadoMetaUsd.toFixed(6)]})}),t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-text-3)"},children:n("costoConversacion.llamadas.facturaDirecta")}),l.data.llamadas.sinTarifa>0&&t.jsx("div",{style:{fontSize:11.5,color:"var(--cia-warn-ink)"},children:n("costoConversacion.llamadas.sinTarifaN",{n:l.data.llamadas.sinTarifa})})]})]})]}),l.data.turnos.length>0&&t.jsx("div",{className:"cia-scroll-x",style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",fontSize:12.5,borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{textAlign:"left",color:"var(--cia-text-3)"},children:[t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:n("costoConversacion.cuando")}),t.jsx("th",{style:{padding:"3px 8px 3px 0",fontWeight:500},children:n("costoConversacion.modelo")}),t.jsx("th",{style:{padding:"3px 0",fontWeight:500,textAlign:"right"},children:n("costoConversacion.costo")})]})}),t.jsx("tbody",{children:l.data.turnos.map(d=>t.jsxs(m.Fragment,{children:[t.jsxs("tr",{style:{borderTop:"1px solid var(--cia-border-2)"},children:[t.jsx("td",{style:{padding:"5px 8px 5px 0",whiteSpace:"nowrap"},children:d.trazado?t.jsxs("button",{type:"button",onClick:()=>o(r===d.id?null:d.id),"aria-expanded":r===d.id,style:{background:"none",border:"none",padding:0,cursor:"pointer",color:"inherit",font:"inherit",display:"inline-flex",alignItems:"center",gap:5},children:[t.jsx("span",{style:{color:"var(--cia-text-3)",fontSize:10},children:r===d.id?"▾":"▸"}),Be(d.occurredAt)]}):Be(d.occurredAt)}),t.jsxs("td",{style:{padding:"5px 8px 5px 0",color:"var(--cia-text-2)"},children:[d.model??"—",d.errorCode&&t.jsxs("span",{style:{color:d.errorCode==="llego_otro_globo"?"var(--cia-text-3)":"var(--cia-bad-500)"},children:[" · ",n(`costoConversacion.motivoDeTurno.${d.errorCode}`,{defaultValue:d.errorCode})]}),!d.trazado&&t.jsxs("span",{style:{color:"var(--cia-text-3)"},children:[" · ",n("costoConversacion.sinTrazar")]})]}),t.jsxs("td",{style:{padding:"5px 0",textAlign:"right"},children:[d.parcial&&"≥ ",c(d.totalTrazadoUsd??d.costUsd)]})]}),r===d.id&&d.cobros.map((u,p)=>t.jsxs("tr",{style:{fontSize:12},children:[t.jsx("td",{style:{padding:"3px 8px 3px 16px",color:"var(--cia-text-3)"},children:n(`costoConversacion.concepto.${u.concept}`,{defaultValue:u.concept})}),t.jsxs("td",{style:{padding:"3px 8px 3px 0",color:"var(--cia-text-3)"},children:[u.quantity," ",n(`costoConversacion.unidad.${u.unit}`,{defaultValue:u.unit}),u.model?` · ${u.model}`:""]}),t.jsx("td",{style:{padding:"3px 0",textAlign:"right",color:"var(--cia-text-3)"},children:u.providerCostUsd===null?n("costoConversacion.sinCotizar"):c(u.providerCostUsd)})]},`${d.id}-${u.concept}-${p}`))]},d.id))})]})})]}):null)})})}function kO(e){return(e.acciones?.length??0)>0||(e.fallidos??0)>0||(e.pendiente??"")!==""||(e.modelos?.length??0)>1}function NO({conversationId:e,puedeVer:a}){const{t:n}=M("misc"),[s,i]=m.useState(!1),o=e0("(max-height: 800px), (max-width: 480px)")?1:3,l=se({queryKey:["wa-informe-traspaso",e],queryFn:async()=>(await T.get(`/whatsapp/conversations/${e}/informe`)).data,enabled:a,staleTime:3e4});if(!a)return null;const c=l.data;if(!c||!kO(c))return null;const d=c.intentosSinLograr>0?t.jsx(at,{tone:"danger",label:n("whatsapp.informe.chipSinLograr",{n:c.intentosSinLograr})}):c.pendiente?t.jsx(at,{tone:"warning",label:n("whatsapp.informe.chipPendiente")}):c.acciones.length>0?t.jsx(at,{tone:"neutral",label:n("whatsapp.informe.chipAcciones",{n:c.acciones.length}),icon:!1}):null,u=[n("whatsapp.informe.turnos",{n:c.turnos}
976),c.desde&&c.hasta?`${Be(c.desde)} → ${Be(c.hasta)}`:null,c.fallidos>0?n("whatsapp.informe.fallidos",{n:c.fallidos}):null].filter(Boolean).join(" · ");return t.jsx(Rs,{title:n("whatsapp.informe.titulo"),icon:_S,hint:u,aside:d,children:t.jsx("div",{style:{display:"grid",gap:8},children:c?t.jsxs(t.Fragment,{children:[c.pendiente?t.jsx(le,{tone:"warn",children:c.pendiente}):null,c.intentosSinLograr>0?t.jsx(le,{tone:"bad",children:n("whatsapp.informe.revisarChat",{n:c.intentosSinLograr})}):null,c.modelos.length>1?t.jsx(le,{tone:"warn",children:n("whatsapp.informe.dosModelos",{modelos:c.modelos.join(" → ")})}):null,c.acciones.length>0?t.jsxs("div",{children:[t.jsx("ul",{className:"cia-informe-acciones",children:(s?c.acciones:c.acciones.slice(-o)).map((p,f)=>t.jsxs("li",{title:p.say||void 0,"data-tono":p.escribe?p.logrado?"ok":"bad":"neutral",children:[t.jsx("span",{className:"cia-informe-icono","aria-hidden":!0,children:p.escribe?p.logrado?t.jsx(Nt,{size:13}):t.jsx(cs,{size:13}):t.jsx(Mn,{size:12})}),t.jsx("span",{className:"cia-informe-op",children:n(`whatsapp.informe.op.${p.op}`,{defaultValue:p.op})}),p.say?t.jsx("span",{className:"cia-informe-say",children:p.say}):null]},`${p.op}-${f}`))}),c.acciones.length>o?t.jsx("button",{type:"button",className:"cia-inbox-ver-todas",onClick:()=>i(p=>!p),children:s?n("whatsapp.informe.verMenos"):n("whatsapp.informe.verTodos",{n:c.acciones.length})}):null]}):null,c.fallas.length>0?t.jsxs("div",{style:{fontSize:12,color:"var(--cia-text-3)"},children:[n("whatsapp.informe.fallas")," ",c.fallas.map(p=>p.errorCode??n("whatsapp.informe.sinCodigo")).join(" · ")]}):null]}):null})})}function F1(e){const a=(e.etiquetas??[]).map(n=>n.id).sort().join(",");return[e.state,e.mode,e.assigneeUserId??"",e.snoozedUntil??"",a].join("|")}async function O1(e){return(await T.get(`/whatsapp/conversations/${e}/ficha`)).data}function SO(e){return se({queryKey:["wa-ficha",e.id,F1(e)],queryFn:()=>O1(e.id),staleTime:6e4,placeholderData:a=>a?.conversationId===e.id?a:void 0})}function CO(e){return se({queryKey:["wa-ficha",e?.id??null,e?F1(e):""],queryFn:()=>O1(e.id),enabled:!!e,staleTime:6e4})}function Lg(e){const a=(e.telefono??"").trim();if(a)return a;const n=(e.usuarioDeWhatsapp??"").trim();return n?`@${n}`:null}const _O={open:"success",snoozed:"warning",closed:"neutral"};function EO({conversacion:e}){const{t:a}=M("misc"),n=Pe(u=>u.user),s=lt(n,"workflows.view"),i=S1(e.id,R1(e),{enabled:s});if(!s||!i.data?.disponible)return null;const r=i.data.corrida,o=H6(r);if(!r||!o)return null;const l=o.detalle.params?.evento,c=a(o.detalle.clave,{...o.detalle.params??{},...l?{evento:a(K6(l),{defaultValue:l})}:{},cuando:o.detalle.hastaIso?Ci(o.detalle.hastaIso).replace(/ /g," "):void 0}),d=o.tono==="aviso";return t.jsx("div",{className:"cia-ficha-flujo","data-tono":o.tono,children:t.jsx(Ws,{variant:"plain",size:"sm",icon:d?Tt:en,tone:d?"var(--cia-warn-ink)":"var(--cia-info-ink)",title:a(o.titulo.clave,o.titulo.params),subtitle:c,tooltip:o.detalle.hastaIso?Be(o.detalle.hastaIso):void 0,trailing:t.jsxs(et,{to:"/workflows/$flowId",params:{flowId:r.flowId},search:{tab:"corridas"},className:"cia-ficha-enlace","aria-label":a("flows.bandeja.ficha.verCorridaDe",{nombre:r.flowName}),children:[a("flows.bandeja.ficha.verCorrida"),t.jsx(nn,{"aria-hidden":"true"})]})})})}function AO({conversacion:e,tipificaciones:a,puedeVerContactos:n=!1}){const{t:s}=M("misc"),i=SO(e),r=Bc(),o=e.contactName||e.contactExternalId,l=e.etiquetas?.length??0,c=(b,g)=>t.jsx(Rs,{title:s("whatsapp.inbox.ficha.tipificaciones"),icon:Hl,aside:l>0?t.jsx("span",{className:"cia-inbox-sub",children:l}):void 0,children:a(b,g)});if(i.isError)return t.jsxs(t.Fragment,{children:[t.jsx(le,{tone:"warn",children:s("whatsapp.inbox.ficha.error")}),c(void 0,void 0)]});const d=i.data;if(!d)return t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},"aria-busy":"true",children:[t.jsx(ge,{h:52,r:8}),t.jsx(ge,{h:14,w:"60%"}),t.jsx(ge,{h:14,w:"80%"}),t.jsx(ge,{h:14,w:"50%"})]}),c(void 0,void 0)]});const u=d.estado==="snoozed"&&d.snoozedUntil?s("whatsapp.inbox.posponer.hasta",{cuando:Be(d.snoozedUntil)}):s(`whatsapp.inbox.${d.estado==="snoozed"?"snoozedBadge":d.estado}
976`),p=d.atiende.tipo==="persona"?d.atiende:null,f=p?r.data?.find(b=>b.id===p.id):void 0,x=d.linea?.numero?[d.linea.numero,d.linea.nombre].filter(Boolean).join(" · "):null,h=p?t.jsxs("span",{className:"cia-ficha-atiende",title:f?.email,children:[t.jsx(Sn,{name:f?.name??p.nombre??"?",size:"sm"}),t.jsx("span",{className:"cia-ficha-atiende-nombre",children:f?.name??p.nombre??s("whatsapp.inbox.ficha.alguienDelEquipo")})]}):d.atiende.tipo==="asistente"?t.jsxs("span",{className:"cia-ficha-atiende",children:[t.jsx("span",{className:"cia-ficha-atiende-icono","aria-hidden":!0,children:t.jsx(Ft,{size:13})}),t.jsx("span",{className:"cia-ficha-atiende-nombre",children:d.atiende.agenteNombre?`${s("whatsapp.inbox.ficha.asistente")} · ${d.atiende.agenteNombre}`:s("whatsapp.inbox.ficha.asistente")})]}):t.jsxs("span",{className:"cia-ficha-atiende",title:s("whatsapp.inbox.ficha.sinAsignarSub"),children:[t.jsx("span",{className:"cia-ficha-atiende-icono","data-tono":"nadie","aria-hidden":!0,children:t.jsx(mo,{size:13})}),t.jsx("span",{className:"cia-ficha-atiende-nombre",children:s("whatsapp.inbox.ficha.sinAsignar")})]});return t.jsxs(t.Fragment,{children:[t.jsx(Ws,{variant:"plain",leading:t.jsx(Sn,{name:o}),title:o,subtitle:d.telefono??(d.usuarioDeWhatsapp?`@${d.usuarioDeWhatsapp}`:d.identificadorDeUsuario)??void 0,subtitleMono:!0,trailing:t.jsx(at,{tone:_O[d.estado],label:u,icon:!1})}),t.jsx(EO,{conversacion:e}),t.jsxs(Rs,{title:s("whatsapp.inbox.ficha.datosDelContacto"),icon:En,hint:s("whatsapp.inbox.ficha.hintContacto"),aside:d.contactId&&n&&Lg(d)?t.jsxs(et,{to:"/contactos",search:{q:Lg(d)??void 0},className:"cia-ficha-enlace",children:[s("whatsapp.inbox.ficha.verEnContactos"),t.jsx(nn,{"aria-hidden":"true"})]}):void 0,children:[t.jsx(Zt,{inline:!0,label:s("whatsapp.inbox.ficha.telefono"),mono:!!d.telefono,action:d.telefono?t.jsx(kl,{value:d.telefono,label:s("whatsapp.inbox.ficha.copiarTelefono")}):void 0,children:d.telefono??t.jsx("span",{className:"cia-inbox-sub",children:s("whatsapp.inbox.ficha.sinTelefono")})}),t.jsx(Zt,{inline:!0,label:s("whatsapp.inbox.ficha.usuarioDeWhatsapp"),action:d.usuarioDeWhatsapp?t.jsx(kl,{value:`@${d.usuarioDeWhatsapp}`,label:s("whatsapp.inbox.ficha.copiarUsuario")}):void 0,children:d.usuarioDeWhatsapp?`@${d.usuarioDeWhatsapp}`:t.jsx("span",{className:"cia-inbox-sub",children:s("whatsapp.inbox.ficha.sinUsuario")})}),!d.telefono&&!d.usuarioDeWhatsapp&&d.identificadorDeUsuario?t.jsx(Zt,{inline:!0,label:s("whatsapp.inbox.ficha.identificador"),mono:!0,action:t.jsx(kl,{value:d.identificadorDeUsuario,label:s("whatsapp.inbox.ficha.copiarIdentificador")}),children:d.identificadorDeUsuario}):null]}),t.jsxs(Rs,{title:s("whatsapp.inbox.ficha.infoDelChat"),icon:sn,children:[x?t.jsx(Zt,{inline:!0,label:s("whatsapp.inbox.ficha.linea"),children:x}):null,t.jsx(Zt,{inline:!0,label:s("whatsapp.inbox.ficha.quienAtiende"),children:h}),t.jsx(Zt,{inline:!0,label:s("whatsapp.inbox.ficha.actividad"),children:t.jsxs("span",{title:`${s("whatsapp.inbox.ficha.creada")}: ${Be(d.creadaEl)} · ${s("whatsapp.inbox.ficha.ultimoMensaje")}: ${Be(e.lastMessageAt??d.ultimoMensajeEl)}`,children:[kn(d.creadaEl)," → ",kn(e.lastMessageAt??d.ultimoMensajeEl)]})}),d.cerradaEl?t.jsxs(Zt,{inline:!0,label:s("whatsapp.inbox.ficha.cerradaEl"),children:[Be(d.cerradaEl)," · ",d.cerradaPor?s("whatsapp.inbox.ficha.cerradaPorPersona",{nombre:d.cerradaPor.nombre??s("whatsapp.inbox.ficha.alguienDelEquipo")}):s("whatsapp.inbox.ficha.cerradaPorAsistente")]}):null]}),c(Object.fromEntries(d.etiquetas.map(b=>[b.id,b.puestaEl])),Object.fromEntries(d.etiquetas.flatMap(b=>b.puestaPor?[[b.id,b.puestaPor.nombre??s("whatsapp.inbox.ficha.alguienDelEquipo")]]:[])))]})}function Fg(e){const a=Math.max(0,Math.round(Number(e)||0));return a<60?`${a} s`:a<3600?`${Math.floor(a/60)} min`:a<86400?`${Math.floor(a/3600)} h`:`${Math.floor(a/86400)} d`}const ou=30;function RO({puedeVer:e}){const{t:a}=M("misc"),[n,s]=m.useState(!1),i=se({queryKey:["wa-metricas-servicio",ou],queryFn:async()=>(await T.get(`/whatsapp/conversations/servicio?dias=${ou}`)).data,enabled:e&&n,staleTime:5*6e4});if(!e)return null;const r=i.data;return t.jsx(mh,{title:a("whatsapp.servicio.titulo",{dias:ou}),icon:co,open:n,onToggle:()=>s(o=>!o),children:t.jsx("div",{style:{display:"grid",gap:12},children:n?i.isLoading?t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-3)"},children:a("whatsapp.servicio.cargando")}):i.isError?t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-3)"},children:a("whatsapp.servicio.error")}):r?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("div",{className:"cia-servicio-rotulo",children:a("whatsapp.servicio.primeraRespuesta")}),t.jsx("div",{className:"cia-servicio-grilla",children:[["agente",r.primeraRespuesta.agente],["equipo",r.primeraRespuesta.equipo]].map(([o,l])=>t.jsxs("div",{className:"cia-servicio-dato",children:[t.jsx("div",{className:"cia-servicio-quien",children:a(`whatsapp.servicio.${o}`)}),l?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"cia-servicio-numero",children:Fg(l.medianaSegundos)}),t.jsxs("div",{className:"cia-servicio-pie",children:[a("whatsapp.servicio.casos",{n:l.casos})," ·"," ",a("whatsapp.servicio.p90",{v:Fg(l.p90Segundos)})]})]}):t.jsx("div",{className:"cia-servicio-pie",children:a("whatsapp.servicio.sinCasos")})]},o))}),r.primeraRespuesta.sinResponder>0?t.jsx(le,{tone:"warn",children:a("whatsapp.servicio.sinResponder",{n:r.primeraRespuesta.sinResponder})}):null]}),t.jsxs("div",{children:[t.jsx("div",{className:"cia-servicio-rotulo",children:a("whatsapp.servicio.sinTraspaso")}),r.sinTraspaso.cerradas===0?t.jsx("div",{className:"cia-servicio-pie",children:a("whatsapp.servicio.sinCerradas")}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"cia-servicio-numero","data-juicio":r.sinTraspaso.muestraSuficiente?"1":void 0,children:[r.sinTraspaso.tasa,"%"]}),t.jsx("div",{className:"cia-servicio-pie",children:a("whatsapp.servicio.deCerradas",{sin:r.sinTraspaso.sinPersona,total:r.sinTraspaso.cerradas})}),r.sinTraspaso.muestraSuficiente?null:t.jsx("div",{className:"cia-servicio-pie","data-aviso":"1",children:a("whatsapp.servicio.muestraChica")})]})]}),t.jsx("p",{className:"cia-servicio-nota",children:a("whatsapp.servicio.comoSeCuenta")})]}):null:null})})}const lu=30;function TO({puedeVer:e,puedeCurar:a,filtrada:n,onFiltrar:s}){const{t:i}=M("misc"),[r,o]=m.useState(!1),l=se({queryKey:["wa-etiquetas-resumen",lu],queryFn:async()=>(await T.get(`/whatsapp/etiquetas/resumen?dias=${lu}`)).data,enabled:e&&r,staleTime:5*6e4}),c=se({queryKey:["wa-etiquetas-catalogo"],queryFn:async()=>(await T.get("/whatsapp/etiquetas")).data.items,enabled:e&&r,staleTime:5*6e4});if(!e)return null;const d=l.data,u=c.data??[],p=d?vF(d):null,f=a?t.jsxs(et,{to:"/whatsapp",search:{tab:"atencion"},className:"cia-wa-administrar",children:[i("whatsapp.etiquetas.administrar"),t.jsx(oa,{"aria-hidden":"true"})]}):null;return t.jsx(mh,{title:i("whatsapp.etiquetas.titulo",{dias:lu}),icon:Pu,open:r,onToggle:()=>
976o(x=>!x),children:t.jsx("div",{style:{display:"grid",gap:12},children:r?l.isLoading||c.isLoading?t.jsx("p",{className:"cia-inbox-sub",children:i("whatsapp.etiquetas.cargando")}):l.isError?t.jsx("p",{className:"cia-inbox-sub",children:i("whatsapp.etiquetas.error")}):t.jsxs(t.Fragment,{children:[u.length===0?t.jsx("p",{className:"cia-inbox-sub",children:i(a?"whatsapp.etiquetas.vacioPuedeCurarEnAtencion":"whatsapp.etiquetas.vacioSoloMira")}):null,d&&u.length>0?t.jsxs("div",{children:[d.etiquetas.length===0?t.jsx("p",{className:"cia-inbox-sub",children:i("whatsapp.etiquetas.sinUsoEnElPeriodo")}):t.jsx("div",{className:"cia-row",style:{gap:6,flexWrap:"wrap"},children:d.etiquetas.map(x=>t.jsx(ps,{label:x.nombre,tone:x.color,count:x.hilos,active:n===x.id,onClick:()=>s(n===x.id?null:x.id)},x.id))}),t.jsxs("p",{className:"cia-inbox-sub",style:{marginTop:8},children:[i("whatsapp.etiquetas.particion",{con:d.conEtiqueta,total:d.hilos,sin:d.sinEtiqueta}),p==null?null:` · ${i("whatsapp.etiquetas.sinTipificar",{pct:p})}`]}),d.etiquetas.length>1?t.jsx("p",{className:"cia-servicio-nota",children:i("whatsapp.etiquetas.comoSeCuenta")}):null]}):null,f]}):null})})}function $1({conversationId:e,puestas:a,puedeOperar:n,onCambio:s,fechas:i,autores:r}){const{t:o}=M("misc"),l=xe(),c=se({queryKey:["wa-etiquetas-catalogo"],queryFn:async()=>(await T.get("/whatsapp/etiquetas")).data.items,staleTime:5*6e4,enabled:!0}),d=oe({mutationFn:async h=>("poner"in h?await T.post(`/whatsapp/conversations/${e}/etiquetas`,{tagId:h.poner}):await T.delete(`/whatsapp/conversations/${e}/etiquetas/${h.quitar}`)).data.items,onSuccess:()=>{s(),l.invalidateQueries({queryKey:["wa-etiquetas-catalogo"]}
976),l.invalidateQueries({queryKey:["wa-etiquetas-resumen"]})}}),u=jF(c.data??[],a),p=(c.data?.length??0)>0,f=!!i&&a.length>0,x=h=>i?.[h]?r?.[h]?o("whatsapp.etiquetas.puestaElPor",{cuando:Be(i[h]),nombre:r[h]}):o("whatsapp.etiquetas.puestaEl",{cuando:Be(i[h])}):void 0;return t.jsxs("div",{className:f?void 0:"cia-row",style:f?{display:"flex",flexDirection:"column",gap:10,alignItems:"flex-start"}:{gap:6,flexWrap:"wrap",alignItems:"center"},children:[f?a.map(h=>t.jsx(Ws,{size:"sm",style:{alignSelf:"stretch"},icon:Hl,tone:`var(--cia-tag-${h.color??"gris"})`,title:h.nombre,meta:x(h.id),tooltip:x(h.id),trailing:n?t.jsx(Lt,{icon:t.jsx(nt,{size:14}),label:o("whatsapp.etiquetas.quitar",{nombre:h.nombre}),size:"sm",variant:"ghost",disabled:d.isPending,onClick:()=>d.mutate({quitar:h.id})}):void 0},h.id)):null,f?null:a.map(h=>t.jsx(ps,{label:h.nombre,tone:h.color,onRemove:n?()=>d.mutate({quitar:h.id}):void 0,removeLabel:o("whatsapp.etiquetas.quitar",{nombre:h.nombre}),disabled:d.isPending},h.id)),n?p?t.jsx(vn,{disabled:d.isPending||u.length===0,"aria-label":o("whatsapp.etiquetas.agregar"),trigger:t.jsxs("span",{className:"cia-row",style:{gap:6,alignItems:"center"},children:[t.jsx(Hl,{size:13,"aria-hidden":!0}),o("whatsapp.etiquetas.agregar")]}),items:u.map(h=>({key:h.id,label:h.nombre,onSelect:()=>d.mutate({poner:h.id})}))}):a.length===0?t.jsx("span",{className:"cia-inbox-sub",children:o("whatsapp.etiquetas.sinCatalogo")}):null:null]})}function MO({conversationId:e,onCerrar:a,onIrAMensaje:n,avisoNoAlcanzado:s}){const{t:i}=M("misc"),[r,o]=m.useState(""),[l,c]=m.useState(""),[d,u]=m.useState(0);m.useEffect(()=>{const b=setTimeout(()=>c(r.trim()),300);return()=>clearTimeout(b)},[r]),m.useEffect(()=>u(0),[l]);const p=se({queryKey:["wa-buscar-en-hilo",e,l],queryFn:async()=>(await T.get(`/whatsapp/conversations/${e}/messages/buscar`,{params:{q:l}})).data.items,enabled:l.length>=2}),f=p.data??[],x=f.length,h=b=>{const g=f[b];g&&(u(b),n(g))};return t.jsxs("div",{className:"cia-inbox-buscar-hilo",onKeyDown:b=>{b.key==="Escape"?(b.stopPropagation(),a()):b.key==="Enter"&&x>0&&(b.preventDefault(),h((d+1)%x))},children:[t.jsxs("div",{className:"cia-inbox-buscar-hilo-fila",children:[t.jsx(ph,{size:"sm",value:r,onChange:o,placeholder:i("whatsapp.inbox.buscarHilo.placeholder"),width:"100%","aria-label":i("whatsapp.inbox.buscarHilo.placeholder")}),t.jsx(Lt,{icon:t.jsx(nt,{}),label:i("whatsapp.inbox.buscarHilo.cerrar"),size:"md",onClick:a,tooltipPosition:"bottom"})]}),l.length>=2&&t.jsxs("div",{className:"cia-inbox-buscar-hilo-nav",children:[t.jsx("span",{className:"cia-inbox-sub",children:p.isLoading?i("whatsapp.inbox.buscarHilo.buscando"):x===0?i("whatsapp.inbox.buscarHilo.sinResultados",{q:l}):i("whatsapp.inbox.buscarHilo.contador",{actual:d+1,total:x})}),t.jsx("span",{style:{flex:1}}),t.jsxs(Ll,{size:"sm",children:[t.jsx(Lt,{icon:t.jsx(Rn,{}),label:i("whatsapp.inbox.buscarHilo.anterior"),variant:"outline",disabled:x===0,onClick:()=>h((d-1+x)%x)}),t.jsx(Lt,{icon:t.jsx(Ut,{}),label:i("whatsapp.inbox.buscarHilo.siguiente"),variant:"outline",disabled:x===0,onClick:()=>h((d+1)%x)})]})]}),x>0&&t.jsx("div",{role:"listbox","aria-label":i("whatsapp.inbox.buscarHilo.placeholder"),className:"cia-inbox-buscar-hilo-resultados",children:f.map((b,g)=>t.jsxs("button",{type:"button",role:"option","aria-selected":g===d,className:"cia-inbox-buscar-hilo-item","data-activo":g===d||void 0,onClick:()=>h(g),children:[t.jsx("span",{className:"cia-mono cia-inbox-buscar-hilo-hora",children:cv(b.occurredAt)}),t.jsx("span",{className:"cia-inbox-buscar-hilo-fragmento",children:b.fragmento})]},b.id))}),s?t.jsx(le,{tone:"warn",children:i("whatsapp.inbox.buscarHilo.noAlcanzado")}):null]})}function PO({seleccionados:e,onCancelar:a,onCerrado:n}){const{t:s}=M("misc"),i=xe(),[r,o]=m.useState(!1),[l,c]=m.useState(""),d=se({queryKey:["wa-etiquetas-catalogo"],queryFn:async()=>(await T.get("/whatsapp/etiquetas")).data.items,staleTime:5*6e4}),u=(d.data?.length??0)>0,p=oe({mutationFn:async()=>(await T.post("/whatsapp/conversations/cerrar-lote",{ids:e,...l?{etiqueta:l}:{}})).data,onSuccess:h=>{o(!1),c(""),i.invalidateQueries({queryKey:["wa-conversations"]}),i.invalidateQueries({queryKey:jo}),n(h)}}),f=e.length,x=f>=wh;return t.jsxs("div",{className:"cia-inbox-seleccion-barra",children:[t.jsx("span",{className:"cia-mono",children:s("whatsapp.inbox.seleccion.contador",{count:f})}),x?t.jsx("span",{className:"cia-inbox-sub",children:s("whatsapp.inbox.seleccion.tope")}):null,t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-sm",onClick:a,children:s("whatsapp.inbox.seleccion.cancelar")}
976),t.jsx("button",{type:"button",className:"cia-btn cia-btn-sm cia-btn-cta",disabled:f===0,onClick:()=>o(!0),children:s(u?"whatsapp.inbox.seleccion.tipificarYCerrar":"whatsapp.inbox.seleccion.cerrarSinTipificar")}),t.jsx(ot,{open:r,onClose:()=>o(!1),title:s("whatsapp.inbox.seleccion.modalTitulo",{count:f}),footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"cia-btn",onClick:()=>o(!1),children:s("whatsapp.inbox.closeCancel")}),t.jsx("button",{type:"button",className:"cia-btn cia-btn-cta",disabled:p.isPending,onClick:()=>p.mutate(),children:s("whatsapp.inbox.seleccion.confirmar")})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx("p",{className:"cia-inbox-sub",children:s("whatsapp.inbox.seleccion.modalDesc")}),u?t.jsx(hn,{label:s("whatsapp.inbox.seleccion.etiquetaLabel"),value:l,onChange:c,placeholder:s("whatsapp.inbox.seleccion.etiquetaVacia"),options:(d.data??[]).map(h=>({value:h.id,label:h.nombre}))}):null,p.isError?t.jsx(le,{tone:"bad",children:s("whatsapp.inbox.seleccion.fallo")}):null]})})]})}function zO({seleccionando:e,onSeleccionar:a,onResumen:n,onEscribirPrimero:s,puedeResponder:i,avisos:r}){const{t:o}=M("misc");return t.jsxs("div",{className:"cia-waenc",children:[t.jsx("span",{className:"cia-waenc-icono","aria-hidden":"true",children:t.jsx(sn,{})}),t.jsx("h2",{className:"cia-waenc-titulo",children:o("whatsapp.inbox.encabezado.titulo")}),t.jsxs(Ll,{size:"md","aria-label":o("whatsapp.inbox.encabezado.acciones"),children:[i?t.jsx(Lt,{icon:t.jsx(KS,{}),label:o("whatsapp.inbox.seleccion.boton"),active:e,onClick:a,tooltipPosition:"bottom"}):null,t.jsx(Lt,{icon:t.jsx(us,{}),label:o("whatsapp.inbox.resumenBoton"),onClick:n,"aria-haspopup":"dialog",tooltipPosition:"bottom"}),r,i?t.jsx(Lt,{icon:t.jsx(Fe,{}),label:o("whatsapp.enviarPlantilla.abrirNuevo"),variant:"cta",shape:"circle",className:"cia-waenc-cta",onClick:s,"aria-haspopup":"dialog",tooltipPosition:"bottom"}):null]})]})}function Og(e,a){e.removeQueries({queryKey:["wa-messages",a]}),e.removeQueries({queryKey:["wa-messages-historial",a]}),e.removeQueries({queryKey:["wa-ficha",a]}),e.removeQueries({queryKey:["wa-notas",a]}),e.invalidateQueries({queryKey:["wa-conversations"]}),e.invalidateQueries({queryKey:jo}),e.invalidateQueries({queryKey:Wc})}function DO({open:e,onClose:a,conversationId:n,nombreDelContacto:s,onEliminada:i}){const{t:r}=M("misc"),o=xe(),[l,c]=m.useState(!1),d=m.useId(),u=oe({mutationFn:async x=>(await T.delete(`/whatsapp/conversations/${x}`)).data,onSuccess:(x,h)=>{Og(o,h),J({tone:"ok",title:r("whatsapp.inbox.eliminar.listo"),desc:x.archivosPendientes>0?r("whatsapp.inbox.eliminar.listoPendientes",{count:x.archivosPendientes}):r("whatsapp.inbox.eliminar.listoDesc")}),a(),i()},onError:(x,h)=>{ec(x)===404&&(Og(o,h),J({tone:"info",title:r("whatsapp.inbox.eliminar.yaNoExiste")}),a(),i())}}),p=u.isError&&ec(u.error)!==404?(()=>{const x=jR(u.error);return x?r(x):_a(u.error)??r("whatsapp.inbox.eliminar.falloDesc")})():null,f=[{icono:sn,clave:"borraMensajes"},{icono:Zp,clave:"borraMedios"},{icono:hy,clave:"borraNotas"}];return t.jsx(ot,{open:e,onClose:a,maxWidth:520,title:r("whatsapp.inbox.eliminar.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{"data-cia-autofocus":"",onClick:a,children:r("whatsapp.inbox.eliminar.cancelar")}
976),t.jsx(Ie,{variant:"danger",icon:t.jsx(mt,{}),disabled:!l,loading:u.isPending,onClick:()=>{l&&!u.isPending&&u.mutate(n)},children:r("whatsapp.inbox.eliminar.confirmar")})]}),children:t.jsxs("div",{className:"cia-waop-cuerpo",children:[t.jsx("p",{className:"cia-waop-desc",children:r("whatsapp.inbox.eliminar.intro",{nombre:s})}),t.jsxs("section",{className:"cia-waop-bloque","aria-labelledby":`${d}-borra`,children:[t.jsx("h4",{id:`${d}-borra`,className:"cia-waop-bloque-titulo",children:r("whatsapp.inbox.eliminar.seBorraTitulo")}),t.jsx("ul",{className:"cia-waop-items",children:f.map(({icono:x,clave:h})=>t.jsxs("li",{children:[t.jsx(x,{"aria-hidden":"true"}),t.jsx("span",{children:r(`whatsapp.inbox.eliminar.${h}`)})]},h))})]}),t.jsxs("section",{className:"cia-waop-bloque","aria-labelledby":`${d}-conserva`,children:[t.jsx("h4",{id:`${d}-conserva`,className:"cia-waop-bloque-titulo",children:r("whatsapp.inbox.eliminar.seConservaTitulo")}),t.jsx("ul",{className:"cia-waop-items",children:t.jsxs("li",{children:[t.jsx(oy,{"aria-hidden":"true"}),t.jsx("span",{children:r("whatsapp.inbox.eliminar.seConserva")})]})})]}),t.jsx("p",{className:"cia-waop-desc",children:r("whatsapp.inbox.eliminar.despues")}),t.jsx(mn,{checked:l,onChange:c,disabled:u.isPending,label:r("whatsapp.inbox.eliminar.entiendo")}),p?t.jsx(le,{tone:"bad",title:r("whatsapp.inbox.eliminar.fallo"),children:p}):null]})})}function IO({open:e,onClose:a,conversationId:n}){const{t:s}=M("misc"),i=xe(),[r,o]=m.useState("unaHora"),l=oe({mutationFn:async u=>(await T.patch(`/whatsapp/conversations/${u.id}/posponer`,{hasta:u.hasta})).data,onSuccess:(u,p)=>{tn(i,p.id),J({tone:"ok",title:s("whatsapp.inbox.posponerModal.listo"),desc:s("whatsapp.inbox.posponer.hasta",{cuando:Ci(p.hasta)})}),a()}}),c=new Date,d=Jl.map(u=>({value:u.clave,label:s(`whatsapp.inbox.posponer.${u.clave}`),description:s("whatsapp.inbox.posponerModal.vuelve",{cuando:Ci(rp(u.clave,c.getTime()),c)})}));return t.jsx(ot,{open:e,onClose:a,maxWidth:380,title:s("whatsapp.inbox.posponerModal.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{onClick:a,children:s("whatsapp.inbox.silenciar.cancelar")}
976),t.jsx(Ie,{variant:"cta",loading:l.isPending,onClick:()=>{l.isPending||l.mutate({id:n,hasta:rp(r,Date.now())})},children:s("whatsapp.inbox.posponerModal.confirmar")})]}),children:t.jsxs("div",{className:"cia-waop-cuerpo",children:[t.jsx("p",{className:"cia-waop-desc",children:s("whatsapp.inbox.posponer.explicacion")}),t.jsx(wo,{legend:s("whatsapp.inbox.posponer.accion"),opciones:d,value:r,onChange:u=>o(u),disabled:l.isPending}),l.isError?t.jsx(le,{tone:"bad",title:s("whatsapp.inbox.posponerModal.fallo"),children:_a(l.error)??s("whatsapp.inbox.menu.reintentar")}):null]})})}function LO({open:e,onClose:a,conversationId:n,nombreDelContacto:s}){const{t:i}=M("misc"),r=xe(),o=dt(),l=C1({enabled:e}),[c,d]=m.useState(""),u=g6(c),{lanzables:p,fuera:f}=Q6(l.data?.items??[]),x=p.find(k=>k.id===c)??null,h=()=>{a(),o({to:"/workflows"})},b=()=>{!x||u.isPending||u.mutate({conversationId:n},{onSuccess:()=>{tn(r,n),J({tone:"ok",title:i("flows.bandeja.lanzar.listo",{nombre:x.name}),desc:i("flows.bandeja.lanzar.listoDesc")}),a()}})},g=u.isError?(()=>{const k=G6(u.error);return k?i(k,{nombre:x?.name??""}):xn(u.error,i("flows.bandeja.lanzar.rechazo.generico"))})():null,v=l.isPending?i("flows.bandeja.lanzar.motivo.cargando"):x?void 0:i("flows.bandeja.lanzar.motivo.elegi");let y;return l.isPending?y=t.jsxs("div",{"aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"var(--cia-space-sm)"},children:[t.jsx(ge,{h:14,w:"40%"}),t.jsx(ge,{h:32,r:8}),t.jsx(ge,{h:12,w:"70%"})]}):l.isError?y=t.jsx(le,{tone:"bad",title:i("flows.bandeja.lanzar.errorLista"),action:{label:i("flows.modulo.reintentar"),icon:Na,onClick:()=>void l.refetch()},actionPlacement:"end",children:xn(l.error,i("flows.modulo.errorGenerico"))}):l.data===null?y=t.jsx(le,{tone:"info",children:i("flows.bandeja.lanzar.noDisponible")}):p.length===0?y=t.jsx(st,{mini:!0,icon:en,title:i("flows.bandeja.lanzar.vacioTitulo"),desc:i("flows.bandeja.lanzar.vacioDesc"),action:{label:i("flows.bandeja.lanzar.irAFlujos"),icon:nn,onClick:h}}):y=t.jsxs(t.Fragment,{children:[t.jsx(hn,{id:`lanzar-flujo-${n}`,label:i("flows.bandeja.lanzar.campo"),value:c,placeholder:i("flows.bandeja.lanzar.placeholder"),options:p.map(k=>({value:k.id,label:k.name})),disabled:u.isPending,disabledReason:u.isPending?i("flows.bandeja.lanzar.motivo.lanzando"):void 0,onChange:k=>{d(k),u.reset()}}),t.jsx("span",{className:"cia-waop-ayuda","aria-live":"polite",children:x&&(x.corridasVivas??0)>0?i("flows.bandeja.lanzar.enCurso",{count:x.corridasVivas??0}):""}),f>0?t.jsxs("p",{className:"cia-waop-ayuda",children:[i("flows.bandeja.lanzar.fuera",{count:f})," ",t.jsxs(et,{to:"/workflows",className:"cia-ficha-enlace",onClick:a,children:[i("flows.bandeja.lanzar.irAFlujos"),t.jsx(nn,{"aria-hidden":"true"})]})]}):null]}),t.jsx(ot,{open:e,onClose:a,maxWidth:420,title:i("flows.bandeja.lanzar.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{onClick:a,children:i("flows.modulo.cancelar")}),t.jsx(Ie,{variant:"cta",icon:t.jsx(en,{}),disabled:!!v,disabledReason:v,loading:u.isPending,onClick:b,children:i("flows.bandeja.lanzar.confirmar")})]}),children:t.jsxs("div",{className:"cia-waop-cuerpo",children:[t.jsx("p",{className:"cia-waop-desc",children:i("flows.bandeja.lanzar.desc",{nombre:s})}),y,g?t.jsx(le,{tone:"bad",title:i("flows.bandeja.lanzar.rechazo.titulo"),children:g}):null]})})}const FO={RotateCcw:po,ArrowUpRight:nn,CircleCheck:Nt,FileText:_n,ArrowRightLeft:gS,UserPlus:v2,Star:Ii,BellOff:Qp,Download:Tn,Copy:bn,Trash2:mt,Clock:Qa,Sunrise:d2,Tag:Hl,Workflow:en,CircleStop:SS},OO=m.forwardRef(function(a,n){return t.jsx(Ii,{ref:n,...a,fill:"var(--cia-warn-500)",color:"var(--cia-warn-ink)"})});async function $O(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}try{const a=document.createElement("textarea");a.value=e,a.setAttribute("readonly",""),a.style.position="fixed",a.style.opacity="0",document.body.appendChild(a),a.select();const n=document.execCommand("copy");return a.remove(),n}catch{return!1}}function qO({conversacion:e,permisos:a,masRecienteId:n,agenteActualId:s,yo:i,size:r,onNavegar:o,onReabierta:l,onCerrar:c,onPlantilla:d,onEliminada:u}){const{t:p}=M("misc"),f=xe(),[x,h]=m.useState(null),[b,g]=m.useState(!1),[v,y]=m.useState(null),k=Ah(b&&a.puedeVer),w=(k.data?.items??[]).find(z=>z.conversationId===e.id),j=v?.id===e.id?v:null,C=j?.importante??e.importante??!1,N=j?.silenciada??e.silenciada??!!w,S=t0({conversationId:e.id,onNavegar:o,onReabierta:l}),_=Pe(z=>z.user),R=lt(_,"workflows.operate"),A=S1(e.id,R1(e),{enabled:R}),E=A.data?.disponible?A.data.corrida:void 0,I=b6(),P=async()=>
976{if(!E||I.isPending)return;const z=E.flowName.trim();let D=!1;await pa({title:z?p("flows.bandeja.sacar.titulo",{nombre:z}):p("flows.bandeja.sacar.tituloSinNombre"),message:p("flows.bandeja.sacar.mensaje",{contacto:ga(e)}),confirmLabel:p("flows.bandeja.sacar.confirmar"),cancelLabel:p("flows.modulo.cancelar"),onConfirm:async()=>{try{await I.mutateAsync(E.runId)}catch(G){if(Z6(G)){D=!0,await f.invalidateQueries({queryKey:Qe.porConversacionTodas()});return}throw new Error(xn(G,p("flows.bandeja.sacar.fallo")))}}})&&(tn(f,e.id),J({tone:"ok",title:p(D?"flows.bandeja.sacar.yaTermino":"flows.bandeja.sacar.listo"),desc:p("flows.bandeja.sacar.listoDesc")}))},O=oe({mutationFn:async z=>(await T.patch(`/whatsapp/conversations/${z.id}/importante`,{importante:z.valor})).data,onMutate:async z=>(y(D=>({...D?.id===z.id?D:{},id:z.id,importante:z.valor})),{restaurar:await op(f,z.id,{importante:z.valor})}),onError:(z,D,F)=>{F?.restaurar(),y(G=>G?.id===D.id?{...G,importante:void 0}:G),J({tone:"bad",title:p("whatsapp.inbox.menu.importanteFallo"),desc:_a(z)??p("whatsapp.inbox.menu.reintentar")})},onSettled:async(z,D,F)=>{await tn(f,F.id),y(G=>G?.id===F.id?{...G,importante:void 0}:G)}}),K=oe({mutationFn:async z=>(await T.delete(`/whatsapp/conversations/${z.id}/silencio`)).data,onMutate:async z=>(y(D=>({...D?.id===z.id?D:{},id:z.id,silenciada:!1})),{restaurar:await op(f,z.id,{silenciada:!1})}),onSuccess:()=>J({tone:"ok",title:p("whatsapp.inbox.silenciar.reactivado")}),onError:(z,D,F)=>{F?.restaurar(),y(G=>G?.id===D.id?{...G,silenciada:void 0}:G),J({tone:"bad",title:p("whatsapp.inbox.silenciar.falloReactivar"),desc:_a(z)??p("whatsapp.inbox.menu.reintentar")})},onSettled:async(z,D,F)=>{await Promise.all([f.invalidateQueries({queryKey:Wc}),f.invalidateQueries({queryKey:["wa-conversations"]})]),y(G=>G?.id===F.id?{...G,silenciada:void 0}:G)}}),W=oe({mutationFn:async z=>{const D=await T.get(`/whatsapp/conversations/${z}/export`,{responseType:"blob",timeout:6e4}),F=ac(D,`conversacion-${z}.txt`);return ao(D.data,F),F},onSuccess:z=>J({tone:"ok",title:p("whatsapp.inbox.menu.exportarListo"),desc:p("whatsapp.inbox.menu.exportarListoDesc",{archivo:z})}),onError:async z=>J({tone:"bad",title:p("whatsapp.inbox.menu.exportarFallo"),desc:await bR(z)??p("whatsapp.inbox.menu.reintentar")})}),V=oe({mutationFn:async z=>(await T.patch(`/whatsapp/conversations/${z}/posponer`,{hasta:null})).data,onSuccess:(z,D)=>{tn(f,D),J({tone:"ok",title:p("whatsapp.inbox.menu.despertado")})},onError:z=>J({tone:"bad",title:p("whatsapp.inbox.menu.despertarFallo"),desc:_a(z)??p("whatsapp.inbox.menu.reintentar")})}),U=async()=>{const z=(e.contactUsername??"").trim(),D=wR({nombre:(e.contactName??"").trim()||null,telefono:Ov(e.contactExternalId)?NR(e.contactExternalId):null,usuario:z?`@${z}`:null,linea:Xv(e.numeroPropioNombre,e.numeroPropio),estado:p(`whatsapp.inbox.menu.copiarEstado.${e.state}`),enlace:kR(window.location.origin,e.id)},{nombre:p("whatsapp.inbox.menu.copiarRotulo.nombre"),telefono:p("whatsapp.inbox.menu.copiarRotulo.telefono"),usuario:p("whatsapp.inbox.menu.copiarRotulo.usuario"),linea:p("whatsapp.inbox.menu.copiarRotulo.linea"),estado:p("whatsapp.inbox.menu.copiarRotulo.estado"),enlace:p("whatsapp.inbox.menu.copiarRotulo.enlace")}),F=await $O(D);J(F?{tone:"ok",title:p("whatsapp.inbox.menu.copiado"),desc:p("whatsapp.inbox.menu.copiadoDesc")}:{tone:"bad",title:p("whatsapp.inbox.menu.copiarFallo"),desc:p("whatsapp.inbox.menu.copiarFalloDesc")})},X={reabrir:S.reabrir,irAReciente:()=>{n&&o(n)},cerrar:c,plantilla:d,transferir:()=>h("transferir"),asignar:()=>h("asignar"),posponer:()=>h("posponer"),despertar:()=>{V.isPending||V.mutate(e.id)},tipificar:()=>h("tipificar"),importante:()=>{O.isPending||O.mutate({id:e.id,valor:!C})},silenciar:()=>{N?K.isPending||K.mutate({id:e.id}):h("silenciar")},exportar:()=>{W.isPending||W.mutate(e.id)},copiar:()=>void U(),eliminar:()=>h("eliminar"),lanzarFlujo:()=>h("lanzarFlujo"),sacarDelFlujo:()=>void P()},ie=mR({estado:e.state,importante:C,silenciada:N,puedeOperar:a.puedeOperar,puedeVer:a.puedeVer,esAdminReal:a.esAdminReal,puedeManejar:a.puedeManejar,hayMasReciente:!!n,pospuestaHasta:e.snoozedUntil??null,silencioHasta:k.isSuccess&&w?w.hasta:void 0,enCurso:{reabrir:S.enCurso,exportar:W.isPending,despertar:V.isPending,sacarDelFlujo:I.isPending}
976,flujo:{disponible:A.data?A.data.disponible:!0,puedeOperar:R,corrida:E,falloLaConsulta:A.isError&&!A.data}}).map(z=>({key:z.key,items:z.items.map(D=>({key:D.key,label:p(D.rotulo),icon:D.icono==="Star"&&D.checked?OO:FO[D.icono],type:D.tipo,checked:D.checked,danger:D.danger,disabled:D.disabled,disabledReason:D.motivo?p(D.motivo):void 0,description:D.descripcion?p(D.descripcion.clave,{cuando:D.descripcion.hastaIso?Ci(D.descripcion.hastaIso):void 0,...D.descripcion.params??{}}):void 0,keepOpen:D.mantenerAbierto,onSelect:X[D.key]}))}));if(ie.length===0)return null;const de=ga(e),$=()=>h(null);return t.jsxs(t.Fragment,{children:[t.jsx(vn,{"aria-label":p("whatsapp.inbox.menu.aria"),iconTrigger:{icon:t.jsx(zi,{}),label:p("whatsapp.inbox.masOpciones"),size:r},groups:ie,align:"end",minWidth:248,onOpenChange:g}),x==="transferir"?t.jsx(zR,{open:!0,onClose:$,conversationId:e.id,nombreDelContacto:de,assigneeUserId:e.assigneeUserId,agenteActualId:e.mode==="agent"?s:null,yo:i}):null,x==="asignar"?t.jsx(BO,{open:!0,onClose:$,conversationId:e.id,mode:e.mode,assigneeUserId:e.assigneeUserId,yo:i}):null,x==="silenciar"?t.jsx(DR,{open:!0,onClose:$,conversationId:e.id}):null,x==="posponer"?t.jsx(IO,{open:!0,onClose:$,conversationId:e.id}):null,x==="tipificar"?t.jsx(WO,{open:!0,onClose:$,conversationId:e.id,nombreDelContacto:de,puestas:e.etiquetas??[]}):null,x==="lanzarFlujo"?t.jsx(LO,{open:!0,onClose:$,conversationId:e.id,nombreDelContacto:de}):null,x==="eliminar"?t.jsx(DO,{open:!0,onClose:$,conversationId:e.id,nombreDelContacto:de,onEliminada:u}):null]})}const mr="__sin_asignar__";function BO({open:e,onClose:a,conversationId:n,mode:s,assigneeUserId:i,yo:r}){const{t:o}=M("misc"),l=xe(),c=!i&&s==="agent",d=i??(c?null:mr),[u,p]=m.useState(d),f=Bc(),x=s0(),h=_h(),b=j=>j===r?o("whatsapp.inbox.asignar.yo"):f.data?.find(C=>C.id===j)?.name??"",g=oe({mutationFn:async j=>(await T.patch(`/whatsapp/conversations/${j.id}/asignar`,j.destino===mr?{tipo:"nadie"}:{tipo:"persona",userId:j.destino})).data,onSuccess:(j,C)=>{tn(l,C.id),l.invalidateQueries({queryKey:Eh}),J({tone:"ok",title:C.destino===mr?o("whatsapp.inbox.asignarModal.listoSinAsignar"):C.destino===r?o("whatsapp.inbox.asignarModal.listoAMi"):o("whatsapp.inbox.asignarModal.listo",{nombre:b(C.destino)})}),a()}}),v=[...Ch(f.data??[],x.data?.porUsuario).map(j=>({value:j.id,label:j.id===r?o("whatsapp.inbox.asignar.yo"):j.name,description:[eo(o,Jr(x.data?.porUsuario?.[j.id])),j.id===i?o("whatsapp.inbox.asignarModal.actualPersona"):null].filter(Boolean).join(" · ")||void 0,icon:t.jsx(En,{}),trailing:h.data?.online?.includes(j.id)?t.jsx(n0,{texto:o("whatsapp.inbox.presencia.conectado")}):void 0})),{value:mr,label:o("whatsapp.inbox.asignar.nadie"),description:[eo(o,Jr(x.data?.sinAsignar)),d===mr?o("whatsapp.inbox.asignarModal.actualSinAsignar"):null].filter(Boolean).join(" · ")||void 0,icon:t.jsx(mo,{})}],y=u===d,k=u===null?o("whatsapp.inbox.asignarModal.elegi"):y?o("whatsapp.inbox.asignarModal.sinCambio"):null;let w;return f.isPending?w=t.jsx(a0,{etiqueta:o("whatsapp.inbox.transferir.cargando")}):f.isError?w=t.jsx(le,{tone:"bad",title:o("whatsapp.inbox.transferir.errorPersonas"),action:{label:o("whatsapp.inbox.transferir.reintentar"),onClick:()=>void f.refetch()},actionPlacement:"end",children:_a(f.error)??o("whatsapp.inbox.transferir.errorDesc")}):w=t.jsxs(t.Fragment,{children:[(f.data??[]).length===0?t.jsx(st,{mini:!0,icon:En,title:o("whatsapp.inbox.transferir.sinPersonas"),desc:o("whatsapp.inbox.transferir.sinPersonasDesc")}):null,t.jsx(wo,{legend:o("whatsapp.inbox.asignarModal.aria"),opciones:v,value:u,onChange:p,disabled:g.isPending})]}),t.jsx(ot,{open:e,onClose:a,maxWidth:380,title:o("whatsapp.inbox.asignarModal.titulo"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{onClick:a,children:o("whatsapp.inbox.transferir.cancelar")}
976),t.jsx(Ie,{variant:"cta",disabled:y||u===null||f.isPending,loading:g.isPending,onClick:()=>{u!==null&&!y&&!g.isPending&&g.mutate({id:n,destino:u})},children:o("whatsapp.inbox.asignarModal.confirmar")})]}),children:t.jsxs("div",{className:"cia-waop-cuerpo",children:[t.jsx("p",{className:"cia-waop-desc",children:o(c?"whatsapp.inbox.asignarModal.descIa":"whatsapp.inbox.asignarModal.desc")}),t.jsx("div",{className:"cia-waop-panel",children:w}),t.jsx("span",{className:"cia-waop-ayuda","aria-live":"polite",children:f.isPending?null:k}),g.isError?t.jsx(le,{tone:"bad",title:o("whatsapp.inbox.asignarModal.fallo"),children:_a(g.error)??o("whatsapp.inbox.transferir.falloDesc")}):null]})})}function WO({open:e,onClose:a,conversationId:n,nombreDelContacto:s,puestas:i}){const{t:r}=M("misc"),o=xe();return t.jsx(ot,{open:e,onClose:a,maxWidth:380,title:r("whatsapp.inbox.tipificarModal.titulo"),footer:t.jsx(Ie,{onClick:a,children:r("whatsapp.inbox.tipificarModal.listo")}),children:t.jsxs("div",{className:"cia-waop-cuerpo",children:[t.jsx("p",{className:"cia-waop-desc",children:r("whatsapp.inbox.tipificarModal.desc",{nombre:s})}),t.jsx($1,{conversationId:n,puestas:i,puedeOperar:!0,onCambio:()=>void tn(o,n)})]})})}function UO({conversationId:e,puedeOperar:a,masRecienteId:n,onNavegar:s,onReabierta:i}){const{t:r}=M("misc"),o=t0({conversationId:e,onNavegar:s,onReabierta:i}),l=c=>t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"cia-waop-aviso-largo",children:r(c)}),t.jsx("span",{className:"cia-waop-aviso-corto",children:r("whatsapp.inbox.chatCerrado.textoCorto")})]});return n?t.jsx("div",{className:"cia-waop-aviso","data-medida":"reciente",children:t.jsx(le,{variant:"compact",tone:"neutral",icon:wc,action:{label:r("whatsapp.inbox.chatCerrado.irAReciente"),icon:nn,onClick:()=>s(n)},children:l("whatsapp.inbox.chatCerrado.masReciente")})}):a?t.jsx("div",{className:"cia-waop-aviso","data-medida":"reabrir",children:t.jsx(le,{variant:"compact",tone:"neutral",icon:yi,action:{label:r("whatsapp.inbox.chatCerrado.reabrir"),icon:po,loading:o.enCurso,onClick:o.reabrir},children:l("whatsapp.inbox.chatCerrado.texto")})}):t.jsx("div",{className:"cia-waop-aviso",children:t.jsx(le,{tone:"neutral",icon:yi,children:r("whatsapp.inbox.chatCerrado.sinPermiso")})})}const Sp=50,q1=20;function Lr(e){const a=e?Date.parse(e):Number.NaN;return Number.isFinite(a)?a:Number.NaN}function VO(e,a){return(e.lineaNumero??"")===(a.lineaNumero??"")}function KO(e){const a=e.find(i=>i.actual);if(!a)return null;const n=Lr(a.creadaEl);if(!Number.isFinite(n))return null;let s=null;for(const i of e){if(i.actual||!VO(i,a))continue;const r=Lr(i.creadaEl);if(!(r>n))continue;if(!s){s=i;continue}const o=Lr(s.creadaEl);(r>o||r===o&&i.id>s.id)&&(s=i)}return s}function B1(e){if(e)return e.hilos.filter(a=>!a.actual).length+(e.llamadas?.length??0)}function HO(e){return e?e.hilos.length>=Sp||(e.llamadas?.length??0)>=q1:!1}function QO(e){return(B1(e)??0)>0}function GO(e){return e.ultimoMensajeEl??e.creadaEl}function ZO(e){if(!e)return[];const a=e.hilos.map(i=>({tipo:"hilo",id:`hilo:${i.id}`,fecha:GO(i),hilo:i})),n=(e.llamadas??[]).map(i=>({tipo:"llamada",id:`llamada:${i.id}`,fecha:i.inicio,llamada:i})),s=i=>{const r=Lr(i.fecha);return Number.isFinite(r)?r:Number.NEGATIVE_INFINITY};return[...a,...n].map((i,r)=>({e:i,i:r})).sort((i,r)=>s(r.e)-s(i.e)||i.i-r.i).map(({e:i})=>i)}function YO(e){const a=[];for(const n of e){const s=Lr(n.fecha),i=Number.isFinite(s)?new Date(s):null,r=i?`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}`:"sin-fecha",o=a[a.length-1];o&&o.clave===r?o.entradas.push(n):a.push({clave:r,inicio:i?new Date(i.getFullYear(),i.getMonth(),1):new Date(Number.NaN),entradas:[n]})}return a}function XO(e,a){if(!(!e||!e.hilos.some(n=>n.id===a)))return{...e,hilos:e.hilos.map(n=>({...n,actual:n.id===a}))}}function W1(e){const a=e??"",n=se({queryKey:["wa-historial",a],queryFn:async()=>(await T.get(`/whatsapp/conversations/${a}/historial`)).data,enabled:!!e,staleTime:6e4,placeholderData:r=>XO(r,a)}),[s]=m.useState(()=>n.data!==void 0),i=n.data;return{data:i,cargando:!!e&&i===void 0&&!n.isError,isError:n.isError,error:n.error,isFetching:n.isFetching,refetch:()=>{n.refetch()},masReciente:i?KO(i.hilos):null,contador:B1(i),yaEstabaEnCache:s}}const JO={open:"success",snoozed:"warning",closed:"neutral"},$g=2,e8=8;function t8({conversationId:e,onAbrir:a}){const{t:n}=M(["misc","calls","format"]),s=dt(),i=W1(e),r=m.useId();if(i.cargando)return t.jsxs("div",{className:"cia-historial","aria-busy":"true","aria-label":n("whatsapp.inbox.historial.cargando"),children:[t.jsx(ge,{w:104,h:12,r:4}),[0,1,2].map(f=>t.jsxs("div",{className:"cia-historial-esqueleto","aria-hidden":"true",children:[t.jsx(ge,{w:24,h:24,r:7}),t.jsxs("div",{className:"cia-historial-esqueleto-texto",children:[t.jsx(ge,{h:12,w:"55%",r:4}),t.jsx(ge,{h:11,w:"85%",r:4}),t.jsx(ge,{h:20,w:"40%",r:10})]})]},f))]});if(i.isError&&!i.data)return t.jsx(le,{tone:"bad",title:n("whatsapp.inbox.historial.errorTitulo"),action:{label:n("whatsapp.inbox.historial.reintentar"),icon:po,onClick:i.refetch,loading:i.isFetching},children:_a(i.error)??n("whatsapp.inbox.historial.errorDesc")});const o=i.data;if(!o||!QO(o))return t.jsx(st,{mini:!0,icon:wc,title:n("whatsapp.inbox.historial.vacioTitulo"),desc:o&&o.llamadas===null?n("whatsapp.inbox.historial.vacioDescSinLlamadas"):n("whatsapp.inbox.historial.vacioDesc")});const l=YO(ZO(o)),c=new Intl.DateTimeFormat(Te(),{month:"long",year:"numeric"}),d=f=>{if(Number.isNaN(f.getTime()))return n("whatsapp.inbox.historial.sinFecha");const x=c.format(f);return x.charAt(0).toLocaleUpperCase(Te())+x.slice(1)};let u=0;const p=f=>s({to:"/history",search:{callId:f.id}});return t.jsxs("div",{className:"cia-historial","data-entrada":i.yaEstabaEnCache?void 0:"",children:[l.map(f=>{const x=`${r}-${f.clave}`;return t.jsxs("section",{className:"cia-historial-grupo","aria-labelledby":x,children:[t.jsx("h3",{id:x,className:"cia-historial-mes",children:d(f.inicio)}),t.jsx("ul",{className:"cia-historial-lista","aria-labelledby":x,children:f.entradas.map(h=>{const b=Math.min(u++,e8);return t.jsx("li",{style:{"--i":b},children:h.tipo==="hilo"?t.jsx(s8,{entrada:h,t:n,onAbrir:a}):t.jsx(i8,{llamada:h.llamada,t:n,onAbrir:()=>p(h.llamada)})},h.id)})})]},f.clave)}),HO(o)?t.jsx("p",{className:"cia-historial-pie",children:o.llamadas===null?n("whatsapp.inbox.historial.recortadoSinLlamadas",{hilos:Sp}):n("whatsapp.inbox.historial.recortado",{hilos:Sp,llamadas:q1})}):null]})}function U1({iso:e}){return t.jsx("time",{className:"cia-historial-fecha",dateTime:e,title:Be(e),children:kn(e)})}function V1(e,a){if(e.contenidoVencido)return a("whatsapp.inbox.historial.vencido");const n=e.ultimoMensaje;if(!n)return e.mensajes===0?a("whatsapp.inbox.historial.sinMensajes"):null;const s=n.texto?n.texto:n.tipo&&n.tipo!=="text"?a(`whatsapp.inbox.resumen.${n.tipo}`,{defaultValue:a("whatsapp.inbox.resumen.archivo")}):null;return s?n.direction==="outbound"?a("whatsapp.inbox.resumen.propio",{texto:s}):s:null}function a8(e,a){const n=V1(e,a);return e.contenidoVencido?t.jsxs("span",{className:"cia-historial-vencido",children:[t.jsx(bc,{"aria-hidden":"true"}),n]}):n??void 0}function n8(e,a){return a(`whatsapp.inbox.${e.estado==="snoozed"?"snoozedBadge":e.estado}`)}function s8({entrada:e,t:a,onAbrir:n}){const s=e.hilo,i=s.lineaNombre||s.lineaNumero||a("whatsapp.inbox.historial.sinLinea"),r=[[s.lineaNombre,s.lineaNumero].filter(
976Boolean).join(" · "),s.contenidoVencido?a("whatsapp.inbox.historial.vencidoHint"):V1(s,a)].filter(Boolean).join(`
977`)||void 0,o=s.etiquetas.slice(0,$g),l=s.etiquetas.slice($g),c=t.jsxs(t.Fragment,{children:[t.jsx(Ws,{size:"sm",icon:Ba,tone:"var(--cia-ok-ink)",title:t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"cia-sr-only",children:[a("whatsapp.inbox.historial.srHilo")," ",i]}),t.jsx("span",{"aria-hidden":"true",children:a("whatsapp.inbox.historial.chatEn",{linea:i})})]}),subtitle:a8(s,a),trailing:t.jsx(U1,{iso:e.fecha}),tooltip:r}),t.jsxs("span",{className:"cia-historial-marcas",children:[t.jsx(at,{tone:JO[s.estado],label:n8(s,a),icon:!1}),s.actual?t.jsx(at,{tone:"info",label:a("whatsapp.inbox.historial.actual"),icon:!1}):null,o.map(d=>t.jsx(ps,{label:d.nombre,tone:d.color},d.id)),l.length>0?t.jsx("span",{className:"cia-historial-mas",title:l.map(d=>d.nombre).join(", "),children:a("whatsapp.inbox.historial.etiquetasMas",{n:l.length})}):null,s.mensajes>0?t.jsx("span",{className:"cia-historial-cuenta",children:a("whatsapp.inbox.historial.mensajes",{count:s.mensajes})}):null]})]});return s.actual?t.jsx("div",{className:"cia-historial-fila","data-actual":"","aria-current":"true",children:c}):t.jsx("button",{type:"button",className:"cia-historial-fila",onClick:()=>n(s.id),children:c})}function i8({llamada:e,t:a,onAbrir:n}){const i=e.direccion==="outbound"?ka:yn,r=e.medio==="whatsapp"?a("whatsapp.inbox.historial.llamadaWhatsapp"):a("whatsapp.inbox.historial.llamadaTelefonica"),o=a(`whatsapp.inbox.historial.direccion.${e.direccion}`,{defaultValue:e.direccion}),l={status:e.estado,durationSeconds:e.duracionSegundos},c=la(l);let d;if(!c&&e.duracionSegundos>0)d=Ca(e.duracionSegundos);else{const{ns:p,key:f}=Ih(l);d=a(`${p}:${f}`,{defaultValue:e.estado})}const u=[o,c?null:d,e.agenteNombre].filter(Boolean).join(" · ");return t.jsxs("button",{type:"button",className:"cia-historial-fila",onClick:n,title:`${u}
978${a("whatsapp.inbox.historial.verLlamada")}`,children:[t.jsx(Ws,{size:"sm",icon:i,tone:"var(--cia-select-ink)",title:r,subtitle:u,trailing:t.jsx(U1,{iso:e.inicio})}),c?t.jsx("span",{className:"cia-historial-marcas",children:t.jsx(at,{tone:"success",label:d,pulse:!0})}):null]})}async function qg(e){return(await T.get(`/whatsapp/conversations/${e}`)).data}const r8=900,o8=1280;function l8(){const{t:e}=M("misc"),a=xe(),n=dt(),s=Os({strict:!1}),i=Pe(q=>q.user),r=lt(i,"whatsapp.operate"),o=rt(q=>q.isActive()),l=s.c??null,[c,d]=m.useState(9999),u=m.useRef(null),p=m.useCallback(q=>{if(u.current?.disconnect(),u.current=null,!q||typeof ResizeObserver>"u")return;const Ne=new ResizeObserver(jt=>{const Rt=jt[0]?.contentRect.width;Rt!=null&&d(Rt)});Ne.observe(q),u.current=Ne},[]),f=c<r8,x=c>=o8,h=q=>{n({to:"/whatsapp/bandeja",search:Ne=>({...Ne,c:q??void 0}),replace:!f})},b=()=>h(null),[g,v]=m.useState(()=>Ml(l)),[y,k]=m.useState(!1),[w,j]=m.useState(!1),[C,N]=m.useState(new Set),[S,_]=m.useState(null),R=()=>{j(!1),N(new Set)},A=q=>{N(Ne=>{if(Ne.has(q)){const Rt=new Set(Ne);return Rt.delete(q),Rt}if(!OA(Ne,q))return Ne;const jt=new Set(Ne);return jt.add(q),jt})};m.useEffect(()=>{if(!w)return;const q=Ne=>{Ne.key==="Escape"&&R()};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[w]);const[E,I]=m.useState(!1),[P,O]=m.useState(null),[K,W]=m.useState(null),[V,U]=m.useState(!1);m.useEffect(()=>{I(!1),U(!1),W(null)},[l]);const X=se({queryKey:["wa-snippets"],queryFn:async()=>(await T.get("/whatsapp/snippets")).data.items,staleTime:5*6e4}),ie=q=>{v(q.texto),T.post(`/whatsapp/snippets/${q.id}/uso`).catch(()=>{})},[de,$]=m.useState(null),z=q=>$(Ne=>({texto:q,nonce:(Ne?.nonce??0)+1})),D=(q,Ne)=>{$(jt=>({texto:Ne,nonce:(jt?.nonce??0)+1})),T.post(`/whatsapp/snippets/${q}/uso`).catch(()=>{})},[F,G]=m.useState(null),[te,B]=m.useState(null),[ne,me]=m.useState("todas"),[Ee,L]=m.useState(null),[re,ke]=m.useState(null),[H,fe]=m.useState(""),[Z,ae]=m.useState("");m.useEffect(()=>{const q=setTimeout(()=>ae(H.trim()),300);return()=>clearTimeout(q)},[H]);const[pe,ye]=m.useState(!1),[qe,ut]=m.useState(()=>{try{return localStorage.getItem("cia-wa-aside-open")!=="0"}catch{return!0}});m.useEffect(()=>{try{localStorage.setItem("cia-wa-aside-open",qe?"1":"0")}catch{}},[qe]);const[bt,Ge]=m.useState(!1);m.useEffect(()=>{Ge(!1)},[l]);const yt=x?qe:bt,[ve,Ke]=m.useState("detalle"),He=q=>{x?ut(q):Ge(q)},[Xe,Et]=m.useState({}),{intervaloDeRespaldo:Yt}=TR({activa:l,historialALaVista:()=>yt&&ve==="historial"||ee?.state==="closed",onMensajeEnHiloAbierto:q=>{document.visibilityState==="visible"&&Eo(q)},onReabierta:q=>h(q)}),It=Hm({queryKey:["wa-conversations",ne,Z,Ee,re],initialPageParam:void 0,queryFn:async({pageParam:q})=>{try{const Ne={...WF(ne),...VF({buscar:Z,etiqueta:Ee,linea:re})};return q&&(Ne.cursor=q),(await T.get("/whatsapp/conversations",{params:Ne})).data}catch(Ne){if(Ne?.response?.status===501||Ne?.response?.status===404)return null;throw Ne}}
978,getNextPageParam:q=>q?q.siguiente??void 0:void 0,placeholderData:q=>q,refetchInterval:Yt,refetchIntervalInBackground:!0}),Pn=It.data?.pages??[],St=Pn[0],sa=St===null,ma=$A(Pn.flatMap(q=>q?q.items:[])),$e=RR({habilitado:!sa,intervalo:Yt}),ce=XF(!!St),Se=P1(!!St),De=(St?.numerosDelTenant??1)>1,[ue,Ze]=m.useState(()=>Date.now()),ze=CA(ma,ue)||_A(ma,ue);m.useEffect(()=>{if(!ze)return;const q=window.setInterval(()=>Ze(Date.now()),1e3);return()=>window.clearInterval(q)},[ze]);const Ot=m.useMemo(()=>ma.find(q=>q.id===l)??null,[ma,l]),fa=se({queryKey:["wa-conversations","hilo",l],enabled:!!l&&!Ot&&!!St&&!It.isPlaceholderData,queryFn:()=>qg(l),retry:(q,Ne)=>Ne?.response?.status!==404&&q<2,refetchInterval:Yt}),Ui=m.useRef(null),Vi=Ot??fa.data??null;Vi&&(Ui.current=Vi);const ee=Vi??(Ui.current?.id===l&&!fa.isError?Ui.current:null),Oe=!!l&&!ee&&!fa.isError,At=m.useRef(null);m.useEffect(()=>{!l||!fa.isError||fa.error?.response?.status===404&&(At.current!==l&&J({tone:"info",title:e("whatsapp.inbox.eliminada.titulo"),desc:e("whatsapp.inbox.eliminada.desc")}),h(null))},[l,fa.isError,fa.error]);const Jt=W1(ee?.id),Gh=Jt.masReciente?.id??null,Zh=CO(ee),lj=Zh.data?.atiende.tipo==="asistente"?Zh.data.atiende.agenteId:null,Eo=q=>{if(!(ma.find(Da=>Da.id===q)??(fa.data?.id===q?fa.data:null))?.sinLeer)return;const jt=Date.now(),Rt=Xe[q]??0;jt-Rt<3e3||(Et(Da=>({...Da,[q]:jt})),T.post(`/whatsapp/conversations/${q}/leida`).then(()=>{a.invalidateQueries({queryKey:["wa-conversations"]}),a.invalidateQueries({queryKey:["wa-conversations-conteos"]})}).catch(()=>{}))},Yc=ee?.sinLeer?ee.id:null;m.useEffect(()=>{if(!Yc)return;const q=()=>{document.visibilityState==="visible"&&Eo(Yc)};return q(),document.addEventListener("visibilitychange",q),()=>document.removeEventListener("visibilitychange",q)},[Yc]);const Gt=ee?Tl(ee,ue):null,[cj,Ki]=m.useState(!1),Hi=ee?Vf(ee,ue):null,Ao=ee?Uf(ee.turno,ue):null,Yh=ee?EA(ee.turno,ue):null,Xc=se({queryKey:["wa-messages",l],enabled:!!l,queryFn:async()=>(await T.get(`/whatsapp/conversations/${l}/messages`)).data,refetchInterval:Yt,refetchIntervalInBackground:!0}),Ro=m.useMemo(()=>[...Xc.data?.items??[]].reverse(),[Xc.data]),Xh=m.useRef(Ro);Xh.current=Ro;const jn=Hm({queryKey:["wa-messages-historial",l],enabled:!1,initialPageParam:void 0,queryFn:async({pageParam:q})=>{const Ne=q??Xh.current[0]?.occurredAt;return Ne?(await T.get(`/whatsapp/conversations/${l}/messages`,{params:{antesDe:Ne}})).data:{items:[],hayMas:!1}},getNextPageParam:q=>q.hayMas&&q.items.length>0?q.items[q.items.length-1].occurredAt:void 0});m.useEffect(()=>{a.resetQueries({queryKey:["wa-messages-historial",l]})},[l,a]);const[Jh,To]=m.useState(null),[Mo,Qi]=m.useState(null),em=m.useMemo(()=>[...jn.data?.pages.flatMap(q=>q.items)??[]].reverse(),[jn.data]),Vs=m.useMemo(()=>{const q=new Set,Ne=[];for(const jt of[...em,...Ro])q.has(jt.id)||(q.add(jt.id),Ne.push(jt));return Ne},[em,Ro]),Po=m.useMemo(()=>PA(Vs),[Vs]),tm=m.useMemo(()=>Vs.flatMap(q=>{const Ne=_o(q);return Ne!=="imagen"&&Ne!=="video"&&Ne!=="sticker"?[]:Qh(q)!=="listo"?[]:[{id:q.id,clase:Ne,autor:Si(q)==="in"&&ee?ga(ee):e("whatsapp.inbox.you"),fecha:Be(q.occurredAt)}]}),[Vs,ee,e]),am=m.useRef(jn);am.current=jn;const nm=m.useRef(Vs);nm.current=Vs;const dj=20,uj=async q=>{U(!1);let Ne=nm.current.some(Ia=>Ia.id===q.id),jt=0;for(;!Ne&&jt<dj;){const Ia=await am.current.fetchNextPage();if(jt+=1,Ne=(Ia.data?.pages??[]).some(gj=>gj.items.some(bj=>bj.id===q.id)),Ia.hasNextPage===!1)break}let Rt=null;for(let Ia=0;Ia<10&&!Rt;Ia++)Rt=document.getElementById(`cia-msg-${q.id}`),Rt||await new Promise(um=>requestAnimationFrame(um));if(!Rt){U(!0);return}const Da=typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;Rt.scrollIntoView({behavior:Da?"auto":"smooth",block:"center"}),W(q.id),window.setTimeout(()=>W(Ia=>Ia===q.id?null:Ia),1700)},sm=oe({mutationFn:async q=>(await T.patch(`/whatsapp/conversations/${l}/mode`,{mode:q})).data,onSuccess:()=>{G(null),a.invalidateQueries({queryKey:["wa-conversations"]})},onError:q=>G(q?.response?.data?.message??e("whatsapp.inbox.modeFailed"))}),im=oe({mutationFn:async()=>(await T.post(`/whatsapp/conversations/${l}/close`)).data,onSuccess:()=>{Ki(!1),G(null),a.invalidateQueries({queryKey:["wa-conversations"]})},onError:q=>{Ki(!1),G(q?.response?.data?.message??e("whatsapp.inbox.closeFailed"))}}),Jc=q=>{q!==l&&(Ad(l,g),h(q),v(Ml(q)),G(null),Qi(null),To(null),Eo(q))},rm=async(q,Ne)=>{try{const jt=await a.fetchQuery({queryKey:["wa-conversations","hilo",q],queryFn:()=>qg(q)});Tl(jt,Date.now())?.abierta||B({tipo:"hilo",conversationId:q,contacto:Ne})}catch{}},pj=()=>{const q=l;At.current=q,h(null),q&&a.removeQueries({queryKey:["wa-conversations","hilo",q]}),a.invalidateQueries({queryKey:["wa-historial"]})},om=m.useRef(null),hj="image/jpeg,image/png,image/webp,application/pdf,audio/mpeg,audio/ogg,video/mp4,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/plain",ed=8,zo=oe({mutationFn:async q=>{const Ne=new FormData;return Ne.append("archivo",q,q.name),Ne.append("clientToken",Qo()),(await T.post(`/whatsapp/conversations/${l}/attachments`,Ne,{headers:{"Content-Type":"multipart/form-data"}})).data},onSuccess:()=>{G(null),a.invalidateQueries({queryKey:["wa-messages",l]}),a.invalidateQueries({queryKey:["wa-conversations"]})},onError:q=>
978{const Ne=q?.response?.status===413?e("whatsapp.inbox.attach.tooLarge",{mb:ed}):q?.response?.data?.message??e("whatsapp.inbox.attach.failed");G(Ne)}}),mj=async(q,Ne)=>{const jt=new FormData;jt.append("audio",q,"nota-de-voz"),jt.append("clientToken",Qo());try{return await T.post(`/whatsapp/conversations/${l}/nota-de-voz`,jt,{headers:{"Content-Type":"multipart/form-data"}}),G(null),a.invalidateQueries({queryKey:["wa-messages",l]}),a.invalidateQueries({queryKey:["wa-conversations"]}),!0}catch(Rt){return G(Rt?.response?.status===413?e("whatsapp.inbox.voz.demasiadoLarga"):Rt?.response?.data?.message??e("whatsapp.inbox.voz.fallo")),console.warn(`[nota de voz] falló el envío (grabado como ${Ne})`),!1}},fj=q=>{if(q){if(q.size>ed*1024*1024){G(e("whatsapp.inbox.attach.tooLarge",{mb:ed}));return}zo.mutate(q)}},xj=oe({mutationFn:async q=>(await T.post(`/whatsapp/conversations/${l}/reaccion`,{messageId:q.messageId,emoji:q.emoji,clientToken:Qo()})).data,onSuccess:()=>{G(null),a.invalidateQueries({queryKey:["wa-messages",l]})},onError:q=>{const Ne=q?.response?.data?.message;G(Array.isArray(Ne)?Ne.join(" · "):Ne||e("whatsapp.inbox.sendError"))}}),lm=oe({mutationFn:async q=>{const Ne=Qo();return(await T.post(`/whatsapp/conversations/${l}/messages`,{texto:q,clientToken:Ne,...Mo?{replyToMessageId:Mo.id}:{}})).data},onSuccess:()=>{v(""),Ad(l,""),Qi(null),G(null),a.invalidateQueries({queryKey:["wa-messages",l]}),a.invalidateQueries({queryKey:["wa-conversations"]})},onError:q=>{G(q?.response?.data?.message??e("whatsapp.inbox.sendFailed"))}});if(It.isLoading)return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{title:e("whatsapp.inbox.title")}),t.jsx(Do,{mode:"cards",showDetail:!1,list:t.jsx("div",{style:{padding:14},children:t.jsx(ge,{h:280})}),detail:t.jsx("div",{style:{padding:14},children:t.jsx(ge,{h:320})})})]});if(sa)return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{title:e("whatsapp.inbox.title")}),t.jsx(So,{icon:Ba,eyebrow:e("whatsapp.eyebrow"),title:e("whatsapp.inbox.title"),description:e("whatsapp.description")})]});const cm=!!(Ee||re),dm=ma.map(q=>{const Ne=Tl(q,ue),jt=Vf(q,ue),Rt=Uf(q.turno,ue),Da=jt==="esperando"&&Rt!==null?e("whatsapp.inbox.turn.inList",{seconds:Rt}):jt==="contestando"?e("whatsapp.inbox.turn.answeringShort"):q.mode==="human"?e("whatsapp.inbox.turn.humanShort"):null;return{id:q.id,title:ga(q),subtitle:[De?x8(q,e):null,f8(q,e),Da].filter(Boolean).join(" · "),at:q.lastMessageAt,tone:Ne?.abierta?"ok":"neutral",avatar:t.jsx(Sn,{name:ga(q),shape:"square",status:Ne?.abierta?"ok":void 0,statusLabel:Ne?.abierta?e("whatsapp.inbox.windowOpenStatus"):void 0}),unread:q.sinLeer===!0,marks:d8(q,e),extra:c8(q,Ne,i?.id??null,e,l,g)}});return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{title:e("whatsapp.inbox.title")}),t.jsx("div",{ref:p,style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:t.jsx(Do,{mode:"cards",showDetail:!!ee||Oe,aside:ee?t.jsxs("div",{className:"cia-inbox-aside",children:[t.jsx("div",{className:"cia-inbox-aside-pestanas","aria-label":e("whatsapp.inbox.aside.tabs.aria"),role:"group",children:t.jsx(Fi,{items:[{id:"detalle",label:e("whatsapp.inbox.aside.tabs.detalle"),panelId:"cia-inbox-panel-detalle"},{id:"historial",label:e("whatsapp.inbox.historial.titulo"),count:Jt.contador,panelId:"cia-inbox-panel-historial"}],active:ve,onChange:q=>Ke(q==="historial"?"historial":"detalle")})}),ve==="historial"?t.jsx("div",{id:"cia-inbox-panel-historial",role:"tabpanel","aria-label":e("whatsapp.inbox.historial.titulo"),className:"cia-inbox-aside-historial",children:t.jsx(t8,{conversationId:ee.id,onAbrir:Jc})}):t.jsx("div",{id:"cia-inbox-panel-detalle",role:"tabpanel","aria-label":e("whatsapp.inbox.aside.tabs.detalle"),children:m8(ee,e,i,r,L,a)})]}):null,asideOpen:yt&&!!ee,onCloseAside:()=>He(!1),asideTitle:ee?e("whatsapp.inbox.aside.titulo"):void 0,list:t.jsxs(Do.Panel,{header:t.jsxs("div",{className:"cia-inbox-lista-head",children:[t.jsx(zO,{seleccionando:w,onSeleccionar:()=>w?R():j(!0),onResumen:()=>ye(!0),onEscribirPrimero:()=>B({tipo:"nuevo"}),puedeResponder:r,avisos:t.jsx(FR,{variant:"ghost"})}),w?t.jsx(PO,{seleccionados:[...C],onCancelar:R,onCerrado:q=>{_(q),R()}}):null,S?t.jsxs(le,{tone:S.fallidas.length?"warn":"ok",action:{label:e("whatsapp.inbox.seleccion.resultadoCerrar"),onClick:()=>_(null)},children:[e("whatsapp.inbox.seleccion.resultado",{cerradas:S.cerradas,yaCerradas:S.yaCerradas,fallidas:S.fallidas.length}),S.fallidas.length>0&&t.jsx("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:S.fallidas.map(q=>t.jsx("li",{children:e(`whatsapp.inbox.seleccion.motivo.${q.motivo}`,{defaultValue:q.motivo})},q.id))})]}):null,t.jsx(ZF,{zona:ne,onZona:me,conteos:$e.data,buscar:H,onBuscar:fe,etiqueta:Ee,onEtiqueta:L,linea:re,onLinea:ke,etiquetas:ce.etiquetas,lineas:Se,onReintentarEtiquetas:ce.reintentar})]}),children:[It.isError?t.jsx(le,{tone:"bad",children:e("whatsapp.loadError")}):t.jsx("div",{className:"cia-inbox-lista-cuerpo","data-actualizando":It.isPlaceholderData||void 0,"aria-busy":It.isPlaceholderData||void 0,children:t.jsx(c_,{variant:"bandeja",items:dm,activeId:l,selectable:w,selectedIds:C,onToggleSelect:A,seleccionAlTope:C.size>=wh,hasMore:It.hasNextPage===!0,loadingMore:It.isFetchingNextPage,onEndReached:()=>{It.isFetchingNextPage||It.hasNextPage!==!0||It.fetchNextPage()},onSelect:q=>{Ad(l,g),h(q),v(Ml(q)),G(null),Qi(null),To(null),Eo(q)},title:!1})}),!It.isError&&!It.isPlaceholderData&&dm.length===0?t.jsx(st,{mini:!0,icon:Ba,title:Z?e("whatsapp.inbox.vacio.busqueda",{q:Z}):e(cm?"whatsapp.inbox.vacio.filtros":ne==="todas"?"whatsapp.inbox.vacio.todas":"whatsapp.inbox.vacio.zona"),secondaryAction:cm?{label:e("whatsapp.inbox.vacio.limpiarFiltros"),onClick:()=>{L(null),ke(null)}}:void 0}):null]}),detail:ee?t.jsxs(Do.Panel,{scroll:"children",header:t.jsxs(t.Fragment,{children:[t.jsx("header",{className:"cia-inbox-head",children:t.jsxs("div",{className:"cia-inbox-head-fila",children:[t.jsxs("div",{className:"cia-inbox-head-izq",children:[f?t.jsx(Lt,{icon:t.jsx(gn,{}),label:e("whatsapp.inbox.volver"),size:"md",onClick:b,tooltipPosition:"bottom"}):null,t.jsx(Sn,{name:ga(ee),shape:"circle"}),t.jsxs("div",{className:"cia-inbox-head-id",children:[t.jsxs("span",{className:"cia-inbox-head-nombre",children:[t.jsx("strong",{children:ga(ee)}),ee.importante?t.jsx(K1,{t:e}):null]}),t.jsxs("span",{className:"cia-inbox-head-estado",children:[t.jsx("span",{className:"cia-inbox-sub",children:TA(ee)}),ee.state==="closed"?t.jsx(at,{tone:"neutral",label:e("whatsapp.inbox.closed"),icon:!1}):ee.state==="snoozed"?t.jsx(at,{tone:"neutral",label:e("whatsapp.inbox.snoozedBadge"),icon:!1}):t.jsx(at,{tone:"success",label:e("whatsapp.inbox.open"),icon:!1}),Gt?.abierta&&br(Gt.segundosRestantes)?t.jsx(Ra,{label:e("whatsapp.inbox.windowLeft",{time:br(Gt.segundosRestantes)}),position:"bottom",children:t.jsxs("span",{className:"cia-inbox-head-ventana",children:[t.jsx("span",{"aria-hidden":"true",children:t.jsx(at,{tone:Gt.segundosRestantes<3600?"warning":"info",icon:Qa,label:e("whatsapp.inbox.windowLeftShort",{time:br(Gt.segundosRestantes)})})}),t.jsx("span",{className:"cia-sr-only",children:e("whatsapp.inbox.windowLeft",{time:br(Gt.segundosRestantes)})})]})}):ee.state!=="closed"&&Gt&&!Gt.abierta?t.jsx(at,{tone:"warning",label:e("whatsapp.inbox.windowExpiredShort")}):null,Hi==="esperando"&&Ao!==null?t.jsx(at,{tone:"info",pulse:!0,label:e("whatsapp.inbox.turn.waiting",{seconds:Ao})}):null,t.jsx("span",{ref:O,className:"cia-inbox-head-llamada"})]}),ee.numeroPropio?t.jsxs("span",{className:"cia-inbox-linea-head",children:[t.jsx(yn,{"aria-hidden":!0}),ee.numeroPropioNombre?e("whatsapp.inbox.receivedOnNamed",{number:ee.numeroPropio,name:ee.numeroPropioNombre}):e("whatsapp.inbox.receivedOn",{number:ee.numeroPropio})]}):null]})]}),t.jsxs("div",{className:"cia-inbox-head-der",children:[r&&ee.state!=="closed"?t.jsxs("span",{className:"cia-inbox-atiende",children:[t.jsx("span",{className:"cia-inbox-atiende-label","aria-hidden":"true",children:e("whatsapp.inbox.atiende")}),t.jsx(MR,{conversationId:ee.id,mode:ee.mode,assigneeUserId:ee.assigneeUserId,puedeOperar:r,yo:i?.id??null,onCambio:()=>{a.invalidateQueries({queryKey:["wa-conversations"]})}},ee.id)]}):null,t.jsxs(Ll,{size:"md","aria-label":e("whatsapp.inbox.encabezado.accionesDelChat"),children:[ee.state!=="closed"?t.jsx(jO,{conversationId:ee.id,contactExternalId:ee.contactExternalId,llamadas:ee.llamadas??null,puedeLlamar:lt(i,"calls.operate"),puedeVerLlamadas:lt(i,"calls.view"),puedeOperar:r,estadoEn:P},ee.id):null,t.jsx(Lt,{icon:t.jsx(Mn,{}),label:e("whatsapp.inbox.buscarHilo.abrir"),active:E,onClick:()=>I(q=>!q),tooltipPosition:"bottom"}),t.jsx(Lt,{icon:t.jsx(Mi,{}),label:e("whatsapp.inbox.detalle"),active:yt,onClick:()=>He(q=>!q),tooltipPosition:"bottom"}),t.jsx(qO,{conversacion:ee,permisos:{puedeOperar:r,puedeVer:lt(i,"whatsapp.view"),puedeManejar:lt(i,"whatsapp.manage"),esAdminReal:i?.role==="admin"&&!o},masRecienteId:Gh,agenteActualId:lj,yo:i?.id??null,onNavegar:Jc,onReabierta:q=>void rm(q,ga(ee)),onCerrar:()=>Ki(!0),onPlantilla:()=>B({tipo:"hilo",conversationId:ee.id,contacto:ga(ee)}),onEliminada:pj},ee.id)]})]})]})}),E?t.jsx(MO,{conversationId:ee.id,onCerrar:()=>I(!1),onIrAMensaje:q=>void uj(q),avisoNoAlcanzado:V}
978):null,t.jsx(ot,{open:cj,onClose:()=>Ki(!1),title:e("whatsapp.inbox.closeTitle"),footer:t.jsxs(t.Fragment,{children:[t.jsx(Ie,{onClick:()=>Ki(!1),children:e("whatsapp.inbox.closeCancel")}),t.jsx(Ie,{variant:"cta",onClick:()=>im.mutate(),loading:im.isPending,children:e("whatsapp.inbox.closeConfirm")})]}),children:e("whatsapp.inbox.closeDesc")}),F?t.jsx(le,{tone:"bad",children:F}):null,r&&ee.state!=="closed"&&Gt&&!Gt.abierta?t.jsx(le,{tone:"info",action:{label:e("whatsapp.enviarPlantilla.abrirDesdeHilo"),onClick:()=>B({tipo:"hilo",conversationId:ee.id,contacto:ga(ee)})},children:Gt.motivo==="vencida"?e("whatsapp.inbox.windowExpired"):e("whatsapp.inbox.neverWrote")}):null,Hi&&r?t.jsxs(le,{tone:"info",action:sm.isPending?void 0:{label:e("whatsapp.inbox.turn.take"),onClick:()=>sm.mutate("human")},children:[Hi==="esperando"&&Ao!==null?e("whatsapp.inbox.turn.aboutToAnswer",{seconds:Ao}):e("whatsapp.inbox.turn.answeringNow"),Hi==="esperando"&&Yh?` ${e(`whatsapp.inbox.turn.porque.${Yh}`,{defaultValue:""})}`:null]}):null]}),footer:t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:om,type:"file",accept:hj,hidden:!0,onChange:q=>{fj(q.target.files?.[0]??null),q.target.value=""}}),r&&Gt?.abierta&&ee.state!=="closed"&&!g.trim()&&(X.data?.length??0)>0?t.jsx(iE,{items:X.data.slice(0,6).map(q=>({id:q.id,text:q.texto})),onSelect:(q,Ne)=>D(Ne.id,q),ariaLabel:e("whatsapp.inbox.snippets.sugeridas")}):null,t.jsx(tv,{layout:"apilado",value:g,onChange:v,insertar:de,onSubmit:q=>lm.mutate(q),loading:lm.isPending||zo.isPending,placeholder:e("whatsapp.inbox.placeholder"),noticeReplacesField:ee.state==="closed",header:ee.state==="closed"?t.jsx(UO,{conversationId:ee.id,puedeOperar:r,masRecienteId:Gh,onNavegar:Jc,onReabierta:q=>void rm(q,ga(ee))},ee.id):Mo?t.jsxs("div",{className:"cia-inbox-citando",children:[t.jsx("span",{className:"cia-inbox-citando-icono","aria-hidden":"true",children:t.jsx(Yb,{})}),t.jsxs("span",{className:"cia-inbox-citando-texto",children:[t.jsx("strong",{children:e("whatsapp.inbox.respondiendoA")})," ",Mo.resumen||e("whatsapp.inbox.citaSinTexto")]}),t.jsx(Lt,{size:"sm",icon:t.jsx(nt,{}),label:e("whatsapp.inbox.quitarCita"),className:"cia-inbox-citando-quitar",onClick:()=>Qi(null)})]}):void 0,leadingActions:t.jsxs(Ll,{size:"md","aria-label":e("whatsapp.inbox.composer.acciones"),children:[t.jsx(Or,{iconTrigger:{icon:t.jsx(py,{}),label:e("whatsapp.inbox.emoji.abrir"),variant:"outline"},ariaLabel:e("whatsapp.inbox.emoji.abrir"),width:296,open:y,onOpenChange:k,disabled:!r||!Gt?.abierta||ee.state==="closed",children:t.jsx(I_,{embedded:!0,onClose:()=>k(!1),onPick:z,labels:{titulo:e("whatsapp.inbox.emoji.abrir"),buscar:e("whatsapp.inbox.emoji.buscar"),sinResultados:e("whatsapp.inbox.emoji.sinResultados"),grupos:{frecuentes:e("whatsapp.inbox.emoji.grupos.frecuentes"),gente:e("whatsapp.inbox.emoji.grupos.gente"),gestos:e("whatsapp.inbox.emoji.grupos.gestos"),objetos:e("whatsapp.inbox.emoji.grupos.objetos"),simbolos:e("whatsapp.inbox.emoji.grupos.simbolos")}}})}),t.jsx(Or,{iconTrigger:{icon:t.jsx(fy,{}),label:e("whatsapp.inbox.snippets.titulo"),variant:"outline"},ariaLabel:e("whatsapp.inbox.snippets.titulo"),width:320,disabled:!r||!Gt?.abierta||ee.state==="closed",children:({close:q})=>t.jsxs(t.Fragment,{children:[t.jsx("div",{role:"listbox","aria-label":e("whatsapp.inbox.snippets.titulo"),style:{display:"flex",flexDirection:"column",gap:2,maxHeight:280,overflowY:"auto"},children:(X.data??[]).length?X.data.map(Ne=>t.jsxs("button",{type:"button",className:"cia-snippet-elegir",onClick:()=>{D(Ne.id,Ne.texto),q()},children:[t.jsxs("span",{className:"cia-snippet-atajo",children:["/",Ne.atajo]}),t.jsx("span",{className:"cia-snippet-texto",children:Ne.texto})]},Ne.id)):t.jsx("div",{className:"cia-snippet-vacio",children:t.jsx("span",{children:e("whatsapp.inbox.snippets.vacioLista")})})}),t.jsxs(et,{to:"/whatsapp",search:{tab:"atencion"},className:"cia-snippet-administrar",onClick:()=>q(),children:[e("whatsapp.inbox.snippets.administrar"),t.jsx(oa,{"aria-hidden":"true"})]})]})}),t.jsx($F,{borrador:g,respuestas:X.data??[],onElegir:ie}),t.jsx(Lt,{icon:t.jsx(e2,{}),variant:"outline",label:e("whatsapp.inbox.attach.button"),onClick:()=>om.current?.click(),disabled:!r||!Gt?.abierta||ee.state==="closed"||zo.isPending})]}),trailingActions:t.jsx(yO,{deshabilitado:!r||!Gt?.abierta||ee.state==="closed"||zo.isPending,onMandar:mj,labels:{grabar:e("whatsapp.inbox.voz.grabar"),parar:e("whatsapp.inbox.voz.parar"),mandar:e("whatsapp.inbox.voz.mandar"),descartar:e("whatsapp.inbox.voz.descartar"),sinPermiso:e("whatsapp.inbox.voz.sinPermiso")}}),disabled:!r||!Gt?.abierta||ee.state==="closed",disabledReason:g8(e,{puedeResponder:r,cerrada:ee.state==="closed",motivo:Gt?.motivo})})]}),children:[Xc.isLoading?t.jsx(ge,{h:320}):t.jsx(x_,{items:Po.visibles,keyOf:q=>q.id,dayKeyOf:q=>MA(q.occurredAt),dayLabelOf:q=>n_(q),emptyText:e("whatsapp.inbox.threadEmpty"),onLoadOlder:()=>{jn.isFetchingNextPage||jn.fetchNextPage()},loadingOlder:jn.isFetchingNextPage,noMoreOlder:!!jn.data&&jn.hasNextPage===!1,renderItem:(q,Ne)=>{const jt=IA(q);if(jt)return t.jsx(hO,{tarjeta:jt,occurredAt:q.occurredAt});const Rt=AA(Po.visibles,Ne),Da=RA(q);
978return t.jsxs(p_,{id:`cia-msg-${q.id}`,highlighted:K===q.id,side:Si(q),runStart:Rt.runStart,runEnd:Rt.runEnd,metaPosition:"arriba",senderLabel:u8(q,ee,e),timeLabel:h8(q.occurredAt),timeTitle:Be(q.occurredAt),avatar:Rt.runEnd?p8(q,ee):void 0,actions:t.jsx(uO,{onResponder:q.citable?()=>Qi({id:q.id,resumen:zA(q)}):void 0,onReaccionar:q.citable?Ia=>xj.mutate({messageId:q.id,emoji:Ia}):void 0,reacciones:Po.reaccionesPor[q.id]}),status:jh(q)==="celular_del_dueno"?t.jsx("span",{className:"cia-inbox-confirmando",children:e("whatsapp.inbox.fromPhone")}):Da==="confirmando"?t.jsx("span",{className:"cia-inbox-confirmando",children:e("whatsapp.inbox.confirming")}):Da?t.jsx(Uj,{state:Da}):void 0,children:[t.jsx(dO,{conversationId:ee.id,mensaje:q,onVer:To,reacciones:Po.reaccionesPor[q.id]}),Da==="failed"?t.jsx("div",{className:"cia-inbox-motivo-fallo",role:"note",children:q.errorCode&&q.errorCode!=="rechazo_desconocido"?e(`whatsapp.errors.${q.errorCode}`,{defaultValue:e("whatsapp.inbox.falloMotivoDesconocido")}):e("whatsapp.inbox.falloMotivoDesconocido")}):null]})}}),Hi==="contestando"?t.jsxs("div",{className:"cia-inbox-typing",children:[t.jsx(tE,{}),t.jsx("span",{children:e("whatsapp.inbox.turn.answeringNow")})]}):null,Jh&&tm.length?t.jsx(vO,{conversationId:ee.id,medios:tm,inicial:Jh,onCerrar:()=>To(null)}):null]}):Oe?t.jsx("div",{style:{padding:14},"aria-busy":"true",children:t.jsx(ge,{h:320})}):t.jsx(st,{icon:Ba,title:e("whatsapp.inbox.emptyTitle"),desc:e("whatsapp.inbox.emptyDesc")})})}),t.jsx(Rp,{open:pe,onClose:()=>ye(!1),title:e("whatsapp.inbox.resumenBoton"),width:420,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsx(RO,{puedeVer:lt(i,"whatsapp.view")}),t.jsx(TO,{puedeVer:lt(i,"whatsapp.view"),puedeCurar:lt(i,"whatsapp.manage"),filtrada:Ee,onFiltrar:q=>{L(q),ye(!1)}})]})}),te?t.jsx(sO,{abierto:!0,destino:te,onCerrar:()=>B(null),onEnviada:q=>{B(null),h(q),a.invalidateQueries({queryKey:["wa-conversations"]})}}):null]})}function c8(e,a,n,s,i,r){const l=a?.abierta&&a.segundosRestantes!==null&&a.segundosRestantes<10800?br(a.segundosRestantes):null,c=e.assigneeUserId?e.assigneeUserId===n?s("whatsapp.inbox.asignar.yo"):null:e.mode==="agent"?s("whatsapp.inbox.asignar.ia"):s("whatsapp.inbox.asignar.nadie");return t.jsxs(t.Fragment,{children:[FA(e.id,i,r)?t.jsx(at,{tone:"info",label:s("whatsapp.inbox.borrador.chip"),icon:!1}):null,c?t.jsx(at,{tone:"neutral",label:c,icon:!1}):null,e.state==="closed"?t.jsx(at,{tone:"neutral",label:s("whatsapp.inbox.closed"),icon:!1}):null,e.state==="snoozed"?t.jsx(at,{tone:"neutral",label:s("whatsapp.inbox.snoozedBadge"),icon:!1}):null,l?t.jsx(at,{tone:"warning",label:s("whatsapp.inbox.windowLeft",{time:l})}):null,e.etiquetas&&e.etiquetas.length>0?t.jsxs(t.Fragment,{children:[e.etiquetas.slice(0,3).map(d=>t.jsx(ps,{label:d.nombre,tone:d.color},d.id)),e.etiquetas.length>3?t.jsxs("span",{style:{fontSize:"var(--cia-fs-2xs)",color:"var(--cia-text-2)"},children:["+",e.etiquetas.length-3]}):null]}):null]})}function d8(e,a){if(!(!e.importante&&!e.silenciada))return t.jsxs(t.Fragment,{children:[e.importante?t.jsx(K1,{t:a}):null,e.silenciada?t.jsxs("span",{className:"cia-inbox-marca","data-marca":"silenciada",children:[t.jsx(Qp,{"aria-hidden":"true"}),t.jsx("span",{className:"cia-sr-only",children:a("whatsapp.inbox.marcas.silenciada")})]}):null]})}function K1({t:e}){return t.jsxs("span",{className:"cia-inbox-marca","data-marca":"importante",children:[t.jsx(Ii,{"aria-hidden":"true"}),t.jsx("span",{className:"cia-sr-only",children:e("whatsapp.inbox.marcas.importante")})]})}function u8(e,a,n){if(Si(e)==="in")return ga(a);const s=jh(e);if(s==="celular_del_dueno")return n("whatsapp.inbox.fromPhone");if(s==="agente")return n("whatsapp.inbox.autoria.agente");if(s==="equipo")return n("whatsapp.inbox.autoria.equipo")}function p8(e,a){if(Si(e)==="in")return t.jsx(Sn,{name:ga(a),size:"sm"});const n=jh(e);return n==="agente"?t.jsx(Sn,{name:"IA",initials:"IA",size:"sm",tone:"var(--cia-brand-500)"}):n==="celular_del_dueno"?t.jsx(Sn,{name:"•",initials:"•",size:"sm"}):t.jsx(Sn,{name:"Equipo",initials:"EQ",size:"sm"})}function h8(e){const a=new Date(e);return Number.isNaN(a.getTime())?"":a.toLocaleTimeString(Te(),{hour:"2-digit",minute:"2-digit"})}function m8(e,a,n,s,i,r){const o=()=>{r.invalidateQueries({queryKey:["wa-conversations"]})};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:12},children:[t.jsx(AO,{conversacion:e,puedeVerContactos:lt(n,"contacts.view"),tipificaciones:(l,c)=>t.jsx($1,{conversationId:e.id,puestas:e.etiquetas??[],puedeOperar:s,onCambio:o,fechas:l,autores:c})},e.id),t.jsx(NO,{conversationId:e.id,puedeVer:lt(n,"whatsapp.view")}),t.jsx(PR,{conversationId:e.id,state:e.state,snoozedUntil:e.snoozedUntil??null,puedeOperar:s,onCambio:o},e.id),t.jsx(wO,{conversationId:e.id,esSuperadmin:n?.role==="superadmin"})]})}function f8(e,a){const n=e.ultimoMensaje;if(!n)return null;const s=n.texto?n.texto:n.tipo&&n.tipo!=="text"?a(`whatsapp.inbox.resumen.${n.tipo}`,{defaultValue:a("whatsapp.inbox.resumen.archivo")}):null;return s?n.direction==="outbound"?a("whatsapp.inbox.resumen.propio",{texto:s}):s:null}function x8(e,a){const n=e.numeroPropioNombre??e.numeroPropio;return n?a("whatsapp.inbox.enLinea",{linea:n}):null}function g8(e,a){if(!a.cerrada){if(!a.puedeResponder)return e("whatsapp.inbox.noPermission");if(a.motivo==="vencida")return e("whatsapp.inbox.windowExpired");if(a.motivo==="sin_mensaje_entrante")return e("whatsapp.inbox.neverWrote")}}const ls="knowledge";function cu(e){return he.t(`${ls}:status.${e}`,{defaultValue:e})}function Cp(e){return e?he.t(`${ls}:error.${e}`,{defaultValue:e}):he.t(`${ls}:error.unknown`)}function b8(e){const n={file:"sources.typeFile",text:"sources.typeText",faq:"sources.typeFaq",url:"sources.typeUrl",site:"sources.typeSite"}[e];return n?he.t(`${ls}:${n}`):e}function y8(e){return he.t(`${ls}:sources.pageStatus.${e}`,{defaultValue:e})}function v8(e){return e?he.t(`${ls}:sources.pageReason.${e}`,{defaultValue:e}):he.t("format:dash")}function j8(e,a){const n=e||"cap";return he.t(`${ls}:sources.truncated.${n}`,{max:ja(a),defaultValue:he.t(`${ls}:sources.truncated.cap`,{max:ja(a)})})}function ja(e){const a=Number(e??0);
978return(isFinite(a)?a:0).toLocaleString(Te(),{maximumFractionDigits:0})}function uc(e){const a=Number(e??0);if(!isFinite(a)||a<=0)return he.t("format:dash");const n=(s,i)=>s.toLocaleString(Te(),{maximumFractionDigits:i});return a<1024?`${n(a,0)} B`:a<1024*1024?`${n(a/1024,1)} KB`:`${n(a/(1024*1024),1)} MB`}function w8({usage:e,loading:a}){const{t:n}=M("knowledge");if(a)return t.jsxs("div",{className:"cia-card",style:{padding:16},children:[t.jsx(ge,{w:"40%",h:12}),t.jsxs("div",{style:{marginTop:12,display:"grid",gap:10},children:[t.jsx(ge,{w:"100%",h:8}),t.jsx(ge,{w:"100%",h:8})]})]});if(!e)return null;const{limits:s}=e,i=e.storageBytes/(1024*1024),r=(l,c,d)=>c==null?`${l} · ${n("limits.unlimited")}`:n("limits.usedOf",{used:l,max:c}),o=[{icon:Jb,label:n("limits.bases"),detail:r(e.kbCount,s.maxKnowledgeBases),value:s.maxKnowledgeBases?e.kbCount/s.maxKnowledgeBases:null},{icon:ey,label:n("limits.sources"),detail:r(e.sourceCount,s.maxKbSources),value:s.maxKbSources?e.sourceCount/s.maxKbSources:null},{icon:ty,label:n("limits.storage"),detail:s.maxKbStorageMb==null?`${uc(e.storageBytes)} · ${n("limits.unlimited")}`:n("limits.usedOf",{used:uc(e.storageBytes),max:`${s.maxKbStorageMb} MB`}),value:s.maxKbStorageMb?i/s.maxKbStorageMb:null},{icon:Jp,label:n("limits.urls"),detail:r(e.urlCount,s.maxKbUrls),value:s.maxKbUrls?e.urlCount/s.maxKbUrls:null}];return t.jsxs("div",{className:"cia-card",style:{padding:16,display:"flex",flexDirection:"column",gap:12},children:[t.jsx("div",{className:"cia-eyebrow",children:n("limits.title")}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:14},children:o.map(l=>{const c=l.icon;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx(c,{size:13,style:{color:"var(--cia-brand-500)",flex:"none"},"aria-hidden":!0}),t.jsx("span",{style:{fontSize:12,fontWeight:600,color:"var(--cia-text-2)"},children:l.label})]}),t.jsx(Ic,{value:l.value??0,variant:l.value==null?"ok":"auto",height:6}),t.jsx("span",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)"},children:l.detail})]},l.label)})}),s.maxKbCrawlPages!==void 0&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[t.jsx(Va,{size:13,style:{color:"var(--cia-brand-500)",flex:"none"},"aria-hidden":!0}),t.jsx("span",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)"},children:s.maxKbCrawlPages===0?n("limits.sitePagesNone"):n("limits.sitePages",{max:ja(Z0(s.maxKbCrawlPages))})})]}),!e.enabled&&t.jsx(le,{tone:"warn",children:n("limits.disabled")})]})}function H1({open:e,onClose:a,onSubmit:n,saving:s,error:i,mode:r="create",initial:o}){const{t:l}=M("knowledge"),[c,d]=m.useState(""),[u,p]=m.useState(""),[f,x]=m.useState(null),h=r==="edit",b=o?.name??"",g=o?.description??"";m.useEffect(()=>{e&&(d(b),p(g),x(null))},[e,b,g]);function v(){x(null);const y=c.trim();if(!y||y.length>120)return x(l("create.errName"));n({name:y,description:u.trim()||void 0})}return t.jsx(ot,{open:e,onClose:a,maxWidth:520,eyebrow:l("create.eyebrow"),title:l(h?"create.titleEdit":"create.titleCreate"),footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"cia-btn cia-btn-outline",onClick:a,disabled:s,children:l("create.cancel")}),t.jsxs("button",{className:"cia-btn cia-btn-cta",onClick:v,disabled:s,children:[s&&t.jsx(je,{className:"animate-spin",size:15}),l(h?"create.submitEdit":"create.submitCreate")]})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:l("create.nameLabel")}),t.jsx("input",{className:"input",style:{width:"100%",marginTop:4},type:"text",placeholder:l("create.namePh"),value:c,maxLength:120,autoFocus:!0,onChange:y=>d(y.target.value)})]}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:l("create.descLabel")}),t.jsx("textarea",{className:"input",style:{width:"100%",minHeight:80,marginTop:4,resize:"vertical"},placeholder:l("create.descPh"),value:u,maxLength:500,onChange:y=>p(y.target.value)}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:6},children:l("create.descHint")})]}),(f||i)&&t.jsx(le,{tone:f?"bad":"warn",children:f||i})]})})}function ya(e){const a=e?.response?.data?.message;return Array.isArray(a)?a.join(" · "):a||he.t("knowledge:errors.generic")}function k8(e){const a=e?.response?.data;return e?.response?.status!==409||a?.code!=="kb_en_uso_por_whatsapp"?null:(Array.isArray(a?.agents)?a.agents:[]).filter(s=>s&&typeof s.id=="string"&&s.id).map(s=>({id:s.id,name:typeof s.name=="string"&&s.name.trim()?s.name:s.id}))}function N8({agents:e}){const{t:a}=M("agents"),n=dt();return t.jsxs(le,{tone:"bad",title:a("knowledge.deleteBlocked.title"),children:[t.jsx("span",{style:{display:"block"},children:a("knowledge.deleteBlocked.body")}),e.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{display:"block",marginTop:8,fontWeight:600},children:a("knowledge.deleteBlocked.agentsLabel",{count:e.length})}),t.jsx("ul",{style:{listStyle:"none",margin:"4px 0 0",padding:0,display:"flex",flexDirection:"column",gap:2,minWidth:0},children:e.map(s=>t.jsx("li",{style:{minWidth:0},children:t.jsxs("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{color:"inherit",maxWidth:"100%"},onClick:()=>n({to:"/agents/$agentId",params:{agentId:s.id}}),"aria-label":a("knowledge.deleteBlocked.openAgent",{name:s.name}),children:[t.jsx(Ft,{size:12,"aria-hidden":!0}),t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.name}),t.jsx(oa,{size:12,"aria-hidden":!0})]})},s.id))})]})]})}function S8({onOpen:e,autoOpenCreate:a=!1,initial:n,onAutoOpenDismiss:s}){const{t:i}=M("knowledge");Pe(E=>E.user?.role);const{can:r}=tt(),o=r("knowledge.operate"),l=Hc(),c=J0(),d=Zz(),[u,p]=m.useState(!1),[f,x]=m.useState(null),[h,b]=m.useState(!1),[g,v]=m.useState(null),y=m.useRef(!1),k=l.data?.bases??[],w=c.data,j=w?.limits.maxKnowledgeBases??null,C=j!=null&&(w?.kbCount??0)>=j,N=w?!w.enabled:!1,S=o&&!C&&!N;m.useEffect(()=>{if(!(!a||y.current||c.isLoading)){if(y.current=!0,S){x(null),b(!0),p(!0);return}v(o?C?"limit":null:"permission")}},[a,c.isLoading,S,o,C]);const _=()=>{x(null),b(!1),p(!0)},R=()=>{p(!1),h&&(b(!1),s?.())},A=E=>{x(null);const I=h;d.mutate(E,{onSuccess:P=>{p(!1),b(!1),J({tone:"ok",title:i("create.toastCreated",{name:P.name})}),e(P.id,I)},onError:P=>x(ya(P))})};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(w8,{usage:w,loading:c.isLoading}),t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[t.jsx("p",{style:{fontSize:13.5,color:"var(--cia-text-3)",maxWidth:560,margin:0,lineHeight:1.6},children:i("list.intro")}),o&&t.jsx("span",{title:C?i("list.newKbBlocked"):void 0,style:{flex:"none"},children:t.jsxs("button",{className:"cia-btn cia-btn-primary",disabled:!S,onClick:_,children:[t.jsx(Fe,{size:15})," ",i("list.newKb")]})})]}),g&&t.jsx(le,{tone:g==="limit"?"warn":"info",children:i(g==="limit"?"list.newKbBlocked":"common:noPermission")}),l.isLoading?t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(280px, 1fr))",gap:14},children:[0,1,2].map(E=>t.jsxs("div",{className:"cia-card",style:{padding:18},children:[t.jsx(ge,{w:"60%",h:14}),t.jsx("div",{style:{marginTop:10},children:t.jsx(ge,{w:"90%",h:10})})]},E))}):l.error?t.jsx(le,{tone:"bad",children:i("list.loadError")}):k.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{icon:ua,title:i("list.empty.title"),desc:i("list.empty.desc"),action:S?{label:i("list.newKb"),onClick:_,icon:Fe}:void 0})}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(280px, 1fr))",gap:14},children:k.map(E=>t.jsx(C8,{kb:E,onOpen:()=>e(E.id)},E.id))}),t.jsx(H1,{open:u,onClose:R,onSubmit:A,saving:d.isPending,error:f,mode:"create",initial:h?n:void 0})]})}function C8({kb:e,onOpen:a}){const{t:n}=M("knowledge");return t.jsxs("button",{type:"button",className:"cia-card cia-fade-up cia-row-hover",onClick:a,style:{padding:18,dis
978play:"flex",flexDirection:"column",alignItems:"stretch",gap:10,textAlign:"left",cursor:"pointer",font:"inherit",color:"var(--cia-text)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[t.jsx(ua,{size:16,style:{color:"var(--cia-brand-500)",flex:"none"},"aria-hidden":!0}),t.jsx("span",{style:{fontSize:14.5,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]}),e.description&&t.jsx("p",{style:{margin:0,fontSize:12.5,lineHeight:1.5,color:"var(--cia-text-3)",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:e.description}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:"auto"},children:[t.jsxs("span",{className:"cia-badge",children:[t.jsx(ey,{size:11,"aria-hidden":!0})," ",n("list.card.sources",{count:e.sourceCount})]}),t.jsxs("span",{className:"cia-badge",children:[t.jsx(ty,{size:11,"aria-hidden":!0})," ",uc(e.storageBytes)]}),e.pendingCount>0&&t.jsxs("span",{className:"cia-badge",children:[t.jsx(je,{className:"animate-spin",size:11,"aria-hidden":!0})," ",n("list.card.processing",{count:e.pendingCount})]}),e.failedCount>0&&t.jsx("span",{className:"cia-badge cia-badge-warn",children:n("list.card.failed",{count:e.failedCount})}),e.agentsCount>0&&t.jsxs("span",{className:"cia-badge cia-badge-success",children:[t.jsx(Ft,{size:11,"aria-hidden":!0})," ",n("list.card.agents",{count:e.agentsCount})]})]}),t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-4)"},children:n("list.card.updated",{date:ts(e.updatedAt)})})]})}const _8=[25,50,100],E8={ready:"cia-badge cia-badge-success",skipped:"cia-badge",failed:"cia-badge cia-badge-bad"},A8=e=>/^https?:\/\//i.test(e);function R8({open:e,onClose:a,kbId:n,doc:s}){const{t:i}=M("knowledge"),r=dt(),{can:o}=tt(),[l,c]=m.useState("all"),[d,u]=m.useState(0),[p,f]=m.useState(50),x=Qz(n,s?.id,{status:l,offset:d*p,limit:p},e&&!!s),h=s?.crawl??null,b=!!h&&h.maxPages>0&&(h.pagesFetched>=h.maxPages||h.truncated&&h.truncatedReason==="cap"),g=[{key:"url",header:i("sources.pages.colPage"),render:(k,w)=>t.jsxs("div",{style:{minWidth:0,maxWidth:320},children:[t.jsx("div",{style:{fontSize:12.5,fontWeight:600,wordBreak:"break-word"},children:w.title||i("sources.pages.untitled")}),A8(w.url)?t.jsxs("a",{href:w.url,target:"_blank",rel:"noopener noreferrer nofollow","aria-label":i("sources.pages.openAria",{url:w.url}),className:"cia-mono",style:{display:"inline-flex",alignItems:"center",gap:4,marginTop:2,fontSize:10.5,color:"var(--cia-text-3)",wordBreak:"break-all"},children:[w.url,t.jsx(Ja,{size:10,"aria-hidden":!0,style:{flex:"none"}})]}):t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)",wordBreak:"break-all"},children:w.url})]})},{key:"status",header:i("sources.pages.colStatus"),width:"150px",render:(k,w)=>t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,alignItems:"flex-start"},children:[t.jsx("span",{className:E8[w.status]??"cia-badge",children:y8(w.status)}),w.reason&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-text-3)",lineHeight:1.35},children:v8(w.reason)})]})},{key:"chunkCount",header:i("sources.pages.colChunks"),align:"right",width:"90px",render:(k,w)=>t.jsx("span",{className:"cia-mono",style:{fontSize:12,color:"var(--cia-text-2)"},children:w.status==="ready"?ja(w.chunkCount):i("format:dash")})}],v=x.data,y=v?.items??[];return t.jsx(Rp,{open:e,onClose:a,eyebrow:s?.name,title:i("sources.pages.title"),width:640,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx("p",{style:{margin:0,fontSize:12.5,color:"var(--cia-text-3)",lineHeight:1.55},children:i("sources.pages.readOnly")}),b&&h&&t.jsx(le,{tone:"warn",action:o("billing.manage")?{label:i("sources.siteLimitCta"),icon:oa,onClick:()=>{a(),r({to:"/plan"})}}:void 0,children:i("sources.siteLimitNotice",{max:ja(h.maxPages)})}),t.jsx("div",{style:{overflowX:"auto",maxWidth:"100%"},className:"cia-scroll-x",children:t.jsx(Yn,{ariaLabel:i("sources.pages.filterAria"),value:l,onChange:k=>{c(k),u(0)},options:[{value:"all",label:i("sources.pages.filterAll")},{value:"ready",label:i("sources.pages.filterReady")},{value:"skipped",label:i("sources.pages.filterSkipped")},{value:"failed",label:i("sources.pages.filterFailed")}]})}),x.isError?t.jsx(le,{tone:"bad",action:{label:i("sources.pages.retry"),icon:Di,onClick:()=>void x.refetch(),loading:x.isFetching},children:i("sources.pages.loadError")}):x.isLoading||!v?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[0,1,2,3].map(k=>t.jsxs("div",{className:"cia-card",style:{padding:12,display:"grid",gap:6},children:[t.jsx(ge,{w:"45%",h:12}),t.jsx(ge,{w:"80%",h:10})]},k))}):v.total===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{mini:!0,icon:IS,title:i(l==="all"?"sources.pages.emptyNoCrawl.title":"sources.pages.empty.title"),desc:i(l==="all"?"sources.pages.emptyNoCrawl.desc":"sources.pages.empty.desc")})}):t.jsxs(t.Fragment,{children:[t.jsx(hh,{columns:g,rows:y,rowKey:"id"}),t.jsx(Yy,{page:d,pageSize:p,total:v.total,pageSizeOptions:_8,onPageChange:u,onPageSizeChange:k=>{f(k),u(0)},itemLabel:i("sources.pages.itemLabel")})]})]})})}const T8={file:_n,text:fS,faq:GS,url:Jp,site:Va},M8={pending:"cia-badge",processing:"cia-badge",ready:"cia-badge cia-badge-success",failed:"cia-badge cia-badge-bad"};function P8(e){const a=(e.mimeType??"").toLowerCase(),n=(e.name??"").toLowerCase();return a.includes("csv")||a.includes("spreadsheet")||a.includes("ms-excel")||/\.(csv|xlsx)$/.test(n)}function z8({kbId:e,docs:a,loading:n,usage:s,onAddSource:i}){const{t:r}=M("knowledge");Pe(N=>N.user?.role);const{can:o}=tt(),l=o("knowledge.operate"),c=tD(),d=aD(),u=ng(),p=ng(),[f,x]=m.useState(null),h=f?(a??[]).find(N=>N.id===f)??null:null,b=async N=>{await pa({message:r("sources.deleteConfirm",{name:N.name}),danger:!0})&&c.mutate({kbId:e,docId:N.id},{onSuccess:()=>J({tone:"ok",title:r("sources.toastDeleted")}),onError:S=>J({tone:"bad",title:ya(S)})})},g=N=>{d.mutate({kbId:e,docId:N.id},{onSuccess:()=>
978J({tone:"info",title:r("sources.toastReingest",{name:N.name})}),onError:S=>J({tone:"bad",title:ya(S)})})},v=async N=>{const S=Y0(N.crawl),_=N.crawl?.lastError==="crawl_regressed"&&!S,R=N.crawl?.pagesFetched||N.crawl?.maxPages||1,{min:A,max:E}=Oz(R),I=S?r("sources.refreshSiteRetryConfirm",{name:N.name}):_?r("sources.refreshSiteForceConfirm",{name:N.name,min:A,max:E}):r("sources.refreshSiteConfirm",{name:N.name,min:A,max:E});await pa({message:I,danger:_})&&d.mutate({kbId:e,docId:N.id,force:_},{onSuccess:P=>J({tone:"info",title:P?.mode==="ingest"?r("sources.toastRefreshIngest",{name:N.name}):r("sources.toastRefreshSite",{name:N.name})}),onError:P=>J({tone:"bad",title:ya(P)})})},y=(N,S)=>{u.mutate({kbId:e,docId:N.id,promptMode:S},{onSuccess:()=>J({tone:"ok",title:r(S?"pin.toastOn":"pin.toastOff")}),onError:_=>J({tone:"bad",title:ya(_)})})},k=(N,S)=>{p.mutate({kbId:e,docId:N.id,autoRecrawl:S?"weekly":"off"},{onSuccess:()=>J({tone:"ok",title:S?r("sources.toastWeeklyOn",{name:N.name}):r("sources.toastWeeklyOff",{name:N.name})}),onError:_=>J({tone:"bad",title:ya(_)})})},w=[{key:"name",header:r("sources.colName"),sortable:!0,render:(N,S)=>{const _=T8[S.sourceType]??_n,R=S.sourceType==="site"?S.crawl:null,A=!!R&&(!!R.lastCrawlAt||R.pagesFetched>0||R.skipped>0);return t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,minWidth:0},children:[t.jsx(_,{size:15,style:{color:"var(--cia-brand-500)",flex:"none",marginTop:2},"aria-hidden":!0}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontWeight:600,fontSize:13,wordBreak:"break-word"},children:S.name}),t.jsxs("div",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)",marginTop:2,wordBreak:"break-all"},children:[b8(S.sourceType),(S.sourceType==="url"||S.sourceType==="site")&&S.sourceUrl?` · ${S.sourceUrl}`:""," · ",String(S.lang).toUpperCase()]}),R&&t.jsx("div",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)",marginTop:2},children:R.lastCrawlAt?r("sources.siteCrawled",{done:ja(R.pagesFetched),total:ja(R.maxPages),date:ts(R.lastCrawlAt)}):r("sources.siteNotCrawled")}),R&&A&&t.jsxs("button",{type:"button",className:"cia-badge","aria-label":r("sources.sitePagesAria",{name:S.name}),onClick:()=>x(S.id),style:{marginTop:6,height:24,cursor:"pointer"},children:[t.jsx(sy,{size:11,"aria-hidden":!0}),r("sources.sitePages",{done:ja(R.pagesFetched),skipped:ja(R.skipped)})]}),R&&Dz&&t.jsx(I8,{doc:S,disabled:!l||p.isPending||(s?!s.enabled:!1),onChange:E=>k(S,E)})]})]})}},{key:"sizeBytes",header:r("sources.colSize"),sortable:!0,align:"right",width:"90px",render:(N,S)=>t.jsx("span",{className:"cia-mono",style:{fontSize:12,color:"var(--cia-text-2)"},children:uc(S.sizeBytes)})},{key:"status",header:r("sources.colStatus"),sortable:!0,width:"190px",render:(N,S)=>t.jsx(F8,{doc:S})},{key:"promptMode",header:r("sources.colPin"),align:"center",width:"120px",render:(N,S)=>S.promptEligible?t.jsx("span",{title:r("pin.hint"),children:t.jsx(vt,{checked:S.promptMode,onChange:_=>y(S,_),disabled:!l||u.isPending,label:r("pin.aria",{name:S.name})})}):t.jsx("span",{title:r("pin.ineligible"),style:{color:"var(--cia-text-4)",fontSize:12},children:"—"})},{key:"actions",header:r("sources.colActions"),align:"right",width:"170px",render:(N,S)=>l?t.jsxs("div",{style:{display:"inline-flex",alignItems:"flex-start",gap:4},children:[S.sourceType==="site"&&t.jsx(D8,{doc:S,usage:s,busy:d.isPending,onRefresh:v}),S.sourceType!=="site"&&(S.status==="failed"||S.status==="ready")&&t.jsx("button",{className:"cia-btn cia-btn-outline cia-btn-sm",title:r("sources.retry"),"aria-label":r("sources.retryAria",{name:S.name}),disabled:d.isPending||(s?!s.enabled:!1),onClick:()=>g(S),children:t.jsx(Di,{size:13})}),t.jsx("button",{className:"cia-btn cia-btn-outline cia-btn-sm",style:{color:"var(--cia-bad-500)"},title:r("sources.delete"),"aria-label":r("sources.deleteAria",{name:S.name}),disabled:c.isPending,onClick:()=>b(S),children:t.jsx(mt,{size:13})})]}):null}];if(n)return t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[0,1,2].map(N=>t.jsx("div",{className:"cia-card",style:{padding:14},children:t.jsx(ge,{w:"55%",h:13})},N))});const j=a??[],C=(a??[]).some(P8);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:l&&t.jsxs("button",{className:"cia-btn cia-btn-primary cia-btn-sm",disabled:s?!s.enabled:!1,onClick:i,children:[t.jsx(Fe,{size:14})," ",r("sources.addSource")]})}),C&&t.jsx(le,{tone:"info",children:r("sources.tabularNotice",{rows:s?.limits.maxTabularRows??1e3,cols:s?.limits.maxTabularCols??50})}),j.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{mini:!0,icon:_n,title:r("sources.empty.title"),desc:r("sources.empty.desc"),action:l?{label:r("sources.addSource"),onClick:i,icon:Fe}:void 0})}):t.jsx(hh,{columns:w,rows:j,rowKey:"id"}),t.jsx(R8,{open:!!h,onClose:()=>x(null),kbId:e,doc:h},f??"cerrado")]})}function D8({doc:e,usage:a,busy:n,onRefresh:s}){const{t:i}=M("knowledge"),r=cc(e.crawl),o=r?0:Fz(e.crawl),l=a?!a.enabled:!1,[c,d]=m.useState(0);m.useEffect(()=>{if(o<=0)return;const f=setTimeout(()=>d(x=>x+1),6e4);return()=>clearTimeout(f)},[o,c]);const u=m.useId(),p=r?i("sources.refreshSiteRunning"):o>0?i("sources.refreshCooldown",{count:o}):null;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:3},children:[t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm","aria-label":i("sources.refreshSiteAria",{name:e.name}),"aria-describedby":p?u:void 0,disabled:n||l||r||o>0,onClick:()=>s(e),style:{whiteSpace:"nowrap"},children:[t.jsx(Di,{size:13,"aria-hidden":!0}),i("sources.refreshSite")]}),p&&t.jsx("span",{id:u,className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)",lineHeight:1.35,maxWidth:180,textAlign:"right"},children:p})]})}function I8({doc:e,disabled:a,onChange:n}){const{t:s}=M("knowledge"),i=m.useId(),r=(e.crawl?.autoRecrawl??"weekly")==="weekly",o=r?Wz(e):null,l=o?o.codigo?s("sources.weeklyPausedHint",{error:Cp(o.codigo)}):s("sources.weeklyPausedNoCodeHint"):s(r?"sources.weeklyOnHint":"sources.weeklyOffHint");return t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",ga
978p:8,marginTop:8},children:[t.jsx(vt,{id:i,checked:r,disabled:a,label:s("sources.weeklyAria",{name:e.name}),onChange:n}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("label",{htmlFor:i,style:{fontSize:12,fontWeight:600,color:"var(--cia-text-2)",cursor:a?"default":"pointer"},children:s("sources.weeklyLabel")}),t.jsxs("div",{className:"cia-mono",style:{display:"flex",alignItems:"flex-start",gap:4,fontSize:10.5,color:o?"var(--cia-text-2)":"var(--cia-text-3)",lineHeight:1.35,marginTop:1},children:[o&&t.jsx(Tt,{size:11,"aria-hidden":!0,style:{color:"var(--cia-warn-500)",flex:"none",marginTop:1}}),t.jsx("span",{children:l})]})]})]})}function L8({doc:e}){const{t:a}=M("knowledge"),n=X0(e.crawl),s=n?a("sources.siteProgress",{done:ja(n.hechas),total:ja(n.total)}):e.crawl?.pendingCrawlAt?a("sources.siteIndexing"):a("sources.siteStarting");return t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)"},children:s})}function F8({doc:e}){const{t:a}=M("knowledge"),n=e.sourceType==="site",s=n?e.crawl:null,i=t.jsxs("span",{className:M8[e.status]??"cia-badge",children:[e.status==="processing"&&t.jsx(je,{className:"animate-spin",size:11,"aria-hidden":!0}),cu(e.status)]});if(e.status==="processing")return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:5,minWidth:120},children:[i,t.jsx(qu,{value:e.progressPct??0,height:5,showValue:!0,label:cu(e.status)}),n&&t.jsx(L8,{doc:e})]});if(e.status==="pending"&&n&&cc(s))return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:5,minWidth:120},children:[i,t.jsx(qu,{indeterminate:!0,height:5,label:cu(e.status)}),t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)"},children:a("sources.siteStarting")})]});if(e.status==="failed")return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i,t.jsx("span",{style:{fontSize:11,color:"var(--cia-bad-500)",lineHeight:1.4},children:Cp(e.errorCode)})]});if(e.status==="ready"){const r=cc(s),o=r?X0(s):null;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,alignItems:"flex-start"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,flexWrap:"wrap"},children:[i,r&&t.jsxs("span",{className:"cia-badge",children:[t.jsx(je,{className:"animate-spin",size:11,"aria-hidden":!0}),a("sources.updating")]})]}),o&&t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)"},children:a("sources.updatingProgress",{done:ja(o.hechas),total:ja(o.total)})}),t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)"},children:a("sources.chunksTokens",{chunks:e.chunkCount,tokens:e.tokenCount})}),s?.lastError&&!r&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"cia-badge",style:{whiteSpace:"normal",height:"auto",padding:"3px 8px",lineHeight:1.35},children:[t.jsx(Tt,{size:11,"aria-hidden":!0,style:{color:"var(--cia-warn-500)",flex:"none"}}),a("sources.lastErrorChip",{error:Cp(s.lastError)})]}),t.jsx("span",{style:{fontSize:11,color:"var(--cia-text-3)",lineHeight:1.4},children:a("sources.lastErrorKeep")})]}),s?.truncated&&!r&&t.jsxs("span",{style:{display:"inline-flex",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--cia-text-2)",lineHeight:1.4},children:[t.jsx(Tt,{size:11,"aria-hidden":!0,style:{color:"var(--cia-warn-500)",flex:"none",marginTop:2}}),j8(s.truncatedReason,s.maxPages)]})]})}return i}const O8=".pdf,.docx,.txt,.md,.html,.csv,.xlsx",$8=/\.(pdf|docx|txt|md|html|csv|xlsx)$/i,q8=20,B8=1e5,W8=500;function U8({open:e,onClose:a,kbId:n,kbName:s,usage:i,initialTab:r,initialUrl:o,onAdded:l}){const{t:c}=M("knowledge"),d=Jz(),u=eD(),[p,f]=m.useState("files"),[x,h]=m.useState("es"),[b,g]=m.useState(null),[v,y]=m.useState([]),k=m.useRef(1),[w,j]=m.useState(!1),[C,N]=m.useState(""),[S,_]=m.useState(""),[R,A]=m.useState(""),[E,I]=m.useState([{question:"",answer:""}]),[P,O]=m.useState(""),[K,W]=m.useState(""),[V,U]=m.useState(!1),[X,ie]=m.useState(!1),[de,$]=m.useState(!1),[z,D]=m.useState(""),[F,G]=m.useState(Jx.join(`
979`)),[te,B]=m.useState(!0),ne=i?.limits.maxFileSizeMb??q8,me=i?.limits.maxTextChars??B8,Ee=i?.limits.maxKbCrawlPages,L=Ee===0,re=Iz(P),ke=!L&&(V?X:re);m.useEffect(()=>{e&&(f(r??"files"),h("es"),g(null),y([]),j(!1),N(""),_(""),A(""),I([{question:"",answer:""}]),O(o??""),W(""),U(!1),ie(!1),$(!1),D(""),G(Jx.join(`
980`)),B(!0))},[e]);const H=m.useMemo(()=>[{id:"files",label:c("addSource.tabFiles")},{id:"text",label:c("addSource.tabText")},{id:"faq",label:c("addSource.tabFaq")},{id:"url",label:c("addSource.tabUrl")}],[c]),fe=ve=>{g(null);const Ke=[],He=[];for(const Xe of ve){if(!$8.test(Xe.name)){Ke.push(c("upload.invalidType",{name:Xe.name}));continue}if(Xe.size>ne*1024*1024){Ke.push(c("upload.tooLarge",{name:Xe.name,mb:ne}));continue}He.push({id:k.current++,file:Xe,status:"queued",pct:0})}Ke.length&&g(Ke.join(" · ")),He.length&&y(Xe=>[...Xe,...He])},Z=(ve,Ke)=>y(He=>He.map(Xe=>Xe.id===ve?{...Xe,...Ke}:Xe));async function ae(){const ve=v.filter(Xe=>Xe.status==="queued"||Xe.status==="error");
980if(!ve.length)return g(c("upload.noFiles"));g(null),j(!0);let Ke=0;for(const Xe of ve){Z(Xe.id,{status:"uploading",pct:0,error:void 0});try{await d.mutateAsync({kbId:n,file:Xe.file,lang:x,onProgress:Et=>Z(Xe.id,{pct:Et})}),Z(Xe.id,{status:"done",pct:100}),Ke++}catch(Et){Z(Xe.id,{status:"error",error:ya(Et)})}}j(!1);const He=ve.length;Ke===He?(J({tone:"ok",title:c("upload.toastUploaded",{count:Ke})}),a()):Ke>0&&J({tone:"warn",title:c("upload.toastPartial",{ok:Ke,total:He})})}function pe(){g(null);const ve=C.trim(),Ke=S;if(!ve)return g(c("addText.errTitle"));if(!Ke.trim())return g(c("addText.errContent"));u.mutate({kbId:n,body:{type:"text",title:ve,content:Ke,lang:x}},{onSuccess:()=>{J({tone:"ok",title:c("addText.toastAdded",{name:ve})}),a()},onError:He=>g(ya(He))})}function ye(){g(null);const ve=R.trim();if(!ve)return g(c("addFaq.errTitle"));const Ke=E.map(He=>({question:He.question.trim(),answer:He.answer.trim()})).filter(He=>He.question&&He.answer);if(!Ke.length)return g(c("addFaq.errPairs"));u.mutate({kbId:n,body:{type:"faq",title:ve,faq:Ke,lang:x}},{onSuccess:()=>{J({tone:"ok",title:c("addFaq.toastAdded",{name:ve})}),a()},onError:He=>g(ya(He))})}function qe(ve){const Ke=eg(z),He=eg(F),Xe=tg(Ke,Yx),Et=tg(He,Xx);if(Xe||Et)return $(!0),g(c(Xe??Et,{max:Xe?Yx:Xx,largo:Q0}));u.mutate({kbId:n,body:{type:"site",url:ve,title:K.trim()||void 0,includePaths:Ke,excludePaths:He,autoRecrawl:te?"weekly":"off",lang:x}},{onSuccess:()=>{J({tone:"info",title:c("addUrl.toastSiteQueued")}),l?.(),a()},onError:Yt=>g(ya(Yt))})}function ut(){g(null);const ve=P.trim();if(!ro(ve))return g(c("addUrl.errUrl"));if(ke)return qe(ve);u.mutate({kbId:n,body:{type:"url",url:ve,title:K.trim()||void 0,lang:x}},{onSuccess:()=>{J({tone:"ok",title:c("addUrl.toastAdded")}),l?.(),a()},onError:Ke=>g(ya(Ke))})}const bt=w||u.isPending,Ge=v.filter(ve=>ve.status==="queued"||ve.status==="error").length,yt=t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:c("addSource.langLabel")}),t.jsxs("select",{className:"input",style:{width:"100%",marginTop:4},value:x,disabled:bt,onChange:ve=>h(ve.target.value),children:[t.jsx("option",{value:"es",children:c("addSource.langEs")}),t.jsx("option",{value:"en",children:c("addSource.langEn")})]})]});return t.jsx(ot,{open:e,onClose:bt?()=>{}:a,maxWidth:620,eyebrow:s,title:c("addSource.title"),footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"cia-btn cia-btn-outline",onClick:a,disabled:bt,children:c("addSource.cancel")}),p==="files"&&t.jsxs("button",{className:"cia-btn cia-btn-cta",onClick:ae,disabled:bt||Ge===0,children:[w&&t.jsx(je,{className:"animate-spin",size:15}),c("upload.submit",{count:Math.max(Ge,1)})]}),p==="text"&&t.jsxs("button",{className:"cia-btn cia-btn-cta",onClick:pe,disabled:bt,children:[u.isPending&&t.jsx(je,{className:"animate-spin",size:15}),c("addText.submit")]}),p==="faq"&&t.jsxs("button",{className:"cia-btn cia-btn-cta",onClick:ye,disabled:bt,children:[u.isPending&&t.jsx(je,{className:"animate-spin",size:15}),c("addFaq.submit")]}),p==="url"&&t.jsxs("button",{className:"cia-btn cia-btn-cta",onClick:ut,disabled:bt,children:[u.isPending&&t.jsx(je,{className:"animate-spin",size:15}),c(ke?"addUrl.submitSite":"addUrl.submit")]})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsx(Fi,{items:H,active:p,onChange:ve=>{bt||(f(ve),g(null))}}),p==="files"&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx(ev,{multiple:!0,accept:O8,onFiles:fe,hint:c("upload.dropHint",{mb:ne}),disabled:w}),v.length>0&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:v.map(ve=>t.jsx(V8,{item:ve,disabled:w,onRemove:()=>y(Ke=>Ke.filter(He=>He.id!==ve.id))},ve.id))}),yt]}),p==="text"&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:c("addText.titleLabel")}),t.jsx("input",{className:"input",style:{width:"100%",marginTop:4},type:"text",placeholder:c("addText.titlePh"),value:C,maxLength:255,onChange:ve=>N(ve.target.value)})]}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:c("addText.contentLabel")}),t.jsx("textarea",{className:"input",style:{width:"100%",minHeight:160,marginTop:4,resize:"vertical"},placeholder:c("addText.contentPh"),value:S,maxLength:me,onChange:ve=>_(ve.target.value)}),t.jsx("p",{className:"cia-mono",style:{fontSize:11,marginTop:4,textAlign:"right",color:S.length>=me?"var(--cia-warn-ink)":"var(--cia-text-3)"}
980,children:c("addText.counter",{count:S.length,max:me})})]}),yt]}),p==="faq"&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:c("addFaq.titleLabel")}),t.jsx("input",{className:"input",style:{width:"100%",marginTop:4},type:"text",placeholder:c("addFaq.titlePh"),value:R,maxLength:255,onChange:ve=>A(ve.target.value)})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[E.map((ve,Ke)=>t.jsxs("div",{style:{padding:12,borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-sunken)",display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx("span",{className:"cia-eyebrow",children:c("addFaq.pair",{n:Ke+1})}),E.length>1&&t.jsx("button",{type:"button","aria-label":c("addFaq.removePair",{n:Ke+1}),onClick:()=>I(He=>He.filter((Xe,Et)=>Et!==Ke)),style:{border:"none",background:"transparent",cursor:"pointer",color:"var(--cia-text-3)",display:"inline-flex"},children:t.jsx(mt,{size:14})})]}),t.jsx("input",{className:"input",style:{width:"100%"},type:"text",placeholder:c("addFaq.questionPh"),"aria-label":c("addFaq.question"),value:ve.question,maxLength:500,onChange:He=>I(Xe=>Xe.map((Et,Yt)=>Yt===Ke?{...Et,question:He.target.value}:Et))}),t.jsx("textarea",{className:"input",style:{width:"100%",minHeight:60,resize:"vertical"},placeholder:c("addFaq.answerPh"),"aria-label":c("addFaq.answer"),value:ve.answer,maxLength:4e3,onChange:He=>I(Xe=>Xe.map((Et,Yt)=>Yt===Ke?{...Et,answer:He.target.value}:Et))})]},Ke)),t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",style:{alignSelf:"flex-start"},disabled:E.length>=W8,onClick:()=>I(ve=>[...ve,{question:"",answer:""}]),children:[t.jsx(Fe,{size:13})," ",c("addFaq.addPair")]})]}),yt]}),p==="url"&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"kb-src-url",className:"cia-eyebrow",children:c("addUrl.urlLabel")}),t.jsx("input",{id:"kb-src-url",className:"input cia-mono",style:{width:"100%",marginTop:4},type:"url",inputMode:"url",autoComplete:"url",placeholder:c("addUrl.urlPh"),value:P,maxLength:2048,disabled:bt,onChange:ve=>O(ve.target.value)})]}),t.jsxs("div",{style:{padding:12,borderRadius:"var(--cia-r)",border:`1px solid ${ke?"var(--cia-brand-500)":"var(--cia-border)"}`,background:"var(--cia-bg-sunken)",display:"flex",flexDirection:"column",gap:8,transition:"border-color var(--cia-dur-fast) var(--cia-ease-smooth)"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},children:[t.jsx("label",{htmlFor:"kb-src-crawl",className:"cia-eyebrow",style:{cursor:L?"default":"pointer",margin:0},children:c("addUrl.crawl.label")}),re&&!L&&t.jsx("span",{className:"cia-badge cia-badge-success",children:c("addUrl.crawl.recommended")}),Ee!==void 0&&!L&&t.jsx("span",{className:"cia-badge",children:c("addUrl.crawl.maxChip",{max:ja(Z0(Ee))})})]}),t.jsx(vt,{id:"kb-src-crawl",checked:ke,disabled:bt||L,label:c("addUrl.crawl.aria"),onChange:ve=>{U(!0),ie(ve),g(null)}})]}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",margin:0,lineHeight:1.5},children:c(ke?"addUrl.crawl.desc":"addUrl.hint")})]}),L&&t.jsx(le,{tone:"info",children:c("addUrl.crawl.planNone")}),ke&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("button",{type:"button",className:"cia-btn cia-btn-outline cia-btn-sm",style:{alignSelf:"flex-start"},"aria-expanded":de,"aria-controls":"kb-src-advanced",onClick:()=>$(ve=>!ve),children:[t.jsx(Ut,{size:13,"aria-hidden":!0,style:{transform:de?"rotate(180deg)":"none",transition:"transform var(--cia-dur-fast) var(--cia-ease-smooth)"}}),c("addUrl.crawl.advanced")]}),t.jsx(pv,{open:de,id:"kb-src-advanced",children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,paddingTop:4},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"kb-sr
980c-include",className:"cia-eyebrow",children:c("addUrl.crawl.includeLabel")}),t.jsx("textarea",{id:"kb-src-include",className:"input cia-mono",style:{width:"100%",minHeight:64,marginTop:4,resize:"vertical",fontSize:12.5},placeholder:c("addUrl.crawl.includePh"),value:z,disabled:bt,spellCheck:!1,onChange:ve=>D(ve.target.value)}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:4},children:c("addUrl.crawl.pathsHint")})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"kb-src-exclude",className:"cia-eyebrow",children:c("addUrl.crawl.excludeLabel")}),t.jsx("textarea",{id:"kb-src-exclude",className:"input cia-mono",style:{width:"100%",minHeight:64,marginTop:4,resize:"vertical",fontSize:12.5},placeholder:c("addUrl.crawl.excludePh"),value:F,disabled:bt,spellCheck:!1,onChange:ve=>G(ve.target.value)}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",marginTop:4},children:c("addUrl.crawl.excludeHint")})]})]})}),t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("label",{htmlFor:"kb-src-weekly",className:"cia-eyebrow",style:{cursor:"pointer",margin:0},children:c("addUrl.crawl.weeklyLabel")}),t.jsx("p",{style:{fontSize:11.5,color:"var(--cia-text-3)",margin:"2px 0 0"},children:c("addUrl.crawl.weeklyHint")})]}),t.jsx(vt,{id:"kb-src-weekly",checked:te,disabled:bt,label:c("addUrl.crawl.weeklyAria"),onChange:B})]})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"kb-src-title",className:"cia-eyebrow",children:c("addUrl.titleLabel")}),t.jsx("input",{id:"kb-src-title",className:"input",style:{width:"100%",marginTop:4},type:"text",placeholder:c(ke?"addUrl.crawl.titlePh":"addUrl.titlePh"),value:K,maxLength:255,disabled:bt,onChange:ve=>W(ve.target.value)})]}),yt]}),b&&t.jsx(le,{tone:"warn",children:b})]})})}function V8({item:e,disabled:a,onRemove:n}){const{t:s}=M("knowledge");return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 10px",borderRadius:"var(--cia-r)",border:"1px solid var(--cia-border)",background:"var(--cia-bg-sunken)"},children:[t.jsx(_n,{size:15,style:{color:"var(--cia-brand-500)",flex:"none"},"aria-hidden":!0}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:12.5,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.file.name}),e.status==="uploading"&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4},children:[t.jsx("div",{style:{flex:1},children:t.jsx(Ic,{value:e.pct/100,variant:"ok",height:4})}),t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)"},children:s("upload.uploading",{pct:e.pct})})]}),e.status==="error"&&t.jsx("span",{style:{fontSize:11,color:"var(--cia-bad-500)"},children:e.error||s("upload.failed")}),e.status==="queued"&&t.jsx("span",{className:"cia-mono",style:{fontSize:10.5,color:"var(--cia-text-3)"},children:s("upload.queued")})]}),e.status==="done"?t.jsxs("span",{className:"cia-badge cia-badge-success",style:{flex:"none"},title:s("upload.done"),children:[t.jsx(Nt,{size:11,"aria-hidden":!0})," ",s("upload.done")]}):e.status==="error"?t.jsx(cs,{size:15,style:{color:"var(--cia-bad-500)",flex:"none"},"aria-hidden":!0}):null,e.status!=="uploading"&&e.status!=="done"&&t.jsx("button",{type:"button","aria-label":s("upload.remove",{name:e.file.name}),disabled:a,onClick:n,style:{border:"none",background:"transparent",cursor:"pointer",color:"var(--cia-text-3)",display:"inline-flex",flex:"none"},children:t.jsx(nt,{size:14})})]})}const Bg=420;function K8({kbId:e}){const{can:a}=tt(),n=a("knowledge.operate"),{t:s}=M("knowledge"),i=nD(),[r,o]=m.useState(""),[l,c]=m.useState(null);function d(){const u=r.trim();!u||i.isPending||i.mutate({kbId:e,query:u},{onSuccess:p=>c(p),onError:p=>{p?.response?.status===429?J({tone:"warn",title:s("playground.rateLimited")}):J({tone:"bad",title:ya(p)||s("playground.error")})}})}return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-3)",lineHeight:1.6,maxWidth:620},children:s("playground.intro")}),t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[t.jsx("input",{className:"input",style:{flex:1},type:"text",placeholder:s("playground.queryPh"),value:r,maxLength:500,onChange:u=>o(u.target.value),onKeyDown:u=>{u.key==="Enter"&&d()}}),t.jsx("button",{className:"cia-btn cia-btn-cta",style:{flex:"none"},disabled:i.isPending||!r.trim()||!n,title:n?void 0:s("common:noPermission"),onClick:d,children:i.isPending?t.jsxs(t.Fragment,{children:[t.jsx(je,{className:"animate-spin",size:15})," ",s("playground.running")]}):t.jsxs(t.Fragment,{children:[t.jsx(Mn,{size:15})," ",s("playground.run")]})})]}),l==null?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{mini:!0,icon:_t,title:s("playground.idle.title"),desc:s("playground.idle.desc")})}):t.jsxs("div",{className:"cia-fade-up",style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},children:[t.jsx("span",{className:"cia-badge cia-mono",children:s("playground.took",{ms:l.tookMs})}),t.jsx("span",{className:"cia-badge cia-mono",children:s("playground.chunks",{count:l.chunks.length})}),l.degraded==="lexical_only"&&t.jsx("span",{className:"cia-badge cia-badge-warn",children:s("playground.lexicalOnly")}),l.degraded==="disabled"&&t.jsx("span",{className:"cia-badge cia-badge-warn",children:s("playground.degradedDisabled")})]}),l.chunks.length===0?t.jsx("div",{className:"cia-card",style:{padding:0},children:t.jsx(st,{mini:!0,icon:cy,title:s("playground.noResults.title"),desc:s("playground.noResults.desc")})}):l.chunks.map((u,p)=>t.jsx(H8,{chunk:u,index:p},`${u.docId}-${p}`))]}),l?.degraded==="no_kb"&&t.jsx(le,{tone:"warn",children:s("playground.noResults.desc")})]})}function H8({chunk:e,index:a}){const{t:n}=M("knowledge"),[s,i]=m.useState(!1),r=e.content.length>Bg,o=s||!r?e.content:`${e.content.slice(0,Bg)}…`;return t.jsxs("div",{className:"cia-card",style:{padding:14,display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,minWidth:0},children:[t.jsxs("span",{className:"cia-badge cia-mono",style:{flex:"none"},children:["#",a+1]}),t.jsx("span",{style:{fontSize:12.5,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e.docTitle}),t.jsxs("span",{className:"cia-mono",style:{fontSize:11,color:"var(--cia-text-3)",marginLeft:"auto",flex:"none"},children:[e.distance!=null?`${n("playground.distance",{d:e.distance.toFixed(2)})} · `:"",n("playground.tokens",{count:e.tokens}
980)]})]}),t.jsx("p",{className:"cia-mono",style:{margin:0,fontSize:12,lineHeight:1.6,color:"var(--cia-text-2)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:o}),r&&t.jsx("button",{type:"button",onClick:()=>i(l=>!l),style:{alignSelf:"flex-start",border:"none",background:"transparent",cursor:"pointer",padding:0,fontSize:12,fontWeight:600,color:"var(--cia-brand-500)"},children:n(s?"playground.collapse":"playground.expand")})]})}function Q8({kbId:e,onBack:a,sitioSugerido:n,onSitioSugeridoResuelto:s,onBackToAgent:i}){const{t:r}=M("knowledge");Pe(K=>K.user?.role);const{can:o}=tt(),l=o("knowledge.operate"),c=o("knowledge.manage"),d=Kz(e),u=Hc(),p=J0(),f=Hz(e),x=Yz(),h=Xz(),[b,g]=m.useState("sources"),[v,y]=m.useState(!1),[k,w]=m.useState(null),[j,C]=m.useState(!1),[N,S]=m.useState(null),[_,R]=m.useState(!1),[A,E]=m.useState(!1),I=u.data?.bases.find(K=>K.id===e),P=d.data?{...I??{},...d.data,agentsCount:I?.agentsCount??0}:I;if(d.isLoading&&!P)return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx(ge,{w:"30%",h:16}),t.jsx(ge,{w:"60%",h:12})]});if(!P)return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx(le,{tone:"warn",children:r("detail.notFound")}),t.jsxs("button",{className:"cia-btn cia-btn-outline cia-btn-sm",style:{alignSelf:"flex-start"},onClick:a,children:[t.jsx(du,{size:14})," ",r("detail.back")]})]});const O=K=>{w(null),x.mutate({kbId:e,name:K.name,description:K.description??""},{onSuccess:()=>{y(!1),J({tone:"ok",title:r("create.toastUpdated")})},onError:W=>w(ya(W))})};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"},children:[t.jsxs("button",{type:"button",onClick:a,"aria-label":r("detail.backAria"),style:{display:"inline-flex",alignItems:"center",gap:6,border:"none",background:"transparent",cursor:"pointer",padding:0,fontSize:12.5,fontWeight:600,color:"var(--cia-text-3)"},children:[t.jsx(du,{size:14,"aria-hidden":!0})," ",r("detail.back")]}),i&&t.jsxs("button",{type:"button",onClick:i,"aria-label":r("detail.backToAgentAria"),style:{display:"inline-flex",alignItems:"center",gap:6,border:"none",background:"transparent",cursor:"pointer",padding:0,fontSize:12.5,fontWeight:600,color:"var(--cia-text)"},children:[t.jsx(Ft,{size:14,"aria-hidden":!0})," ",r("detail.backToAgent")]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[t.jsxs("div",{style:{minWidth:0,flex:1},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsx("h2",{style:{margin:0,fontSize:19,fontWeight:650,letterSpacing:"-0.01em",wordBreak:"break-word"},children:P.name}),P.agentsCount>0&&t.jsxs("span",{className:"cia-badge cia-badge-success",children:[t.jsx(Ft,{size:11,"aria-hidden":!0})," ",r("detail.agents",{count:P.agentsCount})]})]}),P.description&&t.jsx("p",{style:{margin:"6px 0 0",fontSize:13,color:"var(--cia-text-3)",lineHeight:1.6,maxWidth:640},children:P.description})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:"none"},children:[l&&t.jsxs("button",{className:"cia-btn cia-btn-outline cia-btn-sm",onClick:()=>{w(null),y(!0)},children:[t.jsx(qt,{size:13})," ",r("detail.edit")]}),c&&t.jsxs("button",{className:"cia-btn cia-btn-outline cia-btn-sm",style:{color:"var(--cia-bad-500)"},onClick:()=>C(!0),children:[t.jsx(mt,{size:13})," ",r("detail.delete")]})]})]})]}),t.jsx(Fi,{items:[{id:"sources",label:r("detail.tabSources"),count:P.sourceCount||void 0},{id:"playground",label:r("detail.tabPlayground")}],active:b,onChange:K=>g(K)}),b==="sources"&&n&&t.jsxs(le,{tone:"info",icon:Va,title:r("detail.siteSuggested.title"),action:l&&(!p.data||p.data.enabled)?{label:r("detail.siteSuggested.add"),icon:Fe,onClick:()=>{E(!0),R(!0)}}:void 0,children:[t.jsx("span",{style:{display:"block"},children:r("detail.siteSuggested.body")}),t.jsx("span",{className:"cia-mono",style:{display:"block",marginTop:4,fontSize:12,wordBreak:"break-all"},children:n}),s&&t.jsx("button",{type:"button",className:"cia-btn cia-btn-ghost cia-btn-sm",style:{marginTop:6,paddingLeft:0},onClick:s,children:r("detail.siteSuggested.dismiss")})]}),b==="sources"&&t.jsx(z8,{kbId:e,docs:f.data,loading:f.isLoading,usage:p.data,onAddSource:()=>{E(!1),R(!0)}}),b==="playground"&&t.jsx(K8,{kbId:e}),t.jsx(H1,{open:v,onClose:()=>y(!1),onSubmit:O,saving:x.isPending,error:k,mode:"edit",initial:{name:P.name,description:P.description}}),t.jsx(U8,{open:_,onClose:()=>R(!1),kbId:e,kbName:P.name,usage:p.data,initialTab:A&&n?"url":void 0,initialUrl:A?n:void 0,onAdded:A?s:void 0}),t.jsx(G8,{open:j,onClose:()=>{C(!1),S(null)},kb:P,deleting:h.isPending,bloqueo:N,onConfirm:()=>h.mutate(e,{onSuccess:()=>{C(!1),S(null),J({tone:"ok",title:r("deleteConfirm.toastDeleted")}),a()},onError:K=>{const W=k8(K);if(W){S(W);return}J({tone:"bad",title:ya(K)})}})})]})}function G8({open:e,onClose:a,kb:n,deleting:s,bloqueo:i,onConfirm:r}){const{t:o}=M("knowledge"),[l,c]=m.useState(""),d=n.agentsCount>0,u=!d||l===n.name;return m.useEffect(()=>{e&&c("")},[e]),t.jsx(ot,{open:e,onClose:a,maxWidth:480,eyebrow:o("deleteConfirm.eyebrow"),title:o("deleteConfirm.title",{name:n.name}),footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"cia-btn cia-btn-outline",onClick:a,disabled:s,children:o("deleteConfirm.cancel")}),t.jsxs("button",{className:"cia-btn cia-btn-primary",style:{background:"var(--cia-bad-500)",borderColor:"var(--cia-bad-500)"},disabled:s||!u||!!i,onClick:r,children:[s&&t.jsx(je,{className:"animate-spin",size:15}),o("deleteConfirm.submit")]})]}),children:t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx("p",{style:{margin:0,fontSize:13,color:"var(--cia-text-2)",lineHeight:1.6},children:o("deleteConfirm.body")}),d&&t.jsxs(t.Fragment,{children:[t.jsx(le,{tone:"warn",children:o("deleteConfirm.agentsWarn",{count:n.agentsCount})}),t.jsxs("div",{children:[t.jsx("label",{className:"cia-eyebrow",children:o("deleteConfirm.typeToConfirm")}),t.jsx("input",{className:"input",style:{width:"100%",marginTop:4},type:"text",placeholder:o("deleteConfirm.inputPh"),value:l,autoFocus:!0,onChange:p=>c(p.target.value)})]})]}),i&&t.jsx(N8,{agents:i})]})})}function Z8(){const{t:e}
980=M("knowledge"),{t:a}=M("misc"),n=xt(g=>g.resolved),s=dt(),i=Os({strict:!1}),r=i.kb,o=i.volver,l=o?{volver:o}:{},c=i.sitio&&ro(i.sitio)?i.sitio:void 0,d=i.nueva==="1",u=m.useMemo(()=>c?{name:Lz(c)}:void 0,[c]),p=Hc();if(Gz(),p.data&&!p.data.available)return t.jsx(So,{eyebrow:a("knowledge.eyebrow"),title:a("knowledge.title"),icon:ua,description:a("knowledge.description"),features:[a("knowledge.f1"),a("knowledge.f2"),a("knowledge.f3")]});const f=(g,v)=>s({to:"/knowledge",search:{kb:g,...v&&c?{sitio:c}:{},...l},...v?{replace:!0}:{}}),x=()=>s({to:"/knowledge",search:{kb:void 0,...l}}),h=()=>s({to:"/knowledge",search:{kb:r,...l},replace:!0}),b=o?()=>s({to:"/agents/$agentId",params:{agentId:o},search:{tab:"knowledge"}}):void 0;return t.jsxs(t.Fragment,{children:[t.jsx(Wt,{eyebrow:e("page.eyebrow"),title:e("page.title")}),t.jsx("main",{className:"cia flex-1 overflow-y-auto cia-scroll","data-theme":n,style:{background:"var(--cia-bg)",color:"var(--cia-text)"},children:t.jsx("div",{className:"cia-fade-up",style:{width:"100%",maxWidth:1080,padding:24},children:p.isLoading&&!p.data?t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsx(ge,{w:"35%",h:16}),t.jsx(ge,{w:"100%",h:80})]}):r?t.jsx(Q8,{kbId:r,onBack:x,sitioSugerido:c,onSitioSugeridoResuelto:h,onBackToAgent:b}):t.jsx(S8,{onOpen:f,autoOpenCreate:d,initial:u,onAutoOpenDismiss:h})})})]})}const Y8=We(()=>Le(()=>import("./tenants--yBXDEZ8.js"),__vite__mapDeps([0,1,2,3,4,5]))),X8=We(()=>Le(()=>import("./tenant-detail-DAbx3Pks.js"),__vite__mapDeps([6,1,2,0,3,4,5,7]))),J8=We(()=>Le(()=>import("./usage-7gnImsEQ.js"),__vite__mapDeps([8,1,2,4,3,9]))),e$=We(()=>Le(()=>import("./ai-keys-CzeeyLxH.js"),__vite__mapDeps([10,1,2,4,3]))),t$=We(()=>Le(()=>import("./network-7wiTBd3L.js"),__vite__mapDeps([11,1,2,3,4]))),a$=We(()=>Le(()=>import("./numbers-qNjC-nW6.js"),__vite__mapDeps([12,1,2,3,4,13]))),n$=We(()=>Le(()=>import("./stt-_3vKAz_6.js"),__vite__mapDeps([14,1,2,4,3]))),s$=We(()=>Le(()=>import("./voices-D1l0MdTg.js"),__vite__mapDeps([15,1,2,3,4,16]))),i$=We(()=>Le(()=>import("./rates-Dd37kzjL.js"),__vite__mapDeps([17,1,2,3,4,13]))),r$=We(()=>Le(()=>import("./plans-VlNKAXNs.js"),__vite__mapDeps([18,1,2,3,4]))),o$=We(()=>Le(()=>import("./recording-Ciro7U9e.js"),__vite__mapDeps([19,1,2,3,4,20]))),l$=We(()=>Le(()=>import("./whatsapp-jFVQvQry.js"),__vite__mapDeps([21,1,2,3,4]))),c$=We(()=>Le(()=>import("./workflows-DZWNEGch.js"),__vite__mapDeps([22,1,2,3,23,5,24]))),d$=We(()=>Le(()=>import("./correo-BPufb6C1.js"),__vite__mapDeps([25,1,2,3]))),u$=We(()=>Le(()=>import("./registro-QDuOJbr4.js"),__vite__mapDeps([26,1,2,3]))),p$=We(()=>Le(()=>import("./email-avbmRqsq.js"),__vite__mapDeps([27,1,2,3,4,13,20]))),h$=We(()=>Le(()=>import("./account-PRSP_Yeu.js"),__vite__mapDeps([28,1,2,3]))),m$=We(()=>Le(()=>import("./voicemail-patterns-BBfyrYVA.js"),__vite__mapDeps([29,1,2,4,3]))),f$=We(()=>Le(()=>import("./audit-DTsFaSIc.js"),__vite__mapDeps([30,1,2,3,4,31]))),x$=We(()=>Le(()=>import("./payments-BX1_xQY4.js"),__vite__mapDeps([32,1,2,3,4]))),g$=We(()=>Le(()=>import("./margin-69L7eGby.js"),__vite__mapDeps([33,1,2,3,34,35]))),b$=We(()=>Le(()=>import("./dashboard-DOBl1Cye.js"),__vite__mapDeps([36,1,2,3,34,37]))),y$=We(()=>Le(()=>import("./churn-DFszf9A1.js"),__vite__mapDeps([38,1,2,3,39]))),v$=We(()=>Le(()=>import("./health-CybLcEA_.js"),__vite__mapDeps([40,1,2,3,4,13,9]))),j$=We(()=>Le(()=>import("./comparatives-Cu3TzsZf.js"),__vite__mapDeps([41,1,2,3,34,39,35]))),w$=We(()=>Le(()=>import("./seo-geo-BOS9IrYQ.js"),__vite__mapDeps([42,1,2,3,34,43]))),k$=We(()=>Le(()=>import("./playbook-BHYdh3Bk.js"),__vite__mapDeps([44,1,2,3,4]))),N$=We(()=>Le(()=>import("./knowledge-DIzNnRar.js"),__vite__mapDeps([45,1,2,4,3,5]))),S$=We(()=>Le(()=>import("./meetings-BakmkjMD.js"),__vite__mapDeps([46,1,2,4,3]))),C$=We(()=>Le(()=>import("./correo-C3_Gaeex.js"),__vite__mapDeps([47,1,2,3,48,49,50,51,34,52,43]))),_$=We(()=>Le(()=>import("./correo.campanas._campaignId-BPJv81oF.js"),__vite__mapDeps([53,1,2,3,48,34,52,43,54,49,50]))),Q1=We(()=>Le(()=>import("./correo.editor-BH3uSzlB.js"),__vite__mapDeps([55,1,2,3,56,48,16,51,43,57,58,37,59]))),G1=We(()=>Le(()=>import("./TemplateEditorPage-Du65Br7P.js"),__vite__mapDeps([60,1,2,3,56,48,16,51,43,59]))),E$=We(()=>Le(()=>import("./contactos-CLZwwwaq.js"),__vite__mapDeps([61,1,2,3,4,34,50]))),A$=We(()=>Le(()=>import("./campaigns-C3IYgpTd.js"),__vite__mapDeps([62,1,2,63,3,4,51]))),R$=We(()=>Le(()=>
980import("./campaigns.new-Bxno9Ntb.js"),__vite__mapDeps([64,1,2,65,3,58,57,37]))),T$=We(()=>Le(()=>import("./campaigns._campaignId-DZm24GvM.js"),__vite__mapDeps([66,1,2,3,54,34,49,63,4,51,65,58]))),M$=We(()=>Le(()=>import("./meetings-B0_Ci28z.js"),__vite__mapDeps([67,1,2,3,51]))),P$=We(()=>Le(()=>import("./meetings._meetingId-Clc_Wa2U.js"),__vite__mapDeps([68,1,2,3,69]))),z$=We(()=>Le(()=>import("./copilot-Bg1hiset.js"),__vite__mapDeps([70,1,2,3,69]))),D$=We(()=>Le(()=>import("./whatsapp-plantillas-7Q_AAR4x.js"),__vite__mapDeps([71,1,2,3,72,73]))),I$=We(()=>Le(()=>import("./workflows._flowId-BJSo8-WE.js").then(e=>e.w),__vite__mapDeps([74,1,2,3,75,76,23,49,24,77,78,59,79,34,31,7,80]))),L$=We(()=>Le(()=>import("./workflows.plantillas-DbjcmTsR.js"),__vite__mapDeps([81,1,2,3,23,77,75]))),F$=We(()=>Le(()=>import("./workflows.corridas-C9oU_T4B.js"),__vite__mapDeps([82,1,2,76,3,75,23,49,24]))),Z1=We(()=>Le(()=>import("./whatsapp-plantillas.editor-Bgp6H8ej.js"),__vite__mapDeps([83,1,2,3,78,73,72]))),O$=new cN({defaultOptions:{queries:{staleTime:3e4,refetchOnWindowFocus:!1,retry:1}}}),Zc=()=>{if(!Pe.getState().isAuthenticated())throw Wa({to:"/login"})},gt=()=>{Zc();const e=Pe.getState().user;if(!e||e.role!=="superadmin")throw Wa({to:"/dashboard"});if(rt.getState().isActive())throw Wa({to:"/dashboard"})},Wi=()=>{Zc();const e=Pe.getState().user,a=rt.getState().isActive();if(e?.role==="superadmin"&&!a)throw Wa({to:"/admin/dashboard"})},ft=e=>()=>{Wi();const a=Up();if(a&&!lt(a,e))throw Wa({to:"/dashboard"})},$$=e=>()=>{Wi();const a=Up();if(a&&!$b(a,e))throw Wa({to:"/dashboard"})},q$=()=>{Zc();const e=Pe.getState().user;if(!rt.getState().isActive()&&gc(e))throw Wa({to:"/onboarding",search:{preview:void 0}})},Us=vk({component:()=>t.jsx(Fp,{})}),B$=we({getParentRoute:()=>Us,path:"/login",component:tT}),W$=we({getParentRoute:()=>Us,path:"/register",component:aT}),U$=we({getParentRoute:()=>Us,path:"/auth/callback",component:nT}),V$=we({getParentRoute:()=>Us,path:"/onboarding",validateSearch:e=>({preview:e.preview==="1"||e.preview===1||e.preview===!0?"1":void 0}),beforeLoad:({search:e})=>{Zc();const a=Pe.getState().user;if(!gc(a)&&a?.role!=="superadmin"&&e.preview!=="1")throw Wa({to:lo(a)})},component:I4}),K$=we({getParentRoute:()=>Us,path:"/embed/$agentId",component:Kj}),_e=we({getParentRoute:()=>Us,id:"app",beforeLoad:q$,component:()=>t.jsx(HR,{children:t.jsx(Fp,{})})}),H$=we({getParentRoute:()=>_e,path:"/",beforeLoad:()=>{throw Wa({to:lo(Pe.getState().user)})}}),Q$=we({getParentRoute:()=>_e,path:"/dashboard",beforeLoad:Wi,component:n3}),G$=we({getParentRoute:()=>_e,path:"/agents",beforeLoad:ft("agents.view"),component:_3}),Y1=we({getParentRoute:()=>_e,path:"/agents/new",beforeLoad:ft("agents.manage"),validateSearch:e=>({...typeof e.template=="string"?{template:e.template}:{},...typeof e.tab=="string"?{tab:e.tab}:{}}),component:()=>{const{template:e,tab:a}=Y1.useSearch();return t.jsx(t1,{agentId:null,template:e??null,initialTab:a})}}),_p=we({getParentRoute:()=>_e,path:"/agents/$agentId",beforeLoad:ft("agents.view"),validateSearch:e=>({...typeof e.tab=="string"?{tab:e.tab}:{},...e.builder==="1"||e.builder==="true"?{builder:"1"}:{}}),component:()=>{const{agentId:e}=_p.useParams(),{tab:a,builder:n}=_p.useSearch();return t.jsx(t1,{agentId:e,initialTab:a,openBuilderOnMount:n==="1"})}}),X1=we({getParentRoute:()=>_e,path:"/live",beforeLoad:ft("calls.view"),validateSearch:e=>({...typeof e.call=="string"&&e.call?{call:e.call}:{}}),component:()=>{const{call:e}=X1.useSearch();return t.jsx(RD,{initialCallId:e})}}),Z$=we({getParentRoute:()=>_e,path:"/history",beforeLoad:ft("calls.view"),validateSearch:e=>({...typeof e.callId=="string"&&e.callId?{callId:e.callId}:{}}),component:()=>t.jsx(m1,{withCost:!1})}),Y$=we({getParentRoute:()=>_e,path:"/reports",beforeLoad:gt,component:()=>t.jsx(QI,{})}),X$=we({getParentRoute:()=>_e,path:"/playground",beforeLoad:ft("playground.use"),component:eL}),J$=we({getParentRoute:()=>_e,path:"/trunks",beforeLoad:ft("phoneNumbers.view"),component:iL}),eq=we({getParentRoute:()=>_e,path:"/campaigns",beforeLoad:ft("campaigns.view"),component:A$}),tq=we({getParentRoute:()=>_e,path:"/campaigns/new",beforeLoad:ft("campaigns.manage"),component:R$}),J1=we({getParentRoute:()=>_e,path:"/campaigns/$campaignId",beforeLoad:ft("campaigns.view"),component:()=>{const{campaignId:e}=J1.useParams();return t.jsx(T$,{campaignId:e})}}),aq=we({getParentRoute:()=>_e,path:"/meetings",beforeLoad:ft("meetings.view"),component:M$}),ej=we({getParentRoute:()=>_e,path:"/meetings/$meetingId",beforeLoad:ft("meetings.view"),component:()=>{const{meetingId:e}=ej.useParams();return t.jsx(P$,{meetingId:e})}}),nq=we({getParentRoute:()=>_e,path:"/whatsapp",beforeLoad:ft("whatsapp.view"),validateSearch:e=>({...typeof e.tab=="string"&&e.tab?{tab:e.tab}:{}}),component:FF}),sq=we({getParentRoute:()=>_e,path:"/whatsapp/bandeja",beforeLoad:ft("whatsapp.view"),validateSearch:e=>({...typeof e.c=="string"&&e.c?{c:e.c}:{}}),component:l8}),iq=we({getParentRoute:()=>_e,path:"/whatsapp/plantillas",beforeLoad:ft("whatsapp.view"),validateSearch:e=>tS(e),component:D$}),tj=we({getParentRoute:()=>_e,path:"/whatsapp/plantillas/nueva",beforeLoad:ft("whatsapp.manage"),validateSearch:e=>aS(e),component:()=>{const{desde:e,cuenta:a}=tj.useSearch();return t.jsx(Z1,{templateId:null,desde:e,cuenta:a})}}),aj=we({getParentRoute:()=>_e,path:"/whatsapp/plantillas/$templateId/editar",beforeLoad:ft("whatsapp.manage"),component:()=>{const{templateId:e}=aj.useParams();return t.jsx(Z1,{templateId:e})}}),rq=we({getParentRoute:()=>_e,path:"/copilot",beforeLoad:ft("copilot.use"),component:z$}),oq=we({getParentRoute:()=>_e,path:"/knowledge",validateSearch:e=>({kb:typeof e.kb=="string"?e.kb:void 0,...e.nueva==="1"||e.nueva===1?{nueva:"1"}:{},...typeof e.sitio=="string"?{sitio:e.sitio}:{},...typeof e.volver=="string"&&/^ag_[a-z0-9]{1,40}$/.test(e.volver)?{volver:e.volver}:{}}),beforeLoad:ft("knowledge.view"),component:Z8}),lq=we({getParentRoute:()=>_e,path:"/workflows",beforeLoad:ft("workflows.view"),component:k6}),cq=we({getParentRoute:()=>_e,path:"/workflows/plantillas",beforeLoad:ft("workflows.view"),component:L$}),dq=we({getParentRoute:()=>_e,path:"/workflows/corridas",beforeLoad:ft("workflows.view"),component:F$}),nj=we({getParentRoute:()=>_e,path:"/workflows/$flowId",beforeLoad:ft("workflows.view"),validateSearch:e=>lS(e),component:()=>{const{flowId:e}=nj.useParams();return t.jsx(I$,{flowId:e},e)}}),uq=we({getParentRoute:()=>_e,path:"/settings",validateSearch:e=>({s:typeof e.s=="string"?e.s:void 0}),beforeLoad:Wi,component:c6}),pq=we({getParentRoute:()=>_e,path:"/plan",beforeLoad:()=>{throw Wi(),Wa({to:"/settings",search:{s:"billing"}})}}),hq=we({getParentRoute:()=>_e,path:"/audit",beforeLoad:()=>{throw Wi(),Wa({to:"/settings",search:{s:"audit"}})}}),mq=we({getParentRoute:()=>_e,path:"/citas",beforeLoad:ft("appointments.view"),component:mL}),fq=we({getParentRoute:()=>_e,path:"/correo",beforeLoad:ft("email.view"),validateSearch:e=>({...typeof e.tab=="string"?{tab:e.tab}:{},...typeof e.estado=="string"?{estado:e.estado}:{},...typeof e.campana=="string"?{campana:e.campana}:{},...typeof e.q=="string"?{q:e.q}:{},...typeof e.cestado=="string"?{cestado:e.cestado}:{},...typeof e.cq=="string"?{cq:e.cq}:{}
980,...typeof e.dias=="string"?{dias:e.dias}:{}}),component:C$}),sj=we({getParentRoute:()=>_e,path:"/correo/campanas/$campaignId",beforeLoad:ft("email.view"),validateSearch:e=>({...typeof e.tab=="string"?{tab:e.tab}:{},...typeof e.estado=="string"?{estado:e.estado}:{}}),component:()=>{const{campaignId:e}=sj.useParams();return t.jsx(_$,{campaignId:e})}}),ij=we({getParentRoute:()=>_e,path:"/correo/editor/nueva",beforeLoad:ft("email.operate"),validateSearch:e=>({...typeof e.template=="string"&&e.template?{template:e.template}:{},...e.paso==="revisar"?{paso:"revisar"}:{}}),component:()=>{const{template:e,paso:a}=ij.useSearch();return t.jsx(Q1,{campaignId:null,template:e??null,paso:a})}}),Ep=we({getParentRoute:()=>_e,path:"/correo/editor/$campaignId",beforeLoad:ft("email.operate"),validateSearch:e=>({...e.paso==="revisar"?{paso:"revisar"}:{}}),component:()=>{const{campaignId:e}=Ep.useParams(),{paso:a}=Ep.useSearch();return t.jsx(Q1,{campaignId:e,paso:a})}}),xq=we({getParentRoute:()=>_e,path:"/correo/plantillas/nueva",beforeLoad:ft("email.operate"),component:()=>t.jsx(G1,{templateId:null})}),rj=we({getParentRoute:()=>_e,path:"/correo/plantillas/$templateId",beforeLoad:ft("email.operate"),component:()=>{const{templateId:e}=rj.useParams();return t.jsx(G1,{templateId:e})}}),gq=we({getParentRoute:()=>_e,path:"/contactos",beforeLoad:ft("contacts.view"),validateSearch:e=>({...typeof e.q=="string"&&e.q.trim()?{q:e.q.trim().slice(0,80)}:{}}),component:E$}),bq=we({getParentRoute:()=>_e,path:"/integraciones",beforeLoad:$$(["webhooks.view","integrations.view"]),component:uL}),yq=we({getParentRoute:()=>_e,path:"/secrets",beforeLoad:ft("secrets.view"),component:fL}),vq=we({getParentRoute:()=>_e,path:"/admin/tenants",beforeLoad:gt,component:Y8}),oj=we({getParentRoute:()=>_e,path:"/admin/tenants/$orgId",beforeLoad:gt,component:()=>{const{orgId:e}=oj.useParams();return t.jsx(X8,{orgId:e})}}),jq=we({getParentRoute:()=>_e,path:"/admin/usage",beforeLoad:gt,component:J8}),wq=we({getParentRoute:()=>_e,path:"/admin/ai-keys",beforeLoad:gt,component:e$}),kq=we({getParentRoute:()=>_e,path:"/admin/network",beforeLoad:gt,component:t$}),Nq=we({getParentRoute:()=>_e,path:"/admin/numbers",beforeLoad:gt,component:a$}),Sq=we({getParentRoute:()=>_e,path:"/admin/stt",beforeLoad:gt,component:n$}),Cq=we({getParentRoute:()=>_e,path:"/admin/voices",beforeLoad:gt,component:s$}),_q=we({getParentRoute:()=>_e,path:"/admin/rates",beforeLoad:gt,component:i$}),Eq=we({getParentRoute:()=>_e,path:"/admin/voicemail-patterns",beforeLoad:gt,component:m$}),Aq=we({getParentRoute:()=>_e,path:"/admin/plans",beforeLoad:gt,component:r$}),Rq=we({getParentRoute:()=>_e,path:"/admin/recording",beforeLoad:gt,component:o$}),Tq=we({getParentRoute:()=>_e,path:"/admin/whatsapp",beforeLoad:gt,component:l$}),Mq=we({getParentRoute:()=>_e,path:"/admin/workflows",beforeLoad:gt,component:c$}),Pq=we({getParentRoute:()=>_e,path:"/admin/correo",beforeLoad:gt,component:d$}),zq=we({getParentRoute:()=>_e,path:"/admin/registro",beforeLoad:gt,component:u$}),Dq=we({getParentRoute:()=>_e,path:"/admin/email",beforeLoad:gt,component:p$}),Iq=we({getParentRoute:()=>_e,path:"/admin/audit",beforeLoad:gt,component:f$}),Lq=we({getParentRoute:()=>_e,path:"/admin/account",beforeLoad:gt,component:h$}),Fq=we({getParentRoute:()=>_e,path:"/admin/payments",beforeLoad:gt,component:x$}),Oq=we({getParentRoute:()=>_e,path:"/admin/dashboard",beforeLoad:gt,component:b$}),$q=we({getParentRoute:()=>_e,path:"/admin/churn",beforeLoad:gt,component:y$}),qq=we({getParentRoute:()=>_e,path:"/admin/margin",beforeLoad:gt,component:g$}),Bq=we({getParentRoute:()=>_e,path:"/admin/health",beforeLoad:gt,component:v$}),Wq=we({getParentRoute:()=>_e,path:"/admin/comparatives",beforeLoad:gt,component:j$}),Uq=we({getParentRoute:()=>_e,path:"/admin/seo-geo",beforeLoad:gt,component:w$}),Vq=we({getParentRoute:()=>_e,path:"/admin/playbook",beforeLoad:gt,component:k$}),Kq=we({getParentRoute:()=>_e,path:"/admin/knowledge",beforeLoad:gt,component:N$}),Hq=we({getParentRoute:()=>_e,path:"/admin/meetings",beforeLoad:gt,component:S$}),Qq=Us.addChildren([B$,W$,U$,V$,K$,_e.addChildren([H$,Q$,G$,Y1,_p,X1,Z$,Y$,X$,J$,eq,tq,J1,aq,ej,nq,sq,iq,tj,aj,rq,oq,lq,cq,dq,nj,mq,fq,sj,ij,Ep,xq,rj,gq,bq,yq,uq,pq,hq,vq,Aq,oj,jq,wq,kq,Nq,Sq,Cq,_q,Eq,Rq,Tq,Mq,Pq,zq,Dq,Iq,Lq,Fq,qq,Oq,$q,Bq,Wq,Uq,Vq,Kq,Hq])]),Gq=Tk({routeTree:Qq});Vj.createRoot(document.getElementById("root")).render(t.jsx(Xa.StrictMode,{children:t.jsx(QR,{children:t.jsx(LN,{i18n:he,children:t.jsx(dN,{client:O$,children:t.jsx(zk,{router:Gq})})})})}));export{hh as $,c9 as A,Hb as B,kB as C,jS as D,tv as E,vo as F,mn as G,gn as H,ca as I,Rn as J,Bu as K,uv as L,vc as M,NS as N,Gb as O,mh as P,So as Q,N_ as R,f0 as S,BT as T,HT as U,bn as V,kl as W,Xb as X,$s as Y,x9 as Z,Vc as _,t_ as a,FL as a$,Jb as a0,Zt as a1,Rs as a2,pv as a3,jc as a4,MS as a5,Tn as a6,vn as a7,ev as a8,zi as a9,bi as aA,et as aB,Jp as aC,sy as aD,KS as aE,yi as aF,g9 as aG,Kr as aH,HS as aI,O_ as aJ,NL as aK,kc as aL,QS as aM,p_ as aN,Ba as aO,GS as aP,ef as aQ,YS as aR,Cr as aS,th as aT,ot as aU,tW as aV,w6 as aW,j6 as aX,Ru as aY,T9 as aZ,ry as a_,Ws as aa,Ja as ab,qs as ac,zS as ad,Zp as ae,IS as af,Eu as ag,ey as ah,_n as ai,sE as aj,LS as ak,Yp as al,T_ as am,ZB as an,co as ao,Va as ap,ty as aq,Xp as ar,wc as as,Au as at,KM as au,Gy as av,Ka as aw,WS as ax,ny as ay,US as az,cE as b,iu as b$,rI as b0,dS as b1,Xq as b2,Yy as b3,Nc as b4,VL as b5,qt as b6,Ma as b7,dn as b8,yn as b9,Nl as bA,dy as bB,as as bC,Cc as bD,Sc as bE,ho as bF,r2 as bG,ji as bH,py as bI,_t as bJ,I5 as bK,ah as bL,No as bM,Yr as bN,$5 as bO,hy as bP,iE as bQ,vt as bR,$_ as bS,xB as bT,Xt as bU,Fi as bV,Hl as bW,ps as bX,Pu as bY,yv as bZ,Lc as b_,ka as ba,at as bb,rn as bc,Fe as bd,qu as be,an as bf,Gl as bg,d9 as bh,b9 as bi,E5 as bj,vi as bk,Di as bl,F5 as bm,po as bn,Na as bo,ly as bp,uE as bq,Z_ as br,Qr as bs,Mn as bt,ph as bu,cy as bv,Yn as bw,hn as bx,Gr as by,oI as bz,Hp as c,qy as c$,c_ as c0,Wt as c1,wa as c2,mt as c3,m2 as c4,x2 as c5,b2 as c6,Ic as c7,my as c8,y2 as c9,ds as cA,n9 as cB,w9 as cC,Te as cD,v6 as cE,d0 as cF,p9 as cG,As as cH,ac as cI,XN as cJ,cS as cK,k1 as cL,C9 as cM,_9 as cN,y9 as cO,cB as cP,uB as cQ,KB as cR,Be as cS,kn as cT,Ca as cU,U
980B as cV,uc as cW,VB as cX,ts as cY,cv as cZ,m9 as c_,v2 as ca,En as cb,Bs as cc,IL as cd,j2 as ce,aO as cf,sh as cg,w2 as ch,_c as ci,Ec as cj,N2 as ck,en as cl,ih as cm,Bb as cn,fy as co,ZD as cp,mB as cq,sS as cr,T as cs,jB as ct,_T as cu,lt as cv,JN as cw,v9 as cx,pa as cy,dB as cz,Jy as d,P9 as d$,wB as d0,g0 as d1,xc as d2,tS as d3,uz as d4,a9 as d5,z9 as d6,kL as d7,jL as d8,xn as d9,Un as dA,pB as dB,nB as dC,V_ as dD,j9 as dE,J as dF,fB as dG,ao as dH,i9 as dI,G9 as dJ,U9 as dK,l9 as dL,Pe as dM,Ik as dN,GB as dO,bL as dP,b6 as dQ,eW as dR,QT as dS,JB as dT,XB as dU,YB as dV,O9 as dW,L9 as dX,F9 as dY,Q9 as dZ,e9 as d_,pz as da,vB as db,yB as dc,rB as dd,s9 as de,iB as df,oB as dg,sB as dh,eB as di,Jq as dj,h9 as dk,hB as dl,UD as dm,lB as dn,u9 as dp,vp as dq,j1 as dr,jp as ds,bB as dt,gB as du,s1 as dv,z0 as dw,HB as dx,f9 as dy,w1 as dz,fS as e,W9 as e0,Kc as e1,f6 as e2,Z9 as e3,h6 as e4,m6 as e5,H9 as e6,o9 as e7,D9 as e8,J9 as e9,t9 as eA,Ea as eB,F_ as eC,xt as eD,A9 as eE,q9 as eF,$9 as eG,lM as eH,cp as eI,oS as eJ,tB as eK,Nr as eL,aB as eM,k9 as eN,V9 as ea,r9 as eb,rt as ec,R9 as ed,S2 as ee,Ua as ef,C1 as eg,e0 as eh,E9 as ei,N9 as ej,S9 as ek,gL as el,B9 as em,oe as en,dt as eo,tt as ep,I9 as eq,K9 as er,se as es,xe as et,Y9 as eu,GT as ev,X9 as ew,M9 as ex,ha as ey,Os as ez,bc as f,xS as g,Vb as h,oa as i,gS as j,nn as k,k_ as l,Sn as m,Gp as n,ua as o,Ft as p,yS as q,Sr as r,yc as s,qb as t,C2 as u,yF as v,Ps as w,DI as x,II as y,us as z};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.