1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/VisitsCard-BdZyOV_y.js","assets/vendor-core-DLV7unHF.js","assets/rolldown-runtime-CXHxssQy.js","assets/vendor-ui-HbZeGnVr.js","assets/card-C09EQudm.js","assets/utils-BUDDtgTh.js","assets/select-CkGTehtz.js"])))=>i.map(i=>d[i]); 2import{r as ke}from"./rolldown-runtime-CXHxssQy.js";import{f as Ae,l as De}from"./vendor-core-DLV7unHF.js";import{b as Te,n as U,r as w}from"./vendor-data-gP-SiX90.js";import{n as Pe,r as je}from"./i18n-BHBA6a-T.js";import{t as Fe}from"./preload-helper-BATLnrmA.js";import{Bt as W,Ct as Le,Dr as Me,Fr as ye,Gn as ee,It as Ie,Jt as Be,Lt as se,Mn as ve,Nr as Oe,On as $e,Ot as Re,Pr as _e,Rr as fe,Sr as P,Tn as J,Ut as Ve,Vr as Ke,Vt as Ue,Xt as be,bn as qe,ci as Ne,fr as L,hr as ze,ir as Ge,jr as He,kt as E,ln as Xe,mn as Qe,mr as Y,on as We,or as Je,pr as we,tr as Ce,vr as Ye,wn as Ze,wr as es,zn as ss,zr as ts,zt as as}from"./vendor-ui-HbZeGnVr.js";import{t as j}from"./button-BpBAlEZu.js";import{n as q}from"./adminHttp-dmZaXYk2.js";import{a as te,n as Se,o as ae,r as re,s as ie,t as ne}from"./dialog-CDZ2249b.js";import{t as B}from"./input-C-oqphw0.js";import{t as z}from"./label-rmk_lUq_.js";import{n as rs,r as is,t as ns}from"./collapsible-DhbTw0wH.js";import{a as y,i as v,n as p,r as b,t as g}from"./card-C09EQudm.js";import{i as ce}from"./date-format-BkrzO8CF.js";import{a as O,i as $,n as R,r as _,t as S}from"./select-CkGTehtz.js";import{o as C,r as ls}from"./types-Jo-g5CPm.js";import{t as k}from"./badge-Ckh5MnAv.js";import{t as cs}from"./switch-DaRePIGG.js";import{n as f}from"./dist-CKggLyJL.js";import{a as os,c as ds,i as G,n as ms,o as xs,r as us,s as hs,t as ps}from"./LineChart-DnavgFQf.js";var u=ke(Ae(),1),e=De();function gs({stats:s,t}){return(0,e.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[(0,e.jsx)(C,{title:t.admin.totalCustomers,value:s?.totalUsers||0,icon:E,subtitle:t.admin.registeredUsers}),(0,e.jsx)(C,{title:t.admin.totalOrders,value:s?.totalOrders||0,icon:be,subtitle:t.admin.ordersPlaced}),(0,e.jsx)(C,{title:t.admin.totalRevenue,value:`${parseFloat(s?.totalRevenue||"0").toFixed(2)}â¬`,icon:ze,subtitle:t.admin.accumulatedSales}),(0,e.jsx)(C,{title:t.admin.pendingMessages,value:s?.pendingMessages||0,icon:$e,subtitle:t.admin.supportUnanswered})]})}function js({stats:s}){return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsx)(v,{children:(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(se,{className:"w-5 h-5"}),"Resumen"]})}),(0,e.jsx)(p,{children:(0,e.jsxs)("p",{className:"text-gray-600",children:["Tienes ",(0,e.jsx)("span",{className:"font-bold text-[#E85A8B]",children:s?.totalUsers||0})," clientes registrados que han realizado"," ",(0,e.jsx)("span",{className:"font-bold text-[#E85A8B]",children:s?.totalOrders||0})," pedidos por un total de"," ",(0,e.jsxs)("span",{className:"font-bold text-[#E85A8B]",children:[parseFloat(s?.totalRevenue||"0").toFixed(2),"â¬"]}),".",(s?.pendingMessages||0)>0&&(0,e.jsxs)("span",{className:"block mt-2 text-amber-600",children:["Tienes ",s?.pendingMessages," mensajes de soporte pendientes de respuesta."]})]})})]})}function ys(){const[s,t]=(0,u.useState)(!1),i="https://www.ignislove.com/sitemap.xml",a=async()=>{await navigator.clipboard.writeText(i),t(!0),setTimeout(()=>t(!1),2e3)};return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(Ce,{className:"w-5 h-5"}),"SEO - Sitemap XML"]}),(0,e.jsx)(b,{children:"Enlace para Google Search Console. El sitemap se genera en tiempo real con todos los productos publicados."})]}),(0,e.jsxs)(p,{children:[(0,e.jsxs)("div",{className:"flex items-center gap-3 p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("code",{className:"flex-1 text-sm text-gray-700 truncate","data-testid":"text-sitemap-url",children:i}),(0,e.jsx)(j,{variant:"outline",size:"sm",onClick:a,className:"shrink-0","data-testid":"button-copy-sitemap",children:s?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(ts,{className:"w-4 h-4 mr-1 text-green-600"}),"Copiado"]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(P,{className:"w-4 h-4 mr-1"}),"Copiar"]})}),(0,e.jsx)(j,{variant:"outline",size:"sm",asChild:!0,className:"shrink-0","data-testid":"button-open-sitemap",children:(0,e.jsxs)("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:[(0,e.jsx)(Y,{className:"w-4 h-4 mr-1"}),"Abrir"]})})]}),(0,e.jsx)("p",{className:"mt-3 text-xs text-gray-500",children:"Incluye: Home, categorÃas, productos publicados (independientemente del stock), blog y páginas estáticas."})]})]})}var vs=(0,u.lazy)(()=>Fe(()=>import("./VisitsCard-BdZyOV_y.js").then(s=>({default:s.VisitsCard})),__vite__mapDeps([0,1,2,3,4,5,6])));function Pt(){const{t:s}=je(),[t,i]=(0,u.useState)("7d"),{data:a,isLoading:r}=w({queryKey:["/api/admin/stats"]}),{data:n,isLoading:l}=w({queryKey:["/api/admin/visits",t],queryFn:async()=>{const c=await fetch(`/api/admin/visits?period=${t}`,{credentials:"include"});if(!c.ok)throw new Error("Failed to fetch");return c.json()}});return r?(0,e.jsx)("div",{className:"text-center py-8",children:s.admin.loading}):(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsx)("h3",{className:"text-lg font-semibold text-gray-800",children:s.admin.panelStatistics}),(0,e.jsx)(gs,{stats:a,t:s}),(0,e.jsx)(u.Suspense,{fallback:(0,e.jsx)("div",{className:"h-64 animate-pulse bg-gray-100 rounded-lg"}),children:(0,e.jsx)(vs,{visitStats:n,visitsLoading:l,visitPeriod:t,setVisitPeriod:i,t:s})}),(0,e.jsx)(js,{stats:a}),(0,e.jsx)(ys,{})]})}var fs=[{value:"7d",label:"Ãltimos 7 dÃas"},{value:"30d",label:"Ãltimos 30 dÃas"},{value:"90d",label:"Ãltimos 90 dÃas"},{value:"custom",label:"Personalizado"}];function V(s,t,i){const a=new Date,r=new Date;if(s==="custom"&&t&&i){const n=new Date(t),l=new Date(i);if(Number.isFinite(n.getTime())&&Number.isFinite(l.getTime())&&n<=l)return l.setHours(23,59,59,999),{start:n,end:l}}switch(s){case"7d":r.setDate(a.getDate()-7);break;case"30d":r.setDate(a.getDate()-30);break;case"90d":r.setDate(a.getDate()-90);break;default:r.setDate(a.getDate()-30)}return{start:r,end:a}}var bs={Spain:"ðªð¸",ES:"ðªð¸",Mexico:"ð²ð½",MX:"ð²ð½",Argentina:"ð¦ð·",AR:"ð¦ð·",Colombia:"ð¨ð´",CO:"ð¨ð´",Chile:"ð¨ð±",CL:"ð¨ð±",Peru:"ðµðª",PE:"ðµðª","United States":"ðºð¸",US:"ðºð¸",Germany:"ð©ðª",DE:"ð©ðª",France:"ð«ð·",FR:"ð«ð·","United Kingdom":"ð¬ð§",GB:"ð¬ð§",Italy:"ð®ð¹",IT:"ð®ð¹",Portugal:"ðµð¹",PT:"ðµð¹",Brazil:"ð§ð·",BR:"ð§ð·",Unknown:"ð"};function Ns(s,t,i,a="all"){const{start:r,end:n}=V(s,t,i);return w({queryKey:["/api/admin/analytics/overview",s,t??null,i??null,a],queryFn:async()=>{const l=await fetch(`/api/admin/analytics/overview?startDate=${r.toISOString()}&endDate=${n.toISOString()}&segment=${a}`,{credentials:"include"});if(!l.ok)throw new Error("Failed to fetch analytics");return l.json()}})}function ws(s,t,i){const{start:a,end:r}=V(s,t,i);return w({queryKey:["/api/admin/analytics/timeseries",s,t??null,i??null],queryFn:async()=>{const n=await fetch(`/api/admin/analytics/timeseries?startDate=${a.toISOString()}&endDate=${r.toISOString()}`,{credentials:"include"});if(!n.ok)throw new Error("Failed to fetch timeseries");return n.json()}})}function Cs(s,t,i){const{start:a,end:r}=V(s,t,i);return w({queryKey:["/api/admin/analytics/sources",s,t??null,i??null],queryFn:async()=>{const n=await fetch(`/api/admin/analytics/sources?startDate=${a.toISOString()}&endDate=${r.toISOString()}`,{credentials:"include"});if(!n.ok)throw new Error("Failed to fetch traffic sources");return n.json()}})}function Ss(s,t,i,a){const{start:r,end:n}=V(t,i,a);return w({enabled:!!s,queryKey:["/api/admin/analytics/page",s??"",t,i??null,a??null],queryFn:async()=>{const l=`/api/admin/analytics/page?path=${encodeURIComponent(s||"")}&startDate=${r.toISOString()}&endDate=${n.toISOString()}`,c=await fetch(l,{credentials:"include"});if(!c.ok)throw new Error("Failed to fetch page detail");return c.json()}})}function Z(s){return s<60?`${s}s`:`${Math.floor(s/60)}m ${s%60}s`}function oe(s,t){if(t===null)return"text-gray-400";switch(s){case"lcp":return t<=2500?"text-green-600":t<=4e3?"text-yellow-600":"text-red-600";case"fid":return t<=100?"text-green-600":t<=300?"text-yellow-600":"text-red-600";case"cls":return t<=.1?"text-green-600":t<=.25?"text-yellow-600":"text-red-600";case"ttfb":return t<=800?"text-green-600":t<=1800?"text-yellow-600":"text-red-600";case"fcp":return t<=1800?"text-green-600":t<=3e3?"text-yellow-600":"text-red-600";case"inp":return t<=200?"text-green-600":t<=500?"text-yellow-600":"text-red-600";default:return"text-gray-600"}}function Es(s,t){if(t===null)return"Sin datos";switch(s){case"lcp":return t<=2500?"Bueno":t<=4e3?"Mejorable":"Malo";
2case"fid":return t<=100?"Bueno":t<=300?"Mejorable":"Malo";case"cls":return t<=.1?"Bueno":t<=.25?"Mejorable":"Malo";case"ttfb":return t<=800?"Bueno":t<=1800?"Mejorable":"Malo";case"fcp":return t<=1800?"Bueno":t<=3e3?"Mejorable":"Malo";case"inp":return t<=200?"Bueno":t<=500?"Mejorable":"Malo";default:return""}}function ks(s){switch(s.toLowerCase()){case"mobile":return Be;case"tablet":return Ve;case"desktop":return J;default:return J}}function de(s){if(s==null)return"";const t=String(s);return/[",\n\r]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function As(s,t){const i=[s.map(a=>de(a.label)).join(",")];for(const a of t)i.push(s.map(r=>de(a[r.key])).join(","));return i.join(`\r 3`)}function Ds(s,t){if(typeof window>"u"||typeof document>"u")return;const i=new Blob(["\uFEFF"+t],{type:"text/csv;charset=utf-8"}),a=URL.createObjectURL(i),r=document.createElement("a");r.href=a,r.download=s.endsWith(".csv")?s:`${s}.csv`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(a),100)}function Ts(s,t,i){Ds(s,As(t,i))}function K({filename:s,headers:t,rows:i,disabled:a,label:r="CSV","data-testid":n}){const l=()=>Ts(s,t,i),c=!i||i.length===0;return(0,e.jsxs)("button",{type:"button",onClick:l,disabled:a||c,className:"inline-flex items-center gap-1.5 px-2 py-1 text-xs font-medium text-gray-600 hover:text-[#E85A8B] border border-gray-200 rounded hover:border-[#E85A8B] transition-colors disabled:opacity-40 disabled:cursor-not-allowed",title:c?"Sin datos para exportar":`Descargar ${s}.csv`,"data-testid":n,children:[(0,e.jsx)(Ye,{className:"w-3 h-3"}),r]})}function Ps({countryBreakdown:s}){const t=Object.values(s).reduce((r,n)=>r+n,0),i=Object.entries(s).sort((r,n)=>n[1]-r[1]),a=i.map(([r,n])=>({country:r,sessions:n,percentage:t>0?(n/t*100).toFixed(1):"0"}));return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsx)(v,{children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(Ce,{className:"w-5 h-5"}),"Visitantes por PaÃs"]}),(0,e.jsx)(b,{children:"Distribución geográfica de visitantes"})]}),(0,e.jsx)(K,{filename:"visitantes-por-pais",headers:[{key:"country",label:"PaÃs"},{key:"sessions",label:"Sesiones"},{key:"percentage",label:"%"}],rows:a,"data-testid":"export-country-csv"})]})}),(0,e.jsx)(p,{children:i.length===0?(0,e.jsx)("p",{className:"text-center text-gray-500 py-4",children:"Sin datos geográficos"}):(0,e.jsx)("div",{className:"space-y-3 max-h-64 overflow-y-auto",children:i.map(([r,n])=>{const l=t>0?n/t*100:0,c=bs[r]||"ð";return(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("span",{className:"text-xl",children:c}),(0,e.jsxs)("div",{className:"flex-1",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,e.jsx)("span",{className:"text-sm font-medium",children:r}),(0,e.jsxs)("span",{className:"text-sm text-gray-500",children:[n," (",l.toFixed(1),"%)"]})]}),(0,e.jsx)("div",{className:"h-2 bg-gray-100 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-[#E85A8B] rounded-full transition-all",style:{width:`${l}%`}})})]})]},r)})})})]})}function Fs({deviceBreakdown:s}){const t=Object.values(s).reduce((a,r)=>a+r,0),i=Object.entries(s).map(([a,r])=>({device:a,sessions:r,percentage:t>0?(r/t*100).toFixed(1):"0"}));return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsx)(v,{children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(J,{className:"w-5 h-5"}),"Dispositivos"]}),(0,e.jsx)(b,{children:"Tipo de dispositivo de los visitantes"})]}),(0,e.jsx)(K,{filename:"dispositivos",headers:[{key:"device",label:"Dispositivo"},{key:"sessions",label:"Sesiones"},{key:"percentage",label:"%"}],rows:i,"data-testid":"export-device-csv"})]})}),(0,e.jsx)(p,{children:Object.keys(s).length===0?(0,e.jsx)("p",{className:"text-center text-gray-500 py-4",children:"Sin datos de dispositivos"}):(0,e.jsx)("div",{className:"space-y-4",children:Object.entries(s).map(([a,r])=>{const n=t>0?r/t*100:0,l=ks(a);return(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("div",{className:"w-10 h-10 bg-[#E85A8B]/10 rounded-full flex items-center justify-center",children:(0,e.jsx)(l,{className:"w-5 h-5 text-[#E85A8B]"})}),(0,e.jsxs)("div",{className:"flex-1",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,e.jsx)("span",{className:"text-sm font-medium capitalize",children:a}),(0,e.jsxs)("span",{className:"text-sm text-gray-500",children:[r," (",n.toFixed(1),"%)"]})]}),(0,e.jsx)("div",{className:"h-2 bg-gray-100 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-[#E85A8B] rounded-full transition-all",style:{width:`${n}%`}})})]})]},a)})})})]})}var Ls=[{key:"lcp",label:"LCP",unit:"ms",description:"Largest Contentful Paint"},{key:"fid",label:"FID",unit:"ms",description:"First Input Delay"},{key:"cls",label:"CLS",unit:"",description:"Cumulative Layout Shift"},{key:"ttfb",label:"TTFB",unit:"ms",description:"Time to First Byte"},{key:"fcp",label:"FCP",unit:"ms",description:"First Contentful Paint"},{key:"inp",label:"INP",unit:"ms",description:"Interaction to Next Paint"}];function Ms({performance:s}){return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(Ge,{className:"w-5 h-5"}),"Core Web Vitals"]}),(0,e.jsx)(b,{children:"Métricas de rendimiento (promedios del perÃodo)"})]}),(0,e.jsx)(p,{children:(0,e.jsx)("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4",children:Ls.map(({key:t,label:i,unit:a,description:r})=>{const n=s?.[t],l=n==null?null:typeof n=="number"?n:Number.isFinite(parseFloat(String(n)))?parseFloat(String(n)):null,c=l!==null?t==="cls"?l.toFixed(3):Math.round(l):"â";return(0,e.jsxs)("div",{className:"bg-gray-50 rounded-lg p-4 text-center",children:[(0,e.jsx)("p",{className:"text-xs text-gray-500 mb-1",title:r,children:i}),(0,e.jsxs)("p",{className:`text-2xl font-bold ${oe(t,l)}`,children:[c,l!==null&&a]}),(0,e.jsx)("p",{className:`text-xs mt-1 ${oe(t,l)}`,children:Es(t,l)})]},t)})})})]})}function Is(s){if(!s)return"Elemento desconocido";
3const t=String(s).trim(),i=t.match(/^([a-z0-9]+)((?:\.[\w-]+){0,3})/i);if(i){const a=i[1],r=i[2];return r?`<${a}>${r}`:`<${a}>`}return t.slice(0,50)}function Bs({uxIssues:s}){return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(Ie,{className:"w-5 h-5"}),"Problemas de UX"]}),(0,e.jsx)(b,{children:"Clics frustrados detectados"})]}),(0,e.jsxs)(p,{children:[(0,e.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,e.jsxs)("div",{className:"bg-red-50 rounded-lg p-4 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-gray-600 mb-1",children:"Rage Clicks"}),(0,e.jsx)("p",{className:"text-3xl font-bold text-red-600",children:s?.rageClicks||0}),(0,e.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Clics repetidos de frustración"})]}),(0,e.jsxs)("div",{className:"bg-yellow-50 rounded-lg p-4 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-gray-600 mb-1",children:"Dead Clicks"}),(0,e.jsx)("p",{className:"text-3xl font-bold text-yellow-600",children:s?.deadClicks||0}),(0,e.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Clics sin respuesta"})]})]}),(s?.topRageClickElements?.length||0)>0&&(0,e.jsxs)("div",{className:"mt-4",children:[(0,e.jsx)("p",{className:"text-sm font-semibold text-gray-700 mb-2",children:"Elementos con más problemas:"}),(0,e.jsx)("div",{className:"space-y-2 max-h-32 overflow-y-auto",children:s?.topRageClickElements.slice(0,5).map((t,i)=>{const a=t.selector||t.element||"",r=Is(a),n=t.page||t.path;return(0,e.jsxs)("div",{className:"flex items-center justify-between p-2 bg-gray-50 rounded text-sm gap-2",children:[(0,e.jsxs)("code",{className:"text-xs bg-gray-200 px-2 py-1 rounded truncate max-w-[70%]",title:a+(n?` 4en ${n}`:""),children:[r,n?` · ${n}`:""]}),(0,e.jsxs)("span",{className:"text-red-600 font-medium whitespace-nowrap",children:[t.clickCount||t.count||1," veces"]})]},i)})})]})]})]})}function Os({topPages:s,onPageClick:t}){const i=(s||[]).map((a,r)=>({rank:r+1,page:a.page,views:a.views,uniqueVisitors:a.uniqueVisitors}));return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsx)(v,{children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(Le,{className:"w-5 h-5"}),"Páginas Más Visitadas"]}),(0,e.jsx)(b,{children:"Top 10 páginas con más tráfico"})]}),(0,e.jsx)(K,{filename:"top-paginas",headers:[{key:"rank",label:"#"},{key:"page",label:"Página"},{key:"views",label:"Vistas"},{key:"uniqueVisitors",label:"Ãnicos"}],rows:i,"data-testid":"export-toppages-csv"})]})}),(0,e.jsx)(p,{children:(s?.length||0)===0?(0,e.jsx)("p",{className:"text-center text-gray-500 py-4",children:"Sin datos de páginas"}):(0,e.jsx)("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:s?.map((a,r)=>{const n=(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,e.jsxs)("span",{className:"text-xs text-gray-400 w-5",children:[r+1,"."]}),(0,e.jsx)("span",{className:"text-sm truncate",title:a.page,children:a.page})]}),(0,e.jsxs)("div",{className:"flex items-center gap-3 flex-shrink-0",children:[(0,e.jsxs)("span",{className:"text-sm font-medium text-[#E85A8B]",children:[a.views," vistas"]}),(0,e.jsxs)("span",{className:"text-xs text-gray-500",children:[a.uniqueVisitors," únicos"]})]})]});return t?(0,e.jsx)("button",{type:"button",onClick:()=>t(a.page),className:"w-full flex items-center justify-between p-2 bg-gray-50 hover:bg-[#E85A8B]/5 rounded transition-colors text-left","data-testid":`top-page-${r}`,children:n},r):(0,e.jsx)("div",{className:"flex items-center justify-between p-2 bg-gray-50 rounded",children:n},r)})})})]})}function me(s){const t=new Date(s);return Number.isFinite(t.getTime())?t.toLocaleDateString("es-ES",{day:"2-digit",month:"short"}):s}function $s({data:s,isLoading:t}){const i=Array.isArray(s)&&s.length>0;return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(se,{className:"w-5 h-5"}),"Tendencia del Tráfico"]}),(0,e.jsx)(b,{children:"Sesiones, visitantes y páginas vistas por dÃa"})]}),(0,e.jsxs)(p,{children:[t&&(0,e.jsx)("div",{className:"h-64 flex items-center justify-center text-gray-400",children:"Cargandoâ¦"}),!t&&!i&&(0,e.jsx)("div",{className:"h-64 flex items-center justify-center text-gray-400",children:"Sin datos en el perÃodo"}),!t&&i&&(0,e.jsx)("div",{className:"h-64","data-testid":"timeseries-chart",children:(0,e.jsx)(xs,{width:"100%",height:"100%",children:(0,e.jsxs)(ps,{data:s,margin:{top:10,right:20,left
4:0,bottom:0},children:[(0,e.jsx)(os,{strokeDasharray:"3 3",stroke:"#e5e7eb"}),(0,e.jsx)(us,{dataKey:"date",tickFormatter:me,tick:{fontSize:11,fill:"#6b7280"},minTickGap:20}),(0,e.jsx)(ms,{tick:{fontSize:11,fill:"#6b7280"}}),(0,e.jsx)(hs,{labelFormatter:me}),(0,e.jsx)(ds,{wrapperStyle:{fontSize:12}}),(0,e.jsx)(G,{type:"monotone",dataKey:"sessions",name:"Sesiones",stroke:"#E85A8B",strokeWidth:2,dot:!1}),(0,e.jsx)(G,{type:"monotone",dataKey:"uniqueVisitors",name:"Visitantes únicos",stroke:"#9333ea",strokeWidth:2,dot:!1}),(0,e.jsx)(G,{type:"monotone",dataKey:"pageViews",name:"Páginas vistas",stroke:"#2563eb",strokeWidth:2,dot:!1})]})})})]})]})}function Rs(s){if(!s)return[];const t=[];for(const[i,a]of Object.entries(s.referrerGroups))t.push({type:"referrer",key:i,sessions:a});for(const[i,a]of Object.entries(s.utmSources))t.push({type:"utm_source",key:i,sessions:a});for(const[i,a]of Object.entries(s.utmMediums))t.push({type:"utm_medium",key:i,sessions:a});for(const[i,a]of Object.entries(s.utmCampaigns))t.push({type:"utm_campaign",key:i,sessions:a});return t}function H({label:s,count:t,total:i}){const a=i>0?t/i*100:0;return(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsx)("div",{className:"w-32 truncate text-sm text-gray-700",title:s,children:s}),(0,e.jsx)("div",{className:"flex-1 bg-gray-100 rounded-full h-2 overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-[#E85A8B]",style:{width:`${a}%`}})}),(0,e.jsxs)("div",{className:"text-xs text-gray-500 w-24 text-right whitespace-nowrap",children:[t," (",a.toFixed(1),"%)"]})]})}function X(s,t){const i=Object.entries(s).sort((r,n)=>n[1]-r[1]).slice(0,t),a=Object.values(s).reduce((r,n)=>r+n,0);return i.map(([r,n])=>({key:r,count:n,total:a}))}function _s({sources:s}){const t=X(s?.referrerGroups||{},8),i=X(s?.utmSources||{},5),a=X(s?.utmMediums||{},5),r=i.length>0||a.length>0;return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsx)(v,{children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(es,{className:"w-5 h-5"}),"Fuentes de Tráfico"]}),(0,e.jsx)(b,{children:"Referrers + parámetros UTM (sesiones en el perÃodo)"})]}),(0,e.jsx)(K,{filename:"fuentes-trafico",headers:[{key:"type",label:"Tipo"},{key:"key",label:"Fuente"},{key:"sessions",label:"Sesiones"}],rows:Rs(s),"data-testid":"export-sources-csv"})]})}),(0,e.jsx)(p,{children:(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2",children:"De dónde vienen"}),t.length===0&&(0,e.jsx)("p",{className:"text-sm text-gray-400",children:"Sin datos"}),(0,e.jsx)("div",{className:"space-y-2",children:t.map(n=>(0,e.jsx)(H,{label:n.key,count:n.count,total:n.total},n.key))})]}),r&&(0,e.jsxs)("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t border-gray-100",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2",children:"UTM Source"}),(0,e.jsx)("div",{className:"space-y-2",children:i.map(n=>(0,e.jsx)(H,{label:n.key,count:n.count,total:n.total},n.key))})]}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2",children:"UTM Medium"}),(0,e.jsx)("div",{className:"space-y-2",children:a.map(n=>(0,e.jsx)(H,{label:n.key,count:n.count,total:n.total},n.key))})]})]})]})})]})}function Vs(){const s="https://clarity.microsoft.com/projects/view/rcxibn1b75/dashboard",t=`${s}?filters=%5B%7B%22type%22%3A%22RAGE_CLICK%22%7D%5D`;return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(Re,{className:"w-5 h-5"}),"Session Replay (Clarity)"]}),(0,e.jsx)(b,{children:"Grabaciones reales de sesiones. Filtra por rage clicks para ver en vivo las frustraciones."})]}),(0,e.jsx)(p,{children:(0,e.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,e.jsxs)("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-[#E85A8B] hover:underline text-sm","data-testid":"clarity-dashboard-link",children:[(0,e.jsx)(Y,{className:"w-4 h-4"}),"Abrir dashboard completo"]}),(0,e.jsxs)("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-[#E85A8B] hover:underline text-sm","data-testid":"clarity-rage-link",children:[(0,e.jsx)(Y,{className:"w-4 h-4"}),"Ver sesiones con rage clicks"]})]})})]})}var xe={champions:"Champions",loyal:"Clientes fieles",potential_loyalists:"Potenciales fieles",new_customers:"Nuevos",promising:"Prometedores",needs_attention:"Necesitan atención",at_risk:"En riesgo",cant_lose:"No podemos perder",hibernating:"Hibernando",lost:"Perdidos"},Ks={champions:"bg-green-500",loyal:"bg-emerald-500",potential_loyalists:"bg-teal-500",
4new_customers:"bg-cyan-500",promising:"bg-sky-500",needs_attention:"bg-amber-500",at_risk:"bg-orange-500",cant_lose:"bg-red-600",hibernating:"bg-gray-400",lost:"bg-gray-600"};function T(s){return new Intl.NumberFormat("es-ES",{style:"currency",currency:"EUR",maximumFractionDigits:0}).format(s)}function Us(){const{data:s,isLoading:t,error:i}=w({queryKey:["admin","customer-intelligence"],queryFn:async()=>{const r=await fetch("/api/admin/analytics/customer-intelligence",{credentials:"include"});if(!r.ok)throw new Error(`status_${r.status}`);return r.json()},staleTime:3e5});if(t)return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsx)(v,{children:(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(E,{className:"w-5 h-5"}),"Inteligencia de clientes (RFM + LTV)"]})}),(0,e.jsx)(p,{children:(0,e.jsx)("p",{className:"text-sm text-gray-500",children:"Cargando segmentaciónâ¦"})})]});if(i||!s)return(0,e.jsxs)(g,{className:"bg-white",children:[(0,e.jsx)(v,{children:(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(E,{className:"w-5 h-5"}),"Inteligencia de clientes (RFM + LTV)"]})}),(0,e.jsx)(p,{children:(0,e.jsx)("p",{className:"text-sm text-red-600",children:"No se pudieron cargar los datos."})})]});const a=Math.max(1,s.totals.customers);return(0,e.jsxs)(g,{className:"bg-white","data-testid":"customer-intelligence-card",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(E,{className:"w-5 h-5"}),"Inteligencia de clientes (RFM + LTV)"]}),(0,e.jsx)(b,{children:"Recencia à Frecuencia à Monetario + estimación de valor vitalicio a 3 años. Ideal para dirigir campañas de retención y upsell."})]}),(0,e.jsxs)(p,{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"Clientes"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:s.totals.customers.toLocaleString("es-ES")})]}),(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"LTV total estimado"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:T(s.totals.totalLTV)})]}),(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"LTV medio"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:T(s.totals.avgLTV)})]}),(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"AOV medio"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:T(s.totals.avgOrderValue)})]})]}),(0,e.jsxs)("div",{children:[(0,e.jsx)("h4",{className:"text-sm font-semibold text-gray-800 mb-2",children:"Distribución por segmento"}),(0,e.jsx)("div",{className:"space-y-2",children:s.segments.map(r=>{const n=Math.round(r.count/a*100);return(0,e.jsxs)("div",{className:"flex items-center gap-3","data-testid":`segment-${r.segment}`,children:[(0,e.jsx)("div",{className:"w-36 text-xs text-gray-700 shrink-0",children:xe[r.segment]??r.segment}),(0,e.jsx)("div",{className:"flex-1 bg-gray-100 h-2 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:`${Ks[r.segment]??"bg-gray-500"} h-full`,style:{width:`${n}%`}})}),(0,e.jsxs)("div",{className:"w-20 text-right text-xs text-gray-600 shrink-0 tabular-nums",children:[r.count.toLocaleString("es-ES")," (",n,"%)"]})]},r.segment)})})]}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-800 mb-2 flex items-center gap-2",children:[(0,e.jsx)(se,{className:"w-4 h-4"})," Top clientes por LTV"]}),(0,e.jsx)("div",{className:"overflow-x-auto",children:(0,e.jsxs)("table",{className:"w-full text-xs",children:[(0,e.jsx)("thead",{children:(0,e.jsxs)("tr",{className:"text-gray-500 text-left",children:[(0,e.jsx)("th",{className:"py-2 font-medium",children:"Cliente"}),(0,e.jsx)("th",{className:"py-2 font-medium",children:"Pedidos"}),(0,e.jsx)("th",{className:"py-2 font-medium",children:"Gastado"}),(0,e.jsx)("th",{className:"py-2 font-medium",children:"AOV"}),(0,e.jsx)("th",{className:"py-2 font-medium",children:"LTV"}),(0,e.jsx)("th",{className:"py-2 font-medium",children:"Segmento"})]})}),(0,e.jsx)("tbody",{children:s.topCustomers.map((r,n)=>(0,e.jsxs)("tr",{className:"border-t border-gray-100",children:[(0,e.jsx)("td",{className:"py-2 text-gray-900",children:r.label}),(0,e.jsx)("td",{className:"py-2 tabular-nums",children:r.orders}),(0,e.jsx)("td",{className:"py-2 tabular-nums",children:T(r.totalSpent)}
4),(0,e.jsx)("td",{className:"py-2 tabular-nums",children:T(r.avgOrderValue)}),(0,e.jsx)("td",{className:"py-2 tabular-nums font-medium",children:T(r.ltv)}),(0,e.jsx)("td",{className:"py-2 text-gray-600",children:xe[r.segment]??r.segment})]},`${r.label}-${n}`))})]})})]})]})]})}var ue={position:"Position-based (40/20/40)",last:"Last-touch",first:"First-touch",linear:"Linear (igualitaria)"};function he(s){return new Intl.NumberFormat("es-ES",{style:"currency",currency:"EUR",maximumFractionDigits:0}).format(s)}function qs(){const[s,t]=(0,u.useState)("position"),{data:i,isLoading:a,error:r}=w({queryKey:["admin","attribution"],queryFn:async()=>{const c=await fetch("/api/admin/analytics/attribution",{credentials:"include"});if(!c.ok)throw new Error(`status_${c.status}`);return c.json()},staleTime:6e5}),n=i?Object.entries(i.byModel[s]||{}).sort((c,o)=>o[1]-c[1]):[],l=n.length>0?n[0][1]:1;return(0,e.jsxs)(g,{className:"bg-white","data-testid":"attribution-card",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(Xe,{className:"w-5 h-5"}),"Atribución multi-touch"]}),(0,e.jsxs)(_,{value:s,onValueChange:c=>t(c),children:[(0,e.jsx)($,{className:"w-56 h-8 text-xs","data-testid":"attribution-model-select",children:(0,e.jsx)(O,{})}),(0,e.jsx)(R,{children:Object.keys(ue).map(c=>(0,e.jsx)(S,{value:c,className:"text-xs",children:ue[c]},c))})]})]}),(0,e.jsx)(b,{children:"Distribución de ingresos por canal bajo cuatro modelos. Sólo clientes registrados con sesiones atribuibles (últimos 90 dÃas)."})]}),(0,e.jsxs)(p,{className:"space-y-4",children:[a&&(0,e.jsx)("p",{className:"text-sm text-gray-500",children:"Cargando atribuciónâ¦"}),r&&(0,e.jsx)("p",{className:"text-sm text-red-600",children:"Error al cargar la atribución."}),i&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"Pedidos totales"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:i.totalOrders.toLocaleString("es-ES")})]}),(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"Pedidos atribuidos"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:i.attributedOrders.toLocaleString("es-ES")})]}),(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"Ingresos atribuidos"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:he(i.totalRevenue)})]})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[n.length===0&&(0,e.jsx)("p",{className:"text-sm text-gray-500",children:"Sin datos suficientes en los últimos 90 dÃas."}),n.map(([c,o])=>{const x=Math.round(o/Math.max(1,l)*100);return(0,e.jsxs)("div",{className:"flex items-center gap-3","data-testid":`attrib-source-${c}`,children:[(0,e.jsx)("div",{className:"w-32 text-xs text-gray-700 truncate shrink-0",children:c}),(0,e.jsx)("div",{className:"flex-1 bg-gray-100 h-2 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:"bg-[#E85A8B] h-full",style:{width:`${x}%`}})}),(0,e.jsx)("div",{className:"w-24 text-right text-xs tabular-nums shrink-0",children:he(o)})]},c)})]})]})]})]})}var Q=["Lun","Mar","Mié","Jue","Vie","Sáb","Dom"];function pe(s){return new Intl.NumberFormat("es-ES",{style:"currency",currency:"EUR",maximumFractionDigits:0}).format(s)}function zs(){const{data:s,isLoading:t,error:i}=w({queryKey:["admin","conversion-heatmaps"],queryFn:async()=>{const l=await fetch("/api/admin/analytics/conversion-heatmaps",{credentials:"include"});if(!l.ok)throw new Error(`status_${l.status}`);return l.json()},staleTime:6e5}),a=(0,u.useMemo)(()=>{const l=[];for(let o=0;o<7;o++)l.push(Array(24).fill(null));let c=1;if(s)for(const o of s.byHour)o.dow>=0&&o.dow<7&&o.hour>=0&&o.hour<24&&(l[o.dow][o.hour]={orders:o.orders,avgTotal:o.avgTotal},o.orders>c&&(c=o.orders));return{cells:l,max:c}},[s]),r=s?.byProvince.slice(0,12)??[],n=r.length>0?r[0].revenue:1;return(0,e.jsxs)(g,{className:"bg-white","data-testid":"conversion-heatmaps-card",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(ve,{className:"w-5 h-5"}),"Mapas de conversión (geográfico + horario)"]}),(0,e.jsx)(b,{children:"Dónde y cuándo convierten tus clientes en los últimos 90 dÃas."})]}),(0,e.jsxs)(p,{className:"space-y-6",children:[t&&(0,e.jsx)("p",{className:"text-sm text-gray-500",children:"Cargando mapasâ¦"}),i&&(0,e.jsx)("p",{className:"text-sm text-red-600",children:"Error al cargar los mapas."}),s&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h4",{className:"text-sm font-semibold text-gray-800 mb
4-2",children:"Top provincias por ingresos"}),(0,e.jsxs)("div",{className:"space-y-1.5",children:[r.length===0&&(0,e.jsx)("p",{className:"text-xs text-gray-500",children:"Sin datos."}),r.map(l=>{const c=Math.round(l.revenue/Math.max(1,n)*100);return(0,e.jsxs)("div",{className:"flex items-center gap-3","data-testid":`prov-${l.province}`,children:[(0,e.jsx)("div",{className:"w-32 text-xs text-gray-700 truncate shrink-0",children:l.province}),(0,e.jsx)("div",{className:"flex-1 bg-gray-100 h-2 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:"bg-[#E85A8B] h-full",style:{width:`${c}%`}})}),(0,e.jsxs)("div",{className:"w-28 text-right text-xs tabular-nums shrink-0",children:[l.orders," · ",pe(l.revenue)]})]},l.province)})]})]}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-800 mb-2 flex items-center gap-2",children:[(0,e.jsx)(Me,{className:"w-4 h-4"})," DÃa à hora (pedidos)"]}),(0,e.jsx)("div",{className:"overflow-x-auto",children:(0,e.jsxs)("table",{className:"text-[10px] border-separate border-spacing-[1px]",children:[(0,e.jsx)("thead",{children:(0,e.jsxs)("tr",{children:[(0,e.jsx)("th",{className:"text-left w-10","aria-label":"DÃa"}),Array.from({length:24},(l,c)=>(0,e.jsx)("th",{className:"text-center text-gray-500 w-6",children:c},c))]})}),(0,e.jsx)("tbody",{children:a.cells.map((l,c)=>(0,e.jsxs)("tr",{children:[(0,e.jsx)("td",{className:"text-gray-700 pr-1",children:Q[c]}),l.map((o,x)=>{const m=o?Math.min(1,o.orders/Math.max(1,a.max)):0,h=m===0?"#f3f4f6":`rgba(16, 185, 129, ${Math.max(.08,m)})`,d=o?`${Q[c]} ${x}h: ${o.orders} pedidos · AOV ${pe(o.avgTotal)}`:`${Q[c]} ${x}h: sin pedidos`;return(0,e.jsx)("td",{title:d,"aria-label":d,style:{backgroundColor:h},className:"w-6 h-5 rounded-[2px]","data-testid":`heatcell-${c}-${x}`},x)})]},c))})]})})]})]})]})]})}function Gs(){const{data:s,isLoading:t,error:i}=w({queryKey:["admin","behaviour-events"],queryFn:async()=>{const a=await fetch("/api/admin/analytics/behaviour-events",{credentials:"include"});if(!a.ok)throw new Error(`status_${a.status}`);return a.json()},staleTime:3e5});return(0,e.jsxs)(g,{className:"bg-white","data-testid":"behaviour-events-card",children:[(0,e.jsxs)(v,{children:[(0,e.jsxs)(y,{className:"text-[#E85A8B] flex items-center gap-2",children:[(0,e.jsx)(Ne,{className:"w-5 h-5"}),"Comportamiento del usuario"]}),(0,e.jsx)(b,{children:"Búsquedas, uso de filtros, profundidad de scroll y embudo del quiz (últimos 30 dÃas)."})]}),(0,e.jsxs)(p,{className:"space-y-6",children:[t&&(0,e.jsx)("p",{className:"text-sm text-gray-500",children:"Cargando comportamientoâ¦"}),i&&(0,e.jsx)("p",{className:"text-sm text-red-600",children:"Error al cargar los eventos de comportamiento."}),s&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("section",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-800 mb-2 flex items-center gap-2",children:[(0,e.jsx)(We,{className:"w-4 h-4"})," Top búsquedas internas"]}),s.topSearches.length===0?(0,e.jsx)("p",{className:"text-xs text-gray-500",children:"Sin búsquedas capturadas todavÃa."}):(0,e.jsxs)("table",{className:"w-full text-xs",children:[(0,e.jsx)("thead",{children:(0,e.jsxs)("tr",{className:"text-gray-500 text-left",children:[(0,e.jsx)("th",{className:"py-2 font-medium",children:"Consulta"}),(0,e.jsx)("th",{className:"py-2 font-medium text-right",children:"Usos"}),(0,e.jsx)("th",{className:"py-2 font-medium text-right",children:"Sin resultados"})]})}),(0,e.jsx)("tbody",{children:s.topSearches.map(a=>(0,e.jsxs)("tr",{className:"border-t border-gray-100",children:[(0,e.jsx)("td",{className:"py-2 text-gray-900",children:a.query}),(0,e.jsx)("td",{className:"py-2 tabular-nums text-right",children:a.uses}),(0,e.jsx)("td",{className:`py-2 tabular-nums text-right ${a.zeroResults>0?"text-red-600 font-medium":"text-gray-500"}`,children:a.zeroResults})]},a.query))})]})]}),(0,e.jsxs)("section",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-800 mb-2 flex items-center gap-2",children:[(0,e.jsx)(Ze,{className:"w-4 h-4"})," Profundidad de scroll"]}),(0,e.jsx)("div",{className:"space-y-1.5",children:[25,50,75,100].map(a=>{const r=s.scrollDepth.find(c=>c.bucket===a)?.visitors??0,n=Math.max(1,...s.scrollDepth.map(c=>c.visitors)),l=Math.round(r/n*100);return(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsxs)("div",{className:"w-12 text-xs text-gray-700 shrink-0",children:[a,"%"]}),(0,e.jsx)("div",{className:"flex-1 bg-gray-100 h-2 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:"bg-indigo-500 h-full",style:{width:`${l}%`}})}),(0,e.jsx)("div",{className:"w-20 text-right text-xs tabular-nums shrink-0",children:r.toLocaleStr
4ing("es-ES")})]},a)})})]}),(0,e.jsxs)("section",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-800 mb-2 flex items-center gap-2",children:[(0,e.jsx)(ss,{className:"w-4 h-4"})," Filtros más usados"]}),s.topFacets.length===0?(0,e.jsx)("p",{className:"text-xs text-gray-500",children:"Sin uso de filtros capturado todavÃa."}):(0,e.jsx)("div",{className:"flex flex-wrap gap-2",children:s.topFacets.map((a,r)=>(0,e.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-xs px-2 py-1 rounded-full bg-pink-50 border border-pink-100 text-pink-800",children:[(0,e.jsx)("span",{className:"font-medium",children:a.field}),(0,e.jsx)("span",{className:"text-pink-400",children:"·"}),(0,e.jsx)("span",{children:a.value||"(sin valor)"}),(0,e.jsx)("span",{className:"text-pink-400",children:"·"}),(0,e.jsx)("span",{className:"tabular-nums",children:a.uses})]},`${a.field}-${a.value}-${r}`))})]}),(0,e.jsxs)("section",{children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-800 mb-2 flex items-center gap-2",children:[(0,e.jsx)(He,{className:"w-4 h-4"})," Embudo del quiz"]}),(0,e.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"Inicios"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:s.quizFunnel.starts.toLocaleString("es-ES")})]}),(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"Completados"}),(0,e.jsx)("div",{className:"text-lg font-semibold text-gray-900",children:s.quizFunnel.completes.toLocaleString("es-ES")})]}),(0,e.jsxs)("div",{className:"p-3 bg-gray-50 rounded-lg",children:[(0,e.jsx)("div",{className:"text-xs text-gray-500",children:"% finalización"}),(0,e.jsxs)("div",{className:"text-lg font-semibold text-gray-900",children:[s.quizFunnel.completionRate.toFixed(1),"%"]})]})]}),s.quizFunnel.steps.length>0&&(0,e.jsx)("div",{className:"mt-3 space-y-1.5",children:s.quizFunnel.steps.map(a=>(0,e.jsxs)("div",{className:"flex items-center gap-3",children:[(0,e.jsxs)("div",{className:"w-16 text-xs text-gray-700 shrink-0",children:["Paso ",a.stepIndex+1]}),(0,e.jsx)("div",{className:"flex-1 bg-gray-100 h-2 rounded-full overflow-hidden",children:(0,e.jsx)("div",{className:"bg-teal-500 h-full",style:{width:`${Math.max(0,Math.min(100,s.quizFunnel.starts>0?a.events/s.quizFunnel.starts*100:0))}%`}})}),(0,e.jsx)("div",{className:"w-20 text-right text-xs tabular-nums shrink-0",children:a.events.toLocaleString("es-ES")})]},a.stepIndex))})]})]})]})]})}function Hs({path:s,open:t,onOpenChange:i,dateRange:a,customStart:r,customEnd:n}){const{data:l,isLoading:c}=Ss(s,a,r,n),o=Object.entries(l?.referrerBreakdown||{}).sort((m,h)=>h[1]-m[1]).slice(0,8),x=o.reduce((m,[,h])=>m+h,0);return(0,e.jsx)(ae,{open:t,onOpenChange:i,children:(0,e.jsxs)(ie,{className:"max-w-2xl",children:[(0,e.jsxs)(re,{children:[(0,e.jsx)(te,{className:"text-[#E85A8B]",children:"Detalle de página"}),(0,e.jsx)(ne,{className:"truncate font-mono text-xs",children:s})]}),c&&(0,e.jsx)("div",{className:"py-8 text-center text-gray-500",children:"Cargandoâ¦"}),!c&&l&&(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[(0,e.jsx)(I,{icon:L,label:"Vistas",value:l.summary.views}),(0,e.jsx)(I,{icon:E,label:"Ãnicos",value:l.summary.uniqueVisitors}),(0,e.jsx)(I,{icon:W,label:"Duración media",value:Z(l.summary.avgDuration)}),(0,e.jsx)(I,{icon:W,label:"Máx. duración",value:Z(l.summary.maxDuration)})]}),(0,e.jsxs)("div",{className:"bg-white border border-gray-100 rounded-lg p-4",children:[(0,e.jsxs)("h4",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[(0,e.jsx)(ve,{className:"w-4 h-4 text-[#E85A8B]"}),"De dónde llegan"]}),o.length===0&&(0,e.jsx)("p",{className:"text-sm text-gray-400",children:"Sin datos de referrer"}),(0,e.jsx)("div",{className:"space-y-2",children:o.map(([m,h])=>{const d=x>0?h/x*100:0;return(0,e.jsxs)("div",{className:"flex items-center gap-3","data-testid":`page-ref-${m}`,children:[(0,e.jsx)("div",{className:"w-28 truncate text-sm text-gray-700",title:m,children:m}),(0,e.jsx)("div",{className:"flex-1 bg-gray-100 rounded-full h-2 overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-[#E85A8B]",style:{width:`${d}%`}})}),(0,e.jsxs)("div",{className:"text-xs text-gray-500 w-20 text-right",children:[h," (",d.toFixed(1),"%)"]})]},m)})})]}),(0,e.jsxs)("div",{className:"bg-white border border-gray-100 rounded-lg p-4",children:[(0,e.jsx)("h4",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Evolución por dÃa"}),l.timeseries.length===0?(0,e.jsx)("p",{className:"text-sm text-gray-400",children:"Sin actividad"}):(0,e.jsx)("div",{className:"max-h-48 overflow-y-auto",children:(0,e.jsxs)("table",{className:"w-full text-sm",children:[(0,e.jsx)("thead",{className:"text-left text-xs text-gray-500",children:(0,e.jsxs)("tr",{children:[(0,e.jsx)("th",{className:"py-1",children:"DÃa"}),(0,e.jsx)("th",{className:"py-1 text-right",children:"Vistas"})]})}),(0,e.jsx)("tbody",{children:l.timeseries.slice().reverse().map(m=>(0,e.jsxs)("tr",{className:"border-t border-gray-50",children:[(0,e.jsx)("td",{className:"py-1",children:m.date}),(0,e.jsx)("td",{className:"py-1 text-right font-medium",children:m.views})]},m.date))})]})})]})]})]})})}function I({icon:s,label:t,value:i}){return(0,e.jsxs)("div",{className:"bg-gray-50 rounded-lg p-3",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-xs text-gray-500 mb-1",children:[(0,e.jsx)(s,{className:"w-3.5 h-3.5"}),t]}),(0,e.jsx)("div",{className:"text-xl font-bold text-[#E85A8B]",children:i})]})}function ge(){return new Date().toISOString().slice(0,10)}function Xs(s){const t=new Date;return t.setDate(t.getDate()-s),t.toISOString().slice(0,10)}function Ft(){const[s,t]=(0,u.useState)("30d"),[i,a]=(0,u.useState)(Xs(30)),[r,n]=(0,u.useState)(ge()),[l,c]=(0,u.useState)(null),[o,x]=(0,u.useState)("all"),m=s==="custom"?i:void 0,h=s==="custom"?r:void 0,{data:d,isLoading:A}=Ns(s,m,h,o),{data:D,isLoading:M}=ws(s,m,h),{data:Ee}=Cs(s,m,h),le=(0,u.useMemo)(()=>s==="custom"&&(!i||!r||new Date(i)>new Date(r)),[s,i,r]);return A?(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsx)("h3",{className:"text-lg font-semibold text-gray-800",children:"AnalÃticas Avanzadas"}),(0,e.jsx)("div",{className:"text-center py-8 text-gray-500",children:"Cargando datos..."})]}):(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[(0,e.jsx)("h3",{className:"text-lg font-semibold text-gray-800",children:"AnalÃticas Avanzadas"}),(0,e.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,e.jsxs)(_,{value:o,onValueChange:N=>x(N),children:[(0,e.jsx)($,{className:"w-40","data-testid":"select-analytics-segment",children:(0,e.jsx)(O,{})}),(0,e.jsxs)(R,{children:[(0,e.jsx)(S,{value:"all",children:"Todos los visitantes"}),(0,e.jsx)(S,{value:"new",children:"Solo nuevos"}),(0,e.jsx)(S,{value:"returning",children:"Solo recurrentes"})]})]}),(0,e.jsxs)(_,{value:s,onValueChange:t,children:[(0,e.jsx)($,{className:"w-40","data-testid":"select-analytics-period",children:(0,e.jsx)(O,{})}),(0,e.jsx)(R,{children:fs.map(N=>(0,e.jsx)(S,{value:N.value,children:N.label},N.value))})]}),s==="custom"&&(0,e.jsxs)("div",{className:"flex items-center gap-1","data-testid":"custom-date-range",children:[(0,e.jsx)("input",{type:"date",value:i,max:r,onChange:N=>a(N.target.value),className:`h-9 rounded-md border px-2 text-sm ${le?"border-red-500":"border-gray-300"}`,"aria-label":"Fecha inicio","data-testid":"input-custom-start"}),(0,e.jsx)("span",{className:"text-gray-400 text-sm",children:"â"}),(0,e.jsx)("input",{type:"date",value:r,min:i,max:ge(),onChange:N=>n(N.target.value),className:`h-9 rounded-md border px-2 text-sm ${le?"border-red-500":"border-gray-300"}`,"aria-label":"Fecha fin","data-testid":"input-custom-end"})]})]})]}),(0,e.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 ga
4p-4",children:[(0,e.jsx)(C,{title:"Sesiones Totales",value:d?.overview.totalSessions||0,icon:Ne,subtitle:"Visitas en el perÃodo",delta:d?.previous?{previous:d.previous.totalSessions,current:d.overview.totalSessions}:void 0}),(0,e.jsx)(C,{title:"Visitantes Ãnicos",value:d?.overview.uniqueVisitors||0,icon:E,subtitle:"Usuarios distintos",delta:d?.previous?{previous:d.previous.uniqueVisitors,current:d.overview.uniqueVisitors}:void 0}),(0,e.jsx)(C,{title:"Páginas Vistas",value:d?.overview.totalPageViews||0,icon:L,subtitle:"Total de visualizaciones",delta:d?.previous?{previous:d.previous.totalPageViews,current:d.overview.totalPageViews}:void 0}),(0,e.jsx)(C,{title:"Duración Media",value:Z(d?.overview.avgSessionDuration||0),icon:W,subtitle:`${(d?.overview.bounceRate||0).toFixed(1)}% rebote`,delta:d?.previous?{previous:d.previous.avgSessionDuration,current:d.overview.avgSessionDuration}:void 0}),(0,e.jsx)(C,{title:"Conversión",value:`${(d?.overview.conversionRate||0).toFixed(2)}%`,icon:Ue,subtitle:`${d?.overview.orders||0} pedidos confirmados`,delta:d?.previous?{previous:d.previous.conversionRate||0,current:d.overview.conversionRate||0}:void 0,"data-testid":"stats-conversion"})]}),(0,e.jsx)($s,{data:D,isLoading:M}),(0,e.jsxs)("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[(0,e.jsx)(Ps,{countryBreakdown:d?.countryBreakdown||{}}),(0,e.jsx)(Fs,{deviceBreakdown:d?.deviceBreakdown||{}})]}),(0,e.jsx)(_s,{sources:Ee}),(0,e.jsx)(Ms,{performance:d?.performance}),(0,e.jsxs)("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[(0,e.jsx)(Bs,{uxIssues:d?.uxIssues}),(0,e.jsx)(Os,{topPages:d?.topPages,onPageClick:c})]}),(0,e.jsx)(Vs,{}),(0,e.jsx)(Us,{}),(0,e.jsx)(qs,{}),(0,e.jsx)(zs,{}),(0,e.jsx)(Gs,{}),(0,e.jsx)(Hs,{path:l,open:!!l,onOpenChange:N=>!N&&c(null),dateRange:s,customStart:m,customEnd:h})]})}function Qs(){const[s,t]=(0,u.useState)(!1),[i,a]=(0,u.useState)(""),[r,n]=(0,u.useState)("read"),[l,c]=(0,u.useState)(""),[o,x]=(0,u.useState)(null),[m,h]=(0,u.useState)(!1);return{showCreateDialog:s,setShowCreateDialog:t,newKeyName:i,setNewKeyName:a,newKeyPermissions:r,setNewKeyPermissions:n,newKeyExpiry:l,setNewKeyExpiry:c,generatedKey:o,setGeneratedKey:x,showKey:m,setShowKey:h,resetCreateForm:()=>{a(""),n("read"),c("")}}}function Ws(){const{data:s=[],isLoading:t}=w({queryKey:["/api/admin/api-keys"]});return{apiKeys:s,isLoading:t}}function Js(s,t){const i=Te();return{createKeyMutation:U({mutationFn:async a=>await(await q("/api/admin/api-keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json(),onSuccess:a=>{s(a.key),i.invalidateQueries({queryKey:["/api/admin/api-keys"]}),t()}}),deleteKeyMutation:U({mutationFn:async a=>(await q(`/api/admin/api-keys/${a}`,{method:"DELETE"})).json(),onSuccess:()=>{i.invalidateQueries({queryKey:["/api/admin/api-keys"]})}}),toggleKeyMutation:U({mutationFn:async({id:a,isActive:r})=>(await q(`/api/admin/api-keys/${a}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:r})})).json(),onSuccess:()=>{i.invalidateQueries({queryKey:["/api/admin/api-keys"]})}})}}function Ys({apiKey:s,dateLocale:t,t:i}){return(0,e.jsxs)("div",{className:"flex items-start gap-3",children:[(0,e.jsx)("div",{className:"w-10 h-10 bg-[#E85A8B]/10 rounded-full flex items-center justify-center flex-shrink-0",children:(0,e.jsx)(ee,{className:"w-5 h-5 text-[#E85A8B]"})}),(0,e.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,e.jsx)("h4",{className:"font-semibold text-gray-800 truncate",children:s.name}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-1 mt-1",children:[(0,e.jsx)(k,{variant:s.isActive?"default":"secondary",className:"text-xs",children:s.isActive?i.admin.statusActive:i.admin.statusInactive}),(0,e.jsx)(k,{variant:"outline",className:"text-xs",children:s.permissions})]}),(0,e.jsxs)("p",{className:"text-xs text-gray-500 font-mono mt-1 truncate",children:[s.keyPrefix,"..."]}),(0,e.jsxs)("p",{className:"text-xs text-gray-400 mt-1",children:["Creada:"," ",ce(new Date(s.createdAt),"dd MMM yyyy",{locale:t}),s.lastUsedAt&&(0,e.jsxs)("span",{className:"block sm:inline",children:[" ","· Ãltimo uso:"," ",ce(new Date(s.lastUsedAt),"dd MMM yyyy",{locale:t})]})]})]})]})}function Zs({open:s,onClose:t,keyName:i,revealedKey:a}){const[r,n]=(0,u.useState)(!1),l=()=>{n(!1),t()},c=async()=>
4{if(a)try{if(!navigator.clipboard){f.error("Copia manual: selecciona y copia el texto");return}await navigator.clipboard.writeText(a),f.success("Clave copiada al portapapeles")}catch{f.error("No se pudo copiar")}};return(0,e.jsx)(ae,{open:s,onOpenChange:l,children:(0,e.jsxs)(ie,{children:[(0,e.jsxs)(re,{children:[(0,e.jsxs)(te,{children:["Clave API: ",i]}),(0,e.jsx)(ne,{children:"Copia esta clave para usarla en tu integración."})]}),a&&(0,e.jsx)("div",{className:"space-y-4",children:(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(B,{type:r?"text":"password",value:a,readOnly:!0,className:"font-mono text-sm"}),(0,e.jsx)(j,{variant:"outline",size:"icon",onClick:()=>n(!r),children:r?(0,e.jsx)(we,{className:"w-4 h-4"}):(0,e.jsx)(L,{className:"w-4 h-4"})}),(0,e.jsx)(j,{variant:"outline",size:"icon",onClick:c,children:(0,e.jsx)(P,{className:"w-4 h-4"})})]})}),(0,e.jsx)(Se,{children:(0,e.jsx)(j,{onClick:l,className:"bg-[#E85A8B] hover:bg-[#E85A8B]/90",children:"Cerrar"})})]})})}function et({apiKey:s,onToggle:t,onDelete:i,dateLocale:a,t:r}){const[n,l]=(0,u.useState)(!1),[c,o]=(0,u.useState)(null),[x,m]=(0,u.useState)(!1),h=async()=>{m(!0);try{const A=await fetch(`/api/admin/api-keys/${s.id}/reveal`,{credentials:"include"}),D=await A.json();A.ok?(o(D.key),l(!0)):f.error(D.error||"No se pudo obtener la clave")}catch{f.error("Error al revelar la clave")}finally{m(!1)}},d=()=>{l(!1),o(null)};return(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(g,{className:"bg-white",children:(0,e.jsx)(p,{className:"p-4",children:(0,e.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,e.jsx)(Ys,{apiKey:s,dateLocale:a,t:r}),(0,e.jsxs)("div",{className:"flex items-center justify-between pt-2 border-t border-gray-100",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(cs,{checked:s.isActive,onCheckedChange:t,"data-testid":`switch-api-key-${s.id}`}),(0,e.jsx)("span",{className:"text-xs text-gray-500",children:s.isActive?r.admin.statusActive:r.admin.statusInactive})]}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsxs)(j,{variant:"outline",size:"sm",onClick:h,disabled:x,className:"text-blue-600 hover:text-blue-800","data-testid":`button-reveal-key-${s.id}`,children:[(0,e.jsx)(L,{className:"w-4 h-4 mr-1"}),(0,e.jsx)("span",{className:"hidden sm:inline",children:"Ver"})]}),(0,e.jsxs)(j,{variant:"outline",size:"sm",onClick:i,className:"text-red-500 hover:text-red-700","data-testid":`button-delete-key-${s.id}`,children:[(0,e.jsx)(as,{className:"w-4 h-4 mr-1"}),(0,e.jsx)("span",{className:"hidden sm:inline",children:"Eliminar"})]})]})]})]})})}),(0,e.jsx)(Zs,{open:n,onClose:d,keyName:s.name,revealedKey:c})]})}function F({title:s,icon:t,permission:i,permissionColor:a,endpoints:r,responseExample:n,fields:l}){const[c,o]=(0,u.useState)(!1);return(0,e.jsxs)(ns,{open:c,onOpenChange:o,children:[(0,e.jsx)(is,{asChild:!0,children:(0,e.jsxs)("button",{className:"w-full flex items-center justify-between p-3 bg-white border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors","aria-expanded":c,"data-testid":`button-toggle-${s.toLowerCase().replace(/\s+/g,"-")}-docs`,children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[t,(0,e.jsx)("span",{className:"font-medium text-blue-900 text-sm",children:s}),(0,e.jsx)(k,{className:`text-xs ${a}`,children:i})]}),c?(0,e.jsx)(ye,{className:"w-4 h-4 text-blue-600"}):(0,e.jsx)(fe,{className:"w-4 h-4 text-blue-600"})]})}),(0,e.jsx)(rs,{children:(0,e.jsxs)("div",{className:"mt-2 p-4 bg-white border border-blue-200 rounded-lg space-y-4",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h6",{className:"text-xs font-semibold text-gray-500 uppercase mb-2",children:"Endpoints"}),(0,e.jsx)("div",{className:"space-y-1",children:r.map((x,m)=>(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[(0,e.jsx)(k,{className:x.method==="GET"?"bg-green-100 text-green-800":x.method==="PATCH"?"bg-yellow-100 text-yellow-800":"bg-blue-100 text-blue-800",variant:"secondary",children:x.method}),(0,e.jsx)("code",{className:"text-xs bg-gray-100 px-1 rounded",children:x.path}),(0,e.jsxs)("span",{className:"text-xs text-gray-500",children:["â ",x.description]})]},m))})]}),(0,e.jsxs)("div",{children:[(0,e.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,e.jsx)("h6",{className:"text-xs font-semibold text-gray-500 uppercase",children:"Ejemplo de Respuesta"}),(0,e.jsx)(j,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:async()=>{try{if(!navigator.clipboard){f.error("Copia manual: selecciona y copia el texto");return}await navigator.clipboard.writeText(n),f.success("JSON copiado")}catch{f.error("No se pudo copiar")}},children:(0,e.jsx)(P,{className:"w-3 h-3"})})]}),(0,e.jsx)("pre",{className:"bg-gray-900 text-gray-100 p-3 rounded text-xs font-mono overflow-x-auto max-h-48",children:n})]}),(0,e.jsxs)("div",{children:[(0,e.jsx)("h6",{className:"text-xs font-semibold text-gray-500 uppercase mb-2",children:"Campos"}),(0,e.jsx)("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-1 text-xs",children:l.map((x,m)=>(0,e.jsxs)("div",{children:[(0,e.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:x.name}),(0,e.jsxs)("span",{className:"text-gray-500",children:[" â ",x.desc]})]},m))})]})]})})]})}var st=`{ 5 "products": [ 6 { 7 "id": "prod_123", 8 "name": "Producto Ejemplo", 9 "slug": "producto-ejemplo", 10 "description": "Descripción del producto...", 11 "price": 29.99, 12 "compareAtPrice": 39.99, 13 "stock": 50, 14 "sku": "SKU-001", 15 "categoryId": "cat_abc", 16 "isActive": true, 17 "images": ["https://..."], 18 "createdAt": "2024-01-10T..." 19 } 20 ], 21 "total": 1, 22 "page": 1, 23 "limit": 20 24}`,tt=`{ 25 "categories": [ 26 { 27 "id": "cat_abc", 28 "name": "CategorÃa Ejemplo", 29 "slug": "categoria-ejemplo", 30 "description": "Descripción...", 31 "imageUrl": "https://...", 32 "parentId": null, 33 "isActive": true 34 } 35 ], 36 "total": 1 37}`,at=`{ 38 "orders": [ 39 { 40 "id": "order_xyz", 41 "orderNumber": "IL-20240110-001", 42 "userId": "user_abc", 43 "status": "completed", 44 "subtotal": 59.98, 45 "shipping": 4.99, 46 "total": 64.97, 47 "shippingAddress": {...}, 48 "items": [ 49 { 50 "productId": "prod_123", 51 "name": "Producto", 52 "quantity": 2, 53 "price": 29.99 54 } 55 ], 56 "createdAt": "2024-01-10T..." 57 } 58 ], 59 "total": 1 60}`,rt=`{ 61 "users": [ 62 { 63 "id": "user_abc", 64 "email": "[email protected]", 65 "firstName": "MarÃa", 66 "lastName": "GarcÃa", 67 "phone": "+34612345678", 68 "loyaltyPoints": 150, 69 "createdAt": "2024-01-10T..." 70 } 71 ], 72 "total": 1 73}`,it=`{ 74 "totalOrders": 150, 75 "totalRevenue": 12500.50, 76 "totalProducts": 85, 77 "totalUsers": 320, 78 "ordersToday": 5, 79 "revenueToday": 245.00 80}`;function nt(){const[s,t]=(0,u.useState)(!1),i=typeof window<"u"?window.location.origin:"https://tu-dominio.replit.app";return(0,e.jsx)(g,{className:"bg-blue-50 border-blue-200",children:(0,e.jsxs)(p,{className:"p-4",children:[(0,e.jsxs)("button",{onClick:()=>t(!s),className:"w-full flex items-center justify-between text-left","aria-expanded":s,"aria-controls":"api-docs-full-content","data-testid":"button-toggle-full-api-docs",children:[(0,e.jsxs)("h4",{className:"font-semibold text-blue-800 flex items-center gap-2",children:[(0,e.jsx)(ee,{className:"w-4 h-4"}),"Documentación API Completa"]}),s?(0,e.jsx)(ye,{className:"w-4 h-4 text-blue-600"}):(0,e.jsx)(fe,{className:"w-4 h-4 text-blue-600"})]}),s&&(0,e.jsxs)("div",{id:"api-docs-full-content",className:"mt-4 space-y-4",children:[(0,e.jsxs)("div",{className:"bg-white border border-blue-200 rounded-lg p-4 space-y-3",children:[(0,e.jsx)("h5",{className:"font-semibold text-blue-900 text-sm",children:"Información General"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-xs text-gray-500 w-20",children:"URL Base:"}),(0,e.jsx)("code",{className:"bg-blue-100 px-2 py-1 rounded text-xs flex-1 overflow-x-auto",children:i}),(0,e.jsx)(j,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:async()=>{try{if(!navigator.clipboard){f.error("Copia manual");return}await navigator.clipboard.writeText(i),f.success("URL copiada")}catch{f.error("No se pudo copiar")}},children:(0,e.jsx)(P,{className:"w-3 h-3"})})]}),(0,e.jsxs)("div",{children:[(0,e.jsx)("span",{className:"text-xs text-gray-500",children:"Header requerido:"}),(0,e.jsxs)("div",{className:"bg-gray-900 text-gray-100 p-2 rounded text-xs font-mono mt-1",children:["Authorization: Bearer ",(0,e.jsx)("span",{className:"text-yellow-400",children:"TU_CLAVE_API"})]})]})]})]}),(0,e.jsxs)("div",{className:"bg-white border border-blue-200 rounded-lg p-4 space-y-2",children:[(0,e.jsx)("h5",{className:"font-semibold text-blue-900 text-sm",children:"Niveles de Permiso"}),(0,e.jsxs)("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs",children:[(0,e.jsxs)("div",{className:"p-2 bg-gray-50 rounded",children:[(0,e.jsx)(k,{className:"bg-gray-100 text-gray-700",children:"read"}),(0,e.jsx)("p",{className:"mt-1 text-gray-600",children:"Productos, CategorÃas"})]}),(0,e.jsxs)("div",{className:"p-2 bg-gray-50 rounded",children:[(0,e.jsx)(k,{className:"bg-blue-100 text-blue-700",children:"write"}),(0,e.jsx)("p",{className:"mt-1 text-gray-600",children:"+ Pedidos, Stats, Stock"})]}),(0,e.jsxs)("div",{className:"p-2 bg-gray-50 rounded",children:[(0,e.jsx)(k,{className:"bg-purple-100 text-purple-700",children:"full"}),(0,e.jsx)("p",{className:"mt-1 text-gray-600",children:"+ Usuarios (todos)"})]})]})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("h5",{className:"font-semibold text-blue-900 text-sm",children:"Endpoints por Recurso"}),(0,e.jsx)(F,{title:"Productos",icon:(0,e.jsx)(qe,{className:"w-4 h-4 text-blue-600"}),permission:"read",permissionColor:"bg-gray-100 text-gray-700",endpoints:[{method:"GET",path:"/api/v1/products",description:"Listar productos"},{method:"GET",path:"/api/v1/products/:id",description:"Obtener producto"},{method:"PATCH",path:"/api/v1/products/:id/stock",description:"Actualizar stock (write)"}
80],responseExample:st,fields:[{name:"id",desc:"ID único"},{name:"name",desc:"Nombre"},{name:"slug",desc:"URL amigable"},{name:"price",desc:"Precio actual"},{name:"compareAtPrice",desc:"Precio anterior"},{name:"stock",desc:"Cantidad en stock"},{name:"sku",desc:"Código SKU"},{name:"categoryId",desc:"ID de categorÃa"}]}),(0,e.jsx)(F,{title:"CategorÃas",icon:(0,e.jsx)(Je,{className:"w-4 h-4 text-blue-600"}),permission:"read",permissionColor:"bg-gray-100 text-gray-700",endpoints:[{method:"GET",path:"/api/v1/categories",description:"Listar categorÃas"},{method:"GET",path:"/api/v1/categories/:slug",description:"Obtener categorÃa"}],responseExample:tt,fields:[{name:"id",desc:"ID único"},{name:"name",desc:"Nombre"},{name:"slug",desc:"URL amigable"},{name:"parentId",desc:"ID de categorÃa padre"},{name:"imageUrl",desc:"URL de imagen"}]}),(0,e.jsx)(F,{title:"Pedidos",icon:(0,e.jsx)(be,{className:"w-4 h-4 text-blue-600"}),permission:"write",permissionColor:"bg-blue-100 text-blue-700",endpoints:[{method:"GET",path:"/api/v1/orders",description:"Listar pedidos"},{method:"GET",path:"/api/v1/orders/:id",description:"Obtener pedido con items"}],responseExample:at,fields:[{name:"id",desc:"ID único"},{name:"orderNumber",desc:"Número de pedido"},{name:"userId",desc:"ID del cliente"},{name:"status",desc:"Estado del pedido"},{name:"subtotal",desc:"Subtotal"},{name:"shipping",desc:"Coste de envÃo"},{name:"total",desc:"Total"},{name:"items",desc:"Array de productos"}]}),(0,e.jsx)(F,{title:"Usuarios",icon:(0,e.jsx)(E,{className:"w-4 h-4 text-blue-600"}),permission:"full",permissionColor:"bg-purple-100 text-purple-700",endpoints:[{method:"GET",path:"/api/v1/users",description:"Listar usuarios"},{method:"GET",path:"/api/v1/users/:id",description:"Obtener usuario"}],responseExample:rt,fields:[{name:"id",desc:"ID único"},{name:"email",desc:"Email"},{name:"firstName",desc:"Nombre"},{name:"lastName",desc:"Apellidos"},{name:"phone",desc:"Teléfono"},{name:"loyaltyPoints",desc:"Puntos de fidelidad"}]}),(0,e.jsx)(F,{title:"EstadÃsticas",icon:(0,e.jsx)(Ke,{className:"w-4 h-4 text-blue-600"}),permission:"write",permissionColor:"bg-blue-100 text-blue-700",endpoints:[{method:"GET",path:"/api/v1/stats",description:"EstadÃsticas generales"},{method:"GET",path:"/api/v1/analytics/overview",description:"Resumen analÃticas"},{method:"GET",path:"/api/v1/visits",description:"Datos de visitas"}],responseExample:it,fields:[{name:"totalOrders",desc:"Total pedidos"},{name:"totalRevenue",desc:"Ingresos totales"},{name:"totalProducts",desc:"Productos activos"},{name:"totalUsers",desc:"Usuarios registrados"},{name:"ordersToday",desc:"Pedidos hoy"},{name:"revenueToday",desc:"Ingresos hoy"}]})]}),(0,e.jsxs)("div",{className:"bg-white border border-blue-200 rounded-lg p-4",children:[(0,e.jsx)("h5",{className:"font-semibold text-blue-900 text-sm mb-2",children:"Ejemplo cURL"}),(0,e.jsxs)("div",{className:"relative",children:[(0,e.jsx)("pre",{className:"bg-gray-900 text-gray-100 p-3 rounded text-xs font-mono overflow-x-auto whitespace-pre-wrap",children:`curl -X GET \\ 81 "${i}/api/v1/products" \\ 82 -H "Authorization: Bearer TU_CLAVE_API"`}),(0,e.jsx)(j,{size:"sm",variant:"ghost",className:"absolute top-2 right-2 h-6 w-6 p-0 bg-gray-800 hover:bg-gray-700",onClick:async()=>{try{if(!navigator.clipboard){f.error("Copia manual");return}await navigator.clipboard.writeText(`curl -X GET "${i}/api/v1/products" -H "Authorization: Bearer TU_CLAVE_API"`),f.success("Comando cURL copiado")}catch{f.error("No se pudo copiar")}},"data-testid":"button-copy-api-curl",children:(0,e.jsx)(P,{className:"w-3 h-3 text-gray-300"})})]})]})]}),!s&&(0,e.jsx)("div",{className:"mt-3 text-xs text-blue-600",children:"Haz clic para ver todos los endpoints, ejemplos de respuesta y campos disponibles."})]})})}function lt({generatedKey:s,showKey:t,setShowKey:i}){const a=r=>{navigator.clipboard.writeText(r)};return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsx)("div",{className:"bg-yellow-50 border border-yellow-200 rounded-lg p-4",children:(0,e.jsxs)("div",{className:"flex items-start gap-2",children:[(0,e.jsx)(_e,{className:"w-5 h-5 text-yellow-600 mt-0.5"}),(0,e.jsx)("p",{className:"text-sm text-yellow-800",children:"Esta es la única vez que verás esta clave completa. Cópiala ahora."})]})}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(B,{type:t?"text":"password",value:s,readOnly:!0,className:"font-mono"}),(0,e.jsx)(j,{variant:"outline",size:"icon",onClick:()=>i(!t),children:t?(0,e.jsx)(we,{className:"w-4 h-4"}):(0,e.jsx)(L,{className:"w-4 h-4"})}),(0,e.jsx)(j,{variant:"outline",size:"icon",onClick:()=>a(s),children:(0,e.jsx)(P,{className:"w-4 h-4"})})]})]})}function ct({newKeyName:s,setNewKeyName:t,newKeyPermissions:i,setNewKeyPermissions:a,newKeyExpiry:r,setNewKeyExpiry:n}){return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(z,{children:"Nombre"}),(0,e.jsx)(B,{value:s,onChange:l=>t(l.target.value),placeholder:"Ej: Software de stock","data-testid":"input-api-key-name"})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(z,{children:"Permisos"}),(0,e.jsxs)(_,{value:i,onValueChange:a,children:[(0,e.jsx)($,{"data-testid":"select-api-permissions",children:(0,e.jsx)(O,{})}),(0,e.jsxs)(R,{children:[(0,e.jsx)(S,{value:"read",children:"Solo lectura"}),(0,e.jsx)(S,{value:"write",children:"Lectura y escritura"}),(0,e.jsx)(S,{value:"full",children:"Acceso completo"})]})]})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(z,{children:"Fecha de expiración (opcional)"}),(0,e.jsx)(B,{type:"date",value:r,onChange:l=>n(l.target.value),"data-testid":"input-api-key-expiry"})]})]})}function ot({open:s,onOpenChange:t,generatedKey:i,showKey:a,setShowKey:r,newKeyName:n,setNewKeyName:l,newKeyPermissions:c,setNewKeyPermissions:o,newKeyExpiry:x,setNewKeyExpiry:m,onCreate:h,onClose:d,isPending:A,t:D}){return(0,e.jsx)(ae,{open:s,onOpenChange:M=>
82{t(M),M||d()},children:(0,e.jsxs)(ie,{children:[(0,e.jsxs)(re,{children:[(0,e.jsx)(te,{children:i?"Clave API Generada":"Nueva Clave API"}),(0,e.jsx)(ne,{children:i?"Guarda esta clave en un lugar seguro. No podrás verla de nuevo.":"Crea una nueva clave API para integración externa"})]}),i?(0,e.jsx)(lt,{generatedKey:i,showKey:a,setShowKey:r}):(0,e.jsx)(ct,{newKeyName:n,setNewKeyName:l,newKeyPermissions:c,setNewKeyPermissions:o,newKeyExpiry:x,setNewKeyExpiry:m}),(0,e.jsx)(Se,{children:i?(0,e.jsxs)(j,{onClick:d,className:"bg-[#E85A8B] hover:bg-[#E85A8B]/90",children:[(0,e.jsx)(Oe,{className:"w-4 h-4 mr-2"}),"Entendido"]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(j,{variant:"outline",onClick:()=>t(!1),children:D.admin.cancel}),(0,e.jsx)(j,{onClick:h,className:"bg-[#E85A8B] hover:bg-[#E85A8B]/90",disabled:!n||A,"data-testid":"button-generate-key",children:"Generar Clave"})]})})]})})}function dt(){return(0,e.jsx)(g,{className:"bg-gray-50",children:(0,e.jsxs)(p,{className:"p-8 text-center text-gray-500",children:[(0,e.jsx)(ee,{className:"w-12 h-12 mx-auto mb-4 text-gray-300"}),"No hay claves API creadas"]})})}function Lt(){const{t:s}=je(),{language:t}=Pe(),i=ls(t),a=Qs(),{apiKeys:r,isLoading:n}=Ws(),{createKeyMutation:l,deleteKeyMutation:c,toggleKeyMutation:o}=Js(a.setGeneratedKey,a.resetCreateForm);return n?(0,e.jsx)("div",{className:"text-center py-8",children:s.admin.loading}):(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h3",{className:"text-lg font-semibold text-gray-800",children:s.admin.apiKeys}),(0,e.jsx)("p",{className:"text-sm text-gray-500",children:s.admin.manageApiAccess})]}),(0,e.jsxs)(j,{onClick:()=>a.setShowCreateDialog(!0),className:"bg-[#E85A8B] hover:bg-[#E85A8B]/90 w-full sm:w-auto","data-testid":"button-create-api-key",children:[(0,e.jsx)(Qe,{className:"w-4 h-4 mr-2"}),"Nueva Clave API"]})]}),(0,e.jsx)(nt,{}),(0,e.jsx)("div",{className:"grid gap-4",children:r.map(x=>(0,e.jsx)(et,{apiKey:x,onToggle:m=>o.mutate({id:x.id,isActive:m}),onDelete:()=>c.mutate(x.id),dateLocale:i,t:s},x.id))}),r.length===0&&(0,e.jsx)(dt,{}),(0,e.jsx)(ot,{open:a.showCreateDialog,onOpenChange:a.setShowCreateDialog,generatedKey:a.generatedKey,showKey:a.showKey,setShowKey:a.setShowKey,newKeyName:a.newKeyName,setNewKeyName:a.setNewKeyName,newKeyPermissions:a.newKeyPermissions,setNewKeyPermissions:a.setNewKeyPermissions,newKeyExpiry:a.newKeyExpiry,setNewKeyExpiry:a.setNewKeyExpiry,onCreate:()=>l.mutate({name:a.newKeyName,permissions:a.newKeyPermissions,expiresAt:a.newKeyExpiry||null}),onClose:()=>{a.setShowCreateDialog(!1),a.setGeneratedKey(null),a.setShowKey(!1)},isPending:l.isPending,t:s})]})}export{Ft as AnalyticsTab,Lt as ApiTab,Pt as StatsTab};
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.