1import{c as xt,r as i,s as h,j as e,e as ve,m as Ee,b as ut,d as Ae,q as tt,M as ze,F as we,i as Oe,a8 as Pe,L as st,aj as Je,ah as We,ai as Xe,ag as bt,T as pt,o as ft,ak as ke,J as ht,A as gt,am as jt,k as vt,w as Te,R as _t,U as Le,C as de,X as Re,l as Nt,p as Ze,n as Ye,x as ye,z as yt}from"./index-Tma0Mwcy.js";import{C as wt}from"./CreateTicketForCustomerModal-Df3G3014.js";import{I as Et}from"./ImagePreview-BxgHJrJW.js";import{A as St,L as Ct}from"./LiveChatWindow-X5nhIyXh.js";import{I as Bt}from"./image-C7CAIH9C.js";import{F as kt}from"./file-fIj2sryZ.js";import{T as Tt}from"./tag-BJAd4O7g.js";import{D as qe}from"./download-DawZ4Ihw.js";import{C as at}from"./chevron-up-Cf7SOSM4.js";import{R as Mt}from"./RichTextEditor-CLvpYghu.js";import{P as At}from"./paperclip-CH8zH2Q4.js";import{S as Dt}from"./send-BWDiE6gO.js";import{C as It}from"./CreateCustomerForm-BBUyyVYT.js";import{C as it}from"./check-zeTZEJCf.js";import{l as rt,o as Ft}from"./billingDocuments-C0GpM1mv.js";import{P as Me}from"./plus-37iPIDp3.js";import{S as $t}from"./search-h_IVjVFZ.js";import{B as Ke}from"./building-BJkIyril.js";import{P as Pt}from"./phone-BALIkKLG.js";import{E as Lt}from"./external-link-djkVKw6X.js";import{S as Qe}from"./save-JGa7jTC3.js";import"./upload-LGCfK8A3.js";import"./user-plus-CDacRkDn.js";import"./Modal-DKk7Crit.js";import"./loader-CaeWBbPr.js";import"./sparkles-Dt7f5zSz.js";import"./check-circle-2-DN9WOha1.js";import"./rotate-ccw-D_wYjRqJ.js";import"./pushNotifications-Da3beEkJ.js";import"./pause-BhPE7CWu.js";import"./code-C4N3fYPP.js";import"./play-DKXRMTRb.js";/** 2 * @license lucide-react v0.344.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Rt=xt("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);function zt(t){const[n,x]=i.useState(null),[l,m]=i.useState(!0),[w,v]=i.useState(null),b=async()=>{try{const{data:c,error:p}=await h.from("tickets").select(` 7 *, 8 profiles:user_id ( 9 full_name, 10 email 11 ), 12 assignee:assignee_id ( 13 full_name 14 ), 15 ticket_groups:group_id ( 16 name 17 ), 18 customers:customer_id ( 19 email 20 ) 21 `).eq("id",t).single();if(p)throw console.error("Error loading ticket:",p),p;c&&x(c)}catch(c){throw console.error("Exception in loadTicket:",c),c}};return i.useEffect(()=>{(async()=>{try{m(!0),v(null),await b()}catch(d){console.error("Error loading ticket data:",d),v("Error al cargar los detalles del ticket")}finally{m(!1)}})();const p=h.channel(`ticket-${t}`).on("postgres_changes",{event:"*",schema:"public",table:"tickets",filter:`id=eq.${t}`},()=>{b()}).subscribe();return()=>{h.removeChannel(p)}},[t]),{ticket:n,loading:l,error:w,reload:b}}function Ot(t){const[n,x]=i.useState([]),[l,m]=i.useState(!1),[w,v]=i.useState(new Set),[b,c]=i.useState(new Set),p=async()=>{try{m(!0);const{data:u,error:g}=await h.from("ticket_messages").select(` 22 id, 23 message, 24 body_html, 25 body_text, 26 is_staff, 27 is_internal, 28 created_at, 29 user_id, 30 cc_emails, 31 bcc_emails, 32 from_email, 33 from_name, 34 to_email, 35 to_emails, 36 content_type, 37 content_type_detected, 38 profiles!ticket_messages_user_id_fkey ( 39 full_name, 40 email 41 ) 42 `).eq("ticket_id",t).order("created_at",{ascending:!1});if(g)throw console.error("Error loading messages:",g),g;if(u&&(x(u),u.length>0)){const S=u[0].id;v(new Set([S]))}}catch(u){throw console.error("Exception in loadMessages:",u),u}finally{m(!1)}},d=u=>{v(g=>{const S=new Set(g);return S.has(u)?S.delete(u):S.add(u),S})},o=u=>{c(g=>{const S=new Set(g);return S.has(u)?S.delete(u):S.add(u),S})};return i.useEffect(()=>{p();const u=h.channel(`ticket-messages-${t}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"ticket_messages",filter:`ticket_id=eq.${t}`},()=>{p()}).subscribe();return()=>{h.removeChannel(u)}},[t]),{messages:n,loading:l,expandedMessages:w,expandedEmailDetails:b,loadMessages:p,toggleMessageExpansion:d,toggleEmailDetails:o}}function qt(){const[t,n]=i.useState({}),[x,l]=i.useState(!1);return{messageAttachments:t,loading:x,loadMessageAttachments:async v=>{if(v.length!==0)try{l(!0);const{data:b,error:c}=await h.from("ticket_attachments").select("*").in("message_id",v);if(c){console.error("Error loading attachments:",c);return}if(b){const p={};for(const d of b){const o=d.file_path||d.storage_path;if(!d.file_url&&o){const{data:u}=h.storage.from("ticket-attachments").getPublicUrl(o);u&&(d.file_url=u.publicUrl)}p[d.message_id]||(p[d.message_id]=[]),p[d.message_id].push(d)}n(p)}}catch(b){console.error("Exception in loadMessageAttachments:",b)}finally{l(!1)}},downloadAttachment:async v=>{try{if(v.file_url){const p=document.createElement("a");p.href=v.file_url,p.download=v.file_name,p.target="_blank",document.body.appendChild(p),p.click(),document.body.removeChild(p);return}const b=v.file_path||v.storage_path;if(!b)return;const{data:c}=await h.storage.from("ticket-attachments").download(b);if(c){const p=URL.createObjectURL(c),d=document.createElement("a");d.href=p,d.download=v.file_name,document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(p)}}catch(b){console.error("Error downloading file:",b)}}}}function Ut(t,n){const[x,l]=i.useState(!1),[m,w]=i.useState(!1),[v,b]=i.useState(!1);return{updating:x,closing:m,startingChat:v,updateField:async(o,u)=>{try{l(!0);const{error:g}=await h.from("tickets").update({[o]:u}).eq("id",t);if(g)throw g;n&&n()}catch(g){throw console.error("Error updating ticket:",g),g}finally{l(!1)}},closeTicket:async()=>{try{w(!0);const{error:o}=await h.from("tickets").update({status:"resolved",resolved_at:new Date().toISOString()}).eq("id",t);if(o)throw o;n&&n()}catch(o){throw console.error("Error closing ticket:",o),o}finally{w(!1)}},startChat:async(o,u)=>{try{b(!0);const{data:g}=await h.from("chat_conversations").select("id").eq("ticket_id",t).maybeSingle();if(g)return g.id;const{data:S,error:k}=await h.from("chat_conversations").insert({user_id:o,customer_id:u,ticket_id:t,status:"active"}).select("id").single();if(k)throw k;return(S==null?void 0:S.id)||null}catch(g){throw console.error("Error starting chat:",g),g}finally{b(!1)}}}}function Gt(t){return t&&t.startsWith("image/")?e.jsx(Bt,{className:"w-4 h-4"}):e.jsx(kt,{className:"w-4 h-4"})}function Vt(t){if(!t||t===0)return"0 Bytes";const n=1024,x=["Bytes","KB","MB","GB"],l=Math.floor(Math.log(t)/Math.log(n));return Math.round(t/Math.pow(n,l)*100)/100+" "+x[l]}function Ht(t){return`SDB-${t||"---"}`}function Jt(t){return{waiting_team:"Esperando respuesta SedeBit",waiting_customer:"Esperando tu respuesta",resolved:"Resuelto",escalated:"Escalado",in_progress:"En Progreso",closed:"Cerrado"}[t]||t}function Wt(t){return{low:"Baja",medium:"Media",high:"Alta",urgent:"Urgente"}[t]||t}function Xt(t){return{technical_support:"Soporte Técnico",new_developments:"Nuevos Desarrollos",billing:"Facturación",sales_inquiry:"Consultas Comerciales",administration:"Administración"}[t]||t}function Zt(t){return{waiting_team:"bg-amber-50 text-amber-700 border-2 border-amber-200",waiting_customer:"bg-blue-50 text-blue-700 border-2 border-blue-200",in_progress:"bg-purple-50 text-purple-700 border-2 border-purple-200",escalated:"bg-red-50 text-red-700 border-2 border-red-200",resolved:"bg-green-50 text-green-700 border-2 border-green-200",closed:"bg-gray-50 text-gray-700 border-2 border-gray-200"}[t]||"bg-gray-50 text-gray-700 border-2 border-gray-200"}function Yt(t){return{low:"bg-gray-100 text-gray-700 border-2 border-gray-300",medium:"bg-blue-100 text-blue-700 border-2 border-blue-300",high:"bg-orange-100 text-orange-700 border-2 border-orange-300",urgent:"bg-red-100 text-red-700 border-2 border-red-300"}[t]||"bg-gray-100 text-gray-700 border-2 border-gray-300"}function Kt(t){return{technical_support:"bg-blue-100 text-blue-800 border-2 border-blue-300",new_developments:"bg-purple-100 text-purple-800 border-2 border-purple-300",billing:"bg-emerald-100 text-emerald-800 border-2 border-emerald-300",sales_inquiry:"bg-cyan-100 text-cyan-800 border-2 border-cyan-300",administration:"bg-slate-100 text-slate-800 border-2 border-slate-300"}[t]||"bg-gray-100 text-gray-800 border-2 border-gray-300"}function Be(t){const n=Math.floor(t/36e5),x=Math.floor(t%36e5/6e4);if(n===0)return`${x}m`;if(n<24)return`${n}h ${x}m`;{const l=Math.floor(n/24),m=n%24;return`${l}d ${m}h`}}function nt(t){const n=new Date(t),l=new Date().getTime()-n.getTime(),m=Math.floor(l/6e4);if(m<1)return"Ahora mismo";if(m<60)return`hace ${m}m`;const w=Math.floor(m/60);return w<24?`hace ${w}h`:`hace ${Math.floor(w/24)}d`}function Qt(t,n,x){const l=i.useMemo(()=>
42{if(!t)return null;const b=!!t.first_response_at,c=new Date(t.sla_first_response_due_at),p=t.first_response_at?new Date(t.first_response_at):new Date,d=new Date;if(b){const o=p<=c,u=Math.abs(p.getTime()-new Date(t.created_at).getTime());return{status:o?"ok":"overdue",label:o?"OK":"Vencido",time:Be(u),color:o?"bg-green-100 text-green-800 border-green-300":"bg-red-100 text-red-800 border-red-300"}}else{const o=d>c,u=Math.abs(d.getTime()-new Date(t.created_at).getTime());return{status:o?"overdue":"pending",label:o?"Vencido":"En Tiempo",time:Be(u),color:o?"bg-red-100 text-red-800 border-red-300":"bg-blue-100 text-blue-800 border-blue-300"}}},[t]),m=i.useMemo(()=>{if(!t)return null;const b=t.status==="resolved"&&t.resolved_at,c=new Date(t.sla_resolution_due_at),p=t.resolved_at?new Date(t.resolved_at):new Date,d=new Date;if(b){const o=p<=c,u=Math.abs(p.getTime()-new Date(t.created_at).getTime());return{status:o?"ok":"overdue",label:o?"OK":"Vencido",time:Be(u),color:o?"bg-green-100 text-green-800 border-green-300":"bg-red-100 text-red-800 border-red-300"}}else{const o=d>c,u=Math.abs(d.getTime()-new Date(t.created_at).getTime());return{status:o?"overdue":"pending",label:o?"Vencido":"En Tiempo",time:Be(u),color:o?"bg-red-100 text-red-800 border-red-300":"bg-blue-100 text-blue-800 border-blue-300"}}},[t]),w=i.useMemo(()=>{var c;if(n.length===0)return null;const b=n[0];return x&&b.user_id===x?null:b.is_staff&&b.user_id!==x?{type:"staff",label:`Respuesta ${((c=b.profiles)==null?void 0:c.full_name)||"Compañero"}`,time:b.created_at,icon:ve}:b.cc_emails&&b.cc_emails.length>0?{type:"cc",label:"Respuesta CC",time:b.created_at,icon:ve}:{type:"customer",label:"Respuesta Cliente",time:b.created_at,icon:ve}},[n,x]),v=i.useMemo(()=>{const b=n.filter(c=>!c.is_staff);return b.length>0?b[0]:null},[n]);return{firstResponseStatus:l,resolutionStatus:m,lastActivity:w,lastUserResponse:v}}function es({ticket:t,onClose:n,onCloseTicket:x,closing:l}){return e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-[#e5e7eb] bg-[#f8f9fb] sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("h2",{className:"text-2xl font-bold text-[#111827]",children:Ht(t.display_number)}),e.jsx("span",{className:`px-3 py-1 rounded-full text-sm font-medium ${Zt(t.status)}`,children:Jt(t.status)})]}),e.jsxs("div",{className:"flex items-center space-x-3",children:[x&&t.status!=="resolved"&&e.jsx("button",{onClick:x,disabled:l,className:"px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50",children:l?"Cerrando...":"Cerrar Ticket"}),e.jsx("button",{onClick:n,className:"p-2 hover:bg-[#f1f3f5] rounded-lg transition-colors",children:e.jsx(Ee,{className:"w-6 h-6 text-[#6b7280]"})})]})]})}function et({label:t,status:n}){return n?e.jsxs("div",{className:"flex items-center justify-between p-3 bg-[#f1f3f5] rounded-lg",children:[e.jsx("span",{className:"text-sm font-medium text-[#374151]",children:t}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("span",{className:`px-2 py-1 rounded text-xs font-medium border ${n.color}`,children:n.label}),e.jsx("span",{className:"text-xs text-[#6b7280]",children:n.time})]})]}):null}function ts({ticket:t,firstResponseStatus:n,resolutionStatus:x,lastActivity:l}){var m,w;return e.jsxs("div",{className:"w-80 border-l border-[#e5e7eb] bg-[#f1f3f5] p-6 overflow-y-auto",children:[e.jsx("h3",{className:"text-lg font-semibold text-[#111827] mb-4",children:"Información del Ticket"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-[#6b7280] uppercase",children:"Cliente"}),e.jsxs("div",{className:"mt-1 flex items-center space-x-2",children:[e.jsx(ve,{className:"w-4 h-4 text-[#9ca3af]"}),e.jsx("span",{className:"text-sm text-[#374151]",children:((m=t.profiles)==null?void 0:m.full_name)||((w=t.profiles)==null?void 0:w.email)||t.guest_email||"Sin asignar"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-[#6b7280] uppercase",children:"Prioridad"}),e.jsx("div",{className:"mt-1",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded text-xs font-medium ${Yt(t.priority)}`,children:Wt(t.priority)})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-[#6b7280] uppercase",children:"Tipo"}),e.jsx("div",{className:"mt-1",children:e.jsxs("span",{className:`inline-flex items-center space-x-1 px-2 py-1 rounded text-xs font-medium ${Kt(t.type)}`,children:[e.jsx(Tt,{className:"w-3 h-3"}),e.jsx("span",{children:Xt(t.type)})]})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-[#6b7280] uppercase",children:"Creado"}),e.jsxs("div",{className:"mt-1 flex items-center space-x-2",children:[e.jsx(ut,{className:"w-4 h-4 text-[#9ca3af]"}),e.jsx("span",{className:"text-sm text-[#374151]",children:new Date(t.created_at).toLocaleDateString("es-ES",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})})]})]}),l&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-[#6b7280] uppercase",children:"Ãltima Actividad"}),e.jsxs("div",{className:"mt-1 flex items-center space-x-2",children:[e.jsx(Ae,{className:"w-4 h-4 text-[#9ca3af]"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm text-[#374151]",children:l.label}),e.jsx("span",{className:"text-xs text-[#6b7280]",children:nt(l.time)})]})]})]}),t.assignee&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-[#6b7280] uppercase",children:"Asignado a"}),e.jsxs("div",{className:"mt-1 flex items-center space-x-2",children:[e.jsx(ve,{className:"w-4 h-4 text-[#9ca3af]"}),e.jsx("span",{className:"text-sm text-[#374151]",children:t.assignee.full_name})]})]}),e.jsxs("div",{className:"pt-4 border-t border-[#e5e7eb]",children:[e.jsx("h4",{className:"text-sm font-semibold text-[#111827] mb-3",children:"SLA"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(et,{label:"Primera Respuesta",status:n}),e.jsx(et,{label:"Resolución",status:x})]})]})]})]})}function ss({attachments:t,onDownload:n}){return t.length===0?null:e.jsx("div",{className:"mt-2 space-y-2",children:t.map(x=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-[#f1f3f5] rounded border border-[#e5e7eb] hover:bg-[#f1f3f5] transition-colors",children:[e.jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[Gt(x.file_type||x.mime_type),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[#111827] truncate",children:x.file_name}),e.jsx("p",{className:"text-xs text-[#6b7280]",children:Vt(x.file_size)})]})]}),e.jsx("button",{onClick:()=>n(x),className:"p-1 hover:bg-[#e9ecef] rounded transition-colors",title:"Descargar ar
42chivo",children:e.jsx(qe,{className:"w-4 h-4 text-[#6b7280]"})})]},x.id))})}function as({content:t,maxLines:n=5,className:x="",isInternal:l=!1}){const[m,w]=i.useState(!1),[v,b]=i.useState(!1),c=i.useRef(null);return i.useEffect(()=>{if(c.current){const d=parseInt(getComputedStyle(c.current).lineHeight)*n;b(c.current.scrollHeight>d)}},[t,n]),t?e.jsxs("div",{children:[e.jsx("div",{ref:c,className:`whitespace-pre-wrap leading-relaxed ${x} ${!m&&v?"overflow-hidden":m?"max-h-[300px] overflow-y-auto rounded border border-[#e5e7eb] p-3 bg-[#f1f3f5]":""}`,style:!m&&v?{display:"-webkit-box",WebkitLineClamp:n,WebkitBoxOrient:"vertical",overflow:"hidden"}:void 0,children:t}),v&&e.jsx("button",{onClick:()=>w(!m),className:`mt-2 text-sm font-semibold flex items-center gap-1 transition-colors ${l?"text-indigo-600 hover:text-indigo-700":"text-[#2563EB] hover:text-[#2563EB]"}`,children:m?e.jsxs(e.Fragment,{children:[e.jsx(at,{className:"w-4 h-4"}),"Ocultar"]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"w-4 h-4"}),"Ver más"]})})]}):null}function is({message:t,attachments:n,isExpanded:x,isEmailDetailsExpanded:l,isCurrentUser:m,onToggleExpand:w,onToggleEmailDetails:v,onDownloadAttachment:b}){var o;const c=t.is_staff,p=t.is_internal,d=((o=t.profiles)==null?void 0:o.full_name)||t.from_name||t.from_email||"Usuario";return e.jsx("div",{className:`flex ${m?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-3xl ${m?"bg-[#2563EB]/10":"bg-[#f8f9fb]"} rounded-lg shadow-none border border-[#e5e7eb] p-4`,children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center ${c?"bg-[#2563EB]/15":"bg-[#f1f3f5]"}`,children:e.jsx(ve,{className:`w-4 h-4 ${c?"text-[#2563EB]":"text-[#6b7280]"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[#111827]",children:d}),e.jsx("p",{className:"text-xs text-[#6b7280]",children:nt(t.created_at)})]})]}),p&&e.jsx("span",{className:"px-2 py-1 bg-yellow-100 text-yellow-800 text-xs font-medium rounded",children:"Interno"})]}),(t.to_emails||t.cc_emails||t.bcc_emails)&&e.jsxs("button",{onClick:v,className:"flex items-center space-x-1 text-xs text-[#6b7280] hover:text-[#374151] mb-2",children:[e.jsx(ze,{className:"w-3 h-3"}),e.jsx("span",{children:"Detalles del email"}),l?e.jsx(at,{className:"w-3 h-3"}):e.jsx(tt,{className:"w-3 h-3"})]}),l&&e.jsxs("div",{className:"mb-3 p-2 bg-[#f1f3f5] rounded text-xs space-y-1",children:[t.to_emails&&t.to_emails.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Para:"})," ",t.to_emails.join(", ")]}),t.cc_emails&&t.cc_emails.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"CC:"})," ",t.cc_emails.join(", ")]}),t.bcc_emails&&t.bcc_emails.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"BCC:"})," ",t.bcc_emails.join(", ")]})]}),e.jsx("div",{className:"prose prose-sm max-w-none",children:t.body_html?e.jsx("div",{dangerouslySetInnerHTML:{__html:t.body_html}}):e.jsx(as,{text:t.message,maxLength:300})}),n.length>0&&e.jsx(ss,{attachments:n,onDownload:b})]})})}function rs({ticket:t,messages:n,messageAttachments:x,expandedMessages:l,expandedEmailDetails:m,onToggleExpand:w,onToggleEmailDetails:v,onDownloadAttachment:b,currentUserId:c}){var d;const p=i.useRef(null);return i.useEffect(()=>{setTimeout(()=>{var o;(o=p.current)==null||o.scrollIntoView({behavior:"smooth"})},100)},[n.length]),n.length===0?e.jsx("div",{className:"flex-1 flex items-center justify-center text-[#6b7280]",children:e.jsx("p",{children:"No hay mensajes aún"})}):e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-4",children:[(t==null?void 0:t.description)&&e.jsx("div",{className:"flex justify-start",children:e.jsxs("div",{className:"max-w-[75%] bg-[#f8f9fb] rounded-2xl shadow-none border border-[#e5e7eb] p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(we,{className:"w-4 h-4 text-[#2563EB]"}),e.jsx("span",{className:"text-sm font-semibold text-[#111827]",children:((d=t.profiles)==null?void 0:d.full_name)||"De
42scripción del ticket"}),e.jsx("span",{className:"text-xs text-[#9ca3af]",children:new Date(t.created_at).toLocaleTimeString("es-ES",{hour:"2-digit",minute:"2-digit"})})]}),e.jsx("p",{className:"text-sm text-[#374151] whitespace-pre-wrap leading-relaxed",children:t.description}),e.jsx("p",{className:"text-xs text-[#9ca3af] mt-2",children:new Date(t.created_at).toLocaleDateString("es-ES",{day:"numeric",month:"short",year:"numeric"})})]})}),[...n].reverse().map(o=>e.jsx(is,{message:o,attachments:x[o.id]||[],isExpanded:l.has(o.id),isEmailDetailsExpanded:m.has(o.id),isCurrentUser:c===o.user_id,onToggleExpand:()=>w(o.id),onToggleEmailDetails:()=>v(o.id),onDownloadAttachment:b},o.id)),e.jsx("div",{ref:p})]})}function ns({onSend:t,sending:n,replyType:x,onReplyTypeChange:l}){const[m,w]=i.useState(""),[v,b]=i.useState(""),[c,p]=i.useState([]),[d,o]=i.useState([]),[u,g]=i.useState([]),[S,k]=i.useState([]),[a,y]=i.useState(!1),[E,M]=i.useState(!1),G=i.useRef(null),H=async()=>{!m.trim()&&c.length===0||(await t(m,v,c,d,u,S),w(""),b(""),p([]),o([]),g([]),k([]),y(!1),M(!1))},J=B=>{B.target.files&&p(Array.from(B.target.files))},W=B=>{p(X=>X.filter((V,me)=>me!==B))};return e.jsxs("div",{className:"border-t border-[#e5e7eb] bg-[#f8f9fb] p-4",children:[e.jsxs("div",{className:"flex space-x-2 mb-3",children:[e.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1 rounded text-sm ${x==="all"?"bg-[#2563EB] text-white":"bg-[#f1f3f5] text-[#374151]"}`,children:"Responder a Todos"}),e.jsx("button",{onClick:()=>l("reply"),className:`px-3 py-1 rounded text-sm ${x==="reply"?"bg-[#2563EB] text-white":"bg-[#f1f3f5] text-[#374151]"}`,children:"Responder"}),e.jsx("button",{onClick:()=>l("internal"),className:`px-3 py-1 rounded text-sm ${x==="internal"?"bg-yellow-600 text-white":"bg-[#f1f3f5] text-[#374151]"}`,children:"Nota Interna"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(Mt,{value:m,onChange:(B,X)=>{w(B),b(X)},placeholder:"Escribe tu respuesta..."})}),c.length>0&&e.jsx("div",{className:"mb-3 space-y-2",children:c.map((B,X)=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-[#f1f3f5] rounded",children:[e.jsx("span",{className:"text-sm text-[#374151]",children:B.name}),e.jsx("button",{onClick:()=>W(X),className:"p-1 hover:bg-[#e9ecef] rounded",children:e.jsx(Ee,{className:"w-4 h-4 text-[#6b7280]"})})]},X))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{ref:G,type:"file",multiple:!0,onChange:J,className:"hidden"}),e.jsx("button",{onClick:()=>{var B;return(B=G.current)==null?void 0:B.click()},className:"p-2 hover:bg-[#f1f3f5] rounded transition-colors",title:"Adjuntar archivos",children:e.jsx(At,{className:"w-5 h-5 text-[#6b7280]"})}),e.jsx(St,{text:m,onImproved:B=>w(B)})]}),e.jsxs("button",{onClick:H,disabled:n||!m.trim()&&c.length===0,className:"flex items-center space-x-2 px-4 py-2 bg-[#2563EB] text-white rounded-lg hover:bg-[#2a63e0] disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(Dt,{className:"w-4 h-4"}),e.jsx("span",{children:n?"Enviando...":"Enviar"})]})]})]})}function ls({ticketId:t,onClose:n,onUpdate:x}){const{user:l}=Oe(),{ticket:m,loading:w,error:v,reload:b}=zt(t),{messages:c,expandedMessages:p,expandedEmailDetails:d,loadMessages:o,toggleMessageExpansion:u,toggleEmailDetails:g}=Ot(t),{messageAttachments:S,loadMessageAttachments:k,downloadAttachment:a}=qt(),{closing:y,startingChat:E,closeTicket:M,startChat:G}=Ut(t,x),H=Qt(m,c,l==null?void 0:l.id),[J,W]=i.useState(!1),[B,X]=i.useState("all"),[V,me]=i.useState(null),[ae,ne]=i.useState(null);i.useEffect(()=>(document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",()=>{document.documentElement.style.overflow="",document.body.style.overflow=""}),[]),i.useEffect(()=>{if(c.length>0){const O=c.map(r=>r.id);k(O)}},[c]);const te=async(O,r,N,q,A,U)=>{var Z,D;if(!(!O.trim()&&N.length===0)){W(!0);try{const{data:F}=await h.from("profiles").select("full_name, email, role").eq("id",l==null?void 0:l.id).maybeSingle(),Se=(F==null?void 0:F.email)||(l==null?void 0:l.email)||null,ie=(F==null?void 0:F.full_name)||((Z=l==null?void 0:l.user_metadata)==null?void 0:Z.full_name)||((D=l==null?void 0:l.email)==null?void 0:D.split("@")[0])||null,fe=["admin","super_admin","staff","support"].includes((F==null?void 0:F.role)||""),f=B==="internal";let C=null,$=null,j=[],T=null;const I=r&&r!==O&&r.includes("<"),_e=I?"text/html":"text/plain",he=I?r:null;B==="all"?(C=A.length>0?A:null,$=U.length>0?U:null,j=q.length>0?q:[],T=j.length>0?j[0]:null):B==="reply"&&(c.length>0?(T=c[c.length-1].from_email||(m==null?void 0:m.guest_email),T&&(j=[T])):m&&(T=m.guest_email,T&&(j=[T])),C=A.length>0?A:null,$=U.length>0?U:null);const{data:xe,error:le}=await h.from("ticket_messages").insert({ticket_id:t,user_id:l==null?void 0:l.id,message:O.trim()||"(Archivo adjunto)",body_html:he,is_staff:fe,is_internal:f,cc_emails:C,bcc_emails:$,to_email:T,to_emails:j,from_email:Se,from_name:ie,content_type:_e}).select().single();if(le)throw console.error("[ERROR] Failed to insert message:",le),le;if(N.length>0&&xe&&l)for(const P of N){const ge=`${l.id}/${t}/${Date.now()}_${P.name}`,{error:oe}=await h.storage.from("ticket-attachments").upload(ge,P);if(oe){console.error("Error uploading file:",oe);continue}const{data:se}=h.storage.from("ticket-attachments").getPublicUrl(ge);await h.from("ticket_attachments").insert({message_id:xe.id,ticket_id:t,file_name:P.name,storage_path:ge,file_size:P.size,mime_type:P.type,uploaded_by:l.id,file_url:(se==null?void 0:se.publicUrl)||""})}if(I&&xe&&l&&he){const oe=new DOMParser().parseFromString(he,"text/html").querySelectorAll('img[data-inline="true"]');for(const se of Array.from(oe)){const ue=se.getAttribute("data-file-path"),De=se.getAttribute("data-public-url");if(ue){const Ie=ue.split("/").pop()||"inline-image.png",Y=se.getAttribute("src")||"";let Ce="image/png";if(Y.startsWith("data:")){const re=Y.match(/^data:([^;]+);/);re&&(Ce=re[1])}let Ne=De;if(!Ne){const{data:re}=h.storage.from("ticket-attachments").getPublicUrl(ue);Ne=(re==null?void 0:re.publicUrl)||null}await h.from("ticket_attachments").insert({message_id:xe.id,ticket_id:t,file_name:Ie,storage_path:ue,file_size:0,mime_type:Ce,uploaded_by:l.id,file_url:Ne||"",inline:!0})}}}!f&&fe&&(m==null?void 0:m.status)==="waiting_team"&&await h.from("tickets").update({status:"waiting_customer"}).eq("id",t),await o(),await b(),x&&x()}catch(F){console.error("Error sending message:",F)}finally{W(!1)}}},be=async()=>{await M(),await b(),x&&x()},pe=async()=>
42{if(!l||!m)return;const O=await G(l.id,m.customer_id);O&&ne(O)};return w?Pe.createPortal(e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:e.jsxs("div",{className:"bg-[#f8f9fb] rounded-lg p-8",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"}),e.jsx("p",{className:"mt-4 text-[#6b7280]",children:"Cargando ticket..."})]})}),document.body):v||!m?Pe.createPortal(e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:e.jsxs("div",{className:"bg-[#f8f9fb] rounded-lg p-8 max-w-md",children:[e.jsx("h3",{className:"text-lg font-semibold text-red-400 mb-2",children:"Error"}),e.jsx("p",{className:"text-[#6b7280] mb-4",children:v||"No se pudo cargar el ticket"}),e.jsx("button",{onClick:n,className:"px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700",children:"Cerrar"})]})}),document.body):Pe.createPortal(e.jsxs("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",children:[e.jsxs("div",{className:"bg-[#f8f9fb] rounded-lg shadow-xl w-full max-w-7xl h-[90vh] flex flex-col",children:[e.jsx(es,{ticket:m,onClose:n,onCloseTicket:be,onStartChat:pe,closing:y,startingChat:E}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsxs("div",{className:"flex-1 flex flex-col",children:[e.jsx(rs,{ticket:m,messages:c,messageAttachments:S,expandedMessages:p,expandedEmailDetails:d,onToggleExpand:u,onToggleEmailDetails:g,onDownloadAttachment:a,currentUserId:l==null?void 0:l.id}),e.jsx(ns,{onSend:te,sending:J,replyType:B,onReplyTypeChange:X})]}),e.jsx(ts,{ticket:m,firstResponseStatus:H.firstResponseStatus,resolutionStatus:H.resolutionStatus,lastActivity:H.lastActivity})]})]}),V&&e.jsx(Et,{src:V.src,alt:V.alt,onClose:()=>me(null)}),ae&&e.jsx(Ct,{conversationId:ae,onClose:()=>ne(null)})]}),document.body)}const os=[{key:"soporte_bitrix24",label:"Soporte Bitrix24"},{key:"smartbot_ia",label:"SmartBot IA"},{key:"gestorforms",label:"GestorForms"},{key:"smartcalendar",label:"SmartCalendar"},{key:"smartmarketing",label:"SmartMarketing"},{key:"smartcf7",label:"SmartCF7"},{key:"azlant",label:"Azlant"}];function cs({customerId:t,editable:n,onCountChange:x}){const[l,m]=i.useState({}),[w,v]=i.useState(!0),[b,c]=i.useState(null);i.useEffect(()=>{let d=!1;return(async()=>{v(!0);const{data:o}=await h.from("customer_services").select("service_key, is_active").eq("customer_id",t);if(d)return;const u={};(o||[]).forEach(g=>{u[g.service_key]=g.is_active}),m(u),x==null||x(Object.values(u).filter(Boolean).length),v(!1)})(),()=>{d=!0}},[t]);const p=async d=>{if(!n||b)return;const o=!l[d];c(d);const{error:u}=await h.rpc("admin_set_customer_service",{p_customer_id:t,p_service_key:d,p_is_active:o});if(c(null),u)return;const g={...l,[d]:o};m(g),x==null||x(Object.values(g).filter(Boolean).length)};return e.jsxs("div",{className:"bg-white rounded-2xl border border-[#e5e7eb] p-5",children:[e.jsxs("h3",{className:"text-base font-bold text-[#111827] flex items-center gap-2 mb-4",children:[e.jsx(Rt,{className:"w-4 h-4 text-[#2563EB]"})," Servicios contratados"]}),w?e.jsx("div",{className:"py-6 text-center text-sm text-[#9ca3af]",children:e.jsx(st,{className:"w-5 h-5 animate-spin inline"})}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:os.map(d=>{const o=!!l[d.key];return e.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2.5 rounded-xl border border-[#e5e7eb] bg-[#f8f9fb]",children:[e.jsx("span",{className:"text-sm font-medium text-[#374151]",children:d.label}),n?e.jsx("button",{type:"button",role:"switch","aria-checked":o,onClick:()=>p(d.key),disabled:b===d.key,"aria-label":`${d.label} ${o?"activo":"inactivo"}`,style:{position:"relative",flex:"0 0 auto",width:40,height:22,minWidth:40,minHeight:22,padding:0,border:"none",borderRadius:9999,cursor:b===d.key?"default":"pointer",backgroundColor:o?"#10b981":"#cbd5e1",opacity:b===d.key?.6:1,transition:"background-color .18s ease"},children:e.jsx("span",{style:{position:"absolute",top:3,left:3,width:16,height:16,borderRadius:"50%",backgroundColor:"#fff",boxShadow:"0 1px 2px rgba(0,0,0,.25)",transform:o?"translateX(18px)":"translateX(0)",transition:"transform .18s ease"}})}):e.jsxs("span",{className:`inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full ${o?"bg-emerald-50 text-emerald-700":"bg-[#f1f3f5] text-[#6b7280]"}`,children:[o?e.jsx(it,{className:"w-3 h-3"}):e.jsx(Ee,{className:"w-3 h-3"}),o?"Activo":"Inactivo"]})]},d.key)})})]})}function ds({customerId:t,onDisponibleChange:n}){var y;const[x,l]=i.useState([]),[m,w]=i.useState(null),[v,b]=i.useState(!0);i.useEffect(()=>{let E=!1;return(async()=>{var W;b(!0);const[{data:M},{data:G}]=await Promise.all([h.from("customer_packages").select("id, status, total_hours, used_hours, remaining_hours, expiration_date, purchase_date, snapshot_name, appointment_packages:package_id ( name, color )").eq("customer_id",t),h.from("bolsa_movimientos").select("fecha, created_at, tipo").eq("customer_id",t).in("tipo",["trabajo","reunion","no_presentacion"]).order("created_at",{ascending:!1}).limit(1)]);if(E)return;const H=M||[];l(H),w(G&&((W=G[0])==null?void 0:W.fecha)||null);const J=Je(H);n==null||n(J,H.length===0),b(!1)})(),()=>{E=!0}},[t]);const c=x.filter(E=>We(E)==="activa"),p=c.reduce((E,M)=>E+Xe(M.total_hours),0),d=c.reduce((E,M)=>E+Xe(M.used_hours),0),o=Je(x),u=((y=bt(c)[0])==null?void 0:y.expiration_date)||null,g=x.length===0?"sin_bolsa":c.length>0?"activa":x.some(E=>We(E)==="caducada")?"caducada":"sin_saldo",S={activa:{label:"Activa",chip:"bg-emerald-50 text-emerald-700"},sin_saldo:{label:"Sin saldo",chip:"bg-red-50 text-red-700"},caducada:{label:"Caducada",chip:"bg-red-50 text-red-700"},sin_bolsa:{label:"Sin bolsa",chip:"bg-[#f1f3f5] text-[#6b7280]"}},k=[];if(g==="caducada"&&k.push("Bolsa caducada"),g==="sin_saldo"&&k.push("Sin saldo disponible"),g==="activa"){const E=jt(p,o);if(E===0?k.push("Sin saldo disponible"):E===10?k.push("Queda menos del 10 %"):E===25&&k.push("Queda menos del 25 %"),u){const M=Math.ceil((new Date(u).getTime()-Date.now())/864e5);M>=0&&M<=30&&k.push(`Caduca en ${M}
42 dÃa${M===1?"":"s"}`)}}const a=E=>E?new Date(E).toLocaleDateString("es-ES",{day:"2-digit",month:"2-digit",year:"numeric"}):"â";return e.jsxs("div",{className:"bg-white rounded-2xl border border-[#e5e7eb] p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-4",children:[e.jsxs("h3",{className:"text-base font-bold text-[#111827] flex items-center gap-2",children:[e.jsx(pt,{className:"w-4 h-4 text-[#2563EB]"})," Bolsa de Horas"]}),e.jsx("span",{className:`inline-block px-2.5 py-1 rounded-full text-xs font-semibold ${S[g].chip}`,children:S[g].label})]}),v?e.jsx("div",{className:"py-6 text-center text-sm text-[#9ca3af]",children:e.jsx(st,{className:"w-5 h-5 animate-spin inline"})}):g==="sin_bolsa"?e.jsx("p",{className:"text-sm text-[#6b7280]",children:"Este cliente no tiene ninguna bolsa de horas asignada."}):e.jsxs(e.Fragment,{children:[k.length>0&&e.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:k.map(E=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-amber-50 text-amber-700",children:[e.jsx(ft,{className:"w-3.5 h-3.5"}),E]},E))}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-1.5 text-sm",children:[e.jsx(je,{label:"Bolsas activas",valor:`${c.length}`}),e.jsx(je,{label:"Contratadas",valor:ke(p)}),e.jsx(je,{label:"Consumidas",valor:ke(d)}),e.jsx(je,{label:"Disponibles",valor:ke(o),destacado:!0}),e.jsx(je,{label:"Próxima caducidad",valor:a(u)}),e.jsx(je,{label:"Ãltimo consumo",valor:a(m)})]})]}
42),e.jsxs(ht,{to:`/admin/bolsa-horas?customer_id=${t}`,className:"mt-4 inline-flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-[#2563EB] bg-[#2563EB]/10 hover:bg-[#2563EB]/20 transition-colors",children:["Ver gestión completa ",e.jsx(gt,{className:"w-4 h-4"})]})]})}function je({label:t,valor:n,destacado:x=!1}){return e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[#6b7280]",children:t}),e.jsx("span",{className:x?"font-bold text-[#111827]":"font-medium text-[#374151]",children:n})]})}const lt={ES:"España",FR:"Francia",DE:"Alemania",IT:"Italia",PT:"Portugal",GB:"Reino Unido",US:"Estados Unidos",NL:"PaÃses Bajos",BE:"Bélgica",CH:"Suiza",AT:"Austria",PL:"Polonia",SE:"Suecia",NO:"Noruega",DK:"Dinamarca",FI:"Finlandia",IE:"Irlanda",LU:"Luxemburgo",GR:"Grecia",CZ:"República Checa",RO:"RumanÃa",HU:"HungrÃa",BG:"Bulgaria",HR:"Croacia",SK:"Eslovaquia",SI:"Eslovenia",LT:"Lituania",LV:"Letonia",EE:"Estonia",CY:"Chipre",MT:"Malta"},ot={A:"Alicante",AB:"Albacete",AL:"AlmerÃa",AV:"Ãvila",B:"Barcelona",BA:"Badajoz",BI:"Bizkaia",BU:"Burgos",C:"A Coruña",CA:"Cádiz",CC:"Cáceres",CE:"Ceuta",CO:"Córdoba",CR:"Ciudad Real",CS:"Castellón",CU:"Cuenca",GC:"Las Palmas",GI:"Girona",GR:"Granada",GU:"Guadalajara",H:"Huelva",HU:"Huesca",J:"Jaén",L:"Lleida",LE:"León",LO:"La Rioja",LU:"Lugo",M:"Madrid",MA:"Málaga",ML:"Melilla",MU:"Murcia",NA:"Navarra",O:"Asturias",OR:"Ourense",P:"Palencia",PM:"Islas Baleares",PO:"Pontevedra",S:"Cantabria",SA:"Salamanca",SE:"Sevilla",SG:"Segovia",SO:"Soria",SS:"Gipuzkoa",T:"Tarragona",TE:"Teruel",TF:"Santa Cruz de Tenerife",TO:"Toledo",V:"Valencia",VA:"Valladolid",VI:"Ãlava",Z:"Zaragoza",ZA:"Zamora"},ms=t=>t?lt[t.toUpperCase()]||t:"No informado",xs=t=>t?ot[t.toUpperCase()]||t:"No informado";function Hs(){Oe();const[t,n]=i.useState([]),[x,l]=i.useState([]),[m,w]=i.useState(!0),[v,b]=i.useState(!1),[c,p]=i.useState(""),[d,o]=i.useState("all"),[u,g]=i.useState("all"),[S,k]=i.useState(null),[a,y]=i.useState(""),[E,M]=i.useState(null),[G,H]=i.useState(""),[J,W]=i.useState(!1),[B,X]=i.useState(!1);i.useEffect(()=>{V()},[]),i.useEffect(()=>{me()},[t,c,d,u]);const V=async()=>{try{const{data:r,error:N}=await h.from("customers").select(` 43 *, 44 company_users!company_users_customer_id_fkey(role, user_id) 45 `).is("deleted_at",null).order("created_at",{ascending:!1});if(N)throw N;const q=new Set;(r||[]).forEach(f=>{f.user_id&&q.add(f.user_id),(f.company_users||[]).forEach(C=>{C.user_id&&q.add(C.user_id)})});const A=Array.from(q);let U=new Map;if(A.length>0){const{data:f}=await h.from("profiles").select("id, role").in("id",A);(f||[]).forEach(C=>{U.set(C.id,C.role)})}const{data:Z}=await h.from("company_users").select(` 46 user_id, 47 customer_id, 48 role, 49 customers!company_users_customer_id_fkey( 50 id, 51 name, 52 email 53 ), 54 profiles!company_users_user_id_fkey( 55 id, 56 email, 57 full_name, 58 role 59 ) 60 `).eq("role","member"),D=new Set((r||[]).map(f=>f.user_id).filter(Boolean)),F=(Z||[]).filter(f=>!D.has(f.user_id)).map(f=>{var C,$,j,T,I;return{id:`member-${f.user_id}`,user_id:f.user_id,email:((C=f.profiles)==null?void 0:C.email)||"",name:(($=f.profiles)==null?void 0:$.full_name)||((j=f.profiles)==null?void 0:j.email)||"Sin nombre",is_active:!0,account_role:"member",profile_role:(T=f.profiles)==null?void 0:T.role,company_users:[{role:"member"}],member_of_customer_id:f.customer_id,member_of_customer_name:(I=f.customers)==null?void 0:I.name,created_at:null,is_virtual_member:!0}}),ie=[...(r||[]).map(f=>{let C=null;const $=(f.company_users||[]).find(I=>I.user_id),j=!!(f.user_id||$);if(f.user_id&&f.company_users){const I=f.company_users.find(_e=>_e.user_id===f.user_id);C=(I==null?void 0:I.role)||null}!C&&$&&(C=$.role==="owner"?"owner":$.role),!C&&f.account_type&&(C=f.account_type==="responsible"?"owner":f.account_type);const T=f.user_id||($==null?void 0:$.user_id);return{...f,billing_address:f.billing_address||f.billing_line1,billing_province:f.billing_province||f.billing_state,billing_fiscal_country:f.billing_fiscal_country||f.billing_country,billing_company_name:f.billing_company_name||f.name,account_role:C,profile_role:T?U.get(T):null,is_virtual_member:!1,has_account:j}}),...F],{data:{session:fe}}=await h.auth.getSession();if(!fe){n(ie.map(f=>({...f,total_spent:0,invoice_count:0}))),w(!1);return}try{const f=await rt({limit:1e3}),C=new Map;for(const j of f){const T=j.stripe_customer_id||"";if(!T)continue;const I=C.get(T)??{spent:0,count:0};I.count++,j.type==="invoice"&&(I.spent+=j.amount_cents),C.set(T,I)}const $=ie.map(j=>{const T=C.get(j.stripe_customer_id||"")??{spent:0,count:0};return{...j,total_spent:T.spent,invoice_count:T.count}});n($)}catch(f){console.error("Error loading invoices:",f),n(ie.map(C=>({...C,total_spent:0,invoice_count:0})))}}catch(r){console.error("Error loading customers:",r)}finally{w(!1)}},me=()=>{let r=t;c&&(r=r.filter(N=>{var q,A,U;return((q=N.name)==null?void 0:q.toLowerCase().includes(c.toLowerCase()))||((A=N.email)==null?void 0:A.toLowerCase().includes(c.toLowerCase()))||((U=N.company)==null?void 0:U.toLowerCase().includes(c.toLowerCase()))})),d!=="all"&&(r=r.filter(N=>N.is_active===(d==="active"))),u!=="all"&&(u==="admin_app"?r=r.filter(N=>N.profile_role==="admin"||N.profile_role==="super_admin"):u==="member"?r=r.filter(N=>N.account_role==="member"||N.is_virtual_member):u==="responsible"?r=r.filter(N=>N.account_role==="owner"||N.account_type==="responsible"&&!N.is_virtual_member):r=r.filter(N=>N.account_role===u)),l(r)},ae=async()=>{b(!0),y("");try{const N=await(await fetch("https://zsmlmujjwbwvhplnuzke.supabase.co/functions/v1/sync-stripe-customers",{method:"POST",headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InpzbWxtdWpqd2J3dmhwbG51emtlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjYxNjgzNjcsImV4cCI6MjA4MTc0NDM2N30.XO0Zyi4TdWoBzeTI3bPDRYUT2BrFb-QB5zj3UHNv3ng","Content-Type":"application/json"}})).json();N.success?(y(`Sincronizados: ${N.synced} de ${N.total} clientes`),await V()):y("Error en la sincronización")}catch(r){console.error("Error syncing:",r),y("Error al sincronizar con Stripe")}finally{b(!1),setTimeout(()=>y(""),5e3)}},ne=async(r,N,q)=>{const{data:A,error:U}=await h.functions.invoke("team-admin",{body:{action:"set_customer_active",customer_id:r,activo:N,motivo:q}});return!U&&(A==null?void 0:A.ok)===!0},te=async r=>{if(r.is_active){M(r),H("");return}await ne(r.id,!0,"")&&V()},be=async()=>
60{if(!E||!G.trim())return;W(!0);const r=await ne(E.id,!1,G.trim());W(!1),r&&(M(null),V())},pe=()=>{const r=["Nombre","Email","Teléfono","Empresa","Estado","Gasto Total","Facturas","Fecha Creación"],N=x.map(D=>[D.name||"",D.email||"",D.phone||"",D.company||"",D.is_active?"Activo":"Inactivo",((D.total_spent||0)/100).toFixed(2),D.invoice_count||0,new Date(D.created_at).toLocaleDateString()]),q=[r,...N].map(D=>D.join(",")).join(` 61`),A=new Blob([q],{type:"text/csv"}),U=window.URL.createObjectURL(A),Z=document.createElement("a");Z.href=U,Z.download=`clientes_${new Date().toISOString().split("T")[0]}.csv`,Z.click()},O={total:t.length,responsible:t.filter(r=>r.account_role==="owner"||r.account_type==="responsible"&&!r.is_virtual_member).length,members:t.filter(r=>r.account_role==="member"||r.is_virtual_member).length,inactive:t.filter(r=>!r.is_active).length};return m?e.jsx(vt,{message:"Cargando clientes..."}):S?e.jsx(us,{customer:S,onBack:()=>{k(null),V()},onUpdate:V}):e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[E&&e.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4",children:[e.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm",onClick:()=>!J&&M(null)}),e.jsxs("div",{className:"relative w-full max-w-md bg-white rounded-2xl shadow-2xl border border-[#e5e7eb] p-5",children:[e.jsx("h2",{className:"text-base font-bold text-[#111827] mb-1",children:"Desactivar cliente"}),e.jsxs("p",{className:"text-sm text-[#6b7280] mb-3",children:["«",E.name||E.email,"» quedará inactivo y se bloqueará el acceso de todos sus usuarios del portal. Se conserva todo el histórico (tickets, facturas, usuarios). Podrás reactivarlo y volverán solo los usuarios que estaban activos ahora."]}),e.jsx("label",{className:"block text-xs font-semibold text-[#374151] mb-1",children:"Motivo *"}),e.jsx("textarea",{value:G,onChange:r=>H(r.target.value),rows:3,className:"w-full px-3 py-2 rounded-[10px] border border-[#e5e7eb] text-sm focus:border-[#2563EB] focus:ring-1 focus:ring-[#2563EB]/30 outline-none",placeholder:"Motivo de la desactivación"}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx("button",{onClick:()=>M(null),disabled:J,className:"flex-1 px-4 py-2.5 rounded-xl text-sm font-semibold text-[#374151] bg-[#f1f3f5] hover:bg-[#e9ecef]",children:"Cancelar"}),e.jsx("button",{onClick:be,disabled:J||!G.trim(),className:"flex-1 px-4 py-2.5 rounded-xl text-sm font-semibold text-white bg-red-600 hover:bg-red-700 disabled:opacity-50",children:J?"Desactivandoâ¦":"Desactivar"})]})]})]}),e.jsxs("div",{className:"flex items-start justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-[#111827] mb-2 tracking-tight",children:"Gestión de Clientes"}),e.jsx("p",{className:"text-sm text-[#6b7280]",children:"Administra y da seguimiento a tus clientes"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>X(!0),className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-[12px] text-sm font-semibold text-white bg-gradient-to-r from-[#2563EB] to-[#163168] hover:from-[#152f5f] hover:to-[#0f1f3d] hover:scale-105 transition-all duration-300",children:[e.jsx(Me,{className:"w-4 h-4"}),"Nuevo cliente"]}),e.jsxs("button",{onClick:()=>window.location.hash="#admin-trash",className:"px-4 py-2.5 bg-[#f8f9fb] hover:bg-[#f1f3f5] text-[#374151] text-sm font-semibold rounded-lg border border-[#e5e7eb] transition-colors flex items-center gap-2",children:[e.jsx(Te,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Papelera"})]}),e.jsxs("button",{onClick:pe,className:"px-4 py-2.5 bg-[#f8f9fb] hover:bg-[#f1f3f5] text-[#374151] text-sm font-semibold rounded-lg border border-[#e5e7eb] transition-colors flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Exportar"})]}),e.jsxs("button",{onClick:ae,disabled:v,className:"px-4 py-2.5 bg-[#2563EB] hover:bg-[#2a63e0] text-white text-sm font-semibold rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(_t,{className:`w-4 h-4 ${v?"animate-spin":""}`}),v?"Sincronizando...":"Sincronizar"]})]})]}),a&&e.jsx("div",{className:"bg-[#2563EB]/10 border border-[#2563EB]/20 text-[#2563EB] px-4 py-3 rounded-lg text-sm font-medium",children:a}),e.jsx("div",{className:"bg-[#f8f9fb] border border-[#e5e7eb] rounded-lg shadow-none p-6",children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("button",{onClick:()=>{o("all"),g("all")},className:`p-3 rounded-lg border-2 transition-all hover:scale-105 ${d==="all"&&u==="all"?"border-[#e5e7eb] bg-[#f1f3f5]":"border-[#e5e7eb] hover:border-[#e5e7eb]"}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(Le,{className:"w-3.5 h-3.5 text-[#6b7280]"}),e.jsx("span",{className:"text-xs font-semibold text-[#6b7280] uppercase",children:"Todos"})]}),e.jsx("p",{className:"text-xl font-bold text-[#111827]",children:O.total})]}),e.jsxs("button",{onClick:()=>{g("responsible"),o("all")},className:`p-3 rounded-lg border-2 transition-all hover:scale-105 ${u==="responsible"?"border-blue-300 bg-[#2563EB]/10":"border-[#2563EB]/20 hover:border-[#2563EB]/40"}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(de,{className:"w-3.5 h-3.5 text-[#2563EB]"}),e.jsx("span",{className:"text-xs font-semibold text-[#2563EB] uppercase",children:"Responsables"})]}),e.jsx("p",{className:"text-xl font-bold text-[#2563EB]",children:O.responsible})]}),e.jsxs("button",{onClick:()=>{g("member"),o("all")},className:`p-3 rounded-lg border-2 transition-all hover:scale-105 ${u==="member"?"border-[#e5e7eb] bg-[#f1f3f5]":"border-[#e5e7eb] hover:border-[#e5e7eb]"}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(Le,{className:"w-3.5 h-3.5 text-[#6b7280]"}),e.jsx("span",{className:"text-xs font-semibold text-[#6b7280] uppercase",children:"Miembros"})]}),e.jsx("p",{className:"text-xl font-bold text-[#111827]",children:O.members})]}),e.jsxs("button",{onClick:()=>{o("inactive"),g("all")},className:`p-3 rounded-lg border-2 transition-all hover:scale-105 ${d==="inactive"?"border-white/[0.15] bg-[#f1f3f5]":"border-[#e5e7eb] hover:border-[#e5e7eb]"}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(Re,{className:"w-3.5 h-3.5 text-[#6b7280]"}),e.jsx("span",{className:"text-xs font-semibold text-[#6b7280] uppercase",children:"Inactivos"})]}),e.jsx("p",{className:"text-xl font-bold text-[#6b7280]",children:O.inactive})]})]})}),e.jsx("div",{className:"bg-[#f8f9fb] rounded-xl border border-[#e5e7eb] p-4",children:e.jsxs("div",{className:"flex gap-3 flex-col sm:flex-row",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx($t,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#9ca3af]"}),e.jsx("input",{type:"text",placeholder:"Buscar clientes...",value:c,onChange:r=>p(r.target.value),className:"w-full pl-10 pr-3 py-2 bg-[#f1f3f5] border border-[#e5e7eb] rounded-lg text-sm text-[#374151] placeholder:text-[#9ca3af] focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-[#f8f9fb] transition-all"})]}),e.jsxs("select",{value:d,onChange:r=>o(r.target.value),className:"px-4 py-2 bg-[#f1f3f5] border border-[#e5e7eb] rounded-lg text-sm text-[#374151] focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-[#f8f9fb] transition-all",children:[e.jsx("option",{value:"all",children:"Todos los estados"}),e.jsx("option",{value:"active",children:"Activo"}),e.jsx("option",{value:"inactive",children:"Inactivo"})]}),e.jsxs("select",{value:u,onChange:r=>g(r.target.value),className:"px-4 py-2 bg-[#f1f3f5] border border-[#e5e7eb] rounded-lg text-sm text-[#374151] focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-[#f8f9fb] transition-all",children:[e.jsx("option",{value:"all",children:"Todos los tipos"}),e.jsx("option",{value:"admin_app",children:"Admin App"}),e.jsx("option",{value:"responsible",children:"Responsables"}),e.jsx("option",{value:"member",children:"Miembros"})]})]})}),e.jsxs("div",{className:"bg-[#f8f9fb] rounded-xl border border-[#e5e7eb] overflow-hidden",children:[e.jsx("div",{className:"p-5 border-b border-[#e5e7eb]",children:e.jsxs("div",{className:"mb-2",children:[e.jsxs("h2",{className:"text-base font-semibold text-[#111827] mb-1",children:["Clientes (",x.length,")"]}),e.jsx("p",{className:"text-xs text-[#6b7280]",children:"Gestiona y da seguimiento a tus relaciones"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-[#f1f3f5] border-b border-[#e5e7eb]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 text-left text-xs font-semibold text-[#6b7280] uppercase tracking-wider",children:"Cliente"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-semibold text-[#6b7280] uppercase tracking-wider",children:"Contacto"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-semibold text-[#6b7280] uppercase tracking-wider",children:"Estado"}),e.jsx("th",{className:"px-6 py-3 text-right text-xs font-semibold text-[#6b7280] uppercase tracking-wider",children:"Acciones"})]})}),e.jsx("tbody",{className:"divide-y divide-white/[0.07]",children:x.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-6 py-16 text-center",children:e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-xl bg-[#2563EB]/10 mb-4",children:e.jsx(Le,{className:"w-8 h-8 text-[#2563EB]"})}),e.jsx("h3",{className:"text-xl font-bold text-[#111827] mb-2",children:c||d!=="all"||u!=="all"?"No se encontraron clientes":"No hay clientes"}),e.jsx("p",{className:"text-sm text-[#6b7280] max-w-md text-center",children:c||d!=="all"||u!=="all"?"Intenta ajustar los filtros de búsqueda":"Sincroniza con Stripe para
61importar tus clientes"})]})})}):x.map(r=>e.jsxs("tr",{className:"hover:bg-[#2563EB]/10 transition-all cursor-pointer group",onClick:()=>k(r),children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-[#111827]",children:r.name||"Sin nombre"}),(r.profile_role==="admin"||r.profile_role==="super_admin")&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold bg-[#2563EB]/15 text-[#2563EB]",children:"Admin App"}),r.account_role==="owner"&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold bg-[#2563EB]/15 text-[#2563EB]",children:"Responsable"}),r.account_role==="member"&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold bg-[#f1f3f5] text-[#374151]",children:"Miembro"})]}),r.company&&!r.is_virtual_member&&e.jsxs("div",{className:"text-sm text-[#6b7280] flex items-center gap-1.5 mt-1",children:[e.jsx(Ke,{className:"w-4 h-4 text-[#9ca3af]"}),r.company]}),r.is_virtual_member&&r.member_of_customer_name&&e.jsxs("div",{className:"text-sm text-[#6b7280] flex items-center gap-1.5 mt-1",children:[e.jsx(Ke,{className:"w-4 h-4 text-[#9ca3af]"}),"Miembro de: ",r.member_of_customer_name]})]})}),e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm text-[#374151] flex items-center gap-1.5",children:[e.jsx(ze,{className:"w-4 h-4 text-[#9ca3af]"}),r.email]}),r.phone&&e.jsxs("div",{className:"text-sm text-[#6b7280] flex items-center gap-1.5",children:[e.jsx(Pt,{className:"w-4 h-4 text-[#9ca3af]"}),r.phone]})]})}),e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{onClick:N=>{N.stopPropagation(),te(r)},title:r.is_active?"Desactivar cliente (baja en cascada)":"Reactivar cliente",className:`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold border transition-colors hover:opacity-80 ${r.is_active?"bg-[#2563EB]/10 text-[#2563EB] border-[#2563EB]/20":"bg-[#f1f3f5] text-[#6b7280] border-[#e5e7eb]"}`,children:r.is_active?e.jsxs(e.Fragment,{children:[e.jsx(de,{className:"w-3.5 h-3.5"}),"Activo"]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-3.5 h-3.5"}),"Inactivo"]})}),e.jsx("span",{className:`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold border ${r.user_id||r.has_account?"bg-[#2563EB]/15 text-[#2563EB] border-[#2563EB]/25":"bg-[#f1f3f5] text-[#6b7280] border-[#e5e7eb]"}`,children:r.user_id||r.has_account?e.jsxs(e.Fragment,{children:[e.jsx(de,{className:"w-3.5 h-3.5"}),"Con cuenta"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ae,{className:"w-3.5 h-3.5"}),"Pendiente"]})})]})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsxs("button",{onClick:N=>{N.stopPropagation(),k(r)},className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-semibold text-[#2563EB] hover:text-[#2563EB] hover:bg-[#2563EB]/10 rounded-lg border border-[#2563EB]/20 transition-colors",children:[e.jsx(Nt,{className:"w-4 h-4"}),"Ver detalles"]})})]},r.id))})]})}),x.length>0&&e.jsx("div",{className:"px-5 py-3 border-t border-[#e5e7eb] bg-[#f1f3f5]",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-xs font-medium text-[#6b7280]",children:["Mostrando ",x.length," de ",t.length," clientes"]})})})]}),B&&e.jsx(It,{onClose:()=>X(!1),onSuccess:r=>{X(!1),V(),y(`Cliente "${r.name}" creado exitosamente`),setTimeout(()=>y(""),5e3)}})]})}function us({customer:t,onBack:n,onUpdate:x}){const{user:l,profile:m}=Oe();m==null||m.role;const w=(m==null?void 0:m.role)==="super_admin"||(m==null?void 0:m.role)==="admin",[v,b]=i.useState(null),[c,p]=i.useState(null),[d,o]=i.useState("overview"),[u,g]=i.useState(!1),[S,k]=i.useState(!1),[a,y]=i.useState(t),[E,M]=i.useState([]),[G,H]=i.useState([]),[J,W]=i.useState([]),[B,X]=i.useState([]),[V,me]=i.useState([]),[ae,ne]=i.useState(""),[te,be]=i.useState(""),[pe,O]=i.useState(""),[r,N]=i.useState(null),[q,A]=i.useState(""),[U,Z]=i.useState(null),[D,F]=i.useState(!1),[Se,ie]=i.useState(!1),[fe,f]=i.useState(!1),[C,$]=i.useState(null),[j,T]=i.useState(null),[I,_e]=i.useState(null),[he,xe]=i.useState(!1),[le,P]=i.useState(""),[ge,oe]=i.useState(!1),[se,ue]=i.useState(null),De=async()=>
61{if(t.user_id){P("Este cliente ya tiene una cuenta registrada"),setTimeout(()=>P(""),3e3);return}if(!t.email){P("El cliente no tiene un email registrado"),setTimeout(()=>P(""),3e3);return}if(window.confirm(`¿Enviar invitación a ${t.name||t.email}? 62 63Se enviará un email a ${t.email} con instrucciones para crear su cuenta y acceder al portal.`)){xe(!0),P("");try{const{data:{session:_}}=await h.auth.getSession();if(!_)throw new Error("No session");const R=await fetch("https://zsmlmujjwbwvhplnuzke.supabase.co/functions/v1/send-customer-invitation",{method:"POST",headers:{Authorization:`Bearer ${_.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({customer_id:t.id})}),K=await R.json();if(!R.ok||K.error)throw new Error(K.error||"Error al enviar invitación");P("Invitación enviada correctamente"),await h.from("customer_activities").insert({customer_id:t.id,activity_type:"invitation_sent",title:"Invitación enviada",description:`Invitación enviada a ${t.email}`}),setTimeout(()=>P(""),3e3)}catch(_){console.error("Error sending invitation:",_),P(_.message||"Error al enviar invitación"),setTimeout(()=>P(""),3e3)}finally{xe(!1)}}},Ie=async()=>{if(window.confirm(`¿Mover "${t.name||t.email}" a la papelera? 64 65El cliente y sus datos se moverán a la papelera y podrás restaurarlo más tarde.`))try{const{error:_}=await h.from("customers").update({deleted_at:new Date().toISOString()}).eq("id",t.id);if(_)throw _;await h.from("customer_activities").insert({customer_id:t.id,activity_type:"delete",title:"Cliente movido a la papelera",description:"El cliente fue movido a la papelera"}),n()}catch(_){console.error("Error deleting customer:",_),alert("Error al mover el cliente a la papelera. Por favor, inténtalo de nuevo.")}};i.useEffect(()=>{Y()},[t.id]);const Y=async()=>{try{const{data:{session:s}}=await h.auth.getSession(),[_,L,R]=await Promise.all([h.from("customer_notes").select("*").eq("customer_id",t.id).order("created_at",{ascending:!1}),h.from("customer_activities").select("*").eq("customer_id",t.id).order("created_at",{ascending:!1}),h.from("customer_custom_fields").select("*").eq("customer_id",t.id)]);M(_.data||[]),H(L.data||[]),me(R.data||[]);const{data:K,error:ce}=await h.from("tickets").select("*").eq("customer_id",t.id).order("created_at",{ascending:!1});ce&&console.error("Error loading tickets:",ce);const Q=await Promise.all((K||[]).map(async z=>{const{data:ee}=await h.from("ticket_messages").select("content, created_at").eq("ticket_id",z.id).order("created_at",{ascending:!1}).limit(1);return{...z,last_message_content:ee&&ee.length>0?ee[0].content:null}}));if(X(Q),s&&t.stripe_customer_id){ie(!0);try{const z=await rt({stripe_customer_id:t.stripe_customer_id,limit:200});W(z)}catch(z){console.error("Error loading invoices:",z),W([])}finally{ie(!1)}}else W([]),ie(!1);if(t.user_id){const{data:z}=await h.from("profiles").select("company_name, country, team_size").eq("id",t.user_id).maybeSingle();z&&$(z);const{data:ee}=await h.from("company_bitrix24").select("*").eq("user_id",t.user_id).maybeSingle();ee&&T(ee);const{data:He}=await h.from("billing_information").select("*").eq("user_id",t.user_id).maybeSingle();He&&_e(He)}}catch(s){console.error("Error loading customer data:",s)}},Ce=async()=>{F(!0);try{const{error:s}=await h.from("customers").update({name:a.name,email:a.email,phone:a.phone,company:a.company,website:a.website,priority:a.priority,notes:a.notes,account_type:a.account_type,billing_company_name:a.billing_company_name,billing_email:a.billing_email,billing_phone:a.billing_phone,billing_tax_id:a.billing_tax_id,billing_fiscal_country:a.billing_fiscal_country,billing_address:a.billing_address,billing_line1:a.billing_address,billing_line2:a.billing_line2,billing_postal_code:a.billing_postal_code,billing_city:a.billing_city,billing_province:a.billing_province,billing_state:a.billing_province,billing_country:a.billing_fiscal_country,billing_client_type:a.billing_client_type}).eq("id",t.id);if(s)throw s;await fetch("https://zsmlmujjwbwvhplnuzke.supabase.co/functions/v1/update-stripe-customer",{method:"POST",headers:{Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InpzbWxtdWpqd2J3dmhwbG51emtlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjYxNjgzNjcsImV4cCI6MjA4MTc0NDM2N30.XO0Zyi4TdWoBzeTI3bPDRYUT2BrFb-QB5zj3UHNv3ng","Content-Type":"application/json"},body:JSON.stringify({customer_id:t.id,name:a.billing_company_name||a.name,email:a.billing_email||a.email,phone:a.billing_phone||a.phone,address:{line1:a.billing_address||"",line2:a.billing_line2||"",city:a.billing_city||"",postal_code:a.billing_postal_code||"",state:a.billing_province||"",country:a.billing_fiscal_country||""}})}),await h.from("customer_activities").insert({customer_id:t.id,activity_type:"update",title:"Información básica actualizada",description:"Los datos básicos del cliente fueron actualizados"}),g(!1),f(!0),setTimeout(()=>f(!1),3e3),x(),Y()}catch(s){console.error("Error updating customer:",s),alert("Error al guardar los cambios")}finally{F(!1)}},Ne=async()=>{F(!0);try{const s={has_bitrix24:a.has_bitrix24,bitrix24_url:a.bitrix24_url,bitrix24_goal:a.bitrix24_goal,bitrix24_plan:a.bitrix24_plan,bitrix24_expiry_date:a.bitrix24_expiry_date,bitrix24_needs_upgrade:a.bitrix24_needs_upgrade||!1,bitrix24_license_sedebit:a.bitrix24_license_sedebit||!1,bitrix24_license_plan:a.bitrix24_license_plan||null,bitrix24_license_status:a.bitrix24_license_status||null,bitrix24_license_renewal_date:a.bitrix24_license_renewal_date||null},{error:_}=await h.from("customers").update(s).eq("id",t.id);if(_)throw _;await h.from("customer_activities").insert({customer_id:t.id,activity_type:"update",title:"Información Bitrix24 actualizada",description:"Los datos de Bitrix24 fueron actualizados"}),k(!1),f(!0),setTimeout(()=>f(!1),3e3),Y()}catch(s){console.error("Error updating Bitrix24 info:",s),alert("Error al guardar los cambios")}finally{F(!1)}},re=async()=>
65{if(ae.trim())try{await h.from("customer_notes").insert({customer_id:t.id,user_id:l==null?void 0:l.id,note:ae}),await h.from("customer_activities").insert({customer_id:t.id,activity_type:"note",title:"Nueva nota agregada",description:ae.substring(0,100)}),ne(""),Y()}catch(s){console.error("Error adding note:",s)}},Fe=async()=>{if(te.trim())try{await h.from("customer_custom_fields").insert({customer_id:t.id,field_name:te,field_value:pe,field_type:"text"}),be(""),O(""),Y()}catch(s){console.error("Error adding custom field:",s)}},Ue=(s,_)=>{N(s),A(_)},$e=async s=>{try{await h.from("customer_custom_fields").update({field_value:q}).eq("id",s),N(null),A(""),Y()}catch(_){console.error("Error updating field:",_)}},Ge=()=>{N(null),A("")},ct=async s=>{try{await h.from("customer_custom_fields").delete().eq("id",s),Z(null),Y()}catch(_){console.error("Error deleting field:",_)}},Ve=s=>new Intl.NumberFormat("es-ES",{style:"currency",currency:"EUR"}).format(s/100),dt=s=>{const _=new Date,L=new Date(s),R=_.getTime()-L.getTime(),K=Math.floor(R/6e4),ce=Math.floor(R/36e5),Q=Math.floor(R/864e5);if(K<1)return"Hace un momento";if(K<60)return`Hace ${K} ${K===1?"minuto":"minutos"}`;if(ce<24)return`Hace ${ce} ${ce===1?"hora":"horas"}`;if(Q===1)return"Ayer";if(Q<7)return`Hace ${Q} dÃas`;if(Q<30){const ee=Math.floor(Q/7);return`Hace ${ee} ${ee===1?"semana":"semanas"}`}if(Q<365){const ee=Math.floor(Q/30);return`Hace ${ee} ${ee===1?"mes":"meses"}`}const z=Math.floor(Q/365);return`Hace ${z} ${z===1?"año":"años"}`},mt=s=>{switch(s){case"note":return{icon:e.jsx(Ze,{className:"w-5 h-5"}),bg:"bg-[#2563EB]/15",text:"text-[#2563EB]"};case"invoice":return{icon:e.jsx(we,{className:"w-5 h-5"}),bg:"bg-[#2563EB]/15",text:"text-[#2563EB]"};case"ticket":return{icon:e.jsx(Ye,{className:"w-5 h-5"}),bg:"bg-[#2563EB]/15",text:"text-[#2563EB]"};case"status_change":return{icon:e.jsx(de,{className:"w-5 h-5"}),bg:"bg-[#2563EB]/15",text:"text-[#2563EB]"};case"update":return{icon:e.jsx(ye,{className:"w-5 h-5"}),bg:"bg-[#2563EB]/15",text:"text-[#2563EB]"};case"delete":return{icon:e.jsx(Te,{className:"w-5 h-5"}),bg:"bg-red-500/15",text:"text-red-400"};case"create":return{icon:e.jsx(Me,{className:"w-5 h-5"}),bg:"bg-[#2563EB]/15",text:"text-[#2563EB]"};default:return{icon:e.jsx(Ae,{className:"w-5 h-5"}),bg:"bg-[#f1f3f5]",text:"text-[#6b7280]"}}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("button",{onClick:n,className:"p-2 hover:bg-[#f1f3f5] rounded-[10px] transition-all duration-150",title:"Volver",children:e.jsx(Ee,{className:"w-6 h-6 text-[#374151]"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold text-[#111827]",children:a.name||"Sin nombre"}),e.jsx("p",{className:"text-base text-[#6b7280] mt-1",children:(I==null?void 0:I.billing_email)||a.email})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[!t.user_id&&e.jsxs("button",{onClick:De,disabled:he,className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-[#2563EB] bg-[#f8f9fb] border border-[#2563EB]/20 rounded-[10px] hover:bg-[#2563EB]/10 hover:border-[#2563EB]/40 transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(ze,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:he?"Enviando...":"Invitar al Portal"})]}),t.user_id&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 rounded-[10px]",children:[e.jsx(de,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Cuenta Activa"})]}),e.jsxs("button",{onClick:()=>oe(!0),className:"flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-gradient-to-r from-[#2563EB] to-[#163168] hover:from-[#152f5f] hover:to-[#0f1f3d] rounded-[10px] transition-all hover:scale-105",children:[e.jsx(Ze,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Crear Ticket"})]}),e.jsxs("a",{href:`https://dashboard.stripe.com/customers/${t.stripe_customer_id}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-[#374151] bg-[#f8f9fb] border border-[#e5e7eb] rounded-[10px] hover:bg-[#f1f3f5] hover:border-[#e5e7eb] transition-all duration-150",children:[e.jsx(Lt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Ver en Stripe"})]}),e.jsxs("button",{onClick:Ie,className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-red-400 bg-[#f8f9fb] border border-red-500/20 rounded-[10px] hover:bg-red-500/10 hover:border-red-300 transition-all duration-150",children:[e.jsx(Te,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Eliminar"})]})]})]}),fe&&e.jsxs("div",{className:"bg-[#2563EB]/10 border border-[#2563EB]/20 text-white px-4 py-3 rounded-[14px] text-sm font-medium flex items-center gap-2",children:[e.jsx(de,{className:"w-5 h-5"}),"Cambios guardados correctamente"]}),le&&e.jsxs("div",{className:`${le.includes("correctamente")?"bg-emerald-500/10 border-emerald-500/20 text-emerald-400":"bg-red-500/10 border-red-500/20 text-red-400"} border px-4 py-3 rounded-[14px] text-sm font-medium flex items-center gap-2`,children:[le.includes("correctamente")?e.jsx(de,{className:"w-5 h-5"}):e.jsx(Ye,{className:"w-5 h-5"}),le]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsx("div",{className:"lg:col-span-2 space-y-6",children:e.jsxs("div",{className:"bg-[#f8f9fb] rounded-[14px] border border-[#e5e7eb] overflow-hidden",children:[e.jsx("div",{className:"border-b border-[#e5e7eb]",children:e.jsx("nav",{className:"flex gap-6 px-6",children:[{id:"overview",label:"Vista General"},{id:"activity",label:"Actividad"},{id:"invoices",label:"Facturas"},{id:"tickets",label:"Tickets"},{id:"custom",label:"Campos Personalizados"}].map(s=>e.jsx("button",{onClick:()=>
65o(s.id),className:`py-4 text-sm border-b-2 transition-all duration-150 ${d===s.id?"border-blue-600 text-[#2563EB] font-semibold":"border-transparent text-[#6b7280] hover:text-[#111827] font-medium"}`,children:s.label},s.id))})}),e.jsxs("div",{className:"p-6",children:[d==="overview"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"bg-[#f1f3f5] rounded-[14px] border border-[#e5e7eb] p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-[#111827]",children:"Información básica / Datos de facturación"}),u?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>{g(!1),y(t)},className:"px-4 py-2 text-sm font-medium text-[#374151] bg-[#f8f9fb] border border-[#e5e7eb] rounded-[10px] hover:bg-[#f1f3f5] transition-all duration-150",children:"Cancelar"}),e.jsx("button",{onClick:Ce,disabled:D,className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-[#2563EB] rounded-[10px] hover:bg-[#2a63e0] disabled:opacity-50 transition-all duration-150",children:D?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}),"Guardando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4"}),"Guardar cambios"]})})]}):e.jsxs("button",{onClick:()=>g(!0),className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-[#2563EB] bg-[#2563EB]/10 border border-[#2563EB]/20 rounded-[10px] hover:bg-[#2563EB]/15 hover:border-[#2563EB]/40 transition-all duration-150",children:[e.jsx(ye,{className:"w-4 h-4"}),"Editar información"]})]}),u?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Tipo de cliente"}),e.jsxs("select",{value:a.billing_client_type||"",onChange:s=>y({...a,billing_client_type:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150 bg-[#f8f9fb]",children:[e.jsx("option",{value:"",children:"Seleccionar tipo"}),e.jsx("option",{value:"company",children:"Empresa"}),e.jsx("option",{value:"freelance",children:"Autónomo"}),e.jsx("option",{value:"individual",children:"Particular"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Tipo de cuenta"}),e.jsxs("select",{value:a.account_type||"",onChange:s=>y({...a,account_type:s.target.value||null}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",children:[e.jsx("option",{value:"",children:"No especificado"}),e.jsx("option",{value:"responsible",children:"Responsable"}),e.jsx("option",{value:"member",children:"Miembro"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Empresa / Razón Social"}),e.jsx("input",{type:"text",value:a.billing_company_name||"",onChange:s=>y({...a,billing_company_name:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"CIF/NIF"}),e.jsx("input",{type:"text",value:a.billing_tax_id||"",onChange:s=>y({...a,billing_tax_id:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"CIF/NIF"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"PaÃs fiscal"}),e.jsxs("select",{value:a.billing_fiscal_country||"",onChange:s=>y({...a,billing_fiscal_country:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150 bg-[#f8f9fb]",children:[e.jsx("option",{value:"",children:"Seleccionar paÃs"}
65),Object.entries(lt).map(([s,_])=>e.jsx("option",{value:s,children:_},s))]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Dirección (LÃnea 1)"}),e.jsx("input",{type:"text",value:a.billing_address||"",onChange:s=>y({...a,billing_address:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"Calle Ejemplo 123"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Dirección (LÃnea 2)"}),e.jsx("input",{type:"text",value:a.billing_line2||"",onChange:s=>y({...a,billing_line2:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"Piso 1, Puerta A"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Código Postal"}),e.jsx("input",{type:"text",value:a.billing_postal_code||"",onChange:s=>y({...a,billing_postal_code:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"28001"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Ciudad"}),e.jsx("input",{type:"text",value:a.billing_city||"",onChange:s=>y({...a,billing_city:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"Madrid"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Provincia"}),e.jsxs("select",{value:a.billing_province||"",onChange:s=>y({...a,billing_province:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150 bg-[#f8f9fb]",children:[e.jsx("option",{value:"",children:"Seleccionar provincia"}),Object.entries(ot).map(([s,_])=>e.jsx("option",{value:s,children:_},s))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Email de facturación"}),e.jsx("input",{type:"email",value:a.billing_email||a.email||"",onChange:s=>y({...a,billing_email:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"[email protected]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Teléfono"}),e.jsx("input",{type:"tel",value:a.billing_phone||a.phone||"",onChange:s=>y({...a,billing_phone:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"+34 600 000 000"})]})]}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Tipo de cliente"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_client_type==="company"?"Empresa":a.billing_client_type==="freelance"?"Autónomo":a.billing_client_type==="individual"?"Particular":"No informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Tipo de cuenta"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.account_type==="responsible"?"Responsable":a.account_type==="member"?"Miembro":"No especificado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Empresa / Razón Social"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_company_name||"No informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"CIF/NIF"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_tax_id||"No informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"PaÃs fiscal"}),e.jsx("p",{className:"text-base text-[#374151]",children:ms(a.billing_fiscal_country)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Dirección (LÃnea 1)"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_address||"No informado"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Dirección (LÃnea 2)"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_line2||"No informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Código Postal"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_postal_code||"No informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Ciudad"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_city||"No informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Provincia"}),e.jsx("p",{className:"text-base text-[#374151]",children:xs(a.billing_province)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Email de facturación"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_email||a.email||"No informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Teléfono"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.billing_phone||a.phone||"No informado"})]})]})]}),e.jsxs("div",{className:"bg-[#f1f3f5] rounded-[14px] border border-[#e5e7eb] p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-[#111827]",children:"Información Bitrix24"}),S?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>{k(!1),y(t)},className:"px-4 py-2 text-sm font-medium text-[#374151] bg-[#f8f9fb] border border-[#e5e7eb] rounded-[10px] hover:bg-[#f1f3f5] transition-all duration-150",children:"Cancelar"}),e.jsx("button",{onClick:Ne,disabled:D,className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-[#2563EB] rounded-[10px] hover:bg-[#2a63e0] disabled:opacity-50 transition-all duration-150",children:D?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent roun
65ded-full animate-spin"}),"Guardando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{className:"w-4 h-4"}),"Guardar cambios"]})})]}):e.jsxs("button",{onClick:()=>k(!0),className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-[#2563EB] bg-[#2563EB]/10 border border-[#2563EB]/20 rounded-[10px] hover:bg-[#2563EB]/15 hover:border-[#2563EB]/40 transition-all duration-150",children:[e.jsx(ye,{className:"w-4 h-4"}),"Editar información"]})]}),S?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Estado Bitrix24"}),e.jsxs("select",{value:a.has_bitrix24!==void 0?String(a.has_bitrix24):(j==null?void 0:j.has_bitrix24)!==void 0?String(j.has_bitrix24):"",onChange:s=>y({...a,has_bitrix24:s.target.value==="true"}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",children:[e.jsx("option",{value:"",children:"No especificado"}),e.jsx("option",{value:"true",children:"Tiene cuenta existente"}),e.jsx("option",{value:"false",children:"Necesita crear cuenta"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"URL Bitrix24"}),e.jsx("input",{type:"url",value:a.bitrix24_url||(j==null?void 0:j.bitrix24_url)||"",onChange:s=>y({...a,bitrix24_url:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"https://miempresa.bitrix24.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Plan Bitrix24"}),e.jsxs("select",{value:a.bitrix24_plan||"",onChange:s=>y({...a,bitrix24_plan:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",children:[e.jsx("option",{value:"",children:"No especificado"}),e.jsx("option",{value:"Free",children:"Free"}),e.jsx("option",{value:"Basic",children:"Basic"}),e.jsx("option",{value:"Standard",children:"Standard"}),e.jsx("option",{value:"Professional",children:"Professional"}),e.jsx("option",{value:"Enterprise",children:"Enterprise"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Fecha de caducidad"}),e.jsx("input",{type:"date",value:a.bitrix24_expiry_date||"",onChange:s=>y({...a,bitrix24_expiry_date:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-[#374151] mb-1",children:"Objetivo Bitrix24"}),e.jsx("input",{type:"text",value:a.bitrix24_goal||(j==null?void 0:j.bitrix24_goal)||"",onChange:s=>y({...a,bitrix24_goal:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",placeholder:"Objetivo principal con Bitrix24"})]}),e.jsxs("div",{className:"md:col-span-2 pt-4 border-t border-[#e5e7eb]",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer mb-3",children:[e.jsx("input",{type:"checkbox",checked:a.bitrix24_license_sedebit||!1,onChange:s=>y({...a,bitrix24_license_sedebit:s.target.checked}),className:"accent-[#2563EB]"}),e.jsx("span",{className:"text-sm font-medium text-[#374151]",children:"Licencia Bitrix24 contratada con SedeBit"})]}),a.bitrix24_license_sedebit&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-[#374151] mb-1",children:"Plan / licencia"}),e.jsx("input",{type:"text",value:a.bitrix24_license_plan||"",onChange:s=>y({...a,bitrix24_license_plan:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px]",placeholder:"p.ej. Standard 24"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-[#374151] mb-1",children:"Estado"}),e.jsxs("select",{value:a.bitrix24_license_status||"",onChange:s=>y({...a,bitrix24_license_status:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px]",children:[e.jsx("option",{value:"",children:"â"}),e.jsx("option",{value:"activa",children:"Activa"}),e.jsx("option",{value:"inactiva",children:"Inactiva"}),e.jsx("option",{value:"pendiente_renovacion",children:"Pendiente de renovación"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-[#374151] mb-1",children:"Renovación / caducidad"}),e.jsx("input",{type:"date",value:a.bitrix24_license_renewal_date||"",onChange:s=>y({...a,bitrix24_license_renewal_date:s.target.value}),className:"w-full px-3 py-2 border border-[#e5e7eb] rounded-[10px]"})]})]})]})]}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Estado Bitrix24"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.has_bitrix24!==void 0?a.has_bitrix24?"Tiene cuenta existente":"Necesita crear cuenta":(j==null?void 0:j.has_bitrix24)!==void 0?j.has_bitrix24?"Tiene cuenta existente":"Necesita crear cuenta":"No especificado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"URL Bitrix24"}),a.bitrix24_url||j!=null&&j.bitrix24_url?e.jsx("a",{href:a.bitrix24_url||(j==null?void 0:j.bitrix24_url),target:"_blank",rel:"noopener noreferrer",className:"text-base text-[#2563EB] hover:underline",children:a.bitrix24_url||(j==null?void 0:j.bitrix24_url)}):e.jsx("p",{className:"text-base text-[#374151]",children:"No informado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Plan Bitrix24"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.bitrix24_plan||"No especificado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Fecha de caducidad"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.bitrix24_expiry_date?new Date(a.bitrix24_expiry_date).toLocaleDateString("es-ES",{day:"numeric",month:"long",year:"numeric"}):"No especificada"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Objetivo Bitrix24"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.bitrix24_goal||(j==null?void 0:j.bitrix24_goal)||"No informado"})]}),e.jsxs("div",{className:"md:col-span-2 pt-4 border-t border-[#e5e7eb]",children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-2",children:"Licencia Bitrix24 con SedeBit"}),a.bitrix24_license_sedebit?e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-[#9ca3af] mb-0.5",children:"Contratada"}),e.jsx("p",{className:"text-base font-medium text-emerald-600",children:"SÃ"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-[#9ca3af] mb-0.5",children:"Plan"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.bitrix24_license_plan||"â"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-[#9ca3af] mb-0.5",children:"Estado"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.bitrix24_license_status==="activa"?"Activa":a.bitrix24_license_status==="inactiva"?"Inactiva":a.bitrix24_license_status==="pendiente_renovacion"?"Pendiente de renovación":"â"})]}),e.jsxs("div",{className:"sm:col-span-3",children:[e.jsx("p",{className:"text-[11px] text-[#9ca3af] mb-0.5",children:"Renovación / caducidad"}),e.jsx("p",{className:"text-base text-[#374151]",children:a.bitrix24_license_renewal_date?new Date(a.bitrix24_license_renewal_date).toLocaleDateString("es-ES",{day:"numeric",month:"long",year:"numeric"}):"â"})]})]}):e.jsx("p",{className:"text-base text-[#374151]",children:"No"})]})]})]}),e.jsx(cs,{customerId:t.id,editable:w,onCountChange:b}),e.jsx(ds,{customerId:t.id,onDisponibleChange:(s,_)=>p(_?null:s)}),e.jsxs("div",{className:"bg-[#f1f3f5] rounded-[14px] border border-[#e5e7eb] p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-[#111827]",children:"Datos de Facturación Stripe"}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1 bg-[#2563EB]/10 text-[#2563EB] rounded-full text-xs font-medium",children:[e.jsx(ye,{className:"w-3 h-3"}),"Sincronizado"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Balance"}),e.jsxs("p",{className:`text-base font-semibold ${(t.balance||0)<0?"text-emerald-400":(t.balance||0)>0?"text-red-400":"text-white"}`,children:[((t.balance||0)/100).toFixed(2)," ",(t.currency||"EUR").toUpperCase()]}),e.jsx("p",{className:"text-xs text-[#6b7280] mt-1",children:(t.balance||0)<0?"Crédito a favor":(t.balance||0)>0?"Deuda pendiente":"Sin balance"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Estado de Pago"}),e.jsx("div",{className:"flex items-center gap-2",children:t.delinquent?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-2 h-2 bg-red-500/100 rounded-full"}),e.jsx("span",{className:"text-base font-medium text-red-400",children:"Moroso"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-2 h-2 bg-emerald-500/100 rounded-full"}),e.jsx("span",{className:"text-base font-medium text-emerald-400",children:"Al dÃa"})]})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Exención Fiscal"}),e.jsx("p",{className:"text-base text-[#374151]",children:t.tax_exempt==="exempt"?"Exento":t.tax_exempt==="reverse"?"Inversión de sujeto pasivo":"No exento"})]}),t.billing_line1&&e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Dirección de Facturación"}),e.jsxs("p",{className:"text-base text-[#374151]",children:[t.billing_line1,t.billing_line2&&`, ${t.billing_line2}`,e.jsx("br",{}),t.billing_postal_code&&`${t.billing_postal_code} `,t.billing_city&&`${t.billing_city}`,t.billing_state&&`, ${t.billing_state}`,e.jsx("br",{}),t.billing_country&&t.billing_country]})]}),t.default_source&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Método de Pago Principal"}),e.jsx("p",{className:"text-sm text-[#6b7280] font-mono",children:t.default_source})]}),t.invoice_prefix&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Prefijo de Factura"}),e.jsx("p",{className:"text-base text-[#374151]",children:t.invoice_prefix})]}),t.next_invoice_sequence&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Próximo Nº de Factura"}),e.jsx("p",{className:"text-base text-[#374151]",children:t.next_invoice_sequence})]}),t.created_in_stripe_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Cliente desde"}),e.jsx("p",{className:"text-base text-[#374151]",children:new Date(t.created_in_stripe_at).toLocaleDateString("es-ES",{day:"2-digit",month:"long",year:"numeric"})})]}),t.description&&e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("p",{className:"text-xs font-semibold text-[#6b7280] uppercase tracking-wider mb-1",children:"Descripción"}),e.jsx("p",{className:"text-sm text-[#374151]",children:t.description})]})]})]}),e.jsxs("div",{className:"bg-[#f1f3f5] rounded-[14px] border border-[#e5e7eb] p-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-[#111827] mb-6",children:"Notas rápidas"}),e.jsxs("div",{className:"flex gap-2 mb-4",children:[e.jsx("input",{type:"text",value:ae,onChange:s=>ne(s.target.value),placeholder:"Agregar una nota rápida...",className:"flex-1 px-3 py-2 border border-[#e5e7eb] rounded-[10px] focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-150",onKeyPress:s=>s.key==="Enter"&&re()}),e.jsxs("button",{onClick:re,className:"flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-[#2563EB] rounded-[10px] hover:bg-[#2a63e0] transition-all duration-150",children:[e.jsx(Me,{className:"w-4 h-4"}),"Agregar"]})]}),e.jsx("div",{className:"space-y-3",children:E.length===0?e.jsx("p",{className:"text-center text-[#6b7280] py-8",children:"No hay notas"}):E.map(s=>e.jsxs("div",{className:"bg-[#f8f9fb] p-4 rounded-[10px] border border-[#e5e7eb]",children:[e.jsx("p",{className:"text-sm text-[#374151]",children:s.note}),e.jsx("p",{className:"text-xs text-[#6b7280] mt-2",children:new Date(s.created_at).toLocaleStr
65ing("es-ES")})]},s.id))})]})]}),d==="activity"&&e.jsx("div",{className:"space-y-4",children:G.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-[#f1f3f5] rounded-full flex items-center justify-center mb-4",children:e.jsx(Ae,{className:"w-8 h-8 text-[#9ca3af]"})}),e.jsx("h3",{className:"text-lg font-semibold text-[#111827] mb-2",children:"No hay actividad registrada"}),e.jsx("p",{className:"text-sm text-[#6b7280] text-center max-w-md",children:"Aquà aparecerán las interacciones del cliente: citas, tickets, facturas y cambios importantes."})]}):e.jsxs("div",{className:"relative space-y-4",children:[e.jsx("div",{className:"absolute left-[22px] top-8 bottom-0 w-[2px] bg-gradient-to-b from-gray-200 via-gray-100 to-transparent"}),G.map((s,_)=>{const L=mt(s.activity_type),R=new Date(s.created_at);return e.jsxs("div",{className:"relative bg-[#f8f9fb] border border-[#e5e7eb] rounded-[14px] p-5 hover:shadow-md transition-all duration-200 ml-14",children:[e.jsx("div",{className:`absolute -left-[34px] top-5 w-11 h-11 ${L.bg} rounded-full flex items-center justify-center ${L.text} shadow-none border-4 border-white`,children:L.icon}),e.jsx("div",{className:"flex items-start justify-between gap-4 mb-3",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"text-base font-semibold text-[#111827] mb-1",children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-[#6b7280]",children:[e.jsx("span",{className:"font-medium",children:dt(s.created_at)}),e.jsx("span",{className:"text-[#d1d5db]",children:"â"}),e.jsxs("span",{title:R.toLocaleString("es-ES",{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"}),children:[R.toLocaleDateString("es-ES",{day:"2-digit",month:"2-digit",year:"numeric"})," a ",R.toLocaleTimeString("es-ES",{hour:"2-digit",minute:"2-digit"})]})]})]})}),s.description&&e.jsx("p",{className:"text-sm text-[#374151] leading-relaxed",children:s.description})]},s.id)})]})}),d==="invoices"&&e.jsx("div",{className:"space-y-3",children:Se?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"inline-block animate-spin rounded-full h-10 w-10 border-3 border-[#e5e7eb] border-t-blue-600 mb-4"}),e.jsx("p",{className:"text-[#6b7280] font-medium",children:"Cargando facturas..."})]}):J.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-[#f1f3f5] rounded-full flex items-center justify-center mb-4",children:e.jsx(we,{className:"w-8 h-8 text-[#9ca3af]"})}),e.jsx("h3",{className:"text-lg font-semibold text-[#111827] mb-2",children:"Este cliente aún no tiene facturas"}),e.jsx("p",{className:"text-sm text-[#6b7280] text-center max-w-md",children:"Aquà aparecerán automáticamente cuando se realice un cargo."})]}):e.jsx("div",{className:"space-y-3",children:J.map(s=>{const _=s.type==="credit_note",L=s.status==="paid"||s.status==="completed",R=s.status==="open"||s.status==="draft";return e.jsxs("div",{className:"flex items-center justify-between p-5 bg-[#f8f9fb] border border-[#e5e7eb] rounded-[14px] hover:shadow-md hover:border-[#e5e7eb] transition-all duration-200",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center ${L&&!_?"bg-[#2563EB]/15":"bg-[#f1f3f5]"}`,children:e.jsx(we,{className:`w-5 h-5 ${L&&!_?"text-[#2563EB]":"text-[#6b7280]"}`})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-[#111827] text-base mb-1",children:[s.number,s.rectifies_number&&e.jsxs("span",{className:"block text-xs font-normal text-[#6b7280]",children:["Rectifica ",s.rectifies_number]})]}),e.jsxs("p",{className:"text-sm text-[#6b7280]",children:[s.date?new Date(s.date).toLocaleDateString("es-ES",{day:"2-digit",month:"2-digit",year:"numeric"}):"N/A",e.jsx("span",{className:"ml-2 inline-flex items-center px-2 py-0.5 rounded text-[10px] font-medium bg-[#f1f3f5] text-[#6b7280] border border-[#e5e7eb]",children:s.provider==="holded"?"Holded":"Str
65ipe (histórico)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"font-bold text-[#111827] text-lg mb-1",children:Ve(s.amount_cents)}),e.jsx("span",{className:`inline-flex items-center px-3 py-1 text-xs font-medium rounded-full ${_?"bg-[#f1f3f5] text-[#374151]":L?"bg-[#2563EB]/15 text-[#2563EB]":R?"bg-yellow-100 text-yellow-700":"bg-red-500/15 text-red-400"}`,children:_?"Rectificativa":L?"Pagada":R?"Pendiente":"Fallida"})]}),e.jsx("div",{className:"flex items-center gap-2 pl-4 border-l border-[#e5e7eb]",children:s.download_available&&e.jsx("button",{onClick:()=>{Ft(s.id).catch(()=>alert("No se pudo descargar el documento"))},className:"p-2 text-[#2563EB] hover:bg-[#2563EB]/10 rounded-lg transition-colors group relative",title:"Descargar PDF",children:e.jsx(qe,{size:18})})})]})]},s.id)})})}),d==="tickets"&&e.jsx("div",{className:"space-y-3",children:B.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-[#f1f3f5] rounded-full flex items-center justify-center mb-4",children:e.jsx(we,{className:"w-8 h-8 text-[#9ca3af]"})}),e.jsx("h3",{className:"text-lg font-semibold text-[#111827] mb-2",children:"Este cliente aún no tiene tickets"}),e.jsx("p",{className:"text-sm text-[#6b7280] text-center max-w-md",children:"Aquà aparecerán automáticamente cuando contacte con soporte"})]}):e.jsx("div",{className:"space-y-3",children:B.map(s=>{const _=s.status==="waiting_team",L=s.status==="waiting_customer",R=s.status==="resolved",K=s.due_date&&new Date(s.due_date)<new Date&&!R&&!L,ce=s.priority==="low"?"Baja":s.priority==="medium"?"Media":s.priority==="high"?"Alta":"Urgente",Q=s.display_number||s.id.toString().slice(0,8);let z="";return s.last_message_content?z=s.last_message_content.length>80?s.last_message_content.substring(0,80)+"...":s.last_message_content:s.description&&(z=s.description.length>80?s.description.substring(0,80)+"...":s.description),e.jsxs("div",{onClick:()=>ue(s),className:"p-5 bg-[#f8f9fb] border border-[#e5e7eb] rounded-[14px] hover:shadow-md hover:border-[#e5e7eb] transition-all duration-200 cursor-pointer",children:[e.jsx("div",{className:"flex items-start justify-between mb-3",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsxs("span",{className:"text-sm font-semibold text-[#111827]",children:["SBT-",Q]}),e.jsx("span",{className:"text-[#9ca3af]",children:"â"}),e.jsx("h3",{className:"text-base font-semibold text-[#111827]",children:s.title})]}),z&&e.jsxs("p",{className:"text-sm text-[#6b7280] line-clamp-1 mb-3",children:['"',z,'"']})]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-flex items-center px-3 py-1 text-xs font-medium rounded-full ${K?"bg-gray-900 text-white":"bg-[#2563EB]/15 text-[#2563EB]"}`,children:K?"Vencido":_?"Esperando Equipo":L?"Esperando Cliente":"Resuelto"}),e.jsxs("span",{className:"text-xs text-[#6b7280] font-medium",children:["Prioridad ",ce]})]}),e.jsx("div",{className:"text-sm text-[#6b7280]",children:new Date(s.created_at).toLocaleDateString("es-ES",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]},s.id)})})}),d==="custom"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"p-4 bg-[#2563EB]/10 border border-[#2563EB]/20 rounded-[14px]",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx("input",{type:"text",value:te,onChange:s=>be(s.target.value),placeholder:"Nombre del campo",className:"flex-1 px-4 py-2.5 border border-[#e5e7eb] rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",onKeyDown:s=>{s.key==="Enter"&&te.trim()&&Fe()}}),e.jsx("input",{type:"text",value:pe,onChange:s=>O(s.target.value),placeholder:"Valor",className:"flex-1 px-4 py-2.5 border border-[#e5e7eb] rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",onKeyDown:s=>{s.key==="Enter"&&te.trim()&&Fe()}}),e.jsx("button",{onClick:Fe,disabled:!te.trim(),className:"px-4 py-2.5 bg-[#2563EB] text-white rounded-lg hover:bg-[#2a63e0] transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:e.jsx(Me,{size:18})})]})}),V.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-[#f1f3f5] rounded-full flex items-center justify-center mb-4",children:e.jsx(yt,{className:"w-8 h-8 text-[#9ca3af]"})}),e.jsx("h3",{className:"text-lg font-semibold text-[#111827] mb-2",children:"No hay campos personalizados"}),e.jsx("p",{className:"text-sm text-[#6b7280] text-center max-w-md",children:"Añade información especÃfica para este cliente"})]}):e.jsx("div",{className:"space-y-2",children:V.map(s=>e.jsxs("div",{className:"flex items-center justify-between p-4 bg-[#f8f9fb] border border-[#e5e7eb] rounded-[14px] hover:border-[#e5e7eb] transition-all group",children:[e.jsxs("div",{className:"flex-1 grid grid-cols-2 gap-4",children:[e.jsx("div",{children:e.jsx("p",{className:"text-sm font-medium text-[#6b7280] mb-1",children:s.field_name})}),e.jsx("div",{children:r===s.id?e.jsx("div",{className:"flex gap-2",children:e.jsx("input",{type:"text",value:q,onChange:_=>A(_.target.value),onKeyDown:_=>{_.key==="Enter"?$e(s.id):_.key==="Escape"&&Ge()},onBlur:()=>$e(s.id),autoFocus:!0,className:"flex-1 px-3 py-1.5 text-sm border border-blue-500 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})}):e.jsx("p",{onClick:()=>Ue(s.id,s.field_value),className:"text-sm text-[#374151] cursor-pointer hover:text-[#2563EB] transition-colors",children:s.field_value||e.jsx("span",{className:"text-[#9ca3af] italic",children:"Sin valor"})})})]}),e.jsx("div",{className:"flex items-center gap-2 ml-4 opacity-0 group-hover:opacity-100 transition-opacity",children:r===s.id?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>$e(s.id),className:"p-1.5 text-[#2563EB] hover:bg-[#2563EB]/10 rounded-lg transition-colors",title:"Guardar",children:e.jsx(it,{size:16})}),e.jsx("button",{onClick:Ge,className:"p-1.5 text-[#6b7280] hover:bg-[#f1f3f5] rounded-lg transition-colors",title:"Cancelar",children:e.jsx(Ee,{size:16})})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>Ue(s.id,s.field_value),className:"p-1.5 text-[#2563EB] hover:bg-[#2563EB]/10 rounded-lg transition-colors",title:"Editar",children:e.jsx(ye,{size:16})}),U===s.id?e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>ct(s.id),className:"px-2 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700 transition-colors",children:"Eliminar"}),e.jsx("button",{onClick:()=>Z(null),className:"px-2 py-1 text-xs bg-[#e9ecef] text-[#374151] rounded hover:bg-gray-300 transition-colors",children:"Cancelar"})]}):e.jsx("button",{onClick:()=>Z(s.id),className:"p-1.5 text-red-400 hover:bg-red-500/10 rounded-lg transition-colors",title:"Eliminar",children:e.jsx(Te,{size:16})})]})})]},s.id))})]})]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-[#f8f9fb] p-6 rounded-[14px] border border-[#e5e7eb]",children:[e.jsx("h3",{className:"text-lg font-semibold text-[#111827] mb-6",children:"Información rápida"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[#6b7280]",children:"Estado"}),e.jsx("span",{className:`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium border ${t.is_active?"bg-[#2563EB]/10 text-[#2563EB] border-[#2563EB]/20":"bg-[#f1f3f5] text-[#374151] border-[#e5e7eb]"}`,children:t.is_active?e.jsxs(e.Fragment,{children:[e.jsx(de,{className:"w-4 h-4"}),"Activo"]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{className:"w-4 h-4"}),"Inactivo"]})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[#6b7280]",children:"Servicios activos"}),e.jsx("span",{className:"text-base font-semibold text-[#111827]",children:v??"â"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[#6b7280]",children:"Bolsa disponible"}),e.jsx("span",{className:"text-base font-semibold text-[#111827]",children:c===null?"Sin bolsa":ke(c)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[#6b7280]",children:"Gasto total"}),e.jsx("span",{className:"text-base font-bold text-[#2563EB]",children:Ve(t.total_spent||0)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[#6b7280]",children:"Prioridad"}),e.jsx("span",{className:`text-sm font-semibold ${t.priority==="high"?"text-red-400":t.priority==="medium"?"text-yellow-600":"text-[#6b7280]"}`,children:t.priority==="high"?"Alta":t.priority==="medium"?"Media":"Baja"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[#6b7280]",children:"Facturas"}),e.jsx("span",{className:"text-base font-semibold text-[#111827]",children:J.length})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[#6b7280]",children:"Tickets"}),e.jsx("span",{className:"text-base font-semibold text-[#111827]",children:B.length})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[#6b7280]",children:"Notas"}),e.jsx("span",{className:"text-base font-semibold text-[#111827]",children:E.length})]})]})]}),e.jsxs("div",{className:"bg-gradient-to-br from-[#2563EB]/5 to-[#2563EB]/10 p-6 rounded-[14px] border border-[#2563EB]/20",children:[e.jsx("h3",{className:"text-sm font-semibold text-[#111827] mb-2",children:"Stripe Customer ID"}),e.jsx("p",{className:"text-xs text-[#2563EB] font-mono break-all leading-relaxed",children:t.stripe_customer_id})]}),e.jsxs("div",{className:"bg-[#f8f9fb] p-6 rounded-[14px] border border-[#e5e7eb]",children:[e.jsx("h3",{className:"text-sm font-semibold text-[#111827] mb-2",children:"Fecha de creación"}),e.jsx("p",{className:"text-sm text-[#374151]",children:new Date(t.created_at).toLocaleDateString("es-ES",{weekday:"long",year:"numeric",month:"long",day:"numeric"})})]})]})]}),e.jsx(wt,{isOpen:ge,onClose:()=>oe(!1),onSuccess:()=>{oe(!1),Y()},preSelectedCustomerId:t.id}),se&&e.jsx(ls,{ticketId:se.id,isOpen:!0,onClose:()=>{ue(null),Y()}})]})}export{Hs as default};
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.