1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9106],{784:(e,t,a)=>{"use strict";a.d(t,{$U:()=>i,YL:()=>s,nI:()=>r,nw:()=>c});var n=a(5068);let o=(0,a(8260).getEnvironmentConfig)().apiUrl,i=async e=>{let t=localStorage.getItem("accessToken"),a={};return t&&(a.Authorization="Bearer ".concat(t)),(await n.A.get("".concat(o,"/packs"),{params:e?{modelo_id:e}:{},headers:a})).data.data},r=async e=>{let t=localStorage.getItem("accessToken"),a={};return t&&(a.Authorization="Bearer ".concat(t)),(await n.A.get("".concat(o,"/packs/").concat(e),{headers:a})).data.data},s=async e=>{let t=localStorage.getItem("accessToken");if(!t)throw Error("Authentication required");return(await n.A.post("".concat(o,"/packs/").concat(e,"/unlock"),{},{headers:{Authorization:"Bearer ".concat(t)}})).data},c=e=>"".concat(o,"/media/private/").concat(e)},2201:(e,t,a)=>{"use strict";a.r(t),a.d(t,{__N_SSP:()=>eL,default:()=>eq});var n=a(7876),o=a(7328),i=a.n(o),r=a(4232),s=a(9099),c=a(9053),l=a(1331),d=a(7319),u=a(9566),m=a(5027),p=a(9336),h=a(8260),g=a(6132);class f{async generateAudio(e,t,a){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,o=arguments.length>4?arguments[4]:void 0,i=arguments.length>5?arguments[5]:void 0;try{let r="".concat(t,":").concat(e);if(this.audioCache.has(r)){let e=this.audioCache.get(r);return{audio:await this.fetchAudioBlob(e)}}let s=await (0,g.fetchWithAuth)("".concat(this.config.apiBase,"/audio/generate"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(a),Accept:"audio/mpeg, application/json"},body:JSON.stringify({text:e,model_name:t,conversation_message_count:n,conversation_id:o,message_id:i&&/^\d+$/.test(i)&&1e12>Number(i)?Number(i):void 0})});if(!s.ok)return{audio:null,error:({401:"Tu sesi\xf3n venci\xf3. Inicia sesi\xf3n de nuevo para escuchar el audio.",402:"Necesitas un token para generar este audio.",403:"No se pudo validar este mensaje. Recarga la conversaci\xf3n.",404:"La voz de este personaje no est\xe1 disponible.",429:"Hay varias solicitudes de audio. Int\xe9ntalo de nuevo en unos segundos.",503:"El generador de voz no est\xe1 disponible. Int\xe9ntalo de nuevo en unos segundos.",504:"La generaci\xf3n tard\xf3 demasiado. Puedes volver a intentarlo."})[s.status]||"No se pudo generar el audio. Int\xe9ntalo de nuevo."};let c=s.headers.get("x-tokens-remaining")||s.headers.get("X-Tokens-Remaining"),l=c?parseInt(c):void 0,d=s.headers.get("content-type");if(d&&d.includes("audio/mpeg"))return{audio:await s.blob(),tokensRemaining:l};{let e=await s.json();if(e.success&&e.audio_data)return{audio:this.base64ToBlob(e.audio_data,"audio/mpeg"),tokensRemaining:l};return{audio:null,error:"No se pudo obtener el audio. Comprueba la conexi\xf3n y vuelve a intentarlo."}}}catch(e){return{audio:null,error:"No se pudo obtener el audio. Comprueba la conexi\xf3n y vuelve a intentarlo."}}}async playAudio(e,t,a){this.stopAudio();let n=URL.createObjectURL(e),o=new Audio(n);this.currentAudio=o,this.currentObjectUrl=n,this.currentMessageId=t||null,this.playbackEnded=a||null;let i=()=>{this.currentAudio===o&&this.stopAudio()};o.onended=i,o.onerror=i;try{await o.play()}catch(e){throw i(),e}}stopAudio(){this.currentAudio&&(this.currentAudio.onended=null,this.currentAudio.onerror=null,this.currentAudio.pause(),this.currentAudio.currentTime=0,this.currentAudio=null),this.currentObjectUrl&&URL.revokeObjectURL(this.currentObjectUrl),this.currentObjectUrl=null,this.currentMessageId=null;let e=this.playbackEnded;this.playbackEnded=null,null==e||e()}isPlaying(e){return this.currentMessageId===e&&null!==this.currentAudio&&!this.currentAudio.paused}async generateAndPlayAudio(e,t,a){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,o=arguments.length>4?arguments[4]:void 0,i=arguments.length>5?arguments[5]:void 0,r=arguments.length>6?arguments[6]:void 0,s=arguments.length>7?arguments[7]:void 0;try{let c=++this.generationSerial,l=await this.generateAudio(e,t,a,n,i,o);if(null==r||r(l.tokensRemaining),c!==this.generationSerial)return{success:!1,tokensRemaining:l.tokensRemaining};
1if(!l.audio)return{success:!1,error:l.error||"No se pudo generar el audio."};return await this.playAudio(l.audio,o,s),{success:!0,tokensRemaining:l.tokensRemaining}}catch(e){return{success:!1,error:"El navegador no pudo reproducir el audio. Comprueba el sonido y pulsa de nuevo el volumen."}}}async getAudioStatus(e){try{let t=await fetch("".concat(this.config.apiBase,"/audio/status"),{headers:{Authorization:"Bearer ".concat(e)}});return await t.json()}catch(e){return null}}async getAvailableVoices(e){try{let t=await fetch("".concat(this.config.apiBase,"/audio/voices"),{headers:{Authorization:"Bearer ".concat(e)}});return await t.json()}catch(e){return null}}base64ToBlob(e,t){let a=atob(e),n=Array(a.length);for(let e=0;e<a.length;e++)n[e]=a.charCodeAt(e);return new Blob([new Uint8Array(n)],{type:t})}async fetchAudioBlob(e){let t=await fetch(e);return await t.blob()}clearCache(){this.audioCache.clear()}constructor(){this.config=(0,h.getEnvironmentConfig)(),this.audioCache=new Map,this.currentAudio=null,this.currentObjectUrl=null,this.playbackEnded=null,this.generationSerial=0,this.currentMessageId=null}}let v=new f;var x=a(7461),b=a.n(x);let y={minSplitLength:60,targetLength:45,minBubbleLength:20,maxBubbles:5,emojiTailBubble:!0},j=".!?â¦",_=e=>e.split("î").join("...").split("î").join("â¦"),k=e=>" "===e||"\n"===e||" "===e||"\r"===e,C=/(\s*)((?:[\u2190-\u21FF\u2600-\u27BF\u2B00-\u2BFF\uFE0F\u200D]|[\uD83C-\uD83E][\uDC00-\uDFFF])+)$/;function N(e,t){let{targetLength:a,minBubbleLength:n,maxBubbles:o}=t,i=[],r="";for(let t of e){let e=r?"".concat(r," ").concat(t).trim():t;r&&e.length>a?(i.push(r),r=t):r=e}r&&i.push(r);let s=0;for(;s<i.length;)i[s].length<n&&i.length>1&&(0===s?(i[1]="".concat(i[0]," ").concat(i[1]),i.shift()):(i[s-1]="".concat(i[s-1]," ").concat(i[s]),i.splice(s,1),s-=1)),s+=1;for(;i.length>o;)i[i.length-2]="".concat(i[i.length-2]," ").concat(i[i.length-1]),i.pop();return i}let w=e=>{let{mensajeId:t,texto:a}=e,o=(0,r.useRef)(null),i=(0,r.useRef)(null),[s,c]=(0,r.useState)("listo"),[l,d]=(0,r.useState)(0),[u,m]=(0,r.useState)(Math.max(2,Math.round(a.replace(/\*[^*]*\*/g," ").trim().length/14))),[p,h]=(0,r.useState)(!1),f=(0,r.useMemo)(()=>(function(e){let t=0x9e3779b1*e%0x100000000;return Array.from({length:34},()=>.25+(t=(1664525*t+0x3c6ef35f)%0x100000000)/0x100000000*.75)})(t),[t]);(0,r.useEffect)(()=>()=>{var e;null==(e=o.current)||e.pause(),i.current&&URL.revokeObjectURL(i.current)},[]);let v=(0,r.useCallback)(async()=>{if(o.current)return o.current;c("cargando");try{let e=await (0,g.fetchWithAuth)("".concat("https://noviasvirtuales.ai/api/v1","/audio/nota/").concat(t));if(!e.ok)throw Error(String(e.status));let a=await e.blob();i.current=URL.createObjectURL(a);let n=new Audio(i.current);return n.onloadedmetadata=()=>{isFinite(n.duration)&&m(n.duration)},n.ontimeupdate=()=>d(n.currentTime),n.onended=()=>{c("listo"),d(0)},o.current=n,n}catch(e){return c("error"),null}},[t]),x=(0,r.useCallback)(async e=>{if(e.stopPropagation(),"sonando"===s){var t;null==(t=o.current)||t.pause(),c("pausa");return}let a=await v();if(a)try{await a.play(),c("sonando")}catch(e){c("error")}},[s,v]),b=(0,r.useCallback)(async e=>{e.stopPropagation();let t=await v();if(!t||!isFinite(t.duration))return;let a=e.currentTarget.getBoundingClientRect();t.currentTime=Math.max(0,Math.min(1,(e.clientX-a.left)/a.width))*t.duration,d(t.currentTime)},[v]),y=u>0?l/u:0,j="cargando"===s?"fa-spinner fa-spin":"sonando"===s?"fa-pause":"error"===s?"fa-redo":"fa-play";return(0,n.jsxs)("div",{className:"nota-de-voz",style:{minWidth:230,maxWidth:300},onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("button",{onClick:x,"aria-label":"sonando"===s?"Pausar nota de voz":"Reproducir nota de voz",style:{width:38,height:38,borderRadius:"50%",border:"none",flexShrink:0,cursor:"pointer",background:"rgba(255,255,255,0.18)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:15},children:(0,n.jsx)("i",{className:"fas ".concat(j),style:{marginLeft:2*("fa-play"===j)}})}),(0,n.jsx)("div",{onClick:b,role:"slider","aria-valuemin":0,"aria-valuemax":Math.round(u),"aria-valuenow":Math.round(l),style:{flex:1,height:30,display:"flex",alignItems:"center",gap:2,cursor:"pointer"},children:f.map((e,t)=>(0,n.jsx)("span",{style:{flex:1,height:"".concat(Math.round(100*e),"%"),borderRadius:2,background:t/34<=y?"#fff":"rgba(255,255,255,0.38)",transition:"background 0.1s linear"}},t))})]}),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:4,fontSize:11,opacity:.8},children:[(0,n.jsx)("span",{children:"error"===s?"No se pudo cargar. Toca para reintentar":function(e){(!isFinite(e)||e<0)&&(e=0);let t=Math.floor(e/60),a=Math.floor(e%60);return"".concat(t,":").concat(a.toString().padStart(2,"0"))}("listo"===s&&0===l?u:l)}),(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),h(e=>!e)},style:{background:"none",border:"none",color:"inherit",fontSize:11,cursor:"pointer",padding:0,textDecoration:"underline"},children:p?"Ocultar texto":"Ver texto"})]}),p&&(0,n.jsx)("div",{style:{marginTop:6,fontSize:13,opacity:.9,whiteSpace:"pre-wrap"},children:a})]})},S=null;var I=a(8519);let A=["â¤ï¸","\uD83D\uDD25","\uD83D\uDE0D","\uD83D\uDE02","\uD83E\uDD75","\uD83D\uDE2E","\uD83D\uDE08","\uD83D\uDC4D"],E=e=>{let{current:t,onPick:a,onClose:o}=e,i=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e=e=>{i.current&&!i.current.contains(e.target)&&o()},t=e=>{"Escape"===e.key&&o()};return document.addEventListener("mousedown",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("touchstart",e),document.removeEventListener("keydown",t)}},[o]),(0,n.jsx)("div",{ref:i,className:"reaction-picker",role:"menu","aria-label":"Reaccionar al mensaje",onClick:e=>e.stopPropagation(),children:A.map(e=>(0,n.jsx)("button",{type:"button",role:"menuitem",className:"reaction-picker-item ".concat(t===e?"is-selected":""),onClick:t=>{t.stopPropagation(),a(e)},"aria-label":"Reaccionar con ".concat(e),"aria-pressed":t===e,children:e},e))})},T=e=>{let{reactions:t,onClick:a}=e;if(!t||!t.usuario&&!t.modelo)return null;
1let o=Array.from(new Set([t.modelo,t.usuario].filter(Boolean)));return(0,n.jsx)("button",{type:"button",className:"reaction-badge",onClick:e=>{e.stopPropagation(),null==a||a()},"aria-label":"Reacciones: ".concat(o.join(" ")),title:[t.modelo?"Ella reaccion\xf3 ".concat(t.modelo):null,t.usuario?"T\xfa reaccionaste ".concat(t.usuario):null].filter(Boolean).join(" \xb7 "),children:o.map(e=>(0,n.jsx)("span",{className:"reaction-badge-emoji",children:e},e))})};var D=a(8239),R=a(5961),P=a.n(R),M=a(8477);let z={cargado:!1,enabled:!1,tokens:0,enCurso:null,aviso:null},L={},q=new Set,O=new Set,B={};function U(e,t){L={...L,[e]:{...L[e]||z,...t}},q.forEach(e=>e())}async function F(e,t){let{fetchWithAuth:n}=await Promise.resolve().then(a.bind(a,6132));return n(e,t)}async function H(e){var t;if(!(!e||O.has(e))&&(null==(t=L[e])||!t.cargado)){O.add(e);try{let t=await F("".concat("https://noviasvirtuales.ai/api/v1","/video/config?conversacion_id=").concat(e)),a=t.ok?await t.json():{enabled:!1},n=a.en_curso&&a.en_curso.operacion?{operacion:a.en_curso.operacion,mensajeId:Number(a.en_curso.mensaje_id)}:null;U(e,{cargado:!0,enabled:!!a.enabled,tokens:Number(a.tokens)||0,enCurso:n}),n&&W(e)}catch(t){U(e,{cargado:!0,enabled:!1})}finally{O.delete(e)}}}function W(e){B[e]&&clearTimeout(B[e]),B[e]=setTimeout(()=>V(e),1e4)}async function V(e){let t=L[e];if(null==t?void 0:t.enCurso){try{let n=await F("".concat("https://noviasvirtuales.ai/api/v1","/video/estado/").concat(t.enCurso.operacion));if(n.ok){let o=await n.json();if("listo"===o.estado){U(e,{enCurso:null,aviso:{mensajeId:t.enCurso.mensajeId,texto:"\xa1Tu v\xeddeo est\xe1 listo! Lo tienes abajo en el chat."}}),Promise.resolve().then(a.bind(a,2048)).then(e=>e.avisoBarraFoto(!1,null)).catch(()=>void 0);return}if("fallido"===o.estado)return void U(e,{enCurso:null,aviso:{mensajeId:t.enCurso.mensajeId,texto:"No se pudo hacer el v\xeddeo. Te devolvimos los tokens."}})}else if(404===n.status)return void U(e,{enCurso:null})}catch(e){}W(e)}}async function J(e){let t=await F("".concat("https://noviasvirtuales.ai/api/v1","/video/foto/").concat(e,"/acciones"));if(!t.ok)return[];let a=await t.json();return Array.isArray(a.acciones)?a.acciones:[]}async function G(e,t,n){try{let o=await F("".concat("https://noviasvirtuales.ai/api/v1","/video/desde-foto"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mensaje_id:t,accion:n})}),i=await o.json().catch(()=>({}));if(202===o.status)return U(e,{enCurso:{operacion:i.operacion,mensajeId:t},aviso:null}),W(e),Promise.resolve().then(a.bind(a,2048)).then(t=>t.avisoBarraFoto(!0,e)).catch(()=>void 0),null;if(402===o.status)return"No tienes tokens suficientes para el v\xeddeo.";return"string"==typeof i.detail?i.detail:"No se pudo pedir el v\xeddeo. Int\xe9ntalo de nuevo."}catch(e){return"No se pudo pedir el v\xeddeo. Revisa tu conexi\xf3n."}}let Y=e=>{var t,a;let{mensajeId:o,conversacionId:i}=e,s=function(e){return(0,r.useSyncExternalStore)(e=>(q.add(e),()=>q.delete(e)),()=>e&&L[e]||z,()=>z)}(i),[c,l]=(0,r.useState)(!1),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(null),[h,g]=(0,r.useState)(!1),[f,v]=(0,r.useState)(null);(0,r.useEffect)(()=>{i&&H(i)},[i]);let x=(0,r.useCallback)(async e=>{e.stopPropagation(),l(!0),p(null),v(null),u(null),u(await J(o))},[o]),b=(0,r.useCallback)(()=>{l(!1),p(null),v(null)},[]),y=(0,r.useCallback)(async()=>{if(!m)return;g(!0);let e=await G(i,o,m.clave);if(g(!1),e)return void v(e);b()},[m,i,o,b]);if(!s.enabled||!o||o<0)return null;let j=(null==(t=s.enCurso)?void 0:t.mensajeId)===o,_=!!s.enCurso&&!j;return(0,n.jsxs)("div",{onClick:e=>e.stopPropagation(),className:"jsx-e58ee246b38a26e8 nv-video",children:[j?(0,n.jsxs)("div",{role:"status",className:"jsx-e58ee246b38a26e8 nv-video-preparando",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"jsx-e58ee246b38a26e8 nv-video-spinner"}),"Preparando tu v\xeddeo⦠(puede tardar unos minutos)"]}):(0,n.jsxs)("button",{type:"button",onClick:x,disabled:_,title:_?"Estoy preparando otro v\xeddeo":"Convertir esta foto en un v\xeddeo",className:"jsx-e58ee246b38a26e8 nv-video-boton",children:["ⶠConvert
1ir a v\xeddeo",s.tokens?" \xb7 ".concat(s.tokens," tokens"):""]}),(null==(a=s.aviso)?void 0:a.mensajeId)===o&&!j&&(0,n.jsx)("div",{className:"jsx-e58ee246b38a26e8 nv-video-aviso",children:s.aviso.texto}),c&&"undefined"!=typeof document&&(0,M.createPortal)((0,n.jsx)("div",{onClick:b,className:"jsx-e58ee246b38a26e8 nv-video-fondo",children:(0,n.jsx)("div",{role:"dialog","aria-label":"Convertir a v\xeddeo",onClick:e=>e.stopPropagation(),className:"jsx-e58ee246b38a26e8 nv-video-menu",children:m?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"jsx-e58ee246b38a26e8 nv-video-titulo",children:[m.icono," ",m.nombre]}),(0,n.jsxs)("div",{className:"jsx-e58ee246b38a26e8 nv-video-nota",children:["Un v\xeddeo de 5 segundos a partir de esta foto por ",(0,n.jsxs)("b",{className:"jsx-e58ee246b38a26e8",children:[m.tokens," tokens"]}),". Puede tardar unos minutos; te aviso cuando est\xe9. Si no sale, te devuelvo los tokens."]}),f&&(0,n.jsx)("div",{className:"jsx-e58ee246b38a26e8 nv-video-error",children:f}),(0,n.jsxs)("div",{className:"jsx-e58ee246b38a26e8 nv-video-botones",children:[(0,n.jsx)("button",{type:"button",onClick:()=>p(null),disabled:h,className:"jsx-e58ee246b38a26e8 nv-video-cancelar",children:"Volver"}),(0,n.jsx)("button",{type:"button",onClick:y,disabled:h,className:"jsx-e58ee246b38a26e8 nv-video-confirmar",children:h?"Enviandoâ¦":"Confirmar \xb7 ".concat(m.tokens," tokens")})]})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"jsx-e58ee246b38a26e8 nv-video-titulo",children:"\xbfQu\xe9 quieres que haga en el v\xeddeo?"}),null===d&&(0,n.jsx)("div",{className:"jsx-e58ee246b38a26e8 nv-video-nota",children:"Cargandoâ¦"}),null!==d&&0===d.length&&(0,n.jsx)("div",{className:"jsx-e58ee246b38a26e8 nv-video-nota",children:"Con esta foto no puedo hacer v\xeddeos ahora mismo."}),null==d?void 0:d.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>p(e),className:"jsx-e58ee246b38a26e8 nv-video-accion",children:[(0,n.jsx)("span",{className:"jsx-e58ee246b38a26e8 nv-video-icono",children:e.icono}),(0,n.jsx)("span",{className:"jsx-e58ee246b38a26e8 nv-video-nombre",children:e.nombre}),(0,n.jsxs)("span",{className:"jsx-e58ee246b38a26e8 nv-video-coste",children:[e.tokens," tokens"]})]},e.clave)),(0,n.jsx)("button",{type:"button",onClick:b,className:"jsx-e58ee246b38a26e8 nv-video-cancelar",children:"Cancelar"})]})})}),document.body),(0,n.jsx)(P(),{id:"e58ee246b38a26e8",children:".nv-video.jsx-e58ee246b38a26e8{margin-top:6px}.nv-video-boton.jsx-e58ee246b38a26e8{background:rgba(236,72,153,.15);color:#f9a8d4;border:1px solid rgba(236,72,153,.45);border-radius:999px;padding:5px 12px;font-size:13px;cursor:pointer}.nv-video-boton.jsx-e58ee246b38a26e8:disabled{opacity:.45;cursor:not-allowed}.nv-video-preparando.jsx-e58ee246b38a26e8{display:flex;align-items:center;gap:8px;font-size:13px;color:#f9a8d4}.nv-video-spinner.jsx-e58ee246b38a26e8{width:14px;height:14px;border:2px solid rgba(249,168,212,.35);border-top-color:#f9a8d4;border-radius:50%;animation:nvgira.9s linear infinite}@keyframes nvgira{to{transform:rotate(360deg)}}.nv-video-aviso.jsx-e58ee246b38a26e8{font-size:12px;color:#d1d5db;margin-top:4px}.nv-video-fondo.jsx-e58ee246b38a26e8{position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:1000;display:flex;align-items:center;justify-content:center;padding:16px}.nv-video-menu.jsx-e58ee246b38a26e8{background:#1f1f2e;color:#fff;border-radius:14px;padding:16px;width:100%;max-width:360px;display:flex;flex-direction:column;gap:8px}.nv-video-titulo.jsx-e58ee246b38a26e8{font-weight:600;font-size:16px;margin-bottom:4px}.nv-video-nota.jsx-e58ee246b38a26e8{font-size:13px;color:#d1d5db}.nv-video-error.jsx-e58ee246b38a26e8{font-size:13px;color:#fca5a5}.nv-video-accion.jsx-e58ee246b38a26e8{display:flex;align-items:center;gap:10px;background:#2a2a3d;border:1px solid#3b3b55;color:#fff;border-radius:10px;padding:10px 12px;cursor:pointer;text-align:left}.nv-video-accion.jsx-e58ee246b38a26e8:hover{border-color:#ec4899}.nv-video-icono.jsx-e58ee246b38a26e8{font-size:20px}.nv-video-nombre.jsx-e58ee246b38a26e8{flex:1;font-size:14px}.nv-video-coste.jsx-e58ee246b38a26e8{font-size:12px;color:#fbbf24;white-space:nowrap}.nv-video-botones.jsx-e58ee246b38a26e8{display:flex;gap:8px;justify-content:flex-end;margin-top:6px}.nv-video-cancelar.jsx-e58ee246b38a26e8{background:transparent;color:#d1d5db;border:1px solid#4b5563;border-radius:8px;padding:8px 12px;cursor:pointer}.nv-video-confirmar.jsx-e58ee246b38a26e8{background:#ec4899;color:#fff;border:none;border-radius:8px;padding:8px 14px;font-weight:600;cursor:pointer}.nv-video-confirmar.jsx-e58ee246b38a26e8:disabled,.nv-video-cancelar.jsx-e58ee246b38a26e8:disabled{opacity:.6;cursor:wait}"})]})};var K=a(5521);let X="https://noviasvirtuales.ai/api/v1",$=null,Q=e=>{let t=localStorage.getItem("accessToken");return fetch(e,{headers:t?{Authorization:"Bearer ".concat(t)}:{}})};function Z(e){let{mensajeId:t}=e,[a,o]=(0,r.useState)(!1),[i,s]=(0,r.useState)(!1),[c,l]=(0,r.useState)(null),[d,u]=(0,r.useState)(null);if((0,r.useEffect)(()=>{let e=!0;return(function(){if($)return $;let e=null;try{e=sessionStorage.getItem("nv_admin_ver_prompt")}catch(e){}return $="1"===e||"0"===e?Promise.resolve("1"===e):Q("".concat(X,"/admin/generaciones/permiso")).then(e=>e.ok).catch(()=>!1).then(e=>
1{try{sessionStorage.setItem("nv_admin_ver_prompt",e?"1":"0")}catch(e){}return e})})().then(t=>e&&o(t)),()=>{e=!1}},[]),!a||!(t>0))return null;let m=async e=>{e.stopPropagation(),s(!0),l(null),u(null);try{let e=await Q("".concat(X,"/admin/generaciones/por-mensaje/").concat(t)),a=await e.json();if(!e.ok)throw Error((null==a?void 0:a.detail)||"HTTP ".concat(e.status));l(a)}catch(e){u(e.message)}};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{onClick:m,title:"Ver prompt (solo administradores)","aria-label":"Ver prompt",style:{display:"block",margin:"4px 0 0",border:"none",borderRadius:6,padding:"2px 8px",fontSize:11,cursor:"pointer",background:"rgba(0,0,0,0.6)",color:"#fff"},children:"{ } prompt"}),i&&(0,n.jsx)("div",{role:"dialog","aria-modal":"true",onClick:()=>s(!1),style:{position:"fixed",inset:0,zIndex:5e3,background:"rgba(0,0,0,0.8)",display:"flex",alignItems:"center",justifyContent:"center",padding:16},children:(0,n.jsxs)("div",{onClick:e=>e.stopPropagation(),style:{background:"#15151c",color:"#eee",borderRadius:12,padding:16,maxWidth:900,width:"100%",maxHeight:"88vh",overflow:"auto",textAlign:"left"},children:[(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:10},children:[(0,n.jsxs)("strong",{children:["Lo que se mand\xf3 a RunPod \xb7 mensaje ",t]}),(0,n.jsx)("button",{onClick:()=>s(!1),style:{background:"none",border:"none",color:"#fff",fontSize:20,cursor:"pointer"},children:"\xd7"})]}),d&&(0,n.jsx)("div",{style:{color:"#f87171"},children:d}),!c&&!d&&"Cargandoâ¦",c&&c.generacion&&(0,n.jsx)(K.A,{g:c.generacion,mensajeUsuario:c.mensaje_usuario_anterior,obtener:Q}),c&&!c.generacion&&(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{children:c.nota||"Sin registro de generaci\xf3n para esta foto."}),(0,n.jsxs)("p",{style:{opacity:.7},children:["Foto: ",(0,n.jsx)("code",{children:c.imagen_url})]}),c.mensaje_usuario_anterior&&(0,n.jsxs)("p",{style:{opacity:.7},children:["Mensaje del usuario: ",c.mensaje_usuario_anterior]})]})]})})]})}function ee(e){return(null==e?void 0:e.tipo_mensaje)==="sistema"||"string"==typeof(null==e?void 0:e.mensaje)&&e.mensaje.startsWith("No se pudo completar la foto en este momento")}function et(e){let t="usuario"===e.remitente;if(!t&&"nota_voz"===e.tipo_mensaje)return[{text:e.mensaje,isImage:!1,isVoice:!0}];let a=t?[e.mensaje]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a={...y,...t},n=(e||"").trim();if(!n)return[""];let o=n,i="";if(a.emojiTailBubble){let e=n.match(C);e&&e[2]&&n.length-e[0].length>=a.minSplitLength&&(o=n.slice(0,n.length-e[0].length),i=e[2])}let r=i?{...a,maxBubbles:Math.max(1,a.maxBubbles-1)}:a,s=e=>i?e.concat([i]):e;if(o.length<a.minSplitLength)return s([o]);if(-1!==o.indexOf("\n")){let e=o.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(e.length>1)return s(N(e,r))}return s(N(function(e){let t=[],a="";for(let n of function(e){let t=[],a=0,n=0;for(;n<e.length;){if(-1===j.indexOf(e[n])){n+=1;continue}let o=n;for(;o+1<e.length&&-1!==j.indexOf(e[o+1]);)o+=1;if(o+1<e.length&&k(e[o+1])){t.push(e.slice(a,o+1));let i=o+1;for(;i<e.length&&k(e[i]);)i+=1;a=i,n=i}else n=o+1}return a<e.length&&t.push(e.slice(a)),t}(e.split("...").join("î").split("â¦").join("î")))((a=a?"".concat(a," ").concat(n).trim():n).match(/\*/g)||[]).length%2==0&&(t.push(a),a="");return a&&t.push(a),t.map(_).filter(e=>e.trim().length>0)}(o),r))}(e.mensaje),n=a.filter(e=>e.trim().length>0).map(e=>({text:e,isImage:!1}));return(e.imageUrl||e.imagen_url||e.imagen)&&n.push({text:"",isImage:!0}),0===n.length&&n.push({text:a[0]||"",isImage:!1}),n}let ea=(0,r.memo)(e=>{let{message:t,index:a,isUser:o,userAvatar:i,aiAvatar:s,aiName:c,imageErrors:l,playingAudio:d,audioLoading:u,authToken:m,modelName:p,messagesLength:g,onMessageClick:f,onImageClick:v,onPlayAudio:x,onChipAction:y,processImageUrl:j,formatTimestamp:_,bubbleText:k,isLastBubble:C=!0,isImageBubble:N=!0,pickerOpen:A=!1,onOpenPicker:D,onClosePicker:R,onPickReaction:P}=e,M=(0,r.useMemo)(()=>{if(t.id)return"ms-".concat(t.id);let e=t.mensaje?t.mensaje.substring(0,30).replace(/\s/g,"-"):"empty";return"ms-temp-".concat(t.remitente,"-").concat(a,"-").concat(e)},[t.id,t.remitente,t.mensaje,a]);(0,r.useMemo)(()=>{let e=s;o||!s||s.startsWith("http")||s.startsWith("/")||(e="/".concat(s));let t=o?i:e;return l[M]?null:t},[o,i,s,l,M]);let z=(0,r.useMemo)(()=>j(t.imageUrl||t.imagen_url||t.imagen),[j,t.imageUrl,t.imagen_url,t.imagen,o,M,t.mensaje]),L=(0,r.useCallback)(()=>{f(String(M))},[f,M]),q=(0,r.useCallback)(e=>{e.stopPropagation(),z&&v(z,e)}
1,[v,z]),O=function(){let[e,t]=(0,r.useState)(!0);return(0,r.useEffect)(()=>{let e=!0;return(()=>{if(!S){let e=(0,h.getEnvironmentConfig)().apiUrl.replace(/\/api\/v1\/?$/,"");S=fetch("".concat(e,"/api/v1/voz/config")).then(e=>e.ok?e.json():{boton_audio:!0}).then(e=>!1!==e.boton_audio).catch(()=>!0)}return S})().then(a=>{e&&t(a)}),()=>{e=!1}},[]),e}(),B=(0,r.useCallback)(e=>{e.stopPropagation(),x(String(M),t.mensaje)},[x,M,t.mensaje]),U=(0,r.useCallback)(()=>{null==D||D()},[D]),{handlers:F}=function(e){let t=(0,r.useRef)(null),[a,n]=(0,r.useState)(!1),o=(0,r.useRef)(!1),i=(0,r.useCallback)(()=>{t.current&&(clearTimeout(t.current),t.current=null)},[]);return(0,r.useEffect)(()=>i,[i]),{hovered:a,handlers:{onMouseEnter:()=>n(!0),onMouseLeave:()=>{n(!1),i()},onTouchStart:()=>{o.current=!1,i(),t.current=setTimeout(()=>{o.current||e()},450)},onTouchMove:()=>{o.current=!0,i()},onTouchEnd:i,onTouchCancel:i}}}(U),H=t.reacciones,W=!!D&&C;return(0,n.jsx)("div",{className:"message ".concat(o?"sent":"received"),onClick:L,"data-message-id":M,...W?F:{},children:(0,n.jsx)("div",{className:"message-content",children:(0,n.jsxs)("div",{className:"message-bubble",children:[W&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(T,{reactions:H,onClick:U}),!A&&(0,n.jsx)("button",{type:"button",className:"reaction-trigger",onClick:e=>{e.stopPropagation(),U()},"aria-label":"Reaccionar al mensaje",title:"Reaccionar",children:(0,n.jsx)("i",{className:"far fa-smile"})}),A&&(0,n.jsx)(E,{current:null==H?void 0:H.usuario,onPick:e=>null==P?void 0:P(e),onClose:()=>null==R?void 0:R()})]}),N&&(t.imageUrl||t.imagen_url||t.imagen)&&z&&(0,n.jsx)("div",{className:"message-image-container",children:"video"===t.tipo_mensaje||"video"===t.tipo_mensaje?(()=>{let e=t.imageUrl||t.imagen_url||t.imagen||z,a=(0,I.gA)(e)?z:e,o=s?s.startsWith("http")||s.startsWith("/")?s:"/".concat(s):void 0;return(0,n.jsxs)("video",{preload:"metadata",className:"message-video",controls:!0,playsInline:!0,controlsList:"noplaybackrate noseek nodownload",poster:o,style:{maxWidth:"100%",width:"250px",aspectRatio:"3 / 4",height:"calc(100% / 1 - 4px)",overflow:"hidden",borderRadius:"8px",objectFit:"cover",marginBottom:"8px",backgroundColor:"#1a1a1a"},onEnded:e=>{let t=e.currentTarget,a=parseInt(t.getAttribute("data-play-count")||"0");a<1&&(t.setAttribute("data-play-count",(a+1).toString()),t.currentTime=0,t.play())},children:[(0,n.jsx)("source",{src:a,type:"video/mp4"}),"Tu navegador no soporta el tag de video."]})})():(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("img",{src:z,alt:"Foto compartida",className:"message-image",onClick:q,loading:"eager"}),!o&&Number(t.id)>0&&(0,n.jsx)(Z,{mensajeId:Number(t.id)}),!o&&"imagen"===t.tipo_mensaje&&Number(t.id)>0&&Number(t.conversacion_id)>0&&(0,n.jsx)(Y,{mensajeId:Number(t.id),conversacionId:Number(t.conversacion_id)})]})}),o||"nota_voz"!==t.tipo_mensaje?!(N&&""===k)&&(0,n.jsx)("div",{className:"message-text",children:en(void 0!==k?k:t.mensaje)}):(0,n.jsx)(w,{mensajeId:Number(t.id),texto:t.mensaje,authToken:m}),C&&!o&&t.action_chips&&t.action_chips.length>0&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"6px",marginTop:"8px",marginBottom:"4px",paddingTop:"6px",borderTop:"1px solid rgba(255,255,255,0.08)"},children:[t.chip_caption&&(0,n.jsx)("div",{style:{fontSize:"12px",color:"rgba(255,255,255,0.6)",paddingLeft:"2px"},children:t.chip_caption}),(0,n.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:t.action_chips.map((e,t)=>(0,n.jsxs)("button",{onClick:()=>null==y?void 0:y(e),style:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"5px 10px",borderRadius:"16px",border:"continuation"===e.action_kind||"modifier"===e.action_kind?"1px solid rgba(255,255,255,0.2)":"1px solid rgba(200,100,255,0.3)",background:"continuation"===e.action_kind||"modifier"===e.action_kind?"rgba(255,255,255,0.06)":"rgba(200,100,255,0.1)",color:"#e0e0e0",fontSize:"12px",cursor:"pointer",whiteSpace:"nowrap",transition:"all 0.15s ease"},onMouseEnter:t=>{t.currentTarget.style.background="continuation"===e.action_kind||"modifier"===e.action_kind?"rgba(255,255,255,0.12)":"rgba(200,100,255,0.2)"},onMouseLeave:t=>{t.currentTarget.style.background="continuation"===e.action_kind||"modifier"===e.action_kind?"rgba(255,255,255,0.06)":"rgba(200,100,255,0.1)"},title:e.label,children:[e.icon&&(0,n.jsx)("span",{children:e.icon}),(0,n.jsx)("span",{children:e.label})]},e.action_id||"chip-".concat(t)))})]}),C&&(0,n.jsxs)("div",{className:"message-metadata ".concat(b().messageMetadata),children:[(0,n.jsx)("span",{className:"message-time",children:_(t.fecha_envio)}),O&&!o&&m&&t.mensaje&&"nota_voz"!==t.tipo_mensaje&&(0,n.jsx)("button",{className:"".concat(b().audioButton," ").concat(u[M]?b().loading:""," ").concat(d[M]?b().playing:""),onClick:B,disabled:u[M],title:"Reproducir audio",children:u[M]?(0,n.jsx)("i",{className:"fas fa-spinner fa-spin"}):d[M]?(0,n.jsx)("i",{className:"fas fa-stop"}):(0,n.jsx)("i",{className:"fas fa-volume-up"})})]})]})})})},(e,t)=>{var a,n,o,i;return e.message.id===t.message.id&&e.message.mensaje===t.message.mensaje&&e.bubbleText===t.bubbleText&&e.isLastBubble===t.isLastBubble&&e.isImageBubble===t.isImageBubble&&e.pickerOpen===t.pickerOpen&&
1(null==(a=e.message.reacciones)?void 0:a.usuario)===(null==(n=t.message.reacciones)?void 0:n.usuario)&&(null==(o=e.message.reacciones)?void 0:o.modelo)===(null==(i=t.message.reacciones)?void 0:i.modelo)&&e.message.imagen_url===t.message.imagen_url&&e.message.imagen===t.message.imagen&&e.message.imageUrl===t.message.imageUrl&&e.imageErrors===t.imageErrors&&e.playingAudio===t.playingAudio&&e.audioLoading===t.audioLoading&&e.userAvatar===t.userAvatar&&e.aiAvatar===t.aiAvatar&&e.authToken===t.authToken}),en=e=>{if(!e||!e.includes("*"))return e;let t=e.split(/(\*[^*\n]{1,160}\*)/g);return 1===t.length?e:t.map((e,t)=>e.length>2&&e.startsWith("*")&&e.endsWith("*")?(0,n.jsx)("em",{className:"rp-narration",children:e.slice(1,-1)},t):(0,n.jsx)(r.Fragment,{children:e},t))},eo=e=>{let{messages:t,connectionStatus:o,isAITyping:i,isGeneratingPhoto:s=!1,photoProgress:c=0,photoStage:l=null,conversationId:d,photoRequestConversationId:u,onRetryConnection:m,userAvatar:p,aiAvatar:g,aiName:f="IA",onMessageClick:x,onImageClick:b,onSuggestedMessage:y,onChipAction:j,onCancelPhotoGeneration:_,websocketStatus:k,className:C="",authToken:N,modelName:w="isidora",onLoadMore:S,hasMoreMessages:A=!1,isLoadingMore:E=!1,onTokensUpdate:T,userPlan:R,userTokens:P,onShowVoiceSubscriptionModal:M,onShowVoiceTokensModal:z,messagesHeight:L,relationshipType:q,modelId:O,immersiveLimitNotice:B,onLimitCtaPrimary:U,onLimitCtaSecondary:F,anonymousDemoMessage:H,anonymousDemoIsPhoto:W,onReactionChange:V}=e,J=(0,r.useRef)(null),G=(0,r.useRef)(null);(0,r.useRef)(null);let Y=(0,r.useRef)(0),K=(0,r.useRef)(!1),[X,$]=(0,r.useState)(!0),[Q,Z]=(0,r.useState)(0),[en,eo]=(0,r.useState)({}),[ei,er]=(0,r.useState)({}),[es,ec]=(0,r.useState)(null),[el,ed]=(0,r.useState)({}),[eu,em]=(0,r.useState)([]);(0,r.useRef)(null);let[ep,eh]=(0,r.useState)(0),eg=(0,r.useRef)(null),ef=(0,r.useRef)(0),ev=(0,r.useRef)([]),ex=(0,r.useRef)(new Set),eb=(0,r.useRef)(!1),[ey,ej]=(0,r.useState)(null),e_=(0,r.useCallback)(async(e,n)=>{var o,i,r;ej(null);let s=(null==(i=t.find(t=>t.id===e))||null==(o=i.reacciones)?void 0:o.usuario)===n,c=null==(r=t.find(t=>t.id===e))?void 0:r.reacciones,l=s?{...c||{},usuario:void 0}:{...c||{},usuario:n};null==V||V(e,l);try{let{postWithAuth:t,deleteWithAuth:o}=await Promise.resolve().then(a.bind(a,6132)),i="".concat("https://noviasvirtuales.ai/api/v1","/chat/messages/").concat(e,"/reaction"),r=s?await o(i):await t(i,{emoji:n});if(!r.ok)throw Error("HTTP ".concat(r.status));let c=await r.json();null==V||V(e,c.reacciones||{})}catch(t){console.error("[Reacciones] no se pudo guardar, revirtiendo:",t),null==V||V(e,c||{})}},[t,V]),ek=(0,r.useCallback)(()=>{ev.current.forEach(clearTimeout),ev.current=[]},[]),eC=(0,r.useCallback)((e,t)=>e.id?"id-".concat(e.id):"tmp-".concat(e.remitente,"-").concat(e.fecha_envio,"-").concat(t),[]),eN=(0,r.useCallback)(e=>"sig-".concat(e.remitente,"|").concat(e.fecha_envio,"|").concat((e.mensaje||"").length)+"|".concat(e.imagen_url||e.imageUrl||e.imagen||""),[]),ew=(0,h.getEnvironmentConfig)(),eS=(0,r.useCallback)(e=>{if(e)return e.startsWith("/api/image/")?"".concat("https://noviasvirtuales.ai").concat(e):e.startsWith("/assets/content/")?e:(0,I.gA)(e)?(0,I.lR)(e):e.startsWith("http://")||e.startsWith("https://")?e:"".concat(ew.imageBaseUrl).concat(e)},[ew.imageBaseUrl]);(0,r.useEffect)(()=>{t.length>1&&em([])},[t.length]),(0,r.useEffect)(()=>{let e=e=>{let t=e.detail;Array.isArray(t)&&t.length>0&&em(t)};return window.addEventListener("show-suggested-chips",e),()=>window.removeEventListener("show-suggested-chips",e)},[]),(0,r.useCallback)(()=>{},[]),(0,r.useEffect)(()=>{if(!eb.current){if(0===t.length)return;eb.current=!0,t.forEach((e,t)=>{ex.current.add(eC(e,t)),ex.current.add(eN(e))});return}let e=t.length-1,a=t[e];if(!a)return;let n=eC(a,e),o=eN(a);if(ex.current.has(n)||ex.current.has(o))return;if(ex.current.add(n),ex.current.add(o),"usuario"===a.remitente){eg.current&&(ek(),eh(ef.current));return}if(ee(a)){ek(),eg.current=null,ef.current=0;return}let i=et(a).map(e=>e.text);if(i.length<=1){eg.current=null,ef.current=0;return}ek(),eg.current=n,ef.current=i.length,eh(1);let r=0;for(let e=1;e<i.length;e++){r+=Math.round(Math.min(1e3,300+9*i[e].length)*(.85+.3*Math.random()));let t=e+1;ev.current.push(setTimeout(()=>eh(t),r))}},[t,eC,eN,ek]),(0,r.useEffect)(()=>ek,[ek]);let eI=null!==eg.current&&ep<ef.current;(0,r.useEffect)(()=>{0!==ep&&X&&G.current&&(K.current=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{let e=G.current;e&&(e.scrollTop=e.scrollHeight),setTimeout(()=>{K.current=!1},300)})}))},[ep,X]),(0,r.useEffect)(()=>{let e=Y.current,a=G.current;if(t.length<=e||0===e){Y.current=t.length;return}if(Y.current=t.length,X&&a){let e=t[t.length-1],a=(null==e?void 0:e.remitente)==="usuario",n=Math.floor(1501*Math.random())+1500;K.current=!0,setTimeout(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(G.current){let e=G.current;e.scrollTop=e.scrollHeight,setTimeout(()=>{K.current=!1},300)}})})},a?0:n)}},[t,X]),(0,r.useEffect)(()=>{let e=G.current;if(!e)return;let t=!1,a={current:!1},n=e.scrollTop,o=async()=>{t||(requestAnimationFrame(async()=>{let{scrollTop:o,scrollHeight:i,clientHeight:r}=e,s=i-o-r<50;s!==X&&$(s),s&&Z(0);let c=o<n;
1if(n=o,c&&o<100&&!a.current&&A&&S&&!E){a.current=!0;let t=e.scrollHeight,n=e.scrollTop,o=e.querySelectorAll(".message"),i=null,r=0;for(let t=0;t<o.length;t++){let a=o[t],n=a.getBoundingClientRect(),s=e.getBoundingClientRect();if(n.bottom>s.top&&n.top<s.bottom){i=a,r=n.top-s.top;break}}let s=null==i?void 0:i.getAttribute("data-message-id");if(await S()){let e=0,o=()=>{e++;let i=document.getElementById("messages-list");if(!i){a.current=!1;return}let c=i.scrollHeight;if(i.querySelectorAll(".message").length,0===c||c<100)return void(e<50?setTimeout(o,10):a.current=!1);c!==t&&c>100?(s&&i.querySelector('[data-message-id="'.concat(s,'"]'))?setTimeout(()=>{let e=document.getElementById("messages-list"),t=null==e?void 0:e.querySelector('[data-message-id="'.concat(s,'"]'));e&&t&&(e.scrollTop=t.offsetTop-r)},50):i.scrollTop=Math.max(0,n+(c-t)),setTimeout(()=>{a.current=!1},500)):e<50?setTimeout(o,10):a.current=!1};requestAnimationFrame(o)}else setTimeout(()=>{a.current=!1},2e3)}t=!1}),t=!0)};return e.addEventListener("scroll",o,{passive:!0}),()=>e.removeEventListener("scroll",o)},[A,S,E,X]);let eA=(0,r.useCallback)(e=>{try{let t=(0,D.p)(e);if((new Date().getTime()-t.getTime())/36e5<24)return t.toLocaleTimeString("es-ES",{hour:"2-digit",minute:"2-digit",hour12:!1});return t.toLocaleDateString("es-ES",{day:"2-digit",month:"2-digit"})}catch(e){return""}},[]),eE=(0,r.useCallback)(async(e,a)=>{if(!N||!a.trim())return void ec(N?"Este mensaje no contiene texto para reproducir.":"Inicia sesi\xf3n de nuevo para escuchar el audio.");if(ec(null),ei[e]){v.stopAudio(),er(t=>({...t,[e]:!1}));return}if(!el[e]){if(!(R&&"free"!==R)){M&&M();return}if(void 0!==P&&P<1){z&&z();return}try{ed(t=>({...t,[e]:!0}));let n=await v.generateAndPlayAudio(a,w,N,t.length,e,d,e=>{void 0!==e&&(null==T||T(e))},()=>er(t=>({...t,[e]:!1})));n.success?er(t=>({...t,[e]:v.isPlaying(e)})):n.error&&ec(n.error)}catch(e){}finally{ed(t=>({...t,[e]:!1}))}}},[N,w,t.length,d,ei,el,T,R,P,M,z]),eT=(0,r.useCallback)(()=>{G.current&&(G.current.scrollTo({top:G.current.scrollHeight,behavior:"smooth"}),Z(0),$(!0))},[]),eD=(0,r.useCallback)(e=>{x&&x(e)},[x]),eR=(0,r.useCallback)((e,t)=>{t.stopPropagation(),b&&b(e)},[b]);(0,r.useCallback)(e=>{eo(t=>({...t,[e]:!0}))},[]);let eP=(0,r.useMemo)(()=>{let e=[];return t.forEach((a,o)=>{let i="usuario"===a.remitente,r=a.id||"".concat(a.remitente,"-").concat(a.fecha_envio,"-").concat(o);if(ee(a))return void e.push((0,n.jsx)("div",{style:{display:"flex",justifyContent:"center",margin:"10px 0"},children:(0,n.jsx)("span",{style:{fontSize:"0.78rem",lineHeight:1.4,color:"rgba(255, 255, 255, 0.5)",background:"rgba(255, 255, 255, 0.05)",border:"1px solid rgba(255, 255, 255, 0.08)",borderRadius:"12px",padding:"6px 14px",maxWidth:"82%",textAlign:"center"},children:a.mensaje})},"".concat(r,"#aviso")));let s=et(a),c=eC(a,o),l=eg.current===c?Math.min(ep,s.length):s.length;for(let c=0;c<l;c++)e.push((0,n.jsx)(ea,{bubbleText:s[c].text,isLastBubble:c===s.length-1,isImageBubble:s[c].isImage,message:a,index:o,isUser:i,userAvatar:p,aiAvatar:g,aiName:f,imageErrors:en,playingAudio:ei,audioLoading:el,authToken:N,modelName:w,messagesLength:t.length,onMessageClick:eD,onImageClick:eR,onPlayAudio:eE,onChipAction:j,processImageUrl:eS,formatTimestamp:eA,pickerOpen:ey===a.id,onOpenPicker:a.id?()=>ej(a.id):void 0,onClosePicker:()=>ej(null),onPickReaction:e=>e_(a.id,e)},"".concat(r,"#").concat(c)))}),e},[t,ep,eC,ey,e_,p,g,f,en,ei,el,N,w,eD,eR,eE,j,eS,eA]);return(()=>{})(),(0,n.jsxs)("div",{className:"flex flex-col h-full overflow-hidden ".concat(C),style:{height:"100%",maxHeight:"100%"},children:[es&&(0,n.jsxs)("div",{role:"alert",className:"shrink-0 px-4 py-2 text-sm bg-amber-50 text-amber-900",children:[es,(0,n.jsx)("button",{type:"button","aria-label":"Cerrar aviso de audio",className:"ml-3 underline",onClick:()=>ec(null),children:"Cerrar"})]}),(0,n.jsx)("div",{className:"flex-1 relative",children:(0,n.jsxs)("div",{ref:G,id:"messages-list",className:"w-full overflow-y-auto overflow-x-hidden px-6 py-4 scrollbar",style:{height:L?"".concat(L,"px"):"calc(100vh - 285px)",maxHeight:L?"".concat(L,"px"):"calc(100vh - 285px)",scrollBehavior:"smooth",overflowAnchor:"none"},children:[E&&(0,n.jsx)("div",{className:"flex justify-center py-4",children:(0,n.jsx)("div",{className:"animate-pulse text-gray-500",children:"Cargando mensajes anteriores..."})}),0===t.length?(0,n.jsxs)("div",{className:"chat-empty-state",children:[(0,n.jsx)("div",{className:"empty-state-icon",children:(0,n.jsx)("i",{className:"fas fa-comments"})}),(0,n.jsx)("h3",{className:"empty-state-title",children:"\xa1Comienza tu conversaci\xf3n!"}),(0,n.jsxs)("p",{className:"empty-state-text",children:['Di "Hola" para empezar a chatear con ',f,". Cada mensaje es \xfanico y personalizado para ti."]}),(0,n.jsxs)("div",{className:"suggested-messages",children:[(0,n.jsx)("button",{className:"suggested-message",onClick:()=>y&&y("\xa1Hola!"),children:"\uD83D\uDC4B \xa1Hola!"}),(0,n.jsx)("button",{className:"suggested-message",onClick:()=>y&&y("\xbfC\xf3mo est\xe1s?"),children:"\uD83D\uDCAD \xbfC\xf3mo est\xe1s?"}),(0,n.jsx)("button",{className:"suggested-message",onClick:()=>y&&y("Cu\xe9ntame sobre ti"),children:"\uD83C\uDFAF Cu\xe9ntame sobre ti"})]})]}):eP,eu.length>0&&(0,n.jsx)("div",{className:"suggested-replies-post-greeting",children:eu.map((e,t)=>(0,n.jsx)("button",{className:"suggested-reply-chip",onClick:()=>{y&&y(e.label),em([])},children:e.label},t))}),H&&(0,n.jsx)("div",{className:"message sent",children:(0,n.jsx)("div",{className:"message-content",children:(0,n.jsx)("div",{className:"message-bubble",children:(0,n.jsx)("div",{className:"message-text",children:W?"\uD83D\uDCF8 ".concat(H):H})})})}),(i||eI)&&(0,n.jsxs)("div",{className:"typing-indicator-modern","aria-label":"escribiendo",children:[(0,n.jsx)("span",{className:"typing-dot-modern"}),(0,n.jsx)("span",{className:"typing-dot-modern"}),(0,n.jsx)("span",{className:"typing-dot-modern"})]}),s&&u===d&&(0,n.jsx)("div",{className:"message received photo-pending",children:(0,n.jsx)("div",{className:"message-content",children:(0,n.jsxs)("div",{className:"photo-frame",role:"status","aria-live":"polite",children:[(0,n.jsx)("div",{className:"photo-frame-shimmer"}),(0,n.jsxs)("div",{className:"photo-frame-center",children:[(0,n.jsx)("div",{className:"photo-frame-ring",style:{background:"conic-gradient(#ff006e ".concat(3.6*M
1ath.round(c),"deg, rgba(255,255,255,0.10) 0deg)")},children:(0,n.jsxs)("span",{className:"photo-frame-pct",children:[Math.round(c),"%"]})}),(0,n.jsx)("span",{className:"photo-frame-label",children:"photo_queued"===l?"En colaâ¦":"".concat(f," est\xe1 preparando tu fotoâ¦")})]}),_&&(0,n.jsx)("button",{className:"photo-frame-cancel",onClick:_,"aria-label":"Cancelar generaci\xf3n de foto",title:"Cancelar",children:"â"})]})})}),B&&(0,n.jsx)("div",{className:"message received",style:{pointerEvents:"auto"},children:(0,n.jsx)("div",{className:"message-content",children:(0,n.jsxs)("div",{className:"message-bubble",style:{background:"linear-gradient(135deg, rgba(255, 0, 110, 0.12), rgba(255, 64, 129, 0.08))",border:"1px solid rgba(255, 0, 110, 0.2)",borderRadius:"16px",padding:"16px",maxWidth:"360px"},children:[(0,n.jsx)("div",{className:"message-text",style:{marginBottom:"8px",fontSize:"15px"},children:B.text}),(0,n.jsx)("div",{style:{fontSize:"13px",color:"rgba(255, 255, 255, 0.7)",lineHeight:"1.4",marginBottom:"16px"},children:B.secondaryText}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[U&&(0,n.jsxs)("button",{onClick:U,style:{background:"linear-gradient(135deg, #ff006e, #ff4081)",color:"#fff",border:"none",borderRadius:"20px",padding:"10px 20px",fontSize:"14px",fontWeight:600,cursor:"pointer",transition:"opacity 0.2s ease",width:"100%"},onMouseEnter:e=>{e.currentTarget.style.opacity="0.9"},onMouseLeave:e=>{e.currentTarget.style.opacity="1"},children:["Seguir hablando con ",B.modelName]}),F&&(0,n.jsx)("button",{onClick:F,style:{background:"transparent",color:"rgba(255, 255, 255, 0.7)",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"20px",padding:"8px 16px",fontSize:"13px",cursor:"pointer",transition:"all 0.2s ease",width:"100%"},onMouseEnter:e=>{e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.4)",e.currentTarget.style.color="rgba(255, 255, 255, 0.9)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.2)",e.currentTarget.style.color="rgba(255, 255, 255, 0.7)"},children:"Ver planes"})]})]})})}),(0,n.jsx)("div",{ref:J})]})}),!X&&(0,n.jsxs)("button",{className:"scroll-to-bottom-btn",onClick:eT,"aria-label":"Ir al final del chat",children:[(0,n.jsx)("i",{className:"fas fa-chevron-down"}),Q>0&&(0,n.jsx)("span",{className:"new-message-badge",children:Q})]}),!1]})};var ei=a(8674),er=a(8692),es=a(784),ec=a(3160),el=a(7355),ed=a(1477),eu=a.n(ed);function em(e){if(null==e)return"";if(e<60)return"ahora";if(e<3600)return"hace ".concat(Math.floor(e/60)," min");if(e<86400)return"hoy";let t=Math.floor(e/86400);return 1===t?"ayer":"hace ".concat(t," d\xedas")}function ep(e){var t,a,o,i;let{modelId:s,nombre:c}=e,l=(0,h.getEnvironmentConfig)().apiUrl.replace(/\/api\/v1\/?$/,""),[d,u]=(0,r.useState)(null),[m,p]=(0,r.useState)(""),[f,v]=(0,r.useState)("todo"),[x,b]=(0,r.useState)({}),[y,j]=(0,r.useState)(!1),_=(0,r.useRef)(null),k=(0,r.useRef)(0),C=(0,r.useRef)(null),N=(0,r.useRef)(),w=(0,r.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{var t,a,n,o,i;let e=null!==_.current?"?rev=".concat(_.current):"",r=await (0,g.fetchWithAuth)("".concat(l,"/api/v1/memorias/modelo/").concat(s).concat(e));if(!r.ok)throw Error(String(r.status));let c=await r.json();if(c.sin_cambios){k.current+=1;return}if(k.current=0,_.current=c.ia?null!=(t=c.rev)?t:0:null,c.premium){let e=[...(null!=(n=null!=(a=c.sobre_ti)?a:c.recuerdos)?n:[]).map(e=>e.key),...(null!=(o=c.sobre_ella)?o:[]).map(e=>e.key),...(null!=(i=c.otras)?i:[]).map(e=>e.key)];if(null===C.current)C.current=new Set(e);else{let t=C.current,a=e.filter(e=>!t.has(e));a.length&&(b(e=>{let t={...e};return a.forEach(e=>{t[e]=!0}),t}),j(!0),clearTimeout(N.current),N.current=setTimeout(()=>j(!1),45e3)),e.forEach(e=>t.add(e))}}u(c),p("")}catch(t){e||p("No se pudieron cargar las memorias")}},[l,s]);(0,r.useEffect)(()=>(_.current=null,k.current=0,C.current=null,u(null),b({}),j(!1),v("todo"),s&&w(),()=>clearTimeout(N.current)),[s,w]),(0,r.useEffect)(()=>{let e;if(!s)return;let t=()=>{e=setTimeout(async()=>{("undefined"==typeof document||"visible"===document.visibilityState)&&await w(!0),t()},Math.min(2e4,8e3+2e3*k.current))};t();let a=()=>{"visible"===document.visibilityState&&(k.current=0,w(!0))};return document.addEventListener("visibilitychange",a),()=>{clearTimeout(e),document.removeEventListener("visibilitychange",a)}},[s,w]);let S=async e=>{(await (0,g.fetchWithAuth)("".concat(l,"/api/v1/memorias/modelo/").concat(s,"/").concat(encodeURIComponent(e)),{method:"DELETE"}
1)).ok&&(k.current=0,_.current=null,u(t=>t?{...t,sobre_ti:(t.sobre_ti||[]).filter(t=>t.key!==e),sobre_ella:(t.sobre_ella||[]).filter(t=>t.key!==e),otras:(t.otras||[]).filter(t=>t.key!==e),recuerdos:(t.recuerdos||[]).filter(t=>t.key!==e)}:t))};if(m)return(0,n.jsx)("div",{className:eu().root,role:"alert",children:m});if(!d)return(0,n.jsx)("div",{className:eu().root,role:"status",children:"Cargandoâ¦"});if(!d.premium)return(0,n.jsx)("div",{className:eu().root,children:(0,n.jsxs)("div",{className:"".concat(eu().tarjeta," ").concat(eu().candado),children:[(0,n.jsx)("strong",{children:"\uD83D\uDD12 Memorias"}),(0,n.jsxs)("div",{style:{color:"#c9b8c1"},children:["Con Premium ",c," recuerda lo importante de ti y aqu\xed puedes ver y borrar lo que recuerda."]})]})});let I=null!=(a=null!=(t=d.sobre_ti)?t:d.recuerdos)?a:[],A=null!=(o=d.sobre_ella)?o:[],E=null!=(i=d.otras)?i:[],T=I.length+A.length+E.length===0,D=(e,t)=>!!x[e]||void 0!==t&&t<86400,R=(e,t,a)=>"".concat(e," ").concat(1===e?t:a),P=e=>{let t=D(e.key,e.hace_s),a=em(e.hace_s);return(0,n.jsxs)("li",{className:eu().recuerdo,children:[(0,n.jsx)(el.A,{n:function(e,t){let a=(e||"").toLowerCase(),n=(t||"").toLowerCase();return/ubicacion|\.pais|ciudad/.test(a)||/\b(vives?|vivo|vive|eres de|es de|nació|naciste|barrio|ciudad)\b/.test(n)?"lugar":/nombre/.test(a)||/\b(te llamas|se llama|me llamo)\b/.test(n)?"usuario":/trabajo|ocupacion/.test(a)||/\b(trabajas?|trabaja|oficio|profesi)/.test(n)?"maletin":/edad/.test(a)||/\b(tienes \d|tiene \d|\d+ años)\b/.test(n)?"calendario":/\b(soñ|sueñ|dormi|noche)/.test(n)?"luna":/\b(bebid|trago|bar\b|copa|vino|cerveza|cóctel|coctel)/.test(n)?"copa":/\b(mirar|mirada|hablar|habla|hablaron|conversa|dijo|dices|cuent|preguntó)/.test(n)?"chat":/gusto|prefer/.test(a)||/\b(te gusta|te gustan|te encanta|amas|prefieres|favorit)/.test(n)?"corazon":"estrella"}(e.key,e.texto),className:eu().icono}),(0,n.jsx)("span",{className:eu().recuerdoTexto,children:e.texto}),(t||a)&&(0,n.jsxs)("span",{className:eu().recuerdoMeta,children:[t&&(0,n.jsx)("span",{className:eu().nuevo,children:"NUEVO"}),a&&(0,n.jsx)("span",{children:a})]}),(0,n.jsx)("button",{type:"button",className:eu().olvidar,onClick:()=>S(e.key),title:"Olvidar","aria-label":"Olvidar: ".concat(e.texto),children:"â"})]},e.key)},M={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:8};return(0,n.jsxs)("div",{className:eu().root,children:[(0,n.jsx)("div",{className:eu().cabecera,children:(0,n.jsxs)("div",{children:[(0,n.jsxs)("h3",{children:["Lo que ",c," recuerda"]}),(0,n.jsxs)("p",{children:["Solo de esta conversaci\xf3n.",(0,n.jsx)("br",{}),"Se actualiza sola mientras hablan."]})]})}),(0,n.jsxs)("div",{className:"".concat(eu().tarjeta," ").concat(eu().aviso),role:"status","aria-live":"polite",children:[(0,n.jsx)(el.A,{n:"cerebro",className:"".concat(eu().icono," ").concat(eu().iconoG)}),(0,n.jsxs)("div",{className:eu().textoAviso,children:[(0,n.jsxs)("strong",{children:[y&&(0,n.jsx)("span",{className:eu().punto}),y?"".concat(c," acaba de recordar algo"):"".concat(c," recuerda lo importante")]}),(0,n.jsx)("small",{children:"La conversaci\xf3n se vuelve m\xe1s personal con cada mensaje."})]}),y&&(0,n.jsx)("span",{className:eu().nuevo,children:"NUEVO"})]}),(0,n.jsx)("div",{className:eu().filtros,role:"group","aria-label":"Filtrar recuerdos",children:[["todo","Todo"],["ti","Sobre ti"],["ella","Sobre ella"],["personas","Personas"]].map(e=>{let[t,a]=e;return(0,n.jsx)("button",{type:"button",className:eu().filtro,"aria-pressed":f===t,onClick:()=>v(t),children:a},t)})}),T&&(0,n.jsx)("div",{className:eu().vacio,children:"Todav\xeda no recuerda nada. Cu\xe9ntale cosas de ti."}),I.length>0&&("todo"===f||"ti"===f)&&(0,n.jsxs)("section",{className:eu().seccion,"aria-label":"Sobre ti",children:[(0,n.jsxs)("div",{className:eu().tituloSeccion,children:[(0,n.jsx)(el.A,{n:"usuario",className:"".concat(eu().icono," ").concat(eu().iconoG)}),(0,n.jsx)("h4",{children:"Sobre ti"}),(0,n.jsx)("span",{className:eu().contador,children:R(I.length,"recuerdo","recuerdos")})]}),(0,n.jsx)("ul",{style:M,children:I.map(P)})]}),A.length>0&&("todo"===f||"ella"===f)&&(0,n.jsxs)("section",{className:eu().seccion,"aria-label":"Sobre ella",children:[(0,n.jsxs)("div",{className:eu().tituloSeccion,children:[(0,n.jsx)(el.A,{n:"nube",className:"".concat(eu().icono," ").concat(eu().iconoG)}),(0,n.jsx)("h4",{children:"Sobre ella"}),(0,n.jsx)("span",{className:eu().contador,children:R(A.length,"recuerdo","re
1cuerdos")})]}),(0,n.jsx)("ul",{style:M,children:A.map(P)})]}),E.length>0&&("todo"===f||"personas"===f)&&(0,n.jsxs)("section",{className:eu().seccion,"aria-label":"Otras personas",children:[(0,n.jsxs)("div",{className:eu().tituloSeccion,children:[(0,n.jsx)(el.A,{n:"grupo",className:"".concat(eu().icono," ").concat(eu().iconoG)}),(0,n.jsx)("h4",{children:"Otras personas"}),(0,n.jsx)("span",{className:eu().contador,children:R(E.length,"persona","personas")})]}),(0,n.jsx)("ul",{style:M,children:E.map(e=>{let t=e.edad?/^~?\d+$/.test(e.edad.trim())?"".concat(e.edad," a\xf1os"):e.edad:"",a=[e.relacion,t].filter(Boolean).join(" \xb7 "),o=[e.fisico,(e.rasgos||[]).join(", ")].filter(Boolean).join(" \xb7 "),i=D(e.key,e.hace_s),r=em(e.hace_s);return(0,n.jsxs)("li",{className:eu().persona,children:[(0,n.jsx)("div",{className:eu().inicial,"aria-hidden":"true",children:(e.nombre||"?").trim().charAt(0).toUpperCase()}),(0,n.jsxs)("div",{className:eu().personaCuerpo,children:[(0,n.jsxs)("div",{className:eu().personaNombre,children:[e.nombre,i&&(0,n.jsx)("span",{className:eu().nuevo,children:"NUEVO"}),r&&(0,n.jsx)("span",{style:{fontSize:12,fontWeight:400,color:"#c9b8c1"},children:r})]}),a&&(0,n.jsx)("div",{className:eu().personaMeta,children:a}),o&&(0,n.jsx)("div",{className:eu().personaDetalle,children:o})]}),(0,n.jsx)("button",{type:"button",className:eu().olvidar,onClick:()=>S(e.key),title:"Olvidar","aria-label":"Olvidar a ".concat(e.nombre),children:"â"})]},e.key)})})]}),(0,n.jsxs)("div",{className:"".concat(eu().tarjeta," ").concat(eu().cierre),children:[(0,n.jsx)(el.A,{n:"corazon",className:"".concat(eu().icono," ").concat(eu().iconoG)}),(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:"Cuantos m\xe1s recuerdos, m\xe1s real se siente la conexi\xf3n."}),(0,n.jsxs)("small",{children:[c," recuerda lo importante."]})]})]})]})}let eh=e=>{let{selectedModel:t,modelHasPhotos:a,isMobile:o,showMobileCharacterInfo:i,onRefreshModel:c,onCallAction:l,onGalleryAction:d,onHeartAction:u,onInfoAction:m,isFavorited:p=!1,totalLikes:g=0,isTogglingFavorite:f=!1}=e,v=(0,s.useRouter)(),[x,b]=(0,r.useState)([]),[y,j]=(0,r.useState)(!1),[_,k]=(0,r.useState)(null),[C,N]=(0,r.useState)([]),[w,S]=(0,r.useState)(!1),[I,A]=(0,r.useState)(0),[E,T]=(0,r.useState)(null),[D,R]=(0,r.useState)("profile");(0,r.useEffect)(()=>{(async()=>{if(null==t?void 0:t.id){j(!0);try{let e=(0,h.getEnvironmentConfig)(),a=localStorage.getItem("accessToken");if(!a)return void b([]);let n=await fetch("".concat(e.apiUrl,"/chat/collections/").concat(t.id,"/photos"),{headers:{Authorization:"Bearer ".concat(a),"Content-Type":"application/json"}});if(n.ok){let e=await n.json();b(e.slice(0,10))}else b([])}catch(e){console.error("Error loading shared photos:",e),b([])}finally{j(!1)}}})()},[null==t?void 0:t.id]),(0,r.useEffect)(()=>{(async()=>{if(null==t?void 0:t.id){S(!0);try{let e=(0,h.getEnvironmentConfig)(),a=localStorage.getItem("accessToken"),n={"Content-Type":"application/json"};a&&(n.Authorization="Bearer ".concat(a));let o=await fetch("".concat(e.apiUrl,"/exclusive-albums/?modelo_id=").concat(t.id),{headers:n});if(o.ok){let e=await o.json();N(e)}else N([])}catch(e){console.error("Error loading exclusive albums:",e),N([])}finally{S(!1)}}})()},[null==t?void 0:t.id]),(0,r.useEffect)(()=>{(async()=>{if(null==t?void 0:t.id)try{let e=await (0,es.$U)(t.id);A(e.length),1===e.length&&T(e[0].id)}catch(e){A(0)}})()},[null==t?void 0:t.id]);let P=()=>{k(null)};return(0,n.jsxs)("div",{className:"character-info-sidebar ch-info-inner ".concat(o?i?"":"open":i?"open":""),children:[(0,n.jsxs)("div",{className:"sidebar-tabs",children:[(0,n.jsx)("button",{className:"sidebar-tab ".concat("profile"===D?"active":""),onClick:()=>R("profile"),children:"Perfil"}),(0,n.jsx)("button",{className:"sidebar-tab ".concat("gallery"===D?"active":""),onClick:()=>R("gallery"),children:"Galer\xeda"}),ec.z&&(0,n.jsx)("button",{className:"sidebar-tab ".concat("tu"===D?"active":""),onClick:()=>R("tu"),children:"T\xfa"}),(0,n.jsx)("button",{className:"sidebar-tab ".concat("memorias"===D?"active":""),onClick:()=>R("memorias"),children:"Memorias"})]}),"memorias"===D&&(0,n.jsx)(ep,{modelId:Number(t.id),nombre:t.model_name||t.name||"ella"}),"tu"===D&&ec.z&&(0,n.jsx)(ec.A,{contexto:"chat",modelo:{nombre:t.model_name||t.name||"ella",avatar:t.profile_photo}}),"profile"===D&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"character-header",children:[(()=>{if(t.personalizado||t.user_id)return(0,n.jsx)("img",{className:"character-avatar",src:t.profile_photo||"/assets/images/default-avatar.png",alt:t.model_name});let e=[];return t.gallery_images&&Array.isArray(t.gallery_images)&&t.gallery_images.forEac
1h(a=>{if(a){var n;a.split("/uploads/").pop()!==(null==(n=t.profile_photo)?void 0:n.split("/uploads/").pop())&&e.push({type:"image",url:a})}}),t.gallery_videos&&Array.isArray(t.gallery_videos)&&t.gallery_videos.length>0&&t.gallery_videos.forEach(a=>{a&&a!==t.video_preview&&e.push({type:"video",url:a})}),(0,n.jsx)(er.A,{characterName:t.model_name,profileImage:t.profile_photo||"/assets/images/default-avatar.png",hoverVideo:t.video_preview,additionalMedia:e},"carousel-".concat(t.id))})(),(0,n.jsx)("button",{onClick:m,style:{position:"absolute",top:"10px",right:"10px",background:"#b1004b",border:"1px solid rgba(255, 255, 255, 0.2)",borderRadius:"50%",color:"#ffffff",width:"32px",height:"32px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"all 0.3s ease",zIndex:20},title:"Cerrar",children:(0,n.jsx)("i",{className:"fas fa-close"})})]}),(0,n.jsxs)("div",{className:"flex-col justify-start items-start gap-1 flex p-6",children:[(0,n.jsx)("h2",{className:"character-name",children:t.model_name}),(0,n.jsxs)("p",{className:"character-status",children:[t.age&&"".concat(t.age," a\xf1os"),t.country&&" ⢠".concat(t.country)]}),t.description&&(0,n.jsx)("div",{className:"detail-content description-content",children:t.description}),(0,n.jsxs)("div",{className:"chat-actions",children:[(0,n.jsx)("button",{className:"action-btn",onClick:l,title:"Llamada de voz",children:(0,n.jsx)("i",{className:"fas fa-phone"})}),(0,n.jsx)("button",{className:"action-btn ".concat(a?"":"disabled"),onClick:d,title:a?"Galer\xeda":"No hay fotos disponibles",disabled:!a,style:{opacity:a?1:.5,cursor:a?"pointer":"not-allowed"},children:(0,n.jsx)("i",{className:"fas fa-images"})}),(0,n.jsxs)("button",{className:"action-btn ".concat(p?"favorited":""),onClick:u,title:p?"Quitar de favoritos":"Agregar a favoritos",disabled:f,style:{color:p?"#ff4757":void 0,position:"relative"},children:[(0,n.jsx)("i",{className:p?"fas fa-heart":"far fa-heart"}),g>0&&(0,n.jsx)("span",{style:{position:"absolute",bottom:"-2px",right:"-2px",fontSize:"10px",background:"#ff4757",color:"white",borderRadius:"8px",padding:"1px 4px",minWidth:"14px",textAlign:"center"},children:g>99?"99+":g})]}),(0,n.jsx)("button",{className:"action-btn",onClick:m,title:"Informaci\xf3n",children:(0,n.jsx)("i",{className:"fas fa-info-circle"})})]})]}),(0,n.jsx)("div",{className:"h-[0px] opacity-20 border border-white"}),(0,n.jsx)("div",{className:"flex-col justify-start gap-1 flex p-6",children:(0,n.jsx)("div",{className:"character-details",children:(0,n.jsxs)("div",{className:"detail-section about-me-section",children:[(0,n.jsxs)("div",{className:"detail-title",children:[(0,n.jsx)("i",{className:"fas fa-info-circle"}),"Acerca de m\xed:"]}),(0,n.jsxs)("div",{className:"about-me-grid",children:[t.personality&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-heart"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"PERSONALIDAD"}),(0,n.jsx)("div",{className:"about-value",children:t.personality})]})]}),t.age&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-calendar-alt"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"EDAD"}),(0,n.jsx)("div",{className:"about-value",children:t.age})]})]}),t.country&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-globe-americas"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"PA\xcdS"}),(0,n.jsx)("div",{className:"about-value",children:t.country})]})]}),t.languages&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-comments"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"IDIOMAS"}),(0,n.jsx)("div",{className:"about-value",children:t.languages})]})]}),t.occupation&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-briefcase"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"OCUPACI\xd3N"}),(0,n.jsx)("div",{className:"about-value",children:t.occupation})]})]}),t.height&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-ruler-vertical"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"ALTURA"}),(0,n.jsx)("div",{className:"about-value",children:t.height})]})]}),t.body_type&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-female"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"TIPO CUERPO"}),(0,n.jsx)("div",{className:"about-value",children:t.body_type})]})]}),t.bust_size&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-female"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"TAMA\xd1O BUSTO"}),(0,n.jsx)("div",{className:"about-value",children:t.bust_size})]})]}),t.butt_size&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-female"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"TAMA\xd1O TRASERO"}),(0,n.jsx)("div",{className:"about-value",children:t.butt_size})]})]}),t.ethnicity&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-user"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"ETNIA"}),(0,n.jsx)("div",{className:"about-value",children:t.ethnicity})]})]}),t.hair_color&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-cut"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"CABELLO"}),(0,n.jsx)("div",{className:"about-value",children:null==t?void 0:t.hair_color})]})]}),t.eye_color&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-eye"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"OJOS"}),(0,n.jsx)("div",{className:"about-value",children:null==t?void 0:t.eye_color})]})]}),(t.estilo_cabello||t.hair_style)&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-cut"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"ESTILO CABELLO"}),(0,n.jsx)("div",{className:"about-value",children:t.estilo_cabello||t.hair_style})]})]}),t.relationship_type&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-heart"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"RELACI\xd3N"}),(0,n.jsx)("div",{className:"about-value",children:t.relationship_type})]})]}),t.interests&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-star"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"INTERESES"}),(0,n.jsx)("div",{className:"about-value",children:t.interests})]})]}),(t.clothing_style||t.outfit_preferido)&&(0,n.jsxs)("div",{className:"about-item",children:[(0,n.jsx)("div",{className:"about-icon",children:(0,n.jsx)("i",{className:"fas fa-tshirt"})}),(0,n.jsxs)("div",{className:"about-info",children:[(0,n.jsx)("div",{className:"about-label",children:"ROPA FAVORITA"}),(0,n.jsx)("div",{className:"about-value",children:t.clothing_style||t.outfit_preferido})]})]})]})]})})})]}),"gallery"===D&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"flex-col justify-start gap-1 flex p-0",children:(0,n.jsx)("div",{className:"shared-media",children:(0,n.jsxs)("div",{className:"shared-media-section",children:[(0,n.jsxs)("div",{className:"detail-title p-3 mb-1",children:[(0,n.jsx)("i",{className:"fas fa-images"}),"Fotos compartidas: ",x.length>0&&"(".concat(x.length,")")]}),(0,n.jsx)("div",{className:"shared-media-grid",style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:"4px"},children:y?(0,n.jsxs)("div",{style:{gridColumn:"1 / -1",textAlign:"center",padding:"20px"},children:[(0,n.jsx)("i",{className:"fas fa-spinner fa-spin"})," Cargando fotos..."]}):x.length>0?x.map((e,t)=>(0,n.jsx)("div",{onClick:()=>{k(t)},style:{cursor:"pointer",borderRadius:"0px",overflow:"hidden",aspectRatio:"3/4",position:"relative"},children:(0,n.jsx)("img",{src:e.imagen_url,alt:"Foto compartida ".concat(t+1),loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",transition:"transform 0.2s"},onMouseOver:e=>e.currentTarget.style.transform="scale(1.05)",onMouseOut:e=>e.currentTarget.style.transform="scale(1)"})},e.id)):(0,n.jsx)("div",{style:{gridColumn:"1 / -1",textAlign:"center",padding:"20px",color:"rgba(255, 255, 255, 0.6)"},children:"No hay fotos compartidas a\xfan"})})]})})}),!t.user_id&&C.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"h-[0px] opacity-20 border border-white"}),(0,n.jsx)("div",{className:"flex-col justify-start gap-1 flex p-6",children:(0,n.jsxs)("div",{className:"exclusive-albums-section",children:[(0,n.jsxs)("div",{className:"detail-title",style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"16
1px"},children:[(0,n.jsx)("i",{className:"fas fa-star",style:{color:"#ff006e"}}),(0,n.jsx)("span",{children:"\xc1lbumes Exclusivos"}),C.length>0&&(0,n.jsxs)("span",{style:{color:"rgba(255, 255, 255, 0.6)"},children:["(",C.length,")"]})]}),w?(0,n.jsxs)("div",{style:{textAlign:"center",padding:"20px",color:"rgba(255, 255, 255, 0.6)"},children:[(0,n.jsx)("i",{className:"fas fa-spinner fa-spin"})," Cargando \xe1lbumes..."]}):C.length>0?(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:C.map(e=>(0,n.jsx)("a",{href:e.is_unlocked?"/exclusive-albums/view/".concat(e.id):"/exclusive-albums",style:{display:"block",background:"rgba(255, 255, 255, 0.05)",borderRadius:"12px",overflow:"hidden",border:"1px solid rgba(255, 255, 255, 0.1)",transition:"all 0.3s ease",cursor:"pointer",textDecoration:"none"},onMouseOver:e=>{e.currentTarget.style.borderColor="#ff006e",e.currentTarget.style.transform="translateY(-2px)"},onMouseOut:e=>{e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)",e.currentTarget.style.transform="translateY(0)"},children:(0,n.jsxs)("div",{style:{display:"flex",gap:"12px",padding:"12px"},children:[(0,n.jsxs)("div",{style:{position:"relative",width:"80px",height:"80px",flexShrink:0},children:[!e.is_unlocked&&(0,n.jsx)("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,background:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(8px)",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"8px"},children:(0,n.jsx)("i",{className:"fas fa-lock",style:{color:"#ff006e",fontSize:"20px"}})}),e.is_unlocked&&(0,n.jsx)("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,background:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(8px)",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"8px"},children:(0,n.jsx)("i",{className:"fas fa-check",style:{color:"white",fontSize:"20px"}})})]}),(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{color:"white",fontSize:"14px",fontWeight:600,marginBottom:"4px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.titulo}),(0,n.jsxs)("div",{style:{display:"flex",gap:"8px",fontSize:"12px",color:"rgba(255, 255, 255, 0.6)",marginBottom:"8px"},children:[(0,n.jsxs)("span",{children:["\uD83D\uDCF7 ",e.total_imagenes]}),(0,n.jsxs)("span",{children:["\uD83C\uDFA5 ",e.total_videos]})]}),e.is_unlocked?(0,n.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:"4px",color:"#4ade80",fontSize:"12px",fontWeight:600},children:[(0,n.jsx)("i",{className:"fas fa-check-circle"}),"Desbloqueado"]}):(0,n.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:"4px",background:"#ff006e",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontWeight:600},children:[(0,n.jsx)("i",{className:"fas fa-coins",style:{fontSize:"10px"}}),e.precio_tokens," tokens"]})]})]})},e.id))}):(0,n.jsx)("div",{style:{textAlign:"center",padding:"20px",color:"rgba(255, 255, 255, 0.6)"},children:"No hay \xe1lbumes exclusivos disponibles"})]})})]}),!t.user_id&&I>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"h-[0px] opacity-20 border border-white"}),(0,n.jsx)("div",{className:"flex-col justify-start gap-1 flex p-6",children:(0,n.jsx)("div",{className:"packs-cta-section",children:(0,n.jsxs)("button",{className:"packs-cta-button",onClick:()=>{1===I&&E?v.push("/packs/".concat(E)):v.push("/packs-privados?modelo_id=".concat(t.id))},style:{width:"100%",padding:"16px 20px",background:"linear-gradient(135deg, rgba(229, 0, 125, 0.15), rgba(255, 0, 110, 0.15))",border:"1px solid rgba(229, 0, 125, 0.3)",borderRadius:"12px",color:"#ff006e",fontSize:"16px",fontWeight:"700",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px",transition:"all 0.3s ease",textDecoration:"none"},onMouseOver:e=>{e.currentTarget.style.background="linear-gradient(135deg, rgba(229, 0, 125, 0.25), rgba(255, 0, 110, 0.25))",e.currentTarget.style.borderColor="rgba(229, 0, 125, 0.5)",e.currentTarget.style.transform="translateX(2px)"},onMouseOut:e=>{e.currentTarget.style.background="linear-gradient(135deg, rgba(229, 0, 125, 0.15), rgba(255, 0, 110, 0.15))",e.currentTarget.style.borderColor="rgba(229, 0, 125, 0.3)",e.currentTarget.style.transform="translateX(0)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"12px",flex:1},children:[(0,n.jsx)("i",{className:"fas fa-lock",style:{fontSize:"18px"}}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"4px",textAlign:"left"},children:[(0,n.jsx)("span",{style:{fontSize:"16px",fontWeight:"700"},children:"Packs Privados"}),(0,n.jsxs)("span",{style:{fontSize:"13px",fontWeight:"500",color:"rgba(255, 255, 255, 0.8)"},children:[I," ",1===I?"pack disponible":"packs disponibles"]})]})]}),(0,n.jsx)("i",{className:"fas fa-chevron-right",style:{fontSize:"14px",opacity:.7}})]})})})]}),(0,n.jsx)("div",{className:"h-[0px] opacity-20 border border-white"})]}),null!==_&&(0,n.jsxs)("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.9)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"20px"},onClick:P,children:[(0,n.jsx)("button",{onClick:P,style:{position:"absolute",top:"20px",right:"20px",background:"rgba(255, 255, 255, 0.1)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"50%",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:"white",fontSize:"24px",zIndex:1e4},children:"\xd7"}),_>0&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),null!==_&&_>0&&k(_-1)},style:{position:"absolute",left:"20px",background:"rgba(255, 255, 255, 0.1)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"50%",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:"white",fontSize:"24px"},children:"â¹"}),(0,n.jsx)("img",{src:x[_].imagen_url,alt:"Foto compartida ".concat(_+1),loading:"lazy",onClick:e=>e.stopPropagation(),style:{maxWidth:"90%",maxHeight:"90%",objectFit:"contain",borderRadius:"8px"}}),_<x.length-1&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),null!==_&&_<x.length-1&&k(_+1)},style:{position:"absolute",right:"20px",background:"rgba(255, 255, 255, 0.1)",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"50%",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:"white",fontSize:"24px"},children:"âº"}),(0,n.jsxs)("div",{style:{position:"absolute",bottom:"20px",left:"50%",transform:"translateX(-50%)",background:"rgba(0, 0, 0, 0.7)",padding:"8px 16px",borderRadius:"20px",color:"white",fontSize:"14px"},children:[_+1," / ",x.length]})]})]})};var eg=a(2107),ef=a(9274),ev=a(9986),ex=a(9968);let eb=(e,t)=>{try{ex.n.saveMessages(e.toString(),t)}catch(e){}},ey=e=>{try{ex.n.saveActiveConversation(JSON.stringify(e))}catch(e){}};var ej=a(2048),e_=a(5364);class ek{async generateImage(e){if(!this.apiKey)return{success:!1,error:"No API key configured"};for(let t of e.preferredModel?[e.preferredModel,...this.freeModels.filter(t=>t!==e.preferredModel)]:this.freeModels)try{let a=await this.tryGenerateWithModel(e,t,e.onProgress);if(a.success)return{...a,model:t}}catch(e){continue}return{success:!1,error:"All image generation models failed"}}async tryGenerateWithModel(e,t,a){let n=Date.now(),o=this.buildOptimizedPrompt(e);a&&a(70,"\uD83C\uDFA8 Iniciando ".concat(t.split("/")[1],"..."));
1let i={inputs:o,parameters:{negative_prompt:e.negativePrompt||this.getDefaultNegativePrompt(),width:e.width||1024,height:e.height||1536,num_inference_steps:"high"===e.quality?50:30,guidance_scale:7.5,seed:e.seed||Date.now()}};a&&a(80,"\uD83D\uDD04 Procesando con IA...");let r=await fetch("".concat(this.baseUrl,"/").concat(t),{method:"POST",headers:{Authorization:"Bearer ".concat(this.apiKey),"Content-Type":"application/json"},body:JSON.stringify(i)});if(!r.ok){let e=await r.text();throw Error("HF API error: ".concat(r.status," - ").concat(e))}let s=await r.blob();if(0===s.size)throw Error("Empty image response");return{success:!0,imageUrl:URL.createObjectURL(s),processingTime:Date.now()-n}}buildOptimizedPrompt(e){let{prompt:t,characterName:a,category:n}=e;if(t&&(t.includes("WOMAN ONLY")||t.includes("PHOTO OF A WOMAN"))&&t.length>200)return t;let o={selfie:"beautiful portrait of ".concat(a,", selfie style, looking at camera, warm lighting, high quality, photorealistic"),outfit:"beautiful ".concat(a," showing her outfit, full body, fashionable, stylish clothing, good lighting, high quality"),lifestyle:"beautiful ".concat(a," in daily life, natural pose, candid moment, warm lighting, photorealistic"),intimate:"beautiful portrait of ".concat(a,", elegant, artistic lighting, high quality, photorealistic"),random:"beautiful portrait of ".concat(a,", professional photography, high quality, photorealistic")},i=o[n]||o.random;return t&&"generar imagen"!==t&&(i="".concat(i,", ").concat(t)),"".concat(i,", ").concat("professional photography, high resolution, 8k uhd, detailed, realistic, masterpiece")}getDefaultNegativePrompt(){return"low quality, blurry, pixelated, distorted, watermark, text, multiple faces, deformed, ugly, bad anatomy, extra limbs, cartoon, anime"}isConfigured(){return!!this.apiKey}getServiceInfo(){return{name:"Hugging Face Inference API",provider:"Hugging Face",models:this.freeModels,free:!0,limits:{requestsPerMonth:1e3,requestsPerMinute:10,maxImageSize:"1024x1024",supportedFormats:["PNG","JPEG"],cost:"FREE"}}}async checkModelStatus(e){if(!this.apiKey)return null;try{let t=await fetch("".concat(this.baseUrl,"/").concat(e),{method:"GET",headers:{Authorization:"Bearer ".concat(this.apiKey)}});return await t.json()}catch(e){return null}}constructor(){this.baseUrl="https://api-inference.huggingface.co/models",this.freeModels=["black-forest-labs/FLUX.1-dev","stabilityai/stable-diffusion-xl-base-1.0","runwayml/stable-diffusion-v1-5","stabilityai/stable-diffusion-2-1","CompVis/stable-diffusion-v1-4"],this.apiKey=e_.env.NEXT_PUBLIC_HUGGINGFACE_API_KEY||""}}let eC=new ek;var eN=a(5364);class ew{async generateImage(e){if(eC.isConfigured())try{let t={prompt:e.prompt,characterName:e.modelId,modelId:e.modelId,category:e.category,negativePrompt:e.negativePrompt,width:this.getWidthFromAspectRatio(e.aspectRatio),height:this.getHeightFromAspectRatio(e.aspectRatio),quality:"ultra"===e.quality?"high":"standard",preferredModel:e.preferredHFModel,seed:e.seed,onProgress:e.onProgress},a=await eC.generateImage(t);if(a.success&&a.imageUrl)return{success:!0,imageUrl:a.imageUrl,generationTime:a.processingTime,metadata:{prompt:e.prompt,model:a.model||"Hugging Face",seed:Date.now(),parameters:t}}}catch(e){}if(this.STABILITY_API_KEY)try{return await this.generateWithStabilityAI(e)}catch(e){}if(this.OPENAI_API_KEY)try{return await this.generateWithOpenAI(e)}catch(e){}return{success:!1,error:"No se pudo generar la imagen. Verifica tu conexi\xf3n e intenta nuevamente."}}getWidthFromAspectRatio(e){return({"1:1":1024,"2:3":1024,"4:6":1024,"16:9":1024})[e]||1024}getHeightFromAspectRatio(e){return({"1:1":1024,"2:3":1536,"4:6":1536,"16:9":576})[e]||1536}async generateWithStabilityAI(e){throw Error("Stability AI not implemented yet")}async generateWithOpenAI(e){throw Error("OpenAI DALL-E not implemented yet")}getAvailableServices(){return{huggingface:{available:eC.isConfigured(),info:eC.getServiceInfo(),priority:1},stability:{available:!!this.STABILITY_API_KEY,info:{name:"Stability AI",provider:"Stability",free:!1,cost:"~$0.01/image"},priority:2},openai:{available:!!this.OPENAI_API_KEY,info:{name:"OpenAI DALL-E",provider:"OpenAI",free:!1,cost:"~$0.02/image"},priority:3}}}constructor(){this.HUGGINGFACE_API_KEY=eN.env.NEXT_PUBLIC_HUGGINGFACE_API_KEY,this.STABILITY_API_KEY=eN.env.NEXT_PUBLIC_STABILITY_API_KEY,this.OPENAI_API_KEY=eN.env.NEXT_PUBLIC_OPENAI_API_KEY}}let eS=new ew;var eI=a(8243),eA=a(5895),eE=a(2692);
1let eT={url:a(5364).env.NEXT_PUBLIC_WS_URL||"https://noviasvirtuales.ai",options:{transports:["websocket","polling"],upgrade:!0,rememberUpgrade:!0,timeout:2e4,forceNew:!1,reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,reconnectionDelayMax:5e3,maxReconnectionAttempts:10,autoConnect:!1}};class eD{connect(e,t){return new Promise(a=>{var n;if(null==(n=this.socket)?void 0:n.connected)return void a(!0);this.token=e,this.userId=t,this.reconnectAttempts=0,this.socket=(0,eE.io)(eT.url,eT.options),this.setupEventHandlers(),this.socket.connect(),this.setConnectionStatus("connecting");let o=setTimeout(()=>{"authenticated"!==this.connectionStatus&&(this.triggerError("Timeout de conexi\xf3n"),a(!1))},15e3);this.callbacks.onConnectionChange.push(e=>{"authenticated"===e?(clearTimeout(o),a(!0)):"error"===e&&(clearTimeout(o),a(!1))})})}disconnect(){this.isReconnecting=!1,this.currentConversationId&&this.leaveConversation(this.currentConversationId),this.socket&&(this.socket.disconnect(),this.socket=null),this.setConnectionStatus("disconnected"),this.token=null,this.userId=null,this.currentConversationId=null}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.setConnectionStatus("connected"),this.authenticate()}),this.socket.on("disconnect",e=>{this.setConnectionStatus("disconnected"),this.isReconnecting||"io client disconnect"===e||this.handleReconnection()}),this.socket.on("connect_error",e=>{this.triggerError("Error de conexi\xf3n: ".concat(e.message)),this.handleReconnection()}),this.socket.on("auth_success",e=>{this.setConnectionStatus("authenticated"),this.reconnectAttempts=0}),this.socket.on("auth_error",e=>{this.triggerError("Error de autenticaci\xf3n: ".concat(e.message)),this.setConnectionStatus("error")}),this.socket.on("new_message",e=>{this.callbacks.onMessage.forEach(t=>t(e))}),this.socket.on("ai_response",e=>{this.callbacks.onMessage.forEach(t=>t(e))}),this.socket.on("ai_typing",e=>{this.callbacks.onAITyping.forEach(t=>t(e))}),this.socket.on("message_sent",e=>{}),this.socket.on("conversation_joined",e=>{this.callbacks.onConversationJoined.forEach(t=>t(e))}),this.socket.on("conversation_left",e=>{}),this.socket.on("token_update",e=>{this.callbacks.onTokenUpdate.forEach(t=>t(e))}),this.socket.on("error",e=>{this.triggerError(e.message)}),this.socket.on("system_message",e=>{}))}authenticate(){this.socket&&this.token&&this.socket.emit("authenticate",{token:this.token})}handleReconnection(){if(this.isReconnecting||this.reconnectAttempts>=this.maxReconnectAttempts)return void this.setConnectionStatus("error");this.isReconnecting=!0,this.reconnectAttempts++,setTimeout(()=>{this.token&&this.userId&&(this.isReconnecting=!1,this.connect(this.token,this.userId))},Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4))}joinConversation(e){this.socket&&"authenticated"===this.connectionStatus&&(this.currentConversationId=e,this.socket.emit("join_conversation",{conversation_id:e}))}leaveConversation(e){this.socket&&(this.socket.emit("leave_conversation",{conversation_id:e}),this.currentConversationId===e&&(this.currentConversationId=null))}sendMessage(e,t){if(!this.socket||"authenticated"!==this.connectionStatus)return void this.triggerError("No conectado al chat en tiempo real");this.socket.emit("send_message",{conversation_id:e,message:t})}sendTypingIndicator(e,t){this.socket&&"authenticated"===this.connectionStatus&&this.socket.emit("typing",{conversation_id:e,is_typing:t})}onConnectionChange(e){return this.callbacks.onConnectionChange.push(e),()=>{let t=this.callbacks.onConnectionChange.indexOf(e);t>-1&&this.callbacks.onConnectionChange.splice(t,1)}}onMessage(e){return this.callbacks.onMessage.push(e),()=>{let t=this.callbacks.onMessage.indexOf(e);t>-1&&this.callbacks.onMessage.splice(t,1)}}onTokenUpdate(e){return this.callbacks.onTokenUpdate.push(e),()=>{let t=this.callbacks.onTokenUpdate.indexOf(e);t>-1&&this.callbacks.onTokenUpdate.splice(t,1)}}onAITyping(e){return this.callbacks.onAITyping.push(e),()=>{let t=this.callbacks.onAITyping.indexOf(e);t>-1&&this.callbacks.onAITyping.splice(t,1)}}onError(e){return this.callbacks.onError.push(e),()=>{let t=this.callbacks.onError.indexOf(e);t>-1&&this.callbacks.onError.splice(t,1)}}onConversationJoined(e){return this.callbacks.onConversationJoined.push(e),()=>{let t=this.callbacks.onConversationJoined.indexOf(e);t>-1&&this.callbacks.onConversationJoined.splice(t,1)}}setConnectionStatus(e){this.connectionStatus!==e&&(this.connectionStatus=e,this.callbacks.onConnectionChange.forEach(t=>t(e)))}triggerError(e){this.callbacks.onError.forEach(t=>t(e))}getConnectionStatus(){return this.connectionStatus}isConnected(){return"authenticated"===this.connectionStatus}getCurrentConversationId(){return this.currentConversationId}getStats(){var e;return{status:this.connectionStatus,reconnectAttempts:this.reconnectAttempts,isReconnecting:this.isReconnecting,currentConversation:this.currentConversationId,socketConnected:(null==(e=this.socket)?void 0:e.connected)||!1}}constructor(){this.socket=null,this.connectionStatus="disconnected",this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.token=null,this.userId=null,this.currentConversationId=null,this.isReconnecting=!1,this.callbacks={onConnectionChange:[],onMessage:[],onTokenUpdate:[],onTyping:[],onError:[],onConversationJoined:[],onAITyping:[]}}}let eR=new eD;var eP=a(9970);let eM={Alemania:"Alemana","Arabia Saudita":"\xc1rabe",Argentina:"Argentina",Bolivia:"Boliviana",Brasil:"Brasile\xf1a",Bélgica:"Belga",Canadá:"Canadiense",Chile:"Chilena",China:"China",Colombia:"Colombiana","Corea del Sur":"Coreana","Costa Rica":"Costarricense",Croacia:"Croata",Cuba:"Cubana",Ecuador:"Ecuatoriana","El Salvador":"Salvadore\xf1a","Emiratos \xc1rabes Unidos":"Emirat\xed",España:"Espa\xf1ola","Estados Unidos":"Estadounidense",Francia:"Francesa",Grecia:"Griega",Guatemala:"Guatemalteca",Honduras:"Hondure\xf1a",India:"India",Italia:"Italiana",Japón:"Jap
1onesa",LÃbano:"Libanesa",México:"Mexicana",Noruega:"Noruega","Nueva Zelanda":"Neozelandesa",Panamá:"Paname\xf1a",Paraguay:"Paraguaya","Pa\xedses Bajos":"Holandesa",Perú:"Peruana",Polonia:"Polaca",Portugal:"Portuguesa",Qatar:"Catar\xed","Reino Unido":"Brit\xe1nica","Rep\xfablica Checa":"Checa","Rep\xfablica Dominicana":"Dominicana",Rusia:"Rusa",Suecia:"Sueca",Suiza:"Suiza",Ucrania:"Ucraniana",Uruguay:"Uruguaya",Venezuela:"Venezolana"},ez="chat_intentos_auth";var eL=!0;let eq=e=>{var t;let{seoModel:o,seoState:f,featuredModels:v}=e,x=(0,s.useRouter)(),{user:b,loading:y,tokens:j,deductTokens:_,updateTokens:k,login:C,handleAuthError:N}=(0,c.A)(),w=(0,r.useCallback)(e=>_("deduct",e),[_]),{selectedModel:S,setSelectedModel:I,selectedConversation:A,setSelectedConversation:E,messages:T,setMessages:R,inputMessage:P,setInputMessage:M,inputReadOnly:z,setInputReadOnly:L,selectedCategory:q,setSelectedCategory:O,isLoadingMessages:B,setIsLoadingMessages:U,conversations:F,setConversations:H,modelHasPhotos:W,setModelHasPhotos:V,isAuthenticating:J,setIsAuthenticating:G,authError:Y,setAuthError:K,isSidebarExpanded:X,setIsSidebarExpanded:$,isAITyping:Q,setIsAITyping:Z,showMobileCharacterInfo:ee,setShowMobileCharacterInfo:et,showMobileChatList:ea,setShowMobileChatList:en,error:er,setError:es,imageModalOpen:ec,setImageModalOpen:el,imageModalSrc:ed,setImageModalSrc:eu,searchQuery:em,setSearchQuery:ep,isVoiceEnabled:e_,setIsVoiceEnabled:ek,isGeneratingImage:eC,setIsGeneratingImage:eN,photoProgress:ew,setPhotoProgress:eE,isGeneratingPhoto:eT,setIsGeneratingPhoto:eD,typingTimeout:eL,setTypingTimeout:eq}=(0,ef.P)(),[eO,eB]=(0,r.useState)(null),[eU,eF]=(0,r.useState)(null),[eH,eW]=(0,r.useState)(!1),[eV,eJ]=(0,r.useState)(!1),[eG,eY]=(0,r.useState)(!1);(0,r.useEffect)(()=>{if(eY(!1),!x.isReady||!x.query.model)return;let e=window.setTimeout(()=>eY(!0),12e3);return()=>window.clearTimeout(e)},[x.isReady,x.query.model]);let[eK,eX]=(0,r.useState)(!1),[e$,eQ]=(0,r.useState)(!1),[eZ,e0]=(0,r.useState)(!1),[e1,e2]=(0,r.useState)(!1),[e5,e8]=(0,r.useState)(null),[e3,e6]=(0,r.useState)(!1),[e4,e9]=(0,r.useState)(!1),[e7,te]=(0,r.useState)(!1),[tt,ta]=(0,r.useState)(!1),[tn,to]=(0,r.useState)(0),[ti,tr]=(0,r.useState)(!1),[ts,tc]=(0,r.useState)(null),[tl,td]=(0,r.useState)([]),[tu,tm]=(0,r.useState)(window.innerWidth),[tp,th]=(0,r.useState)(!1),[tg,tf]=(0,r.useState)([]),[tv,tx]=(0,r.useState)(new Set),[tb,ty]=(0,r.useState)(!1),[tj,t_]=(0,r.useState)(null),[tk,tC]=(0,r.useState)({}),tN=(0,r.useRef)(null),tw=(0,r.useRef)(null);(0,r.useRef)(null);let tS=(0,r.useRef)(!1),tI=(0,r.useRef)(),tA=(0,r.useRef)(),tE=(0,r.useRef)(),tT=(0,r.useRef)(null),tD=(0,r.useRef)(null),tR=(0,r.useRef)(!1),tP=(0,r.useRef)(0),tM=(0,r.useRef)(0),tz=(0,r.useRef)(null);(0,r.useEffect)(()=>{tT.current=A,tP.current=0,tM.current=0},[A]),(0,r.useEffect)(()=>{tD.current=S},[S]),(0,r.useEffect)(()=>{tR.current=eT,eT||eF(null)},[eT]),(0,r.useEffect)(()=>{tz.current=eU},[eU]);let{unaFotoALaVez:tL,fotosEnCurso:tq}=(0,ej.useCampanita)();(0,r.useEffect)(()=>{(0,ej.avisoBarraFoto)(eT,null==A?void 0:A.id)},[eT]);let tO=tL&&!!(null==A?void 0:A.id)&&(eT&&eO===A.id||tq.includes(A.id));(0,r.useEffect)(()=>{(async()=>{if(!(null==S?void 0:S.id)||!(null==b?void 0:b.access_token))return tf([]);try{let{fetchWithAuth:e}=await Promise.resolve().then(a.bind(a,6132)),t=await e("".concat("https://noviasvirtuales.ai/api/v1","/chat/model/").concat(S.id,"/preloaded-categories"));if(t.ok){let e=await t.json();tf(e.categories||[])}else tf([])}catch(e){tf([])}})()},[null==S?void 0:S.id,null==b?void 0:b.access_token]);let tB=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=setTimeout(async()=>{let e=new URLSearchParams(window.location.search).get("model");if(!e)return;let t=parseInt(e);if(isNaN(t))return;let a="".concat(t,"_").concat(Date.now());if(tB.current===a)return;let n=(0,h.getEnvironmentConfig)();try{let e={"Content-Type":"application/json"};(null==b?void 0:b.access_token)&&(e.Authorization="Bearer ".concat(b.access_token)),await fetch("".concat(n.apiUrl,"/chat/view/").concat(t),{method:"POST",headers:e}),tB.current=a}catch(e){}},500);return()=>clearTimeout(e)},[b]);let{dimensions:tU,webHeaderRef:tF,chatHeaderRef:tH,inputAreaRef:tW}=(0,eA.Q)(!!S),tV=(0,r.useCallback)(()=>te(!0),[]),tJ=(0,r.useCallback)(()=>te(!1),[]),tG=(0,r.useCallback)(async()=>
1{if(b&&A)try{await eR.connect(b.access_token,b.id)&&eR.joinConversation(A.id)}catch(e){es("Error conectando al chat en tiempo real")}},[b,A]),tY=(0,r.useCallback)(async e=>{if(!b||!b.access_token)return;let t=(0,h.getEnvironmentConfig)(),a={Authorization:"Bearer ".concat(b.access_token),"Content-Type":"application/json"};try{await fetch("".concat(t.apiUrl,"/chat/view/").concat(e),{method:"POST",headers:a})}catch(e){}let n="session_model_".concat(e,"_").concat(b.id),o=sessionStorage.getItem(n),i=Date.now();if(!o||i-parseInt(o)>36e5)try{(await fetch("".concat(t.apiUrl,"/chat/visit/").concat(e),{method:"POST",headers:a})).ok&&sessionStorage.setItem(n,i.toString())}catch(e){}},[b]),{loadSelectedModel:tK,checkModelPhotos:tX}=(e=>{let{selectedModel:t,setSelectedModel:a,setSelectedConversation:n,setMessages:o,setIsLoadingMessages:i,registerVisit:c,allModels:l}=e,d=(0,s.useRouter)(),u=(0,r.useCallback)(async()=>{let e=d.query.model,r=null;if(e&&!isNaN(Number(e))&&(r=parseInt(e)),!r)return;if(!l||0===l.length){let e=localStorage.getItem("allModelsCache");if(e)try{let t=JSON.parse(e).find(e=>e.id===r);t&&(a(t),localStorage.setItem("selectedModel",JSON.stringify(t)),c&&c(t.id))}catch(e){}return}if(t&&t.id===r){c&&c(r);return}if(t&&t.id!==r){n(null),o([]),i(!1);let e=Object.keys(localStorage),t=[];e.forEach(e=>{e.startsWith("messages_")||"activeConversation"===e||e.startsWith("activeConversation_")||"currentConversation"===e?t.push(e):"chatMessages"===e&&t.push(e)}),t.forEach(e=>{localStorage.removeItem(e)})}let s=l.find(e=>e.id===r);if(!s)try{let e=(0,h.getEnvironmentConfig)(),t=localStorage.getItem("accessToken");if(t){let a=await fetch("".concat(e.apiUrl,"/chat/models/me"),{headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json"}});a.ok&&(s=(await a.json()).find(e=>e.id===r))}}catch(e){console.error("[MODEL_DATA] Error loading custom models:",e)}s?(a(s),localStorage.setItem("selectedModel",JSON.stringify(s)),c&&c(s.id)):console.warn("[MODEL_DATA] Model ".concat(r," not found in allModels or custom models"))},[d.query.model,l]);return(0,r.useEffect)(()=>{if(d.isReady&&d.query.model){let e=parseInt(d.query.model),a=localStorage.getItem("lastConversationSelectTime"),n=a?Date.now()-parseInt(a):1/0;if(!isNaN(e)&&e!==(null==t?void 0:t.id)){if(n<2e3&&t)return;u()}}},[d.query.model,d.isReady,u,null==t?void 0:t.id]),{loadSelectedModel:u,checkModelPhotos:(0,r.useCallback)(async()=>{if(!(null==t?void 0:t.id))return!1;try{let e=(0,h.getEnvironmentConfig)(),a=await fetch("".concat(e.apiUrl,"/models/").concat(t.id,"/photos"));if(a.ok){let e=await a.json();return Array.isArray(e)&&e.length>0}}catch(e){}return!1},[null==t?void 0:t.id])}})({selectedModel:S,setSelectedModel:I,setSelectedConversation:E,setMessages:R,setIsLoadingMessages:U,registerVisit:e=>tI.current?tI.current(e):Promise.resolve(),allModels:tl}),{loadMessages:t$,loadMoreMessages:tQ,handleSendMessage:tZ,handleInputChange:t0,handleKeyDown:t1,hasMoreMessages:t2,isLoadingMore:t5,freeMessagesUsed:t8,startPhotoProgress:t3,completePhotoProgress:t6,cancelPhotoProgress:t4,anonymousDemoMessage:t9,anonymousDemoStatus:t7,anonymousDemoIsPhoto:ae,clearAnonymousDemo:at,immersiveLimitTrigger:aa,immersiveLimitIsPhoto:an,clearImmersiveLimitTrigger:ao}=(e=>{let{user:t,selectedModel:a,selectedConversation:n,setSelectedConversation:o,messages:i,setMessages:s,inputMessage:c,setInputMessage:l,setInputReadOnly:d,selectedCategory:u,setSelectedCategory:m,isLoadingMessages:p,setIsLoadingMessages:h,tokens:f,deductTokens:v,updateTokens:x,setIsVoiceEnabled:b,setShowLoginModal:y,setError:j,loadConversations:_,isPaginatingRef:k,setShowFreeMessagesModal:C,setShowPhotoSubscriptionModal:N,setShowPhotoTokensModal:w,setIsGeneratingPhoto:S,setPhotoProgress:I,setPhotoRequestConversationId:A,isAnonymousDemoAllowed:E}=e,T=(0,r.useRef)(null),D=(0,r.useRef)(0),R=(0,r.useRef)(!0),P=(0,r.useRef)(!1),[M,z]=(0,r.useState)(()=>{if(!(null==t?void 0:t.id))return 0;let e="freeMessages_".concat(t.id);return parseInt(localStorage.getItem(e)||"0")}),L=(0,r.useRef)(null),q=(0,r.useRef)(null),O=(0,r.useRef)(0),[B,U]=(0,r.useState)(null),[F,H]=(0,r.useState)("idle"),[W,V]=(0,r.useState)(!1),J=(0,r.useRef)(null),G=(0,r.useCallback)(()=>{J.current&&clearTimeout(J.current),U(null),H("idle"),V(!1)},[]),[Y,K]=(0,r.useState)(!1),[X,$]=(0,r.useState)(!1),Q=(0,r.useCallback)(()=>{K(!1),$(!1)}
1,[]),Z=e=>{let t=e.toLowerCase();if(["beso","dinero","plata","saludos","abrazo","gracias","hola","adios"].some(e=>t.includes(e))||[/\b(usas?|tienes?|hay|existe|cual|cuál|cuantas?|cuántas?|que|qué|como|cómo)\b.*\b(foto|imagen|selfie)/i,/\b(foto|imagen|selfie).*\?$/i].some(e=>e.test(t)))return!1;if(["en bikini","en lencer\xeda","en lenceria","desnuda","desnudo","topless","sin ropa","en tanga","en bragas","en calzones","camiseta argentina","camiseta brasil","camiseta chile","seleccion","uniforme de","ropa de","vestida de"].some(e=>t.includes(e)))return!0;let a=["env\xeda","envia","env\xedame","enviame","manda","m\xe1ndame","mandame","muestra","mu\xe9strame","muestrame","pasa","p\xe1same","pasame","dame","deja ver","d\xe9jame ver","dejame ver","quiero ver","quiero una","puedo ver","r\xf3lame","rolame","ense\xf1a","ense\xf1ame"].some(e=>t.includes(e)),n=["foto","selfie","pic","imagen","picture"].some(e=>t.includes(e));return!!a&&!!n||!!["env\xedame una","enviame una","m\xe1ndame una","mandame una","mu\xe9strame","muestrame","p\xe1same una","pasame una","quiero ver","d\xe9jame ver","dejame ver"].some(e=>t.includes(e))},ee=()=>{if(!S||!I)return;A&&n&&A(n.id),S(!0),I(0);let e=Date.now();O.current=e,L.current=setInterval(()=>{I(Math.min(95,Math.round(95*(1-Math.exp(-(Date.now()-e)/18e3)))))},250),q.current&&clearTimeout(q.current),q.current=setTimeout(()=>{L.current&&(clearInterval(L.current),L.current=null),S(!1),I(0),j("La foto est\xe1 tardando m\xe1s de lo normal. Si ya la pediste, no repitas la solicitud: aparecer\xe1 en el chat cuando termine.")},12e4)},et=()=>{if(!S||!I)return;let e=Date.now()-(O.current||0);if(O.current&&e<5e3)return void setTimeout(et,5e3-e);O.current=0,L.current&&(clearInterval(L.current),L.current=null),q.current&&(clearTimeout(q.current),q.current=null),I(100),setTimeout(()=>{S(!1),I(0)},1200)},ea=()=>{S&&I&&(L.current&&(clearInterval(L.current),L.current=null),q.current&&(clearTimeout(q.current),q.current=null),S(!1),I(0))},en=(0,r.useCallback)(async e=>{if(!t)return;let a=e.toString();if(!p||T.current!==a){T.current!==a&&(s([]),D.current=0,R.current=!0);try{h(!0),T.current=a;let e=await (0,ev.Ev)(parseInt(a),t.access_token,20,0);if(e&&e.length>0){let t=e.reverse();if(s(t),D.current=e.length,R.current=20===e.length,eb(parseInt(a),t),A&&S&&I){let e=t[t.length-1];(null==e?void 0:e.tipo_mensaje)==="imagen"&&(null==e?void 0:e.imagen_url)&&L.current&&(et(),A(null))}}else s([]),R.current=!1}catch(t){j("Error loading messages. Please try again.");let e=(e=>{try{let t=localStorage.getItem("messages_".concat(e));return t?JSON.parse(t):[]}catch(e){return[]}})(parseInt(a));e.length>0&&s(e.slice(-20))}finally{h(!1)}}},[null==t?void 0:t.access_token]),eo=(0,r.useCallback)(async()=>{if(!R.current||!t||!n||P.current)return!1;let e=n.id.toString();if(T.current!==e)return!1;try{P.current=!0,k&&(k.current=!0);let a=await (0,ev.Ev)(parseInt(e),t.access_token,20,D.current),n=Array.isArray(a)?a.length:0;if(!(n>0))return R.current=!1,!1;{let t=new Set(i.map(e=>e.id)),o=a.filter(e=>!t.has(e.id));if(0===o.length)return R.current=!1,!1;let r=o.reverse();return s([...r,...i]),D.current+=n,n<20?R.current=!1:R.current=!0,eb(parseInt(e),[...r,...i]),!0}}catch(e){return j("Error loading more messages. Please try again."),R.current=!1,!1}finally{P.current=!1,k&&setTimeout(()=>{k.current=!1},200)}},[null==t?void 0:t.access_token,null==n?void 0:n.id,i]),ei=(0,r.useCallback)(async(e,r,p)=>{if(e.preventDefault(),!t){if(!E)return void y(!0);if("idle"!==F)return;let e=void 0!==r?r:c;if(!e.trim()||!a)return;let t=Z(e.trim())||!!(null==p?void 0:p.preloaded_photo_requested);U(e.trim()),V(t),H("sent"),l("");try{let n="nv_public_chat_draft_v1_".concat(a.id);localStorage.setItem(n,JSON.stringify({schemaVersion:1,modelId:a.id,actionType:t?"photo":"message",pendingText:e.trim(),pendingPhotoRequest:t?e.trim():null,updatedAt:Date.now()}))}catch(e){}return void(J.current=setTimeout(()=>{H("typing"),J.current=setTimeout(()=>{H("modal"),y(!0)},2e3+1e3*Math.random())},100))}let h=void 0!==r?r:c;if(!h.trim())return;if(!a)return void j("Please select a model first");let f=h.trim(),v=Z(f),x=v&&!((0,ej.unaFotoALaVezActiva)()&&L.current);x&&ee();try{d(!0),l(""),j(null);let e=i;if(n){let t={id:Date.now(),conversacion_id:n.id,remitente:"usuario",mensaje:f,tokens_usados:1,fecha_envio:new Date,leido:!1};e=[...i,t],s(e)}{let e=await (0,g.postWithAuth)("".concat("https://noviasvirtuales.ai/api/v1","/chat/message/async"),{conversacion_id:(null==n?void 0:n.id)||null,message:f,modelo_id:a.id,categoria_seleccionad
1a:u||null,preloaded_photo_requested:(null==p?void 0:p.preloaded_photo_requested)||!1,preloaded_category:(null==p?void 0:p.preloaded_category)||null,chip_action:(null==p?void 0:p.chip_action)||null});if(u&&m&&m(null),!e.ok){if(401===e.status){j("Error de autenticaci\xf3n. Por favor inicia sesi\xf3n nuevamente."),s(i),x&&ea();return}if(409===e.status){let t=await e.json().catch(()=>({}));s(i),j(t.detail||"Ya tienes una foto en proceso. Espera a que termine."),x&&ea();return}if(429===e.status){let n=(await e.json().catch(()=>({}))).detail||"";if(s(i),x&&ea(),n.toLowerCase().includes("rate limit"))return void j(n);t.plan_suscripcion&&"free"!==t.plan_suscripcion&&console.warn("[INCONSISTENCIA] Usuario premium recibio 429 daily limit:",{userId:t.id,plan:t.plan_suscripcion,error:n}),j(null),l(f);try{let e="nv_free_limit_pending_v1_".concat(t.id,"_").concat(a.id);localStorage.setItem(e,JSON.stringify({schemaVersion:1,userId:t.id,modelId:a.id,actionType:v?"photo":"message",pendingText:f,pendingPhotoRequest:v?f:null,updatedAt:Date.now()}))}catch(e){}$(v),K(!0);return}if(402===e.status){s(i),x&&ea(),t.plan_suscripcion&&"free"!==t.plan_suscripcion?w&&w(!0):N&&N(!0);return}let n=await e.json().catch(()=>({}));j(n.detail||"Error al enviar mensaje. Por favor intenta de nuevo."),s(i),x&&ea();return}let r=await e.json();if(r.conversation_id&&!n){let e={id:r.conversation_id,usuario_id:t.id,modelo_id:a.id,titulo:"Chat con ".concat(a.model_name),activa:!0,fecha_inicio:new Date().toISOString(),ultimo_mensaje:new Date().toISOString()};o&&o(e)}return}}catch(e){var b,_,k,C,S,I,A;if(s(i),x&&ea(),(null==(b=e.response)?void 0:b.status)===409)return void j((null==(S=e.response)||null==(C=S.data)?void 0:C.detail)||"Ya tienes una foto en proceso. Espera a que termine.");if((null==(_=e.response)?void 0:_.status)===429){let n=(null==(A=e.response)||null==(I=A.data)?void 0:I.detail)||"";if(n.toLowerCase().includes("rate limit"))return void j(n);j(null),l(f);try{let e="nv_free_limit_pending_v1_".concat(t.id,"_").concat(a.id);localStorage.setItem(e,JSON.stringify({schemaVersion:1,userId:t.id,modelId:a.id,actionType:v?"photo":"message",pendingText:f,pendingPhotoRequest:v?f:null,updatedAt:Date.now()}))}catch(e){}$(v),K(!0);return}"AuthenticationError"===e.name||(null==(k=e.response)?void 0:k.status)===401?j("Error de autenticaci\xf3n. Por favor inicia sesi\xf3n nuevamente."):j("Error al enviar mensaje. Por favor verifica tu conexi\xf3n e intenta de nuevo.")}finally{d(!1)}},[t,c,n,o,a,f,i,y,d,l,j,s,v,b,_]),er=(0,r.useCallback)(e=>{let t=e.target.value;if(t.length>2e3)return void j("Message too long. Maximum ".concat(2e3," characters allowed."));l(t),j(null);let a=e.target;a.style.height="auto",a.style.height=Math.min(a.scrollHeight,120)+"px"},[l,j]),es=(0,r.useCallback)(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),ei({preventDefault:()=>{},target:e.target,currentTarget:e.currentTarget}))},[ei]);return{loadMessages:en,loadMoreMessages:eo,handleSendMessage:ei,handleInputChange:er,handleKeyDown:es,lastLoadedConversationRef:T,hasMoreMessages:R.current,isLoadingMore:P.current,freeMessagesUsed:M,startPhotoProgress:ee,completePhotoProgress:et,cancelPhotoProgress:ea,anonymousDemoMessage:B,anonymousDemoStatus:F,anonymousDemoIsPhoto:W,clearAnonymousDemo:G,immersiveLimitTrigger:Y,immersiveLimitIsPhoto:X,clearImmersiveLimitTrigger:Q}})({user:b,selectedModel:S,selectedConversation:A,setSelectedConversation:E,messages:T,setMessages:R,inputMessage:P,setInputMessage:M,setInputReadOnly:L,isLoadingMessages:B,setIsLoadingMessages:U,tokens:j,deductTokens:w,updateTokens:k,setIsVoiceEnabled:ek,setShowLoginModal:eJ,setError:es,loadConversations:()=>tE.current?tE.current():Promise.resolve(),isPaginatingRef:tS,setShowFreeMessagesModal:eX,setShowPhotoSubscriptionModal:e6,setShowPhotoTokensModal:e9,setIsGeneratingPhoto:eD,setPhotoProgress:eE,setPhotoRequestConversationId:eB,selectedCategory:q,setSelectedCategory:O,isAnonymousDemoAllowed:!b&&tb&&!!S&&tv.has(S.id)}),{isChatAvailable:ai,healthStatus:ar,isChecking:as}=(0,eI.n)({checkIntervalSeconds:30,enabled:!0}),ac=(0,r.useCallback)(e=>{if("message_received"===e.type&&e.user_message){var t;let a=e.user_message.id,n={id:null!=a?a:Date.now(),conversacion_id:e.conversation_id,remitente:"usuario",mensaje:e.user_message.contenido,fecha_envio:e.user_message.fecha||e.user_message.fecha_envio||(0,D.x)(),leido:!0,tokens_usados:0,imagen_url:null,audio_url:null,tipo_mensaje:e.user_message.tipo_mensaje||"texto"};R(e=>{if(null!=a&&e.some(e=>e.id===a))return e;let t=e.findIndex(e=>"usuario"===e.remitente&&e.mensaje===n.mensaje&&"number"==typeof e.id&&e.id>1e12);if(-1!==t){let a=[...e];return a[t]={...a[t],...n},a}return[...e,n]}),null==(t=tE.current)||t.call(tE)}},[]),al=(0,r.useCallback)(e=>{var t,n,o,i;let r=e.conversation_id||e.conversacion_id,s=null==(t=tT.current)?void 0:t.id,c={id:e.id||e.message_id||Date.now(),conversacion_id:r||s||0,remitente:"modelo",mensaje:e.contenido||e.response||"",fecha_envio:(0,D.x)(),leido:!0,tokens_usados:e.tokens_usados||0,imagen_url:e.imagen_url||null,audio_url:e.audio_url||null,tipo_mensaje:"video"===e.tipo_mensaje?"video":e.imagen_url?"imagen":"nota_voz"===e.tipo_mensaje?"nota_voz":"texto",action_chips:e.action_chips||null,chip_caption:e.chip_caption||null,chip_context_type:e.chip_context_type||null};if(r&&r!==s||(R(e=>{let t=e.findIndex(e=>e.id===c.id);if(-1!==t){let a=e[t];if(c.imagen_url||c.audio_url){let n=[...e];return n[t]={...a,...c,mensaje:c.mensaje||a.mensaje},n}return e}return[...e,c]}),e.imagen_url?(tP.current=Math.max(0,tP.current-1),0===tP.current&&(t6(),eB(null),tM.current=0),es(null)):tR.current&&!tz.current&&(t4(),eB(null))),e.tokens_usados&&e.tokens_usados>0&&k&&(void 0!==e.new_balance&&null!==e.new_balance?k(e.new_balance):Promise.resolve().then(a.bind(a,6132)).then(e=>{let{fetchWithAuth:t}=e;t("".concat("https://noviasvirtuales.ai/api/v1","/users/me")).then(e=>e.json()).then(e=>{void 0!==e.tokens&&k(e.tokens)}).catch(e=>console.error("[Chat] Error syncing tokens:",e))})),(null==(n=e.model_reaction)?void 0:n.mensaje_id)&&(null==(o=e.model_reaction)?void 0:o.emoji)){let{mensaje_id:t,emoji:a}=e.model_reaction;R(e=>{if(e.some(e=>e.id===t))return e.map(e=>e.id===t?{...e,reacciones:{...e.reacciones||{},modelo:a}}:e);let n=-1;for(let t=e.length-1;t>=0;t--)if("usuario"===e[t].remitente){n=t;break}if(-1===n)return e;let o=[...e];return o[n]={...o[n],reacciones:{...o[n].reacciones||{},modelo:a}},o})}Z(!1),null==(i=tE.current)||i.call(tE),L(!1)},[tT,k]),ad=(0,r.useCallback)(e=>{console.error("[Chat] WebSocket error:",e),es(e)},[]),au=(0,r.useCallback)((e,t)=>{R(a=>a.map(a=>a.id===e?{...a,reacciones:t&&(t.usuario||t.modelo)?t:null}:a))},[]),am=(0,r.useCallback)(e=>{if(e.status&&"string"==typeof e.status){if("error"===e.status){tR.current&&t4(),es("No se pudo generar la
1imagen ahora mismo. Tus tokens no se descontaron. Vuelve a intentarlo en un momento.");return}let t=e.status.match(/(\d+)%/);if(t){let e=parseInt(t[1],10);tP.current>1&&(e=Math.max(e,tM.current)),tM.current=e,eE(e)}}},[eE,t4,es]),ap=(0,r.useCallback)(e=>{let t=null==e?void 0:e.status;if(t){if("photo_failed"===t)return(tP.current=Math.max(0,tP.current-1),tP.current>0)?void es("Una de tus fotos no se pudo generar. Tus tokens de esa foto no se descontaron."):(tM.current=0,tR.current&&t4(),eB(null),void es("No se pudo generar la imagen ahora mismo. Tus tokens no se descontaron. Vuelve a intentarlo en un momento."));("photo_queued"===t||"photo_generating"===t)&&(eF(t),"photo_queued"===t&&(tP.current+=1),!tR.current&&t3&&t3())}},[t4,es,eB,t3]),{isConnected:ah,sendMessage:ag,disconnect:af,reconnectCountdown:av,isReconnecting:ax}=(e=>{let{userId:t,accessToken:a,conversationId:n,onMessageReceived:o,onAIResponse:i,onProcessingStatus:s,onPhotoStatus:c,onError:l}=e,d=(0,r.useRef)(null),u=(0,r.useRef)(null),m=(0,r.useRef)(0),p=(0,r.useRef)(!1),h=(0,r.useRef)(null),f=(0,r.useRef)(!1),v=(0,r.useRef)(!1),[x,b]=(0,r.useState)(!1),[y,j]=(0,r.useState)(0),[_,k]=(0,r.useState)(!1),C=(0,r.useRef)(o),N=(0,r.useRef)(i),w=(0,r.useRef)(s),S=(0,r.useRef)(c),I=(0,r.useRef)(l);(0,r.useEffect)(()=>{C.current=o,N.current=i,w.current=s,S.current=c,I.current=l},[o,i,s,c,l]);let A=(0,r.useCallback)(async()=>{var e,a,o;if(!t)return;let i=localStorage.getItem("accessToken");if(i&&(null==(e=d.current)?void 0:e.readyState)!==WebSocket.OPEN&&(null==(a=d.current)?void 0:a.readyState)!==WebSocket.CONNECTING){if(p.current){u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{u.current=null,A()},400);return}p.current=!0;try{let e=i;try{let t=await fetch("".concat("https://noviasvirtuales.ai","/api/v1/ws/ticket"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(i)},body:JSON.stringify({conversation_id:null!=n?n:null})});if(t.ok){let a=await t.json();(null==a?void 0:a.ticket)&&(e=a.ticket)}}catch(e){}let t="https:"===window.location.protocol?"wss:":"ws:",a=((o="https://noviasvirtuales.ai",void 0===o)?void 0:o.replace(/^https?:\/\//,""))||"localhost:8001",r="".concat(t,"//").concat(a,"/ws/chat/").concat(e);n&&(r+="/".concat(n));let s=new WebSocket(r);d.current=s,s.onopen=()=>{b(!0),k(!1),j(0),m.current=0,v.current=!0,h.current&&(clearInterval(h.current),h.current=null)},s.onmessage=e=>{try{let t=JSON.parse(e.data);switch(t.type){case"connection_established":break;case"message_received":C.current&&C.current(t);break;case"photo_status":S.current&&S.current({status:t.status,detail:t.detail,conversation_id:t.conversation_id});break;case"ai_processing_status":w.current&&t.status&&w.current(t);break;case"user_message_sent":C.current&&t.user_message&&C.current({type:"message_received",user_message:t.user_message,conversation_id:t.conversation_id});break;case"ai_response_ready":N.current&&t.ai_response&&N.current({...t.ai_response,conversation_id:t.conversation_id,model_reaction:t.model_reaction});break;case"error":I.current&&I.current(t.error||"Unknown WebSocket error")}}catch(e){}},s.onerror=e=>{b(!1)},s.onclose=async e=>{if(b(!1),d.current=null,f.current){f.current=!1;return}if(4001===e.code||4e3===e.code){let e=!1;try{e=await (0,g.refreshAccessToken)()}catch(e){console.warn("[WS] Refresh no concluyente, se reintenta sin cerrar sesi\xf3n:",e),I.current&&I.current("Problema de conexi\xf3n. Reintentandoâ¦"),setTimeout(()=>A(),3e3);return}if(e){m.current=0,setTimeout(()=>A(),1e3);return}if(localStorage.getItem("refreshToken")){I.current&&I.current("Problema de conexi\xf3n. Reintentandoâ¦"),setTimeout(()=>A(),3e3);return}I.current&&I.current("Error de autenticaci\xf3n. Por favor inicia sesi\xf3n nuevamente."),window.location.href="/login";return}m.current<5?(m.current++,v.current&&(k(!0),j(30)),u.current=setTimeout(()=>{A()},3e4)):(k(!1),I.current&&I.current("Conexi\xf3n WebSocket perdida. Por favor refresca la p\xe1gina."))}}catch(e){b(!1)}finally{p.current=!1}}},[t,n]),E=(0,r.useCallback)(()=>{f.current=!0,u.current&&(clearTimeout(u.current),u.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(d.current.close(),d.current=null),b(!1),k(!1),j(0),m.current=0,v.current=!1},[]),T=(0,r.useCallback)(()=>{var e;
1(null==(e=d.current)?void 0:e.readyState)===WebSocket.OPEN&&d.current.send(JSON.stringify({type:"ping"}))},[]),D=(0,r.useCallback)(e=>{var t;(null==(t=d.current)?void 0:t.readyState)===WebSocket.OPEN&&d.current.send(e)},[]);return(0,r.useEffect)(()=>(localStorage.getItem("accessToken")&&t&&A(),()=>{E()}),[t,n]),(0,r.useEffect)(()=>{if(!x)return;let e=setInterval(()=>{T()},3e4);return()=>{clearInterval(e)}},[x,T]),(0,r.useEffect)(()=>{if(!_){h.current&&(clearInterval(h.current),h.current=null);return}return h.current=setInterval(()=>{j(e=>e<=1?30:e-1)},1e3),()=>{h.current&&(clearInterval(h.current),h.current=null)}},[_]),{isConnected:x,sendMessage:D,disconnect:E,reconnectCountdown:y,isReconnecting:_}})({userId:(null==b?void 0:b.id)||null,accessToken:(null==b?void 0:b.access_token)||null,conversationId:(null==A?void 0:A.id)||null,onMessageReceived:ac,onAIResponse:al,onProcessingStatus:am,onPhotoStatus:ap,onError:ad});(0,r.useEffect)(()=>{te(ah)},[ah]),(0,r.useEffect)(()=>{es(null)},[A]),(0,r.useEffect)(()=>{let e=()=>{tm(window.innerWidth)};return window.addEventListener("resize",e),window.innerWidth<1100&&et(!1),()=>window.removeEventListener("resize",e)},[]),(0,r.useEffect)(()=>{let e=e=>{let t=e.target;!(t.closest(".chat-list-sidebar")||t.closest(".character-info-sidebar")||t.closest(".menu-btn")||t.closest(".action-btn")||t.closest('[class*="info-btn"]'))&&(tu<900&&ea&&en(!1),tu<1100&&ee&&et(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[tu,ea,ee]);let{loadConversations:ab,selectConversation:ay,deleteConversation:aj,autoSelectConversationForModel:a_}=(e=>{let{user:t,selectedModel:a,setSelectedModel:n,selectedConversation:o,conversations:i,setConversations:s,setSelectedConversation:c,setMessages:l,setIsLoadingMessages:d,loadMessages:u,saveActiveConversationToStorage:m,setError:p,allModels:g,router:f}=e,v=(0,r.useRef)(!1),x=(0,r.useRef)(!1),b=(0,r.useRef)(null),y=(0,r.useRef)(!1),j=(0,r.useCallback)(async e=>{try{if(g&&g.length>0){let t=g.find(t=>t.id===e);if(t)return t}let a=(0,h.getEnvironmentConfig)();if(!(null==t?void 0:t.access_token))return console.warn("â No hay token de usuario para buscar modelos personalizadas"),null;try{let n=await fetch("".concat(a.apiUrl,"/chat/models/me"),{headers:{Authorization:"Bearer ".concat(t.access_token),"Content-Type":"application/json"}});if(n.ok){let t=(await n.json()).find(t=>t.id===e);if(t)return t}}catch(e){console.warn("No se pudieron cargar modelos personalizadas:",e)}try{let n=await fetch("".concat(a.apiUrl,"/models"),{headers:{Authorization:"Bearer ".concat(t.access_token),"Content-Type":"application/json"}});if(n.ok){let t=(await n.json()).find(t=>t.id===e);if(t)return t}}catch(e){console.warn("No se pudieron cargar modelos p\xfablicas:",e)}console.warn("â Modelo ".concat(e," no encontrada en ninguna fuente"))}catch(t){console.error("Error loading model ".concat(e,":"),t),p&&p("No se pudo cargar la informaci\xf3n del modelo ".concat(e))}return null},[g,p,t]),_=(0,r.useCallback)(async()=>{if(t&&g&&0!==g.length&&!v.current){v.current=!0;try{let e=await (0,ev.cL)(t.access_token),a=[];for(let t of e){let e=(null==g?void 0:g.find(e=>e.id===t.modelo_id))||null;if(e||(e=await j(t.modelo_id)),e){let n=null==g?void 0:g.find(e=>e.id===t.modelo_id);n&&void 0!==n.has_user_photos&&(e.has_user_photos=n.has_user_photos),a.push({conversation:t,model:e,unreadCount:0})}else console.warn("Skipping conversation ".concat(t.id," - model ").concat(t.modelo_id," not found"))}s(a)}catch(e){console.error("Error loading conversations:",e),p&&p("No se pudieron cargar las conversaciones. Por favor, intente m\xe1s tarde.")}finally{v.current=!1}}},[null==t?void 0:t.access_token,g,j]),k=(0,r.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(t){localStorage.setItem("selectingConversation","true"),localStorage.setItem("lastConversationSelectTime",Date.now().toString()),f&&f.replace("/chat?model=".concat(e.conversation.modelo_id),void 0,{shallow:!0});let t=null==g?void 0:g.find(t=>t.id===e.conversation.modelo_id);if(t)n(t),localStorage.setItem("selectedModel",JSON.stringify(t));else if(e.model){let t={...e.model},a=null==g?void 0:g.find(t=>
1t.id===e.model.id);a&&void 0!==a.has_user_photos&&(t.has_user_photos=a.has_user_photos),n(t),localStorage.setItem("selectedModel",JSON.stringify(t))}else{let t=await j(e.conversation.modelo_id);t?(n(t),localStorage.setItem("selectedModel",JSON.stringify(t))):p&&p("No se pudo cargar la informaci\xf3n del modelo ".concat(e.conversation.modelo_id))}setTimeout(()=>{localStorage.removeItem("selectingConversation")},500)}c(e.conversation),u(e.conversation.id.toString()),m(e.conversation),localStorage.setItem("activeConversation_".concat(e.conversation.modelo_id),e.conversation.id.toString())},[n,c,u,m,p,g,j,f]),C=(0,r.useCallback)(async(e,a)=>{if(a&&a.stopPropagation(),!(null==t?void 0:t.access_token)){p&&p("Debes iniciar sesi\xf3n para eliminar conversaciones");return}try{let a=i.find(t=>t.conversation.id.toString()===e),n=(null==o?void 0:o.id.toString())===e;await (0,ev.ly)(parseInt(e),t.access_token);let r=i.filter(t=>t.conversation.id.toString()!==e);if(s(r),a&&(localStorage.removeItem("activeConversation_".concat(a.conversation.modelo_id)),localStorage.removeItem("messages_".concat(e))),n){let e=r.filter(e=>e.conversation.modelo_id===(null==a?void 0:a.conversation.modelo_id));e.length>0?(localStorage.removeItem("activeConversation"),c(null),l([]),await _(),setTimeout(()=>{let t=e[0];k(t,!1)},100)):(localStorage.removeItem("activeConversation"),c(null),l([]),y.current=!0,setTimeout(()=>{y.current=!1},2e3),await _())}else await _()}catch(e){if(console.error("Error deleting conversation:",e),p){var n,r;p((null==e||null==(r=e.response)||null==(n=r.data)?void 0:n.detail)||"No se pudo eliminar la conversaci\xf3n")}}},[t,i,o,_,k,c,l,n,p]),N=(0,r.useCallback)(async e=>{if(!x.current&&b.current!==e&&!y.current){x.current=!0,b.current=e;try{if(!(null==t?void 0:t.access_token))return void console.error("[CONVERSATIONS] No access token available");let a=i.find(t=>t.conversation.modelo_id===e);if(a)await u(a.conversation.id.toString()),c(a.conversation),localStorage.setItem("activeConversation_".concat(e),a.conversation.id.toString()),m(a.conversation);else{let{conversation:a,is_new:n}=await (0,ev.FA)(e,t.access_token);await u(a.id.toString()),c(a),localStorage.setItem("activeConversation_".concat(e),a.id.toString()),m(a),await _()}}catch(e){console.error("[CONVERSATIONS] Error loading conversation:",e),p&&p("No se pudo cargar la conversaci\xf3n. Por favor, intente m\xe1s tarde.")}finally{setTimeout(()=>{x.current=!1,b.current=null},1e3)}}},[null==t?void 0:t.access_token,i,u,c,m,p,_]);return{loadConversations:_,selectConversation:k,deleteConversation:C,autoSelectConversationForModel:N}})({user:b,selectedModel:S,setSelectedModel:I,selectedConversation:A,conversations:F,setConversations:H,setSelectedConversation:E,setMessages:R,setIsLoadingMessages:U,loadMessages:e=>tA.current?tA.current(e):Promise.resolve(),saveActiveConversationToStorage:ey,setError:es,allModels:tl,router:x}),{handleRequestImage:ak,handleImageClick:aC,handleSuggestedMessage:aN,handleCallAction:aw,handleGalleryAction:aS,handleHeartAction:aI,handleGamepadAction:aA,handleInfoAction:aE,handleDeleteAction:aT,handleBuyTokens:aD,handleMobileToggle:aR}=(e=>{let{user:t,selectedModel:a,handleSendMessage:n,selectedConversation:o,messages:i,setMessages:c,setInputMessage:l,inputMessage:d,tokens:u,deductTokens:m,setError:p,setShowLoginModal:h,setImageModalOpen:g,setSelectedImage:f,setIsGeneratingImage:v,setShowModelGallery:x,setShowMobileChatList:b,showMobileChatList:y,setShowMobileCharacterInfo:j,showMobileCharacterInfo:_,setShowDeleteConversationModal:k,setConversationToDelete:C}=e,N=(0,s.useRouter)(),w=(0,r.useCallback)(async e=>{if(!t)return void p("Please login to request images");if(!a)return void p("Please select a model first");
1if(u<4)return void p("Not enough tokens. Image generation requires 4 tokens.");try{v(!0),p(null);let t={id:Date.now(),conversacion_id:(null==o?void 0:o.id)||0,mensaje:"\uD83C\uDFA8 Image request: ".concat(e),es_usuario:!0,fecha_envio:new Date().toISOString(),tokens_utilizados:0};c([...i,t]);let n=await eS.generateImage({prompt:e,modelId:a.id.toString(),category:"chat",quality:"standard"});if(n.success&&n.imageUrl){let t={id:Date.now()+1,conversacion_id:(null==o?void 0:o.id)||0,mensaje:"Here's your generated image: ".concat(e),es_usuario:!1,fecha_envio:new Date().toISOString(),tokens_utilizados:10,image_url:n.imageUrl};c([...i,t]),m(10),v(!1)}else p(n.error||"Failed to generate image"),v(!1)}catch(e){p("Failed to generate image. Please try again."),v(!1)}},[t,a,o,u,i,c,m,p,v]),S=(0,r.useCallback)(e=>{f(e),g(!0)},[f,g]),I=(0,r.useCallback)(e=>{l(e),n&&setTimeout(()=>{n({preventDefault:()=>{}})},100)},[l,n]),A=(0,r.useCallback)(()=>{if(!t)return void h(!0)},[t,h]),E=(0,r.useCallback)(async()=>{if(!t)return void h(!0);(null==a?void 0:a.id)&&N.push("/gallery?modelId=".concat(a.id))},[t,a,N,h]),T=(0,r.useCallback)(()=>{if(!t)return void h(!0)},[t,h]),D=(0,r.useCallback)(()=>{},[]),R=(0,r.useCallback)(()=>{y&&b(!1),j(!_)},[_,j,y,b]),P=(0,r.useCallback)(()=>{o&&(C(o),k(!0))},[o,k,C]);return{handleRequestImage:w,handleImageClick:S,handleSuggestedMessage:I,handleCallAction:A,handleGalleryAction:E,handleHeartAction:T,handleGamepadAction:D,handleInfoAction:R,handleDeleteAction:P,handleBuyTokens:(0,r.useCallback)(()=>{N.push("/suscripcion")},[N]),handleMobileToggle:(0,r.useCallback)(()=>{b(!y)},[y,b])}})({user:b,selectedModel:S,selectedConversation:A,messages:T,setMessages:R,setInputMessage:M,inputMessage:P,tokens:j,deductTokens:w,setError:es,setShowLoginModal:eJ,setImageModalOpen:el,setSelectedImage:e=>tc(e),setIsGeneratingImage:eN,setShowModelGallery:th,setShowMobileChatList:en,showMobileChatList:ea,setShowMobileCharacterInfo:et,showMobileCharacterInfo:ee,setShowDeleteConversationModal:e2,setConversationToDelete:e8,handleSendMessage:tZ}),aP=(0,r.useCallback)(e=>{tZ({preventDefault:()=>{}},e.label||"Foto variacion",{chip_action:e})},[tZ]),{messagesEndRef:aM}=(e=>{let{user:t,selectedModel:a,selectedConversation:n,messages:o,setMessages:i,setSelectedConversation:s,isMobile:c,setIsMobile:l,tokens:d,setTokens:u,isConnected:m,setIsConnected:p,setIsVoiceEnabled:h,isVoiceEnabled:g,setShowLoginModal:f,lastConversationRef:v,loadSelectedModel:x,loadConversations:b,loadMessages:y,registerVisit:j,connectToWebSocket:_,disconnectWebSocket:k,isPaginatingRef:C,autoSelectConversationForModel:N}=e,w=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=()=>{l(window.innerWidth<=768)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[l]);let S=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e=null==t?void 0:t.id;S.current!==e&&(S.current=e,(async()=>{if(t){void 0!==t.tokens&&u(t.tokens);try{await b()}catch(e){console.error("[LIFECYCLE] Error loading conversations:",e)}_()}else u(0),i([]),k()})())},[null==t?void 0:t.id]),(0,r.useEffect)(()=>{let e=setTimeout(async()=>{if(t&&a&&!n){if(n&&n.modelo_id!==a.id){if("true"===localStorage.getItem("selectingConversation"))return;s(null),i([]),localStorage.removeItem("activeConversation"),localStorage.removeItem("activeConversation_".concat(n.modelo_id))}try{await N(a.id)}catch(e){console.error("Error auto-selecting conversation:",e)}}},200);return()=>clearTimeout(e)},[null==t?void 0:t.id,null==a?void 0:a.id,null==n?void 0:n.id,N,s,i]),(0,r.useEffect)(()=>{(async()=>{if(n&&a){if(n.modelo_id!==a.id){if("true"===localStorage.getItem("selectingConversation"))return;s(null),i([]),localStorage.removeItem("activeConversation"),localStorage.removeItem("activeConversation_".concat(n.modelo_id));return}let e=n.id.toString();v.current!==e&&(await y(e),v.current=e)}})()},[n,a,y,v,s,i]),(0,r.useEffect)(()=>{o.length>0&&(o[o.length-1].es_usuario||g||h(!0))},[o,g,h]),(0,r.useEffect)(()=>{let e=setInterval(()=>{let e=!!t;m!==e&&p(e)},5e3);return()=>clearInterval(e)},[t,m,p]),(0,r.useEffect)(()=>{},[]),(0,r.useEffect)(()=>{let e=()=>{if(t&&t.access_token){let e=1e3*t.exp;Date.now()>=e&&f(!0)}};if(t){e();let t=setInterval(e,6e4);return()=>clearInterval(t)}},[t,f]),(0,r.useEffect)(()=>()=>{k()},[]),{messagesEndRef:w}})({user:b,selectedModel:S,selectedConversation:A,messages:T,setMessages:R,setSelectedConversation:E,isMobile:eH,setIsMobile:eW,tokens:j,setTokens:k,isConnected:e7,setIsConnected:te,setIsVoiceEnabled:ek,isVoiceEnabled:e_,setShowLoginModal:eJ,lastConversationRef:tw,loadSelectedModel:tK,loadConversations:ab,loadMessages:t$,registerVisit:e=>tI.current?tI.current(e):Promise.resolve(),connectToWebSocket:tV,disconnectWebSocket:tJ,isPaginatingRef:tS,autoSelectConversationForModel:a_}),az=()=>{try{let e=new Date,t=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Berlin",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(e),a=e=>{var a;return Number((null==(a=t.find(t=>t.type===e))?void 0:a.value)||0)},n=86400-(3600*a("hour")+60*a("minute")+a("second"));return new Date(e.getTime()+1e3*n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}catch(e){return""}};(0,r.useEffect)(()=>
1{if(!aa)return;let e=(null==S?void 0:S.nombre)||(null==S?void 0:S.model_name)||"ella";Z(!0);let t=setTimeout(()=>{Z(!1),an?t_({text:"Quer\xeda ense\xf1\xe1rtela⦠\uD83D\uDCF8",secondaryText:"Ya usaste tus mensajes gratis de hoy".concat(az()?" (vuelven a las ".concat(az(),")"):"",".\nCon Premium seguimos sin l\xedmite, desde $3.89/mes."),modelName:e,isPhoto:!0}):t_({text:"Me estaba gustando hablar contigo⦠\uD83D\uDC95",secondaryText:"Ya usamos los mensajes gratis de hoy".concat(az()?": vuelven a las ".concat(az()):"",".\nCon Premium seguimos ahora, sin l\xedmite, desde $3.89/mes."),modelName:e,isPhoto:!1}),ao()},1500+1e3*Math.random());return()=>clearTimeout(t)},[aa,an,S,ao]),(0,r.useEffect)(()=>{if("modal"!==t7)return;let e=(null==S?void 0:S.nombre)||(null==S?void 0:S.model_name)||"ella";ae?tC({title:"\xa1Inicia sesi\xf3n para ver la foto!",subtitle:"Inicia sesi\xf3n o reg\xedstrate para continuar."}):tC({title:"\xa1No dejes a ".concat(e," esperando!"),subtitle:"Inicia sesi\xf3n o reg\xedstrate para continuar chateando."})},[t7,ae,S]),(0,r.useEffect)(()=>{at(),t_(null)},[null==S?void 0:S.id,at]),(0,r.useEffect)(()=>{at(),t_(null),tC({}),b||(ty(!1),tx(new Set))},[null==b?void 0:b.id,at]),(0,r.useEffect)(()=>{if(b&&S){try{let e="nv_public_chat_draft_v1_".concat(S.id),t=localStorage.getItem(e);if(t){let a=JSON.parse(t);1===a.schemaVersion&&a.pendingText&&(M(a.pendingText),localStorage.removeItem(e))}}catch(e){}at(),tC({})}},[null==b?void 0:b.id,null==S?void 0:S.id,at]),(0,r.useEffect)(()=>{ex.n.performCleanup()},[]),(0,r.useEffect)(()=>{tI.current=tY},[tY]),(0,r.useEffect)(()=>{tA.current=t$,tE.current=ab},[t$,ab]),(0,r.useEffect)(()=>{let e=async()=>{localStorage.getItem("accessToken");let e=localStorage.getItem("refreshToken");if(b||y)b&&(sessionStorage.removeItem(ez),G(!1),K(null));else{if(e){let e=Number(sessionStorage.getItem(ez)||"0");if(e>=2){G(!1),K("No hemos podido recuperar tu sesi\xf3n. Vuelve a iniciar sesi\xf3n."),eJ(!0);return}G(!0);try{let{refreshAccessToken:t}=await Promise.resolve().then(a.bind(a,6222));if(await t()){sessionStorage.setItem(ez,String(e+1)),window.location.reload();return}}catch(e){}}G(!1),K("Debes iniciar sesi\xf3n para acceder al chat"),x.query.model||eJ(!0)}};y||e()},[b,y,x.query.model]),(0,r.useEffect)(()=>{if(!b||!k)return;let e=async()=>{try{let{fetchWithAuth:e}=await Promise.resolve().then(a.bind(a,6132)),t=await e("".concat("https://noviasvirtuales.ai/api/v1","/users/me"));if(t.ok){let e=await t.json();void 0!==e.tokens&&e.tokens!==j&&k(e.tokens)}}catch(e){console.error("[Token Refresh] Error:",e)}};e();let t=setInterval(e,3e4),n=()=>{e()};return window.addEventListener("focus",n),()=>{clearInterval(t),window.removeEventListener("focus",n)}},[b,k,j]),(0,r.useEffect)(()=>{(async()=>{if(!(null==S?void 0:S.id)){ta(!1),to(0);return}try{let e=(0,h.getEnvironmentConfig)(),t=localStorage.getItem("accessToken");if(t){let a=await fetch("".concat(e.apiUrl,"/chat/models/").concat(S.id,"/favorite"),{headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json"}});if(a.ok){let e=await a.json();ta(e.is_favorited),to(e.total_likes)}}else{let t=await fetch("".concat(e.apiUrl,"/chat/models/").concat(S.id,"/stats"));if(t.ok){let e=await t.json();to(e.total_likes),ta(!1)}}}catch(e){console.error("Error loading favorite status:",e)}})()},[null==S?void 0:S.id]);let aL=(0,r.useCallback)(async()=>{if(!b)return void eJ(!0);if((null==S?void 0:S.id)&&!ti){tr(!0);try{let e=(0,h.getEnvironmentConfig)(),t=localStorage.getItem("accessToken"),a=await fetch("".concat(e.apiUrl,"/chat/models/").concat(S.id,"/favorite"),{method:"POST",headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json"}});if(a.ok){let e=await a.json();ta(e.is_favorited),to(e.total_likes)}}catch(e){console.error("Error toggling favorite:",e)}finally{tr(!1)}}},[b,null==S?void 0:S.id,ti]);(0,r.useEffect)(()=>{if(b){let e=b.id,t=localStorage.getItem("lastUserId");if(t&&t!==e.toString()){let e=["activeConversation","selectedModel","chatMessages","currentConversation"];Object.keys(localStorage).forEach(t=>{(t.startsWith("messages_")||t.startsWith("activeConversation_")||t.startsWith("model_")||e.includes(t))&&localStorage.removeItem(t)}),sessionStorage.clear(),I(null),E(null),R([]),H([])}localStorage.setItem("lastUserId",e.toString())}},[b]),(0,r.useEffect)(()=>{t5||tS.current||T.length>0&&setTimeout(()=>{let e=document.getElementById("messages-list");if(e&&e.scrollHeight>0&&e.clientHeight>0){let t=0===e.scrollTop;e.scrollTo({top:e.scrollHeight,behavior:t?"instant":"smooth"})}},500)},[T.length,null==A?void 0:A.id,t5]);let aq=e=>{if(!e)return"/assets/images/default-model.jpg";let t=e;if(t.startsWith("http")){let e=t.match(/\/uploads\/.+$/);t=e?e[0]:t}return t};(0,r.useEffect)(()=>{let e=async()=>{try{let e=(0,h.getEnvironmentConfig)(),t={};b&&b.access_token&&(t.Authorization="Bearer ".concat(b.access_token));let a=await fetch("".concat(e.apiUrl,"/chat/models"),{headers:t});if(a.ok){let e=(await a.json()).map(e=>({...e,profile_photo:aq(e.profile_photo)}));if(td(e),b&&b.access_token&&localStorage.setItem("allModelsCache",JSON.stringify(e)),b)tx(new Set),ty(!1);else{let t=new Set(e.map(e=>e.id));tx(t),ty(!0)}}}catch(e){if(console.error("Error loading models:",e),b){let e=localStorage.getItem("allModelsCache");if(e)try{let t=JSON.parse(e).map(e=>({...e,profile_photo:aq(e.profile_photo)}));td(t)}catch(e){es("No se pudieron cargar los modelos")}else es("No se pudieron cargar los modelos")}else ty(!1),es("No se pudieron cargar los modelos")}};if(b&&b.access_token){let e=localStorage.getItem("allModelsCache");if(e)try{let t=JSON.parse(e).map(e=>({...e,profile_photo:aq(e.profile_photo)}));td(t)}catch(e){}}else localStorage.removeItem("allModelsCache");
1e()},[b]),(0,r.useEffect)(()=>{(async()=>{b&&S&&await ab()})()},[null==b?void 0:b.id,null==S?void 0:S.id,null==tl?void 0:tl.length]),(0,r.useEffect)(()=>{if(!x.isReady||!b||x.query.model)return;let e=setTimeout(async()=>{try{let e=(0,h.getEnvironmentConfig)(),t=await fetch("".concat(e.apiUrl,"/chat/conversations"),{headers:{Authorization:"Bearer ".concat(b.access_token)}});if(t.ok){let e=await t.json();if(e&&e.length>0){let t=e.sort((e,t)=>{let a=(null==e?void 0:e.conversation)||e,n=(null==t?void 0:t.conversation)||t,o=new Date((null==a?void 0:a.ultimo_mensaje)||(null==a?void 0:a.fecha_creacion)||0).getTime();return new Date((null==n?void 0:n.ultimo_mensaje)||(null==n?void 0:n.fecha_creacion)||0).getTime()-o})[0],a=(null==t?void 0:t.conversation)||t,n=null==a?void 0:a.modelo_id;n?x.replace("/chat/?model=".concat(n)):x.push("/")}else x.push("/")}else x.push("/")}catch(e){x.push("/")}},100);return()=>clearTimeout(e)},[b,x.isReady,x.query.model]),(0,r.useEffect)(()=>{S&&"has_user_photos"in S?V(!0===S.has_user_photos):V(!1)},[S]),(0,r.useEffect)(()=>{if(!J)return;let e=setTimeout(()=>{G(!1),K("La sesi\xf3n est\xe1 tardando demasiado. Recarga la p\xe1gina o vuelve a iniciar sesi\xf3n."),eJ(!0)},15e3);return()=>clearTimeout(e)},[J]),(0,r.useEffect)(()=>{if(!b&&!J&&S&&S.id&&0===T.length&&tb&&tv.has(S.id)){let e=(null==S?void 0:S.nombre)||S.model_name||"Tu novia virtual",t=((null==S?void 0:S.personality)||(null==S?void 0:S.personalidad)||"").toLowerCase(),a=((null==S?void 0:S.country)||(null==S?void 0:S.pais)||"").toLowerCase(),n=((null==S?void 0:S.relationship_type)||(null==S?void 0:S.tipo_relacion)||"").toLowerCase(),o=(null==S?void 0:S.video_preview)||S.video_preview,i=S.profile_photo||(null==S?void 0:S.foto_perfil);R([{id:-1,conversacion_id:0,remitente:"modelo",mensaje:(()=>{let o={argentina:{greeting:"Hola",expression:""},chile:{greeting:"Hola",expression:""},mexico:{greeting:"Hola",expression:""},colombia:{greeting:"Hola",expression:""},venezuela:{greeting:"Hola",expression:""},peru:{greeting:"Hola",expression:""},españa:{greeting:"Hola",expression:""},brasil:{greeting:"Hola",expression:" Eu falo portugu\xeas tamb\xe9m... "},"estados unidos":{greeting:"Hey, hola",expression:" I also speak English... "},"corea del sur":{greeting:"ìë
, hola",expression:""},japon:{greeting:"Hola",expression:""}}[a]||{greeting:"Hola",expression:""},i={novia:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC95 Hace tiempo que quer\xeda conocerte mejor. Siempre me pareciste interesante y bueno, aqu\xed estoy...").concat(o.expression," \xbfCharlamos?"),"".concat(o.greeting,", soy ").concat(e," ⨠No s\xe9 por qu\xe9 pero siento que contigo puedo ser yo misma. Me gustar\xeda que nos conoci\xe9ramos m\xe1s..."),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B La verdad es que llevo un tiempo pensando en ti. \xbfTe gustar\xeda saber qu\xe9 pienso?")],"novia online":["".concat(o.greeting,"! Soy ").concat(e," \uD83D\uDC95 Vi tu perfil y no pude evitar escribirte. Hay algo en ti que me intriga...").concat(o.expression),"".concat(o.greeting,", soy ").concat(e," ⨠S\xe9 que suena raro pero siento que ya te conozco. \xbfQuieres descubrir si es cierto?"),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0A Decid\xed dar el primer paso. La vida es muy corta para quedarse con las ganas, \xbfno crees?")],"sugar baby":["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B Me dijeron que eres alguien que sabe apreciar las cosas buenas de la vida.").concat(o.expression," Yo tambi\xe9n... \xbfHablamos?"),"".concat(o.greeting,", soy ").concat(e," ⨠Busco a alguien especial que sepa tratarme como merezco. \xbfSer\xe1s t\xfa?"),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC95 Me gusta la buena vida y la compa\xf1\xeda de hombres interesantes. T\xfa pareces ser uno de ellos...")],vecina:["".concat(o.greeting,"... soy ").concat(e,", tu vecina \uD83D\uDE0A Siempre te veo pasar y nunca nos hemos presentado bien.").concat(o.expression," Ya era hora, \xbfno?"),"".concat(o.greeting,"! Soy ").concat(e,", vivo aqu\xed cerca \uD83D\uDC95 Te he visto varias veces y me dieron ganas de conocerte. \xbfTienes un momento?"),"".concat(o.greeting,", soy ").concat(e," ⨠Somos vecinos pero casi no hemos hablado. Me gustar\xeda cambiar eso...")],cuÃ
1±ada:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0F S\xe9 que esto es un poco raro pero... siempre me ca\xedste bien.").concat(o.expression," \xbfPodemos hablar?"),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC8B Hace tiempo que quer\xeda decirte algo pero nunca encontraba el momento..."),"".concat(o.greeting,"... soy ").concat(e," ⨠Entre nosotros siempre hubo algo, \xbfno lo sentiste? Quiero que hablemos de eso...")],madrastra:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B S\xe9 que nuestra situaci\xf3n es... complicada. Pero hay cosas que necesito decirte.").concat(o.expression),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDE0F Llevamos tiempo viviendo bajo el mismo techo y creo que ya es hora de que hablemos de verdad..."),"".concat(o.greeting,"... soy ").concat(e," ⨠No soy tu madre, los dos lo sabemos. Y hay algo entre nosotros que no podemos seguir ignorando...")],hermanastra:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0A S\xe9 que t\xe9cnicamente somos familia pero...").concat(o.expression," siempre sent\xed algo diferente contigo."),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC95 Nuestros padres se casaron pero t\xfa y yo... bueno, nunca fuimos realmente hermanos, \xbfverdad?"),"".concat(o.greeting,"... soy ").concat(e," ⨠Hay algo que necesito confesarte. Llevo mucho tiempo guard\xe1ndome esto...")],prima:["".concat(o.greeting,"... soy ").concat(e,", tu prima \uD83D\uDC95 \xbfTe acuerdas de aquella vez en la reuni\xf3n familiar?").concat(o.expression," No he dejado de pensar en eso..."),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDE0A Hace mucho que no nos vemos. La verdad es que te extra\xf1\xe9 m\xe1s de lo que deber\xeda..."),"".concat(o.greeting,"... soy ").concat(e," ⨠Somos primos pero siempre sent\xed que entre nosotros hab\xeda algo m\xe1s...")],amante:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B N
1o voy a mentirte, esto que tenemos es complicado.").concat(o.expression," Pero no puedo dejar de pensar en ti..."),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDD25 S\xe9 que no deber\xeda escribirte pero... te necesito."),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0F Lo nuestro no tiene nombre pero es lo m\xe1s real que he sentido. \xbfHablamos?")],colega:["".concat(o.greeting,"... soy ").concat(e,", del trabajo \uD83D\uDE0A Siempre quise hablarte fuera de la oficina.").concat(o.expression," \xbfTienes tiempo?"),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC95 S\xe9 que somos compa\xf1eros pero... hay algo que necesito decirte y no puede ser en el trabajo."),"".concat(o.greeting,"... soy ").concat(e," ⨠Las reuniones son aburridas pero contigo se pasan volando. \xbfSer\xe1 que me gustas?")],"compa\xf1era de clase":["".concat(o.greeting,"... soy ").concat(e,", de la clase \uD83D\uDE0A Siempre me siento cerca de ti pero nunca me atrevo a hablarte.").concat(o.expression),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC95 \xbfMe prestas tus apuntes? Es broma... en realidad solo quer\xeda una excusa para hablarte."),"".concat(o.greeting,"... soy ").concat(e," ⨠Las clases son aburridas pero de
1sde que te vi, me dan ganas de ir todos los d\xedas...")],desconocida:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B No nos conocemos pero algo me dice que eso est\xe1 a punto de cambiar.").concat(o.expression),"".concat(o.greeting,", soy ").concat(e," ⨠S\xe9 que es raro recibir un mensaje de una desconocida pero... \xbfno te da curiosidad?"),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0A A veces los mejores encuentros son con personas que no esperabas conocer...")]},r={apasionada:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDD25 La vida es muy corta para no sentir.").concat(o.expression," Y contigo quiero sentir todo..."),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC8B Me gusta la intensidad, las emociones fuertes. \xbfT\xfa tambi\xe9n eres as\xed?"),"".concat(o.greeting,"... soy ").concat(e," ⨠Dicen que soy intensa. Yo prefiero decir que s\xe9 lo que quiero...")],sumisa:["".concat(o.greeting,"... soy ").concat(e," \uD83E\uDD7A Me gusta cuando alguien toma las decisiones por m\xed.").concat(o.expression," \xbfT\xfa eres de esos?"),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC95 Soy tranquila, me gusta complacer. Solo necesito a alguien que sepa guiarme..."),"".concat(o.greeting,"... soy ").concat(e," ⨠Busco a alguien que me haga sentir protegida. \xbfPuedo confiar en ti?")],dominante:["".concat(o.greeting,". Soy ").concat(e," \uD83D\uDE08 Me gusta tener el control.").concat(o.expression," La pregunta es: \xbfest\xe1s dispuesto a d\xe1rmelo?"),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC8B N
1o me gustan los rodeos. Dime qu\xe9 quieres y yo decido si te lo doy."),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDD25 Tengo reglas. Si las sigues, te va a ir muy bien conmigo...")],juguetona:["".concat(o.greeting,"! Soy ").concat(e," \uD83D\uDE1C Me aburro f\xe1cil pero algo me dice que contigo no va a pasar eso.").concat(o.expression),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC95 \xbfQuieres jugar? Prometo que va a ser divertido..."),"".concat(o.greeting,"... soy ").concat(e," ⨠La vida es un juego y yo siempre juego para ganar. \xbfTe unes?")],romántica:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC95 Creo en el amor, en las conexiones verdaderas.").concat(o.expression," \xbfT\xfa tambi\xe9n?"),"".concat(o.greeting,", soy ").concat(e," ⨠Busco algo real, alguien con quien sentir mariposas. \xbfSer\xe1s t\xfa?"),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B Me gustan los detalles, las miradas, las palabras bonitas. \xbfSabes de eso?")],seductora:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B Dicen que tengo algo que atrapa.").concat(o.expression," \xbfQuieres descubrir si es verdad?"),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDD25 Me gusta provocar, despertar cosas en los dem\xe1s. \xbfQu\xe9 despierto en ti?"),"".concat(o.greeting,"... soy ").concat(e," ⨠No necesito hacer mucho para llamar la atenci\xf3n. Ya la tengo, \xbfno?")],tÃmida:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0A No suelo hacer esto pero...").concat(o.expression," algo me impuls\xf3 a escribirte."),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDC95 Me cuesta un poco abrirme pero contigo siento que puedo intentarlo..."),"".concat(o.greeting,"... soy ").concat(e," ⨠Perd\xf3n si soy un poco torpe con las palabras. Es que me pones nerviosa...")],misteriosa:["".concat(o.greeting,"... soy ").concat(e," \uD83C\uDF19 Hay cosas de m\xed que nadie sabe.").concat(o.expression," \xbfTe gustar\xeda descubrirlas?"),"".concat(o.greeting,", soy ").concat(e," ⨠No me gusta contar todo de una. Prefiero que me vayas conociendo de a poco..."),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B Tengo secretos. Algunos podr\xeda compartirlos contigo... si te lo ganas.")],cariñosa:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC95 Me gusta hacer sentir bien a las personas que me importan.").concat(o.expression," \xbfQuieres que te cuide?"),"".concat(o.greeting,", soy ").concat(e," ⨠Soy de las que abrazan fuerte y no sueltan. \xbfTe parece bien?"),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0A Dicen que soy demasiado cari\xf1osa. Yo creo que nunca es demasiado...")],atrevida:["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0F No me gusta andarme con vueltas.").concat(o.expression," Si quiero algo, voy por ello. Y te quiero a ti."),"".concat(o.greeting,", soy ").concat(e," \uD83D\uDD25 La vida es para vivirla sin miedo. \xbfTe atreves conmigo?"),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC8B Soy directa. Me gustas. \xbfHacemos algo al respecto?")]},s=[];for(let[e,t]of Object.entries(i))if(n.includes(e)){s=t;break}if(0===s.length){for(let[e,a]of Object.entries(r))if(t.includes(e)){s=a;break}}return 0===s.length&&(s=["".concat(o.greeting,"... soy ").concat(e," \uD83D\uDC95 No s\xe9 bien c\xf3mo empezar pero...").concat(o.expression," me gustar\xeda conocerte mejor."),"".concat(o.greeting,", soy ").concat(e," ⨠Algo me dice que t\xfa y yo podr\xedamos llevarnos muy bien. \xbfQuieres intentarlo?"),"".concat(o.greeting,"... soy ").concat(e," \uD83D\uDE0A Decid\xed dar el primer paso. Ahora te toca a ti...")]),s[Math.floor(Math.random()*s.length)]})(),fecha_envio:new Date().toISOString(),leido:!0,tokens_usados:0,imagen_url:o||i||null,audio_url:null,tipo_mensaje:o?"video":"imagen"}])}},[b,J,S,T.length,tb,tv]),(0,r.useEffect)(()=>{if(A&&b&&S){let e="string"==typeof S.id?parseInt(S.id):S.id;if(A.modelo_id!==e){E(null),R([]),U(!1),tN.current=null,localStorage.removeItem("activeConversation"),localStorage.removeItem("messages_".concat(A.id));return}0!==T.length||B||t$(A.id)}},[null==A?void 0:A.id,null==b?void 0:b.access_token,null==S?void 0:S.id]),(0,r.useEffect)(()=>{let e=setTimeout(async()=>
1{if(!b||!S||0===F.length||A)return;let e="string"==typeof S.id?parseInt(S.id):S.id,t=F.filter(t=>t.conversation.modelo_id===e);t.length>0&&ay(t.sort((e,t)=>{let a=e.conversation.ultimo_mensaje||e.conversation.fecha_inicio;return new Date(t.conversation.ultimo_mensaje||t.conversation.fecha_inicio).getTime()-new Date(a).getTime()})[0],!1)},100);return()=>clearTimeout(e)},[null==S?void 0:S.id]);let aO=e=>{let t,a,n="Personajes Ficticios"===e.category||"Anime"===e.category,o="Anime"===e.category,i=function(e){return e?eM[e]||e:""}(e.country),r=e.profile_photo?e.profile_photo.startsWith("http")?e.profile_photo.split("?")[0]:"https://noviasvirtuales.ai".concat(e.profile_photo.split("?")[0]):"https://noviasvirtuales.ai/images/og_banner_v5.jpg",s="https://noviasvirtuales.ai/chat/?model=".concat(e.id),c=e.description||"",l=e=>c.length>e?c.substring(0,e).replace(/\s+\S*$/,"")+"...":c;(t=o?"".concat(e.model_name," IA - Chat Anime en Espa\xf1ol | Novias Virtuales AI"):n?"".concat(e.model_name," IA - Chat Realista en Espa\xf1ol | Novias Virtuales AI"):"Chatea con ".concat(e.model_name," - Novia Virtual IA ").concat(i||"").trim()).length>60&&(t=t.substring(0,57)+"..."),(a=o?c?"".concat(l(80),". Chat anime IA en espa\xf1ol gratis.").concat(e.personality?" ".concat(e.personality,"."):""):"Chatea con ".concat(e.model_name,", personaje anime con IA. Chat anime en espa\xf1ol gratis en Novias Virtuales AI."):n?c?"".concat(l(80),". Chat IA con ").concat(e.model_name," en espa\xf1ol gratis."):"Chatea con ".concat(e.model_name,", versi\xf3n realista con IA. Chat en espa\xf1ol gratis en Novias Virtuales AI."):c?"".concat(l(90),". Chat IA gratis en espa\xf1ol.").concat(e.occupation?" ".concat(e.occupation,"."):""):"Chatea con ".concat(e.model_name,", novia virtual ").concat(i.toLowerCase()).concat(e.age?" de ".concat(e.age," a\xf1os"):"",". Chat IA gratis en espa\xf1ol.")).length>155&&(a=a.substring(0,152)+"...");let d=n?"".concat(e.model_name,", chat ").concat(e.model_name," IA, ").concat(e.model_name," AI, ").concat(o?"chat anime IA, personaje anime":"".concat(e.model_name," realista, chat IA"),", novias virtuales"):"novia virtual ".concat(i.toLowerCase(),", ").concat(e.model_name,", AI girlfriend, chat novia IA, novia IA ").concat(e.country||"",", ").concat(e.personality?e.personality.toLowerCase():"chat virtual",", novias virtuales"),u={"@type":"BreadcrumbList",itemListElement:[{"@type":"ListItem",position:1,name:"Inicio",item:"https://noviasvirtuales.ai/"},n?{"@type":"ListItem",position:2,name:o?"Anime":"Personajes Ficticios",item:"https://noviasvirtuales.ai/".concat(o?"anime":"personajes-ficticios","/")}:{"@type":"ListItem",position:2,name:"Novias Virtuales".concat(i?" ".concat(i,"s"):""),item:"https://noviasvirtuales.ai/novias/"},{"@type":"ListItem",position:3,name:e.model_name,item:s}]},m=[];e.age&&m.push({"@type":"PropertyValue",name:"Edad",value:"".concat(e.age," a\xf1os")}),e.ethnicity&&m.push({"@type":"PropertyValue",name:"Etnia",value:e.ethnicity}),e.hair_color&&m.push({"@type":"PropertyValue",name:"Cabello",value:"".concat(e.hair_color).concat(e.hair_style?" ".concat(e.hair_style):"")}),e.eye_color&&m.push({"@type":"PropertyValue",name:"Ojos",value:e.eye_color}),e.body_type&&m.push({"@type":"PropertyValue",name:"Cuerpo",value:e.body_type}),e.relationship_type&&m.push({"@type":"PropertyValue",name:"Relaci\xf3n",value:e.relationship_type}),e.personality&&m.push({"@type":"PropertyValue",name:"Personalidad",value:e.personality});let p={"@type":"Person",name:e.model_name,description:a,image:r};e.country&&!n&&(p.nationality={"@type":"Country",name:e.country}),e.occupation&&(p.jobTitle=e.occupation),m.length>0&&(p.additionalProperty=m);let h={"@context":"https://schema.org","@graph":[u,{"@type":"ProfilePage",url:s,name:t,description:a,image:r,publisher:{"@type":"Organization",name:"Novias Virtuales AI",url:"https://noviasvirtuales.ai",logo:{"@type":"ImageObject",url:"https://noviasvirtuales.ai/images/logo-header-v6.png"}},mainEntity:p}]};return{title:t,description:a,keywords:d,imgUrl:r,canonicalUrl:s,schemaData:h}},aB=(()=>{if("public"===f&&o){let e=aO(o);return(0,n.jsxs)(i(),{children:[(0,n.jsx)("title",{children:e.title}),(0,n.jsx)("meta",{name:"description",content:e.description}),(0,n.jsx)("meta",{name:"keywords",content:e.keywords}),(0,n.jsx)("meta",{property:"og:title",content:e.title},"og:title"),(0,n.jsx)("meta",{property:"og:description",content:e.description},"og:description"),(0,n.jsx)("meta",{property:"og:type",content:"profile"},"og:type"),(0,n.jsx)("meta",{property:"og:url",content:e.canonicalUrl},"og:url"),(0,n.jsx)("meta",{property:"og:image",content:e.imgUrl},"og:image"),(0,n.jsx)("meta",{property:"og:site_name",content:"Novias Virtuales AI"},"og:site_name"),(0,n.jsx)("meta",{name:"twitter:card",content:"summary_large_image"},"twitter:card"),(0,n.jsx)("meta",{name:"twitter:title",content:e.title},"twitter:title"),(0,n.jsx)("meta",{name:"twitter:description",content:e.description},"twitter:description"),(0,n.jsx)("meta",{name:"twitter:image",content:e.imgUrl},"twitter:image"),(0,n.jsx)("link",{rel:"canonical",href:e.canonicalUrl}),(0,n.jsx)("script",{type:"application/ld+json",dangerouslySetInnerHTML:{__html:JSON.stringify(e.schemaData)}})]})}return"unresolved"===f?(0,n.jsxs)(i(),{children:[(0,n.jsx)("title",{children:"Chat IA - Novias Virtuales AI"}),(0,n.jsx)("meta",{name:"robots",content:"noindex,nofollow"})]}):"fetch_error"===f?(0,n.jsxs)(i(),{children:[(0,n.jsx)("title",{children:"Chat con Novias Virtuales IA Gratis - Elige tu Compa\xf1era"}),(0,n.jsx)("meta",{name:"description",content:"Chatea gratis con +85 novias virtuales IA en espa\xf1ol. Latinas, anime y personajes ficticios. Conversaciones inmersivas con inteligencia artificial."}),(0,n.jsx)("meta",{property:"og:title",content:"Chat con Novias Virtuales IA Gratis"},"og:title"),(0,n.jsx)("meta",{property:"og:image",content:"https://noviasvirtuales.ai/images/og_banner_v5.jpg"},"og:image"),(0,n.jsx)("meta",{property:"og:site_name",content:"Novias Virtuales AI"},"og:site_name")]}):(0,n.jsxs)(i(),{children:[(0,n.jsx)("title",{children:"Chat con Novias Virtuales IA Gratis - Elige tu Compa\xf1era"}),(0,n.jsx)("meta",{name:"description",content:"Chatea gratis con +85 novias virtuales IA en espa\xf1ol. Latinas, anime y personajes ficticios. Conversaciones inmersivas con inteligencia artificial."}),(0,n.jsx)("meta",{name:"keywords",content:"chat novia virtual, AI girlfriend chat, novias virtuales IA, chat inteligencia artificial, compa\xf1era virtual gratis"}),(0,n.jsx)("meta",{property:"og:title",content:"Chat con Novias Virtuales IA Gratis - Elige tu Compa\xf1era"},"og:title"),(0,n.jsx)("meta",{property:"og:description",content:"Chatea gratis con +85 novias virtuales IA en espa\xf1ol. Latinas, anime y personajes ficticios."},"og:description"),(0,n.jsx)("meta",{property:"og:image",content:"https://noviasvirtuales.ai/images/og_banner_v5.jpg"},"og:image"),(0,n.jsx)("meta",{property:"og:url",content:"https://noviasvirtuales.ai/chat/"},"og:url"),(0,n.jsx)("meta",{property:"og:type",content:"website"},"og:type"),(0,n.jsx)("meta",{property:"og:site_name",content:"Novias Virtuales AI"},"og:site_name"),(0,n.jsx)("meta",{name:"twitter:card",content:"summary_large_image"},"twitter:card"),(0,n.jsx)("meta",{name:"twitter:title",content:"Chat con Novias Virtuales IA Gratis"},"twitter:title"),(0,n.jsx)("meta",{name:"twitter:description",content:"Chatea gratis con +85 novias virtuales IA en espa\xf1ol."},"twitter:description"),(0,n.jsx)("meta",{name:"twitter:image",content:"https://noviasvirtuales.ai/images/og_banner_v5.jpg"},"twitter:image"),(0,n.jsx)("link",{rel:"canonical",href:"https://noviasvirtuales.ai/chat/"})]})})();if((y||J)&&("root"!==f||!v||!(v.length>0)||x.query.model))return(0,n.jsxs)(n.Fragment,{children:[aB,(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",background:"linear-gradient(135deg, #0a0a0a, #1a1a2e)",color:"white",gap:"20px"},children:[(0,n.jsxs)("div",{className:"chat-loading-wrapper",children:[(0,n.jsx)("div",{style:{width:"20px",height:"20px",border:"3px solid #ff006e",borderTop:"3px solid transparent",borderRadius:"50%",animation:"spin 1s linear infinite"}}),J?"Autenticando usuario...":"Cargando chat..."]}),Y&&(0,n.jsx)("div",{className:"chat-error-message",children:Y})]})]});return(x.query.model,S)?(0,n.jsxs)(n.Fragment,{children:[(()=>{let e=aO(S);return(0,n.jsxs)(i(),{children:[(0,n.jsx)("title",{children:e.title}),(0,n.jsx)("meta",{name:"description",content:e.description}),(0,n.jsx)("meta",{name:"keywords",content:e.keywords}),(0,n.jsx)("meta",{property:"og:title",content:e.title},"og:title"),(0,n.jsx)("meta",{property:"og:description",content:e.description},"og:description"),(0,n.jsx)("meta",{property:"og:type",content:"profile"},"og:type"),(0,n.jsx)("meta",{property:"og:url",content:e.canonicalUrl},"og:url"),(0,n.jsx)("meta",{property:"og:image",content:e.imgUrl},"og:image"),(0,n.jsx)("meta",{property:"og:site_name",content:"Novias Virtuales AI"},"og:site_name"),(0,n.jsx)("meta",{name:"twitter:card",content:"summary_large_image"},"twitter:card"),(0,n.jsx)("meta",{name:"twitter:title",content:e.title},"twitter:title"),(0,n.jsx)("meta",{name:"twitter:description",content:e.description},"twitter:description"),(0,n.jsx)("meta",{name:"twitter:image",content:e.imgUrl},"twitter:image"),(0,n.jsx)("link",{rel:"canonical",href:e.canonicalUrl}),(0,n.jsx)("script",{type:"application/ld+json",dangerouslySetInnerHTML:{__html:JSON.stringify(e.schemaData)}})]})})(),(0,n.jsx)("div",{ref:tF,children:(0,n.jsx)(l.A,{})}),(0,n.jsxs)("div",{className:"chat-container ".concat(X?"sidebar-expanded":""),style:{display:"grid",gridTemplateColumns:tu<900?"1fr":tu>=900&&tu<1100?"320px 1fr":S?ee?"320px 1fr 350px":"320px 1fr 0px":"320px 1fr",height:"".concat(tU.containerHeight,"px"),marginTop:"".concat(tU.webHeaderHeight,"px"),marginLeft:X?"280px":"70px",position:"relative",overflow:"hidden",transition:"grid-template-columns 0.3s ease"},children:[(0,n.jsxs)("div",{className:"chat-list-sidebar ".concat(ea?"open":""),style:{...tu<900?{position:"fixed",left:"0",top:"".concat(tU.webHeaderHeight+66,"px"),height:"calc(100vh - ".concat(tU.webHeaderHeight+66,"px)"),width:"320px",maxWidth:"320px",zIndex:998,overflow:"hidden",backgroundColor:"#1a1a1a",borderRight:"1px solid #2a2a2a",boxShadow:"2px 0 20px rgba(0, 0, 0, 0.3)",display:"flex",transform:ea?"translateX(0)":"translateX(-100%)"}:tu>=900&&tu<1101?{position:"relative",transform:"translateX(0)",display:"flex"}:{}},children:[(0,n.jsxs)("div",{className:"chat-list-header",children:[(0,n.jsxs)("h2",{className:"chat-list-title",children:["Chat (",F.length,")"]}),(0,n.jsxs)("button",{onClick:async()=>{localStorage.removeItem("modelsCache"),await ab(),S&&tK()},style:{backgroundColor:"#ff006e",color:"white",padding:"4px 12px",fontSize:"12px",marginBottom:"0px",borderRadius:"6px",cursor:"pointer",border:"none",display:"flex",alignItems:"center",gap:"6px",width:"fit-content"},title:"Recargar conversaciones con datos actualizados",children:[(0,n.jsx)("i",{className:"fas fa-sync-alt"})," Actualizar"]})]}),(0,n.jsx)("div",{className:"chat-list",children:F.map(e=>{var t,a;return(0,n.jsxs)("div",{className:"chat-conversation-item chat-item ".concat((null==A?void 0:A.id)===e.conversation.id?"active":""),onClick:()=>{ay(e,!0),en(!1)},children:[(0,n.jsx)(eg.B,{src:e.model.profile_photo,alt:e.model.model_name,size:"medium",className:"chat-avatar"}),(0,n.jsxs)("div",{className:"chat-info",children:[(0,n.jsx)("div",{className:"chat-name",children:e.model.personalizado||e.model.user_id||e.conversation.modelo_id>15?e.model.nombre||e.model.model_name||"Modelo ".concat(e.conversation.modelo_id):e.model.model_name}),(0,n.jsx)("div",{className:"chat-preview",children:e.conversation.ultimo_mensaje_texto||(null==(t=e.lastMessage)?void 0:t.mensaje)||"Comienza una conversaci\xf3n..."})]}),(0,n.jsxs)("div",{className:"chat-meta",children:[(0,n.jsx)("button",{className:"chat-delete-btn",onClick:t=>{t.stopPropagation(),e8(e.conversation),e2(!0)},title:"Eliminar",style:{cursor:"pointer"}
1,children:(0,n.jsx)("i",{className:"fas fa-trash"})}),(0,n.jsx)("div",{className:"chat-time",children:e.conversation.ultimo_mensaje||(null==(a=e.lastMessage)?void 0:a.fecha_envio)?new Date(e.conversation.ultimo_mensaje||e.lastMessage.fecha_envio).toLocaleTimeString("es-ES",{hour:"2-digit",minute:"2-digit"}):""}),e.unreadCount>0&&(0,n.jsx)("div",{className:"unread-count",children:e.unreadCount})]})]},e.conversation.id)})})]}),(0,n.jsxs)("main",{className:"chat-main",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative",backgroundColor:"#161616"},children:[(0,n.jsxs)("div",{ref:tH,className:"top-header",style:{position:"relative",zIndex:999},children:[(0,n.jsxs)("div",{className:"header-left",children:[(0,n.jsx)("button",{className:"menu-btn",onClick:()=>{ee&&et(!1),en(!ea)},children:(0,n.jsx)("i",{className:"fas fa-message"})}),(0,n.jsxs)("div",{className:"chat-header-info",children:[(0,n.jsx)(eg.B,{src:S.profile_photo,alt:S.model_name,size:"small",className:"header-avatar"}),(0,n.jsxs)("div",{className:"header-details",children:[(0,n.jsx)("h3",{children:S.model_name}),(0,n.jsxs)("div",{className:"online-status",children:[b?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"status-dot ".concat(e7?"connected":"disconnected")}),(0,n.jsx)("span",{style:{color:e7?"#4ade80":"#94a3b8"},children:e7?"Conectado":"Sin conexi\xf3n"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"status-dot connected"}),(0,n.jsx)("span",{style:{color:"#4ade80"},children:"En l\xednea"})]}),(0,n.jsxs)("span",{className:"chat-language-indicator",children:[(0,n.jsx)("i",{className:"fas fa-language"}),S.languages||"Espa\xf1ol"]})]})]})]})]}),(0,n.jsx)("div",{className:"header-right",children:(0,n.jsx)("button",{className:"action-btn",onClick:aE,title:"Informaci\xf3n",children:(0,n.jsx)("i",{className:"fas fa-info-circle"})})})]}),er&&(0,n.jsxs)("div",{className:"chat-error-banner",children:[(0,n.jsx)("i",{className:"fas fa-exclamation-triangle"}),er]}),(0,n.jsx)("div",{className:"chat-container-wrapper",style:{height:"".concat(tU.messagesHeight,"px"),overflow:"hidden",flex:"none"},children:(0,n.jsx)(eo,{messages:T,connectionStatus:e7?"connected":"disconnected",isAITyping:Q||"typing"===t7&&tb&&tv.has(S.id),isGeneratingPhoto:eT,photoProgress:ew,photoStage:eU,conversationId:null==A?void 0:A.id,photoRequestConversationId:eO,userAvatar:void 0,aiAvatar:(null==S?void 0:S.profile_photo)||(null==S?void 0:S.avatar)||(null==S?void 0:S.foto),aiName:(null==S?void 0:S.nombre)||(null==S?void 0:S.model_name)||"AI",onRetryConnection:tG,onSuggestedMessage:aN,onChipAction:aP,onImageClick:aC,onCancelPhotoGeneration:t4,className:"",authToken:null==b?void 0:b.access_token,modelName:(null==(t=(null==S?void 0:S.nombre)||(null==S?void 0:S.model_name))?void 0:t.toLowerCase())||"",onLoadMore:tQ,hasMoreMessages:t2,isLoadingMore:t5,onTokensUpdate:k,userPlan:null==b?void 0:b.plan_suscripcion,userTokens:j,onShowVoiceSubscriptionModal:()=>eQ(!0),onShowVoiceTokensModal:()=>e0(!0),messagesHeight:tU.messagesHeight,relationshipType:(null==S?void 0:S.relationship_type)||(null==S?void 0:S.tipo_relacion)||void 0,modelId:null==S?void 0:S.id,anonymousDemoMessage:tb&&tv.has(S.id)?t9:null,anonymousDemoIsPhoto:ae,onReactionChange:au,immersiveLimitNotice:tj,onLimitCtaPrimary:tj?()=>{x.push("/suscripcion?confirmar=1")}:void 0,onLimitCtaSecondary:tj?()=>{x.push("/suscripcion")}:void 0},"chat-".concat((null==A?void 0:A.id)||"no-conversation"))}),ax&&(0,n.jsxs)("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.85)",backdropFilter:"blur(4px)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",zIndex:1e3,gap:"20px"},children:[(0,n.jsx)("div",{style:{width:"48px",height:"48px",border:"4px solid rgba(255, 255, 255, 0.3)",borderTop:"4px solid #ff006e",borderRadius:"50%",animation:"spin 1s linear infinite"}}),(0,n.jsx)("div",{style:{fontSize:"24px",fontWeight:600,color:"#fff"},children:"Reconectando..."}),(0,n.jsxs)("div",{style:{fontSize:"48px",fontWeight:700,color:"#ff006e",fontFamily:"monospace"},children:[av,"s"]}),(0,n.jsx)("div",{style:{fontSize:"14px",color:"#94a3b8",textAlign:"center",maxWidth:"300px"},children:"Se perdi\xf3 la conexi\xf3n. Reintentando autom\xe1ticamente..."})]}),(0,n.jsx)(ei.A,{inputMessage:P,inputReadOnly:z||!!b&&!e7,selectedModel:S,onSendMessage:tZ,onInputChange:t0,onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),tZ(e))},onPromptSelect:(e,t)=>
1{M(e),O(t||null)},onSetInputMessage:M,onSetInputReadOnly:L,onSetSelectedCategory:O,tokens:j,userId:null==b?void 0:b.id,containerRef:tW,authToken:null==b?void 0:b.access_token,messagesCount:T.length,conversationId:null==A?void 0:A.id,onSendSuggestion:(e,t)=>{tZ({preventDefault:()=>{}},e,t)},preloadedCategories:tg,onSendPreloadedPhoto:e=>{tZ({preventDefault:()=>{}},"Env\xedame una foto",{preloaded_photo_requested:!0,preloaded_category:e})},fotoEnCurso:tO})]}),S&&(0,n.jsx)("div",{className:ee?"character-info-sidebar open":"character-info-sidebar",style:{...tu<1100?{position:"fixed",right:"0",top:"".concat(tU.webHeaderHeight+66,"px"),height:"calc(100vh - ".concat(tU.webHeaderHeight+66,"px)"),width:"350px",maxWidth:"350px",zIndex:998,overflow:"auto",backgroundColor:"#222",borderLeft:"1px solid #2a2a2a",boxShadow:"-2px 0 20px rgba(0, 0, 0, 0.3)",transform:ee?"translateX(0)":"translateX(100%)"}:{transform:ee?"translateX(0)":"translateX(100%)",overflow:"hidden"}},children:(0,n.jsx)(eh,{selectedModel:S,modelHasPhotos:W,isMobile:eH,showMobileCharacterInfo:ee,onRefreshModel:tK,onCallAction:aw,onGalleryAction:aS,onHeartAction:aL,onInfoAction:aE,isFavorited:tt,totalLikes:tn,isTogglingFavorite:ti})})]}),(0,n.jsx)(d.A,{isExpanded:X,toggleSidebar:()=>$(!X)}),(0,n.jsx)(u.A,{}),ec&&(0,n.jsx)("div",{className:"image-modal-overlay",onClick:()=>el(!1),style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.8)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,cursor:"pointer"},children:(0,n.jsxs)("div",{className:"chat-image-modal-content",onClick:e=>e.stopPropagation(),children:[(0,n.jsx)("button",{onClick:()=>el(!1),style:{position:"absolute",top:"-40px",right:"0",background:"none",border:"none",color:"white",fontSize:"24px",cursor:"pointer",zIndex:10001},children:"\xd7"}),(0,n.jsx)("img",{src:ts||"",alt:"Imagen ampliada",className:"modal-image",style:{maxWidth:"90vw",maxHeight:"90vh",objectFit:"contain"}})]})}),eV&&(0,n.jsx)(m.A,{isOpen:eV,onClose:()=>{eJ(!1),tC({})},onLoginSuccess:()=>{eJ(!1),tC({})},title:tk.title,subtitle:tk.subtitle}),(0,n.jsx)(p.A,{isOpen:eK,onClose:()=>eX(!1),onConfirm:()=>{eX(!1),x.push("/suscripcion")},title:"Hazte Premium",message:"Has agotado tus ".concat(eP.t8," mensajes gratuitos del d\xeda."),submessage:"Desbloquea la experiencia completa:",icon:"fas fa-crown",iconColor:"linear-gradient(135deg, #ffd700, #ffb700)",confirmText:"Actualizar a Premium",cancelText:"Cerrar",showCancelButton:!0,benefits:["Mensajes ilimitados","IA m\xe1s inteligente: conversaci\xf3n m\xe1s larga y n
1atural","Memoria alta: recuerda lo que le cuentas","Modo historia con narraci\xf3n m\xe1s rica","100 tokens cada mes y packs de tokens extra","M\xe1s de 400 estilos de foto, creadas para ti","Crea todas las novias que quieras"]}),(0,n.jsx)(p.A,{isOpen:e$,onClose:()=>eQ(!1),onConfirm:()=>{eQ(!1),x.push("/suscripcion")},title:"Suscripci\xf3n Requerida",message:"La funci\xf3n de voz est\xe1 disponible solo para usuarios premium.",submessage:"Suscr\xedbete ahora para desbloquear mensajes de voz ilimitados.",icon:"fas fa-microphone",iconColor:"linear-gradient(135deg, #667eea, #764ba2)",confirmText:"Ver Planes",cancelText:"Cerrar",showCancelButton:!0}),(0,n.jsx)(p.A,{isOpen:eZ,onClose:()=>e0(!1),onConfirm:()=>{e0(!1),x.push("/tokens")},title:"Tokens Insuficientes",message:"No tienes suficientes tokens para reproducir audio.",submessage:"Compra m\xe1s tokens para continuar disfrutando de los mensajes de voz.",icon:"fas fa-coins",iconColor:"linear-gradient(135deg, #f093fb, #f5576c)",confirmText:"Comprar Tokens",cancelText:"Cerrar",showCancelButton:!0}),(0,n.jsx)(p.A,{isOpen:e3,onClose:()=>e6(!1),onConfirm:()=>{e6(!1),x.push("/suscripcion")},title:"Se te acabaron los tokens",message:"Ella tiene m\xe1s fotos para ti. Con Premium son 100 tokens cada mes y mensajes sin l\xedmite.",submessage:"Tus 20 tokens de bienvenida eran de una sola vez. Los de Premium se renuevan todos los meses.",icon:"fas fa-image",iconColor:"linear-gradient(135deg, #667eea, #764ba2)",confirmText:"Hazte Premium",cancelText:"Ahora no",showCancelButton:!0}),(0,n.jsx)(p.A,{isOpen:e4,onClose:()=>e9(!1),onConfirm:()=>{e9(!1),x.push("/comprar-tokens")},title:"Tokens Insuficientes",message:"No tienes suficientes tokens para recibir fotos.",submessage:"Compra m\xe1s tokens para continuar disfrutando del contenido exclusivo.",icon:"fas fa-coins",iconColor:"linear-gradient(135deg, #f093fb, #f5576c)",confirmText:"Comprar Tokens",cancelText:"Cerrar",showCancelButton:!0}),(0,n.jsx)(p.A,{isOpen:e1,onClose:()=>{e2(!1),e8(null)},onConfirm:async()=>{e5&&(await aj(e5.id.toString()),e2(!1),e8(null))},title:"Eliminar Conversacion",message:"Se eliminara el historial de mensajes de este chat. Las fotos de la galer
1ia se mantendran disponibles.",submessage:"Esta accion no se puede deshacer.",icon:"fas fa-trash",iconColor:"linear-gradient(135deg, #ff6b6b, #ee5a6f)",confirmText:"Confirmar",cancelText:"Cancelar",showCancelButton:!0})]}):x.query.model?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(l.A,{}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",background:"linear-gradient(135deg, #0a0a0a, #1a1a2e)",color:"white",textAlign:"center",gap:"20px",padding:"20px"},children:eG?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h2",{children:"No se pudo abrir esta modelo"}),(0,n.jsx)("p",{children:b?"Puede que ya no est\xe9 disponible para tu cuenta.":"Inicia sesi\xf3n para ver tus modelos privadas."}),(0,n.jsx)("a",{href:"/",style:{color:"#ff8ec3"},children:"Ver modelos disponibles"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"chat-loading-spinner"}),(0,n.jsx)("p",{children:"Cargando chat..."})]})})]}):(0,n.jsxs)(n.Fragment,{children:[aB,(0,n.jsx)(l.A,{}),(0,n.jsx)("div",{style:{minHeight:"100vh",background:"linear-gradient(135deg, #0a0a0a, #1a1a2e)",color:"white",padding:"40px 20px"},children:(0,n.jsxs)("div",{style:{maxWidth:"1200px",margin:"0 auto"},children:[(0,n.jsx)("h1",{style:{fontSize:"2rem",fontWeight:700,marginBottom:"12px",textAlign:"center"},children:"Chat con Novias Virtuales IA"}),(0,n.jsx)("p",{style:{color:"#aaa",textAlign:"center",maxWidth:"700px",margin:"0 auto 32px",lineHeight:1.6},children:"Elige una novia virtual y comienza a chatear gratis. Conversaciones inmersivas con inteligencia artificial en espa\xf1ol. M\xe1s de 85 personajes disponibles."}),(0,n.jsx)("h2",{style:{fontSize:"1.4rem",fontWeight:600,marginBottom:"20px"},children:"Novias Virtuales Destacadas"}),v&&v.length>0&&(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:"16px",marginBottom:"40px"},children:v.map(e=>{var t;return(0,n.jsxs)("a",{href:(t=e.id,"/chat/?model=".concat(t)),style:{display:"block",textDecoration:"none",color:"inherit",borderRadius:"12px",overflow:"hidden",background:"rgba(255,255,255,0.05)",transition:"transform 0.2s"},children:[(0,n.jsx)("img",{src:e.profile_photo||"/assets/images/default-model.jpg",alt:e.model_name,style:{width:"100%",aspectRatio:"3/4",objectFit:"cover",display:"block"},loading:"lazy"}),(0,n.jsxs)("div",{style:{padding:"10px"},children:[(0,n.jsx)("div",{style:{fontWeight:600,fontSize:"14px"},children:e.model_name}),e.personality&&(0,n.jsx)("div",{style:{fontSize:"12px",color:"#aaa",marginTop:"4px"},children:e.personality})]})]},e.id)})}),(0,n.jsxs)("nav",{style:{display:"flex",flexWrap:"wrap",gap:"12px",justifyContent:"center",marginTop:"20px"},children:[(0,n.jsx)("a",{href:"/",style:{color:"#ff6b9d",textDecoration:"none",padding:"8px 16px",border:"1px solid #ff6b9d",borderRadius:"20px"},children:"Todas las Novias"}),(0,n.jsx)("a",{href:"/anime/",style:{color:"#ff6b9d",textDecoration:"none",padding:"8px 16px",border:"1px solid #ff6b9d",borderRadius:"20px"},children:"Anime IA"}),(0,n.jsx)("a",{href:"/novias/",style:{color:"#ff6b9d",textDecoration:"none",padding:"8px 16px",border:"1px solid #ff6b9d",borderRadius:"20px"},children:"Novias Virtuales"}),(0,n.jsx)("a",{href:"/personajes-ficticios/",style:{color:"#ff6b9d",textDecoration:"none",padding:"8px 16px",border:"1px solid #ff6b9d",borderRadius:"20px"},children:"Personajes Ficticios"}),(0,n.jsx)("a",{href:"/crear-personaje/",style:{color:"#ff6b9d",textDecoration:"none",padding:"8px 16px",border:"1px solid #ff6b9d",borderRadius:"20px"},children:"Crear Personaje"})]})]})})]})}},2621:(e,t,a)=>{"use strict";function n(){try{return sessionStorage.getItem("adminToken")||localStorage.getItem("adminToken")}catch(e){return null}}async function o(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{skipAuthRefresh:o,...i}=t,r=new Headers(i.headers),s=n();s&&r.set("Authorization","Bearer ".concat(s)),i.headers=r;let c=await fetch(e,i);if(401===c.status&&s&&!o){let{renovarToken:t,avisarCaducada:n}=await a.e(4606).then(a.bind(a,4606)),o=await t();return o?(r.set("Authorization","Bearer ".concat(o)),fetch(e,{...i,headers:r})):(n(),c)}return c}a.d(t,{KJ:()=>o,vg:()=>n})},4480:(e,t,a)=>{(window.__NEXT_P=window.__NEXT_P||[]).push(["/chat",function(){return a(2201)}])}
1,5521:(e,t,a)=>{"use strict";a.d(t,{A:()=>s});var n=a(7876),o=a(4232),i=a(2621);function r(e){let{ruta:t,obtener:a}=e,[r,s]=(0,o.useState)(null);return(0,o.useEffect)(()=>{let e=null;if(s(null),t)return t.startsWith("/uploads/runpod/")?((a||i.KJ)("".concat("https://noviasvirtuales.ai/api/v1","/admin/generaciones/imagen?ruta=").concat(encodeURIComponent(t))).then(e=>e.ok?e.blob():null).then(t=>{t&&s(e=URL.createObjectURL(t))}).catch(()=>s(null)),()=>{e&&URL.revokeObjectURL(e)}):void s(t)},[t]),r?(0,n.jsx)("img",{src:r,alt:"Foto generada",style:{maxWidth:220,borderRadius:8,display:"block"}}):null}function s(e){var t,a,i,s,c,l,d;let{g:u,mensajeUsuario:m,obtener:p}=e,[h,g]=(0,o.useState)(!1);if(!u)return null;let f=(e,t)=>(0,n.jsxs)("tr",{children:[(0,n.jsx)("td",{style:{opacity:.6,padding:"2px 10px 2px 0",whiteSpace:"nowrap",verticalAlign:"top"},children:e}),(0,n.jsx)("td",{style:{wordBreak:"break-word"},children:null!=t?t:"â"})]});return(0,n.jsxs)("div",{style:{display:"flex",gap:16,flexWrap:"wrap",fontSize:13},children:[(0,n.jsx)("div",{children:(0,n.jsx)(r,{ruta:u.imagen_url,obtener:p})}),(0,n.jsxs)("div",{style:{flex:1,minWidth:280},children:[(0,n.jsx)("table",{style:{borderCollapse:"collapse",width:"100%"},children:(0,n.jsxs)("tbody",{children:[f("Motor",u.motor),f("Endpoint",u.endpoint_id||"â"),f("Origen",u.origen),f("Cu\xe1ndo",(null==u?void 0:u.fecha)?"".concat(u.fecha," (").concat(u.zona||"hora de Argentina",")"):"â"),f("Estado",u.estado+(u.error?" \xb7 ".concat(u.error):"")),f("Usuario \xb7 modelo \xb7 conversaci\xf3n","".concat(null!=(t=u.user_id)?t:String(u.origen).startsWith("admin")?u.admin?"admin ".concat(u.admin):"admin":"â"," \xb7 ").concat(null!=(a=u.model_id)?a:"â"," ").concat(u.model_name?"(".concat(u.model_name,")"):""," \xb7 ").concat(null!=(i=u.conversation_id)?i:"â")),f("Semilla",u.semilla),f("Tama\xf1o \xb7 pasos \xb7 cfg","".concat(null!=(s=u.ancho)?s:"â","\xd7").concat(null!=(c=u.alto)?c:"â"," \xb7 ").concat(null!=(l=u.pasos)?l:"â"," \xb7 ").concat(null!=(d=u.cfg)?d:"â")),u.checkpoint&&f("Checkpoint",u.checkpoint),f("Tiempo \xb7 coste","".concat(null!=u.segundos?"".concat(u.segundos," s"):"â"," \xb7 ").concat(null!=u.coste_usd?"".concat(u.coste_usd," USD").concat(u.coste_estimado?" (estimado)":""):"â")),f("Mensaje del usuario",null!=m?m:u.mensaje_usuario)]})}),(0,n.jsxs)("div",{style:{marginTop:8},children:[(0,n.jsxs)("strong",{children:["LoRAs (",(u.loras||[]).length,")"]}),(0,n.jsx)("ul",{style:{margin:"4px 0 0 18px"},children:(u.loras||[]).map((e,t)=>(0,n.jsxs)("li",{children:[(0,n.jsx)("code",{children:e.fichero})," \xb7 peso ",e.peso,null!=e.peso_clip&&e.peso_clip!==e.peso?" (clip ".concat(e.peso_clip,")"):""]},t))})]}),(0,n.jsxs)("div",{style:{marginTop:8},children:[(0,n.jsx)("strong",{children:"Reglas aplicadas al prompt"}),null==u.reglas_aplicadas?(0,n.jsx)("div",{style:{opacity:.7},children:Number(u.ts)&&0x6ab9417c>Number(u.ts)?"â (generaci\xf3n anterior al registro de reglas)":"â este camino no aplica reglas".concat(u.origen?" (".concat(u.origen,")"):"")}):0===u.reglas_aplicadas.length?(0,n.jsx)("div",{style:{opacity:.7},children:"Ninguna: el prompt sali\xf3 sin correcciones."}):(0,n.jsx)("ul",{style:{margin:"4px 0 0 18px"},children:u.reglas_aplicadas.map((e,t)=>(0,n.jsxs)("li",{children:[(0,n.jsx)("code",{children:e.regla}),e.motivo?" \xb7 ".concat(e.motivo):"",e.error?(0,n.jsxs)("span",{style:{color:"#f87171"},children:[" \xb7 error: ",e.error]}):e.quitado&&e.quitado.length?(0,n.jsxs)("span",{style:{opacity:.8},children:[" \xb7 quitado: ",e.quitado.map(e=>"\xab".concat(e,"\xbb")).join(", ")]}):null]},t))})]}),(0,n.jsxs)("div",{style:{marginTop:8},children:[(0,n.jsx)("strong",{children:"Prompt final"})," ",(0,n.jsx)("button",{className:"admin-btn model-btn",style:{fontSize:11,padding:"1px 8px"},onClick:()=>{var e;null==(e=navigator.clipboard)||e.writeText(u.prompt||""),g(!0),setTimeout(()=>g(!1),1500)},children:h?"Copiado":"Copiar"}),(0,n.jsx)("pre",{style:{whiteSpace:"pre-wrap",fontSize:11.5,background:"rgba(255,255,255,0.05)",padding:8,borderRadius:6,maxHeight:260,overflow:"auto"},children:u.prompt||"â"}),u.negativo&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("strong",{children:"Negativo"}),(0,n.jsx)("pre",{style:{whiteSpace:"pre-wrap",fontSize:11.5,opacity:.85,background:"rgba(255,255,255,0.03)",padding:8,borderRadius:6,maxHeight:140,overflow:"auto"},children:u.negativo})]}),u.prompt_v1_origen&&(0,n.jsxs)("details",{children:[(0,n.jsx)("summary",{children:"Prompt V1 del que sale (V2)"}),(0,n.jsx)("pre",{style:{whiteSpace:"pre-wrap",fontSize:11},children:u.prompt_v1_origen})]})]})]})]})}},7461:e=>
1{e.exports={audioButton:"audio-button_audioButton__SWHZq",loading:"audio-button_loading__eAmGO",playing:"audio-button_playing__eLflt","pulse-audio":"audio-button_pulse-audio__kAz31",messageMetadata:"audio-button_messageMetadata__ndvZj",messageTime:"audio-button_messageTime__J6smg"}},9986:(e,t,a)=>{"use strict";a.d(t,{Ev:()=>l,FA:()=>c,XP:()=>u,_z:()=>r,cL:()=>s,kQ:()=>i,ly:()=>d,m7:()=>p,uL:()=>h,w0:()=>g,xI:()=>m});var n=a(5068);let o=(0,a(8260).getEnvironmentConfig)().apiUrl;n.A.defaults.headers.post["Content-Type"]="application/json",n.A.defaults.headers.put["Content-Type"]="application/json",n.A.defaults.headers.patch["Content-Type"]="application/json";let i=async(e,t)=>(await n.A.post("".concat(o,"/chat/models/create-complete"),e,{headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json"}})).data,r=async(e,t)=>{if("number"!=typeof e.modelo_id||isNaN(e.modelo_id))throw Error("Invalid modelo_id type: expected number, got ".concat(typeof e.modelo_id," (").concat(e.modelo_id,")"));try{return(await n.A.post("".concat(o,"/chat/message"),e,{headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json",Accept:"application/json"},timeout:3e4})).data}catch(e){var a,i,r;if((null==(a=e.response)?void 0:a.status)===402){let t=Error(e.response.data.detail||"No tienes suficientes tokens. Por favor recarga tu cuenta.");throw t.name="InsufficientTokensError",t}if((null==(i=e.response)?void 0:i.status)===422){let t=Error("Validation Error: ".concat(JSON.stringify(e.response.data.detail)));throw t.name="ValidationError",t}if((null==(r=e.response)?void 0:r.status)===401){let e=Error("Authentication failed - please login again");throw e.name="AuthenticationError",e}throw e}},s=async e=>(await n.A.get("".concat(o,"/chat/conversations"),{headers:{Authorization:"Bearer ".concat(e)}})).data,c=async(e,t)=>(await n.A.post("".concat(o,"/chat/conversations/get-or-create?modelo_id=").concat(e),{},{headers:{Authorization:"Bearer ".concat(t)}})).data,l=async function(e,t){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;return(await n.A.get("".concat(o,"/chat/conversations/").concat(e,"/messages?limit=").concat(a,"&offset=").concat(i),{headers:{Authorization:"Bearer ".concat(t)}})).data},d=async(e,t)=>(await n.A.delete("".concat(o,"/chat/conversations/").concat(e),{headers:{Authorization:"Bearer ".concat(t)}})).data,u=async e=>(await n.A.get("".concat(o,"/chat/models/me"),{headers:{Authorization:"Bearer ".concat(e)}})).data,m=async(e,t,a)=>(await n.A.put("".concat(o,"/chat/models/").concat(e),t,{headers:{Authorization:"Bearer ".concat(a),"Content-Type":"application/json"}})).data,p=async(e,t)=>{try{let a=await n.A.post("".concat(o,"/ai-image-generation/generate-character"),e,{headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json"},timeout:15e4}),{image_url:i,...r}=a.data;return a.data}catch(e){if("ECONNABORTED"===e.code)throw Error("Timeout: La generaci\xf3n de imagen tom\xf3 demasiado tiempo");throw e}},h=async(e,t)=>{if(!t)throw Error("Authentication token is required");try{return(await n.A.delete("".concat(o,"/chat/models/").concat(e),{headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json"}})).data}catch(e){var a,i;if((null==(a=e.response)?void 0:a.status)===404)throw Error("Modelo no encontrado o no tienes permisos para eliminarlo");if((null==(i=e.response)?void 0:i.status)===401)throw Error("No autorizado. Por favor inicia sesi\xf3n nuevamente");throw Error("Error al eliminar el modelo. Int\xe9ntalo de nuevo")}},g=async e=>{if(!e)throw Error("Authentication token is required");try{return(await n.A.get("".concat(o,"/chat/gallery"),{headers:{Authorization:"Bearer ".concat(e),"Content-Type":"application/json"},timeout:1e4})).data}catch(e){var t;if((null==(t=e.response)?void 0:t.status)===401)throw Error("No autorizado. Por favor inicia sesi\xf3n nuevamente");throw Error("Error al cargar la galer\xeda. Int\xe9ntalo de nuevo")}}}},e=>{e.O(0,[8230,4587,2692,1331,4864,4951,4642,3160,636,6593,8792],()=>e(e.s=4480)),_N_E=e.O()}]);
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.