1import{j as e,u as ct,g as Pr,q as Nn,h as On,a as Wr,a6 as Mn,d as Nr,i as Ln,k as Bn,P as Dn,f as D,c as Or,a7 as Vn,a8 as Hn,a9 as Gn}from"./index-C6-4kgOT.js";import{r as i,b as Mr,d as qn,c as Kn}from"./vendor-react--UDKce57.js";import{u as Un,P as Yn}from"./PlatformLoadingState-DQmLdngh.js";import{S as gr,u as ot,C as at,A as Jn,N as Qn,D as Xn,a as Zn,b as es,c as ts,d as rs,e as ns,f as ss,H as os,g as as,h as is,i as ls,j as mr,k as cs,l as ds,m as ps,F as us,n as Be,o as gs,p as ms,q as hs,r as xs,s as Tt,t as fs,U as ys}from"./HourlyAlertsPanel-DG4sHBoq.js";import{S as bs,a as vs,b as ks,c as js,d as Ss}from"./sheet-DQdyTAdl.js";import{R as Lr,A as Br,C as Dr,X as Vr,Y as Hr,T as Gr,b as qr,a as Cs}from"./vendor-recharts-biHjigJL.js";import{u as At}from"./useCloseOnRouteChange-lksL5XVV.js";import{u as ws,L as hr,a as Ts,c as _s,N as $s,O as Rs,p as _t,M as As,f as xr,t as Es,b as fr,d as yr}from"./OrdenDeColumnas-DbF8BMLh.js";import{C as zs,P as Fs}from"./PlatformLoadingPill-9tOhJSKp.js";import{u as Is,v as Ps,p as Ws,c as Ns,d as Os}from"./useLumyPorPauta-t6O1RQ3J.js";import{C as Ms}from"./ConnectPlatformBanner-C9oSAao4.js";import{p as Ls}from"./planAccounts-jrtXKEQ1.js";import{u as Bs}from"./useSelectedCampaigns-BdmoRO3j.js";import{u as Kr}from"./useAutoRefresh-DKHwRdiF.js";import{d as tt,R as br}from"./dia-corto-Qy3qvbbK.js";import{u as Ds,a as $t,D as Vs,c as Ur,S as Hs,h as Gs,p as qs,s as Ks,K as Us,T as Ys,M as Js,d as Qs,C as Xs,b as Zs}from"./vendor-dnd-rAaYhDxI.js";import{P as eo}from"./PlatformLoadingOverlay-DHyzd6Ei.js";import{f as to,g as vr,h as ro,i as no}from"./calculations-tyz_NypE.js";import{I as so}from"./InlineAIChart-K__uBozv.js";import{K as oo,a as ao,b as io,c as lo}from"./KpiCard-B3sleRcq.js";import{c as U,e as kr,a as rt,d as it,g as lt,b as jr,l as Sr,h as Cr,p as wr}from"./semaforo-1n3dRRyu.js";import{R as co}from"./ReorderableKpiStrip-DdP0CWQ3.js";import{e as po}from"./csvExport-DQyG9sid.js";import"./meta-SIn-uAlU.js";import"./customComponents-CaGXrlD8.js";const Yr={spend:{label:"Gasto",format:"currency",extract:n=>n.spend},cpm:{label:"CPM",format:"currency",extract:n=>n.cpm},cpc:{label:"CPC",format:"currency",extract:n=>n.cpc},budget:{label:"Presupuesto",format:"currency",extract:n=>n.budget},cpa:{label:"CPA",format:"currency",extract:n=>n.cpa},impressions:{label:"Impresiones",format:"number",extract:n=>n.impressions},clicks:{label:"Clicks",format:"number",extract:n=>n.clicks},ctr:{label:"CTR",format:"percent",extract:n=>n.ctr},pageviews:{label:"Pageviews",format:"number",extract:n=>n.pageviews},landing_rate:{label:"% Landing rate",format:"percent",extract:n=>n.landingRate},video_2s:{label:"Video 2s",format:"number",extract:n=>n.video_watched_2s},video_6s:{label:"Video 6s",format:"number",extract:n=>n.video_watched_6s},hook_rate:{label:"Hook Rate",format:"percent",extract:n=>n.impressions>0?n.video_watched_2s/n.impressions*100:0},hold_rate:{label:"Hold Rate",format:"percent",extract:n=>n.video_watched_2s>0?n.video_watched_6s/n.video_watched_2s*100:0},conversions:{label:"Conversiones",format:"number",extract:n=>n.conversions},roas:{label:"ROAS",format:"ratio",extract:n=>n.roas},conv_rate:{label:"% Conversión",format:"percent",extract:n=>n.clicks>0?n.conversions/n.clicks*100:0},web_conv:{label:"Web conv.",format:"number",extract:n=>n.webConversions},web_rate:{label:"% Web conv.",format:"percent",extract:n=>n.webConvRate}};function uo(n){return Yr[n]||null}function De(n,c,f="COP"){return!isFinite(n)||n===0?"â":c==="currency"?new Intl.NumberFormat("es-CO",{style:"currency",currency:f,maximumFractionDigits:0}).format(n):c==="percent"?`${n.toFixed(2)}%`:c==="ratio"?`${n.toFixed(2)}x`:n.toLocaleString("es-CO",{maximumFractionDigits:2})}function go(n){const c=[];if(!n||n.spend===0&&n.impressions===0)return c;n.cpm>3e3?c.push({id:"cpm_high",severity:"warning",title:"CPM alto para TikTok",description:`CPM ${De(n.cpm,"currency")}. Benchmark TikTok COD Colombia: <$3.000.`,action:"Revisar audiencia, creatividad o pujar más bajo (cap bid)."}):n.cpm>0&&n.cpm<1500&&c.push({id:"cpm_excellent",severity:"opportunity",title:"CPM excelente",description:`CPM ${De(n.cpm,"currency")} â por debajo del benchmark $1.500.`,action:"Considera escalar presupuesto en este segmento."}),n.ctr>0&&n.ctr<.8?c.push({id:"ctr_low",severity:"critical",title:"CTR bajo",description:`CTR ${n.ctr.toFixed(2)}% â TikTok COD generalmente 0.8-1.5%.`,action:"El thumbnail/primer segundo no está enganchando. Probar otra creatividad."}):n.ctr>=2.5&&c.push({id:"ctr_excellent",severity:"opportunity",title:"CTR alto",description:`CTR ${n.ctr.toFixed(2)}% â la creatividad engancha.`,action:"Ideal para escalar â esta variante está funcionando."}),n.cpa>0&&n.cpa>15e3?c.push({id:"cpa_high",severity:"critical",title:"CPA fuera del techo",description:`CPA ${De(n.cpa,"currency")} â supera el techo razonable de $15.000.`,action:"Pausa si la tendencia se mantiene. Revisar audiencia o producto."}):n.cpa>0&&n.cpa<=1e4&&c.push({id:"cpa_excellent",severity:"opportunity",title:"CPA en zona verde",description:`CPA ${De(n.cpa,"currency")} â bajo del benchmark $10.000.`,action:"Listo para subir presupuesto si el ROAS también aguanta."}),n.roas>0&&n.roas<2?c.push({id:"roas_low",severity:"warning",title:"ROAS bajo el breakeven",description:`ROAS ${n.roas.toFixed(2)}x â suele necesitarse 2.5x para ser rentable en COD.`,action:"Revisar margen del producto o pausar si no mejora en 2-3 dÃas."}):n.roas>=3.5&&c.push({id:"roas_high",severity:"opportunity",title:"ROAS muy bueno",description:`ROAS ${n.roas.toFixed(2)}x â claramente rentable.`,action:"Subir presupuesto 20-30% por dÃa y monitorear."});const f=n.impressions>0?n.video_watched_2s/n.impressions*100:0;f>0&&f<20&&c.push({id:"hook_low",severity:"warning",title:"Hook Rate bajo",description:`${f.toFixed(1)}% pasaron 2s. TikTok benchmark: 20-30%+.`,action:"El primer segundo del video no engancha. Probar otra apertura."});const d=n.video_watched_2s>0?n.video_watched_6s/n.video_watched_2s*100:0;return d>0&&d<15&&c.push({id:"hold_low",severity:"warning",title:"Hold Rate bajo",description:`${d.toFixed(1)}% de los que vieron 2s llegaron a 6s. Benchmark: >15%.`,action:"El video pierde audiencia rápido. Acortar o reorganizar el mensaje."}),c}const nt="#FE2C55",mo={campaigns:"Campaña",adgroups:"Conjunto de Anuncios",ads:"Anuncio",rules:"Reglas"},ho={critical:{color:"#EF4444",bg:"rgba(239,68,68,0.08)",border:"rgba(239,68,68,0.30
1)",icon:"!",label:"CRÃTICO"},warning:{color:"#F59E0B",bg:"rgba(245,158,11,0.08)",border:"rgba(245,158,11,0.30)",icon:"â ",label:"ALERTA"},opportunity:{color:"#10B981",bg:"rgba(16,185,129,0.08)",border:"rgba(16,185,129,0.30)",icon:"â",label:"OPORTUNIDAD"},info:{color:"#3B82F6",bg:"rgba(59,130,246,0.08)",border:"rgba(59,130,246,0.30)",icon:"i",label:"INFO"}},xo=new Set(["actions","account","name","status","type","trend"]),fo=["spend","impressions","clicks","ctr","cpc","cpm","conversions","cpa","roas"];function yo({entity:n,level:c,onClose:f,hiddenCols:d}){const y=i.useMemo(()=>{const v=Object.keys(Yr).filter(m=>!d.has(m)&&!xo.has(m));return v.length>0?v:fo},[d]),p=i.useMemo(()=>{if(!n)return[];const x=[];for(const v of y){const m=uo(v);if(!m)continue;const F=m.extract(n);x.push({key:v,label:m.label,value:De(F,m.format)})}return x},[n,y]),g=i.useMemo(()=>n?go(n):[],[n]),w=i.useMemo(()=>{if(!n)return[];const x=n.video_play_actions||0;if(x===0)return[];const v=m=>m&&x>0?Math.min(100,m/x*100):0;return[{pct_video:0,label:"Inicio",retention:100},{pct_video:25,label:"25% video",retention:v(n.video_views_p25)},{pct_video:50,label:"50% video",retention:v(n.video_views_p50)},{pct_video:75,label:"75% video",retention:v(n.video_views_p75)},{pct_video:100,label:"Completo",retention:v(n.video_views_p100)}]},[n]),T=i.useMemo(()=>{if(w.length===0)return 0;const x=w.slice(1);return x.length===0?0:x.reduce((v,m)=>v+m.retention,0)/x.length},[w]);return e.jsx(bs,{open:!!n,onOpenChange:x=>{x||f()},children:e.jsx(vs,{side:"right",style:{width:"620px",maxWidth:"92vw",overflowY:"auto",display:"flex",flexDirection:"column",gap:0},children:n&&e.jsxs(e.Fragment,{children:[e.jsxs(ks,{children:[e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,marginBottom:4},children:[e.jsxs("span",{style:{fontSize:11,textTransform:"uppercase",letterSpacing:"0.5px",color:"#FE2C55",background:"rgba(254,44,85,0.12)",padding:"3px 8px",borderRadius:4,fontWeight:600},children:["TikTok · ",mo[c]||c]}),e.jsx("span",{style:{fontSize:10,fontWeight:700,padding:"2px 6px",borderRadius:4,background:n.status==="active"?"rgba(16,185,129,0.12)":"var(--bg-tertiary)",color:n.status==="active"?"#10B981":"var(--text-muted)"},children:n.status==="active"?"â ACTIVO":"â PAUSADO"})]}),e.jsx(js,{children:e.jsx("span",{className:"censor-blur",children:n.name})}),e.jsx(Ss,{children:e.jsxs("span",{className:"censor-blur",children:[n.accountName," ",n.id?`· ID: ${n.id}`:""]})})]}),e.jsx("div",{style:{borderBottom:"1px solid var(--border)",margin:"8px 0 16px"}}),p.length>0?e.jsx("div",{className:"summary-kpis",children:p.map(x=>e.jsxs("div",{className:"kpi-item",children:[e.jsx("span",{className:"kpi-label",children:x.label}),e.jsx("span",{className:"kpi-value",children:x.value})]},x.key))}):e.jsx("div",{style:{padding:12,fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"Sin métricas seleccionadas. Activa columnas en la tabla y aparecerán aquÃ."}),g.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{borderBottom:"1px solid var(--border)",margin:"16px 0"}}),e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:700,color:"var(--text-primary)",marginBottom:10},children:[e.jsx("span",{children:"Diagnóstico"}),e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:500},children:"· benchmarks TikTok Colombia COD"})]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:g.map(x=>{const v=ho[x.severity];return e.jsxs("div",{style:{padding:"10px 12px",background:v.bg,border:`1px solid ${v.border}`,borderLeft:`3px solid ${v.color}`,borderRadius:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:3},children:[e.jsx("span",{style:{display:"inline-flex",width:16,height:16,borderRadius:"50%",background:v.color,color:"#fff",fontSize:10,fontWeight:700,alignItems:"center",justifyContent:"center",flexShrink:0},children:v.icon}),e.jsx("span",{style:{fontSize:12,fontWeight:700,color:v.color,letterSpacing:"0.04em"},children:x.title})]}),e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)",lineHeight:1.45,marginBottom:4},children:x.description}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",fontStyle:"italic"},children:["â ",x.action]})]},x.id)})})]})]}),w.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{borderBottom:"1px solid var(--border)",margin:"16px 0"}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:13,fontWeight:700,color:"var(--text-primary)",marginBottom:10},children:"Retención de video"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:8,marginBottom:10},children:[e.jsxs("div",{style:{padding:"10px 12px",background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:8}
1,children:[e.jsx("div",{style:{fontSize:10,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:2},children:"Reproducciones"}),e.jsx("div",{style:{fontSize:16,fontWeight:800,color:"var(--text-primary)"},children:(n.video_play_actions||0).toLocaleString("es-CO")})]}),e.jsxs("div",{style:{padding:"10px 12px",background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:8},children:[e.jsx("div",{style:{fontSize:10,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:2},children:"Retención prom."}),e.jsx("div",{style:{fontSize:16,fontWeight:800,color:"var(--text-primary)"},children:T>0?`${T.toFixed(1)}%`:"â"})]})]}),e.jsx("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:8,padding:"10px 12px"},children:e.jsx(Lr,{width:"100%",height:180,children:e.jsxs(Br,{data:w,margin:{top:6,right:10,left:-10,bottom:5},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"ttRetGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:nt,stopOpacity:.32}),e.jsx("stop",{offset:"95%",stopColor:nt,stopOpacity:0})]})}),e.jsx(Dr,{strokeDasharray:"3 3",stroke:"var(--border)"}),e.jsx(Vr,{dataKey:"pct_video",tick:{fontSize:10,fill:"var(--text-muted)"},tickFormatter:x=>`${x}%`}),e.jsx(Hr,{tick:{fontSize:10,fill:"var(--text-muted)"},tickFormatter:x=>`${x}%`,domain:[0,100],width:36}),e.jsx(Gr,{contentStyle:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:6,fontSize:11},formatter:x=>[`${x.toFixed(1)}%`,"Retención"],labelFormatter:(x,v)=>{var m,F;return((F=(m=v==null?void 0:v[0])==null?void 0:m.payload)==null?void 0:F.label)||`${x}% del video`}}),e.jsx(qr,{type:"monotone",dataKey:"retention",stroke:nt,strokeWidth:2.4,fill:"url(#ttRetGrad)",dot:{r:4,fill:nt},activeDot:{r:6}})]})})}),e.jsx("div",{style:{fontSize:10.5,color:"var(--text-muted)",marginTop:6,fontStyle:"italic"},children:"Curva por cuartil del video (0/25/50/75/100%). TikTok no expone resolución por segundo vÃa API â Meta sÃ."})]})]})]})})})}const He={green:"#10B981",red:"#EF4444",yellow:"#F59E0B"};function bo({entities:n,level:c,onPick:f}){const d=i.useMemo(()=>{const g=n.filter(m=>m.spend>0&&m.status==="active");if(g.length<3)return null;const T=g.reduce((m,F)=>m+F.spend,0)/g.length,x=g.filter(m=>m.spend<T*.5&&m.roas>=2.5&&m.conversions>=1).sort((m,F)=>F.roas-m.roas).slice(0,3),v=g.filter(m=>m.spend>T*1.2&&(m.cpa>15e3&&m.conversions>=1||m.roas<1&&m.spend>5e4&&m.conversions>=1)).sort((m,F)=>F.spend-m.spend).slice(0,3);return{winners:x,losers:v,avgSpend:T}},[n]);if(!d||d.winners.length===0&&d.losers.length===0)return null;const p={campaigns:"campaña",adgroups:"conjunto",ads:"anuncio"}[c];return e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"16px 18px",marginBottom:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[e.jsx("span",{style:{fontSize:16},children:"ð¡"}),e.jsx("span",{style:{fontWeight:700,fontSize:14,color:"var(--text-primary)",letterSpacing:"0.01em"},children:"Acciones sugeridas hoy"}),e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:["· basado en ",p,"s activos del perÃodo seleccionado"]})]}),e.jsxs("div",{className:"tiktok-insights-grid",style:{display:"grid",gridTemplateColumns:d.winners.length>0&&d.losers.length>0?"1fr 1fr":"1fr",gap:14},children:[d.winners.length>0&&e.jsx(Tr,{icon:"ð",title:"Ganadores escondidos",subtitle:"ROAS alto, poco budget â escalar",color:He.green,items:d.winners,metric:"roas",level:c,onPick:f}),d.losers.length>0&&e.jsx(Tr,{icon:"â ï¸",title:"Candidatos a pausar",subtitle:"Alto gasto, mala performance â revisar",color:He.red,items:d.losers,metric:"cpa",level:c,onPick:f})]})]})}function Tr({icon:n,title:c,subtitle:f,color:d,items:y,metric:p,level:g,onPick:w}){return e.jsxs("div",{style:{background:"var(--bg-secondary)",border:`1px solid ${d}35`,borderRadius:10,padding:"12px 14px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:10},children:[e.jsx("span",{style:{fontSize:15},children:n}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1},children:[e.jsx("span",{style:{fontSize:13,fontWeight:700,color:d},children:c}),e.jsx("span",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:f})]})]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:y.map((T,x)=>e.jsx(vo,{entity:T,metric:p,level:g,onPick:w},`${T.id||T.name}-${x}`))})]})}function vo({entity:n,metric:c,level:f,onPick:d}){const y=!!d&&!!n.id,p=()=>{d&&n.id&&d(n.id,n.name)};return e.jsxs("div",{onClick:y?p:void 0,role:y?"button":void 0,tabIndex:y?0:void 0,onKeyDown:y?g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),p())}:void 0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"8px 10px",background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:8,cursor:y?"pointer":"default",transition:"background 0.12s, border-color 0.12s"},onMouseEnter:y?g=>{g.currentTarget.style.background="var(--bg-tertiary)"}:void 0,onMouseLeave:y?g=>{g.currentTarget.style.background="var(--bg-card)"}:void 0,children:[e.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[e.jsx("span",{className:"censor-blur",style:{fontSize:12.5,fontWeight:600,color:"var(--text-primary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n.name}),e.jsxs("span",{style:{fontSize:10.5,color:"var(--text-muted)",display:"flex",gap:8},children:[e.jsxs("span",{children:[e.jsx(gr,{value:n.spend,format:"currency"})," gasto"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[n.conversions," conv."]}),f==="ads"&&n.parentCampaign&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{className:"censor-blur",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:120},children:n.parentCampaign})]})]})]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:1},children:c==="roas"?e.jsxs(e.Fragment,{children:[e.jsxs("span",{style:{fontSize:14,fontWeight:800,color:He.green,fontVariantNumeric:"tabular-nums"},children:[n.roas.toFixed(1),"x"]}),e.jsx("span",{style:{fontSize:9.5,color:"var(--text-muted)",fontWeight:600,letterSpacing:"0.04em"},children:"ROAS"})]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{value:n.cpa,format:"currency",style:{fontSize:14,fontWeight:800,color:n.cpa>15e3?He.red:He.yellow,fontVariantNumeric:"tabular-nums"}}),e.jsx("span",{style:{fontSize:9.5,color:"var(--text-muted)",fontWeight:600,letterSpacing:"0.04em"},children:"CPA"})]})})]})}function ko(n,c,f){if(c.length===0||f)return n;const d=new Set(c),y=n.filter(p=>d.has(p));return y.length===n.length?n:y}const jo=5*6e4;function So(n,c,f=jo){const d=Kr(f,n),[y,p]=i.useState(0);return i.useEffect(()=>{d>0&&p(g=>g+1)},[d]),i.useEffect(()=>{c!=null&&p(g=>g+1)},[c]),y}function Jr(n=!0){const c=i.useRef(null),[f,d]=i.useState(!1);return i.useEffect(()=>{if(!n||f)return;const y=c.current;if(!y||typeof IntersectionObserver>"u"){d(!0);return}const p=new IntersectionObserver(g=>{g.some(w=>w.isIntersecting)&&(d(!0),p.disconnect())},{rootMargin:"300px"});return p.observe(y),()=>p.disconnect()},[n,f]),{caja:c,visto:f}}const _r={ACTIVE:{color:"#10B981",bg:"rgba(16,185,129,0.10)",label:"Activo"},INACTIVE:{color:"#EF4444",bg:"rgba(239,68,68,0.10)",label:"Inactivo"},UNKNOWN:{color:"#64748B",bg:"var(--bg-tertiary)",label:"Sin datos"}},Co={PAGE_VIEW:"PageView",LANDING_PAGE_VIEW:"Landing PV",INITIATE_ORDER:"Initiate Checkout",ON_WEB_ORDER:"Order",SHOPPING:"Purchase",COMPLETE_PAYMENT:"Purchase",ADD_TO_CART:"Add to Cart",VIEW_CONTENT:"View Content",CLICK_BUTTON:"Click Button",SUBMIT_FORM:"Submit Form"};
1function wo(n){if(!n)return null;const c=new Date(n);return isNaN(c.getTime())?null:new Intl.DateTimeFormat("es-CO",{day:"numeric",month:"short",year:"numeric"}).format(c)}function To({collapsible:n=!1}={}){const[c,f]=i.useState([]),[d,y]=i.useState(!0),[p,g]=i.useState(null),{open:w,toggle:T}=ot("tiktok-pixels",!0),{caja:x,visto:v}=Jr();if(i.useEffect(()=>{if(!v)return;let r=!1;return y(!0),g(null),fetch("/api/tiktok/pixels").then(l=>l.json()).then(l=>{if(!r){if(l.error){g(l.error);return}f(l.pixels||[])}}).catch(l=>{r||g(String(l))}).finally(()=>{r||y(!1)}),()=>{r=!0}},[v]),d)return e.jsx("div",{ref:x,style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"14px 18px",marginBottom:14},children:e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",textAlign:"center"},children:"Cargando pixelsâ¦"})});if(p)return e.jsx("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"14px 18px",marginBottom:14},children:e.jsxs("div",{style:{fontSize:12,color:"#EF4444"},children:["Error pixels: ",p]})});if(c.length===0)return e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"14px 18px",marginBottom:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[e.jsx($r,{}),e.jsx("span",{style:{fontWeight:700,fontSize:14,color:"var(--text-primary)"},children:"Pixels TikTok"})]}),e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:8},children:"No hay pixels asociados a las cuentas conectadas."})]});const m=c.filter(r=>r.activity_status==="ACTIVE").length,F=c.filter(r=>r.activity_status==="INACTIVE").length;return e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"14px 18px",marginBottom:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:n&&!w?0:12,gap:10,flexWrap:"wrap"},children:[e.jsxs("button",{type:"button",onClick:n?T:void 0,style:{all:"unset",display:"flex",alignItems:"center",gap:8,cursor:n?"pointer":"default"},children:[n&&e.jsx(at,{open:w}),e.jsx($r,{}),e.jsx("span",{style:{fontWeight:700,fontSize:14,color:"var(--text-primary)"},children:"Pixels TikTok"}),e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["· ",c.length," ",c.length===1?"pixel":"pixels"]})]}),e.jsxs("div",{style:{display:"flex",gap:8,fontSize:11,color:"var(--text-secondary)"},children:[m>0&&e.jsxs("span",{children:[e.jsx("strong",{style:{color:"#10B981"},children:m})," activos"]}),F>0&&e.jsxs("span",{children:[e.jsx("strong",{style:{color:"#EF4444"},children:F})," inactivos"]})]})]}),(!n||w)&&e.jsx(e.Fragment,{children:e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:c.map(r=>e.jsx(_o,{pixel:r},`${r.advertiser_id}-${r.pixel_id}`))})})]})}function _o({pixel:n}){const c=_r[n.activity_status]||_r.UNKNOWN,f=wo(n.create_time),[d,y]=i.useState([]),[p,g]=i.useState(!1);i.useEffect(()=>{let T=!1;return fetch(`/api/tiktok/pixel/${encodeURIComponent(n.pixel_id)}/stats?advertiser_id=${encodeURIComponent(n.advertiser_id)}`).then(x=>x.json()).then(x=>{T||(y(Array.isArray(x.stats)?x.stats:[]),g(!0))}).catch(()=>{T||g(!0)}),()=>{T=!0}},[n.pixel_id,n.advertiser_id]);const w=new Map(d.map(T=>[T.event_type,T.total_count]));return e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderLeft:`3px solid ${c.color}`,borderRadius:8,padding:"10px 12px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,flexWrap:"wrap",marginBottom:6},children:[e.jsxs("div",{style:{minWidth:0,flex:1},children:[e.jsx("div",{style:{fontSize:13,fontWeight:700,color:"var(--text-primary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n.pixel_name}),e.jsxs("div",{style:{fontSize:10.5,color:"var(--text-muted)",marginTop:1,display:"flex",gap:6,flexWrap:"wrap"},children:[e.jsx("span",{children:n.advertiser_name}),f&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{children:["creado ",f]})]}),n.setup_mode&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:n.setup_mode})]})]})]}),e.jsx("span",{style:{fontSize:10,fontWeight:700,padding:"3px 8px",borderRadius:12,background:c.bg,color:c.color,letterSpacing:"0.04em",border:`1px solid ${c.color}30`,whiteSpace:"nowrap"},children:c.label})]}),e.jsx("div",{style:{fontSize:10.5,color:"var(--text-muted)",fontFamily:"ui-monospace, monospace",marginBottom:6},children:n.pixel_code||n.pixel_id}),n.configured_events.length>
10&&e.jsxs("div",{children:[e.jsxs("div",{style:{fontSize:10,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:4},children:["Eventos configurados (",n.configured_events.length,") · últimos 7d"]}),e.jsx("div",{style:{display:"flex",gap:5,flexWrap:"wrap"},children:n.configured_events.map(T=>{const x=w.get(T),v=p&&x!==void 0&&x>0,m=p&&x===0;return e.jsxs("span",{title:p?x===void 0?"TikTok no expone counts para esta cuenta":x===0?"â 0 eventos en 7d â revisar que el pixel esté disparando":`${x.toLocaleString("es-CO")} eventos en 7d`:"Cargandoâ¦",style:{fontSize:10.5,padding:"2px 8px",borderRadius:12,background:m?"rgba(239,68,68,0.08)":"var(--bg-tertiary)",color:m?"#EF4444":"var(--text-secondary)",border:`1px solid ${m?"rgba(239,68,68,0.30)":"var(--border)"}`,whiteSpace:"nowrap",fontWeight:500,display:"inline-flex",alignItems:"center",gap:4},children:[Co[T]||T,v&&e.jsx("strong",{style:{fontWeight:700,color:"var(--text-primary)"},children:x>=1e3?`${(x/1e3).toFixed(1)}k`:x}),m&&e.jsx("span",{style:{fontWeight:700},children:"0"})]},T)})})]})]})}function $r(){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#FE2C55",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"3",y1:"9",x2:"21",y2:"9"}),e.jsx("line",{x1:"9",y1:"21",x2:"9",y2:"9"})]})}function $o(){var G;const n=ct(),[c,f]=i.useState([]),[d,y]=i.useState(""),[p,g]=i.useState([]),[w,T]=i.useState(!1),[x,v]=i.useState(!1),[m,F]=i.useState(""),[r,l]=i.useState(null),[z,M]=i.useState(!1),[b,k]=i.useState(!1),[S,I]=i.useState([]),[$,Q]=i.useState(new Set);i.useEffect(()=>{n("/api/tiktok-direct/status").then(j=>j.json()).then(j=>{const R=(Array.isArray(j==null?void 0:j.advertisers)?j.advertisers:[]).map(Z=>({advertiser_id:String(Z.advertiser_id||""),label:String(Z.name||Z.advertiser_id||"")})).filter(Z=>Z.advertiser_id);f(R),R.length>0&&y(R[0].advertiser_id)}).catch(()=>{l("No pude cargar las cuentas TikTok")})},[]);const V=async j=>{if(j){T(!0),l(null);try{const W=await n(`/api/tiktok-direct/advertiser/${j}/blocked-words`),R=await W.json();if(!W.ok)throw new Error((R==null?void 0:R.error)||(R==null?void 0:R.message)||`HTTP ${W.status}`);g(Array.isArray(R.words)?R.words:[])}catch(W){l((W==null?void 0:W.message)||"Error cargando lista"),g([])}finally{T(!1)}}};i.useEffect(()=>{d&&V(d)},[d]);const H=async j=>{const W=j??m.split(/[,\n]/).map(R=>R.trim()).filter(Boolean);if(W.length!==0){v(!0),l(null);try{const R=await n(`/api/tiktok-direct/advertiser/${d}/blocked-words`,{method:"POST",body:JSON.stringify({words:W})}),Z=await R.json();if(!R.ok)throw new Error((Z==null?void 0:Z.message)||(Z==null?void 0:Z.error)||"Error agregando");j||F(""),j&&(I(ie=>ie.filter(Se=>!W.includes(Se.word))),Q(new Set)),await V(d)}catch(R){l((R==null?void 0:R.message)||"Error agregando")}finally{v(!1)}}},oe=async j=>{if(confirm(`Eliminar "${j}" de la lista de palabras bloqueadas?`)){T(!0),l(null);try{const W=await n(`/api/tiktok-direct/advertiser/${d}/blocked-words`,{method:"DELETE",body:JSON.stringify({words:[j]})}),R=await W.json();if(!W.ok)throw new Error((R==null?void 0:R.message)||(R==null?void 0:R.error)||"Error eliminando");await V(d)}catch(W){l((W==null?void 0:W.message)||"Error eliminando"),T(!1)}}},re=async()=>{if(d){k(!0),l(null);try{const j=await n(`/api/tiktok-direct/advertiser/${d}/blocked-words/ai-suggest`,{method:"POST",body:JSON.stringify({existing:p,niche:"dropshipping COD LATAM"})}),W=await j.json();if(!j.ok)throw new Error((W==null?void 0:W.error)||(W==null?void 0:W.message)||"Error pidiendo sugerencias");I(Array.isArray(W.suggestions)?W.suggestions:[]),Q(new Set)}catch(j){l((j==null?void 0:j.message)||"Error con IA")}finally{k(!1)}}},ne=j=>{Q(W=>{const R=new Set(W);return R.has(j)?R.delete(j):R.add(j),R})},de=()=>{const j=Array.from($);j.length>0&&H(j)},ue=()=>Q(new Set(S.map(j=>j.word))),N=((G=c.find(j=>j.advertiser_id===d))==null?void 0:G.label)||d;return e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"14px 18px",marginBottom:14},children:[e.jsxs("div",{onClick:()=>M(j=>!j),style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",cursor:"pointer",userSelect:"none"},children:[e.jsx(at,{open:z}),e.jsx("span",{style:{fontSize:16},children:"ð«"}),e.jsx("span",{style:{fontWeight:700,fontSize:14,color:"var(--text-primary)"},children:"Palabras bloqueadas"}),e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["· ",w?"cargandoâ¦":`${p.length} ${p.length===1?"palabra activa":"palabras activas"}`]}),N&&e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)",marginLeft:"auto"},children:["Cuenta: ",e.jsx("strong",{style:{color:"var(--text-primary)"},children:N})]})]}),z&&e.jsxs("div",{style:{marginTop:12},children:[e.jsx("div",{style:{fontSize:11.5,color:"var(--text-muted)",marginBottom:12,lineHeight:1.5},children:"TikTok esconde automáticamente los comentarios que contengan estas palabras en tus anuncios. Ãtil para spam, insultos o nombres de competidores."}),c.length>1&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("label",{style:{fontSize:11,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",display:"block",marginBottom:4},children:"Cuenta"}),e.jsx("select",{value:d,onChange:j=>y(j.target.value),style:{width:"100%",padding:"8px 10px",fontSize:12.5,fontFamily:"inherit",background:"var(--bg-tertiary)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text-primary)"},children:c.map(j=>e.jsx("option",{value:j.advertiser_id,children:j.label||j.advertiser_id},j.advertiser_id))})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginBottom:12,flexWrap:"wrap"},children:[e.jsx("input",{type:"text",value:m,onChange:j=>F(j.target.value),placeholder:"palabra1, palabra2, palabra3",onKeyDown:j=>{j.key==="Enter"&&m.trim()&&(j.preventDefault(),H())},style:{flex:1,minWidth:200,padding:"8px 10px",fontSize:12.5,fontFamily:"inherit",background:"var(--bg-tertiary)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text-primary)"}}),e.jsx("button",{onClick:()=>H(),disabled:x||!m.trim()||!d,style:{padding:"8px 16px",fontSize:12.5,fontWeight:700,fontFamily:"inherit",background:"#FE2C55",color:"#fff",border:"none",borderRadius:8,cursor:x||!m.trim()?"not-allowed":"pointer",opacity:x||
1!m.trim()?.5:1},children:x?"Agregandoâ¦":"Agregar"}),e.jsx("button",{onClick:re,disabled:b||!d,title:"Claude sugiere palabras útiles para dropshipping COD",style:{padding:"8px 14px",fontSize:12.5,fontWeight:700,fontFamily:"inherit",background:b?"var(--bg-tertiary)":"linear-gradient(135deg, #7C3AED, #A855F7)",color:"#fff",border:"none",borderRadius:8,cursor:b||!d?"not-allowed":"pointer",opacity:b||!d?.5:1},children:b?"Pensandoâ¦":"⨠Sugerir con IA"})]}),r&&e.jsxs("div",{style:{background:"rgba(239,68,68,0.10)",border:"1px solid rgba(239,68,68,0.30)",color:"#B91C1C",borderRadius:8,padding:"8px 12px",fontSize:12,marginBottom:10},children:["â ",r]}),S.length>0&&e.jsxs("div",{style:{background:"rgba(124,58,237,0.06)",border:"1px solid rgba(124,58,237,0.25)",borderRadius:10,padding:"12px 14px",marginBottom:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,flexWrap:"wrap",marginBottom:10},children:[e.jsxs("div",{style:{fontSize:12,fontWeight:700,color:"var(--text-primary)"},children:["⨠",S.length," sugerencias de IA · marca las que quieras"]}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:ue,style:{padding:"5px 10px",fontSize:11,fontWeight:600,background:"transparent",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-primary)",cursor:"pointer"},children:"Marcar todas"}),e.jsx("button",{onClick:de,disabled:$.size===0||x,style:{padding:"5px 12px",fontSize:11,fontWeight:700,background:$.size===0?"var(--bg-tertiary)":"#7C3AED",color:$.size===0?"var(--text-muted)":"#fff",border:"none",borderRadius:6,cursor:$.size===0||x?"not-allowed":"pointer"},children:x?"Agregandoâ¦":`Bloquear ${$.size>0?$.size:""}`})]})]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:S.map(j=>{const W=$.has(j.word);return e.jsxs("button",{onClick:()=>ne(j.word),title:j.reason,style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,padding:"5px 10px",borderRadius:14,background:W?"#7C3AED":"var(--bg-tertiary)",border:W?"1px solid #7C3AED":"1px solid var(--border)",color:W?"#fff":"var(--text-primary)",fontWeight:W?700:500,fontFamily:"inherit",cursor:"pointer"},children:[W?"â":"+"," ",j.word]},j.word)})})]}),w&&p.length===0?e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",textAlign:"center",padding:14},children:"Cargandoâ¦"}):p.length===0?e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",textAlign:"center",padding:14,fontStyle:"italic"},children:"Aún no tienes palabras bloqueadas en esta cuenta."}):e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:p.map(j=>e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:12,padding:"4px 8px 4px 10px",borderRadius:16,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)",color:"var(--text-primary)",fontWeight:500},children:[j,e.jsx("button",{onClick:()=>oe(j),title:"Eliminar",style:{border:"none",background:"transparent",padding:"0 0 0 4px",cursor:"pointer",color:"#EF4444",fontSize:14,lineHeight:1,fontFamily:"inherit",fontWeight:700},children:"Ã"})]},j))})]})]})}function Ro(){const n=ct(),[c,f]=i.useState(!1),[d,y]=i.useState([]),[p,g]=i.useState(null),[w,T]=i.useState(null),[x,v]=i.useState(null),[m,F]=i.useState(null),[r,l]=i.useState(null),[z,M]=i.useState(!1),[b,k]=i.useState(""),[S,I]=i.useState(""),[$,Q]=i.useState(!1),[V,H]=i.useState(null),[oe,re]=i.useState(null);i.useEffect(()=>{c&&(n("/api/tiktok/pixels").then(N=>N.json()).then(N=>y(Array.isArray(N.pixels)?N.pixels:[])).catch(()=>y([])),ne())},[c]),i.useEffect(()=>{if(!c||!z)return;const N=setInterval(ne,3e3);return()=>clearInterval(N)},[c,z]);const ne=()=>{n("/api/tiktok-direct/offline/config").then(N=>N.json()).then(N=>{var G;g(N.config||null),T(N.stats||null),v(N.refundStats||null),F(N.pending||null),l(N.errors||null),M(!!N.running),(G=N.config)!=null&&G.pixel_code&&k(`${N.config.pixel_code}|${N.config.advertiser_id||""}`)}).catch(()=>{})},de=async()=>{if(!b)return;const[N,G]=b.split("|");H("save"),re(null);try{const j=await n("/api/tiktok-direct/offline/config",{method:"POST",body:JSON.stringify({pixel_code:N,advertiser_id:G,enabled:!0,events_api_token:S.trim()||void 0})}),W=await j.json();if(!j.ok)throw new Error((W==null?void 0:W.message)||(W==null?void 0:W.error)||"Error");let R="â Configuración guardada";W.warning_missing_events_token&&!(p!=null&&p.events_api_token)&&(R+='. â Te falta pegar el Events API Token del pixel â sin él el sync va a fallar. Genéralo en TikTok Events Manager â tu Pixel â Settings â "Generate Access Token". NO es el mismo token del pixel que pegas en tu tienda.'),re({kind:"ok",text:R}),I(""),Q(!1),ne()}catch(j){re({kind:"err",text:(j==null?void 0:j.message)||"Error guardando"})}finally{H(null)}},ue=async()=>{confirm("Desactivar la sincronización Dropi â TikTok? Las órdenes ya subidas no se borran de TikTok.")&&(await n("/api/tiktok-direct/offline/config",{method:"DELETE"}),re({kind:"ok",text:"â Sincronización desactivada"}),ne())};return e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",boxShadow:"var(--shadow-sm)",borderRadius:12,padding:"14px 18px",marginBottom:14},children:[e.jsxs("button",{type:"button",onClick:()=>f(N=>!N),style:{all:"unset",display:"flex",alignItems:"center",gap:10,cursor:"pointer",width:"100%"},children:[e.jsx("span",{style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.15s",color:"var(--text-muted)",fontSize:11},children:"â¶"}),e.jsx("span",{style:{fontSize:18},children:"ð"}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontWeight:800,fontSize:14,color:"var(--text-primary)"},children:"Sincronización Dropi â TikTok"}),e.jsx("div",{style:{fontSize:11.5,color:"var(--text-muted)",marginTop:2},children:"Sube las ventas confirmadas al pixel para que TikTok optimice por compradores reales, no por leads."})]}),(p==null?void 0:p.enabled)&&e.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#10B981",background:"rgba(16,185,129,0.10)",padding:"3px 8px",borderRadius:6,letterSpacing:"0.04em"},children:"ACTIVO"})]}),c&&e.jsxs("div",{style:{marginTop:14},children:[e.jsxs("div",{style:{padding:"10px 12px",borderRadius:8,marginBottom:14,background:"rgba(59,130,246,0.06)",border:"1px solid rgba(59,130,246,0.20)",fontSize:12,color:"var(--text-primary)",lineHeight:1.55},children:[e.jsx("strong",{children:"No tienes que tocar tus campañas."})," Se le suman a TikTok las ventas que tu logÃstica confirmó, para que busque compradores de verdad y no formularios llenados.",e.jsx("br",{}),"Las devoluciones también se suben, como señal en contra: TikTok aprende a evitar clientes parecidos a los que devuelven."]}),e.jsx("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Pixel destino"}),e.jsxs("select",{value:b,onChange:N=>k(N.target.value),style:{width:"100%",padding:"9px 10px",fontSize:12.5,fontFamily:"inherit",background:"var(--bg-tertiary)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text-primary)",marginBottom:6},children:[e.jsx("option",{value:"",children:"â Elegir pixel â"}),d.map(N=>e.jsxs("option",{value:`${N.pixel_code||N.pixel_id}|${N.advertiser_id}
1`,children:[N.pixel_name," (",N.advertiser_name,") ",N.activity_status!=="ACTIVE"?"· INACTIVO":""]},`${N.pixel_id}-${N.advertiser_id}`))]}),(p==null?void 0:p.pixel_code)&&e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",marginBottom:12,fontFamily:"monospace"},children:["Código pixel: ",e.jsx("strong",{style:{color:"var(--text-primary)",userSelect:"all"},children:p.pixel_code})]}),!(p!=null&&p.pixel_code)&&e.jsx("div",{style:{marginBottom:12}}),e.jsx("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Events API Token del pixel"}),p!=null&&p.events_api_token&&!$?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderRadius:8,marginBottom:12,background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.30)"},children:[e.jsx("span",{style:{fontSize:14,color:"#10B981"},children:"â"}),e.jsx("span",{style:{flex:1,fontFamily:"monospace",fontSize:13,color:"var(--text-primary)",letterSpacing:"2px"},children:"â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢"}),e.jsx("span",{style:{fontSize:11,color:"#10B981",fontWeight:700},children:"Token guardado"}),e.jsx("button",{onClick:()=>Q(!0),style:{padding:"4px 10px",fontSize:11,fontWeight:700,fontFamily:"inherit",border:"1px solid var(--border)",background:"transparent",borderRadius:6,color:"var(--text-secondary)",cursor:"pointer"},children:"Cambiar"})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",value:S,onChange:N=>I(N.target.value),placeholder:"pega aquà el token de Events Manager",autoComplete:"off",style:{width:"100%",padding:"9px 10px",fontSize:12.5,fontFamily:"monospace",background:"var(--bg-tertiary)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text-primary)",marginBottom:6,boxSizing:"border-box"}}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",marginBottom:12,lineHeight:1.5},children:[e.jsx("a",{href:"https://ads.tiktok.com/i18n/events_manager_v2/",target:"_blank",rel:"noopener noreferrer",style:{color:"#FE2C55"},children:"Events Manager"}),' â tu Pixel â Settings â "Generate Access Token". ',e.jsx("strong",{children:"NO es"})," el token del pixel que usas en tu tienda â es uno aparte que sale solo desde Events Manager.",(p==null?void 0:p.events_api_token)&&$&&e.jsx("button",{onClick:()=>{Q(!1),I("")},style:{marginLeft:10,padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:11,textDecoration:"underline",fontFamily:"inherit"},children:"cancelar"})]})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:12},children:[e.jsx("button",{onClick:de,disabled:!b||V!==null,style:Ar("#FE2C55",!b||V!==null),children:V==="save"?"Guardandoâ¦":p!=null&&p.enabled?"Actualizar":"Guardar configuración"}),(p==null?void 0:p.enabled)&&e.jsx("button",{onClick:ue,disabled:V!==null,style:Ar("#64748B",V!==null,!0),children:"Desactivar"})]}),oe&&e.jsx("div",{style:{padding:"10px 12px",borderRadius:8,fontSize:12.5,marginBottom:10,lineHeight:1.5,background:oe.kind==="ok"?"rgba(16,185,129,0.08)":"rgba(239,68,68,0.08)",border:`1px solid ${oe.kind==="ok"?"rgba(16,185,129,0.25)":"rgba(239,68,68,0.25)"}`,color:oe.kind==="ok"?"#065F46":"#B91C1C",whiteSpace:"pre-wrap"},children:oe.text}),z&&e.jsxs("div",{style:{marginBottom:10,padding:"10px 12px",borderRadius:8,background:"rgba(59,130,246,0.10)",border:"1px solid rgba(59,130,246,0.30)",fontSize:12.5,color:"#1E40AF",display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{animation:"pulse 1.5s ease-in-out infinite"},children:"â³"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Sincronizando en segundo planoâ¦"})," puedes cerrar esta pestaña, el sistema sigue trabajando. Esta vista se actualiza cada 3 segundos."]}),e.jsx("style",{children:"@keyframes pulse { 0%, 100% { opacity: 1 } 50% { opacity: 0.4 } }"})]}),w&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(()=>{const N=(m==null?void 0:m.total_eligible_purchases)||0,G=(m==null?void 0:m.failed_purchases)||0,j=(m
1==null?void 0:m.pending_purchases)||0,W=Math.max(0,N-j),R=Math.max(0,j-G),Z=(m==null?void 0:m.total_eligible_refunds)||0,ie=(m==null?void 0:m.failed_refunds)||0,Se=(m==null?void 0:m.pending_refunds)||0,Ce=Math.max(0,Z-Se),dt=Math.max(0,Se-ie);return e.jsxs(e.Fragment,{children:[e.jsx(Rr,{label:"Ventas",done:W,pending:R,total:N||w.total,failed:G,color:"#10B981"}),e.jsx(Rr,{label:"Devoluciones",done:Ce,pending:dt,total:Z||(x==null?void 0:x.total)||0,failed:ie,color:"#F59E0B"})]})})(),e.jsx(Jn,{platform:"tiktok"}),w.last_sync_at&&e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)"},children:["Ãltima sincronización: ",e.jsx("strong",{style:{color:"var(--text-primary)"},children:Eo(w.last_sync_at)})]}),((m==null?void 0:m.skipped_no_phone)||0)>0&&e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)"},children:["â ï¸ ",e.jsx("strong",{children:m.skipped_no_phone})," órdenes sin teléfono â no se pueden subir al pixel."]}),((r==null?void 0:r.purchases)||(r==null?void 0:r.refunds))&&e.jsxs("div",{style:{marginTop:4,padding:"10px 12px",borderRadius:8,background:"rgba(239,68,68,0.06)",border:"1px solid rgba(239,68,68,0.20)",fontSize:11.5,color:"var(--text-primary)",lineHeight:1.55},children:[e.jsx("div",{style:{fontWeight:700,marginBottom:4,color:"#B91C1C"},children:"Detalle de errores:"}),r.purchases&&e.jsxs("div",{style:{marginBottom:r.refunds?4:0},children:[e.jsxs("strong",{children:["Ventas (",r.purchases.count,"):"]})," ",e.jsx("code",{style:{fontFamily:"monospace",fontSize:11},children:r.purchases.message.slice(0,200)})]}),r.refunds&&e.jsxs("div",{children:[e.jsxs("strong",{children:["Devoluciones (",r.refunds.count,"):"]})," ",e.jsx("code",{style:{fontFamily:"monospace",fontSize:11},children:r.refunds.message.slice(0,200)})]})]})]}),p!=null&&p.enabled?e.jsx(Ao,{lastSyncAt:p==null?void 0:p.last_sync_at,intervalHours:1,destination:"TikTok"}):e.jsx("div",{style:{marginTop:12,fontSize:11.5,color:"var(--text-muted)",lineHeight:1.5},children:'ð¡ Pasos: 1) Elige el pixel · 2) Pega el Events API Token · 3) Guarda configuración · 4) Click "Sincronizar últimas órdenes Dropi" â sube las ENTREGADO de los últimos 30 dÃas al pixel.'})]})]})}function Ao({lastSyncAt:n,intervalHours:c,destination:f}){const[d,y]=i.useState(Date.now());i.useEffect(()=>{const w=setInterval(()=>y(Date.now()),3e4);return()=>clearInterval(w)},[]);let p=null;if(n){const w=new Date(n+(n.endsWith("Z")?"":"Z")).getTime();isNaN(w)||(p=w+c*36e5)}let g=`Próximo envÃo automático en menos de ${c}h`;if(p){const w=p-d;if(w<=0)g=`Enviando datos a ${f} ahora mismoâ¦`;else{const T=Math.ceil(w/6e4);if(T<60)g=`Estamos alistando tus datos · en ~${T} min los enviamos a ${f}`;else{const x=Math.floor(T/60),v=T%60;g=`Estamos alistando tus datos · en ${x}h ${v>0?v+"m":""} los enviamos a ${f}`}}}return e.jsxs("div",{style:{marginTop:12,padding:"10px 12px",borderRadius:8,background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.25)",fontSize:12,color:"#065F46",fontWeight:600},children:["ð¤ ",g]})}function Eo(n){if(!n)return"";const c=n.includes("T")?n:n.replace(" ","T"),f=/[zZ]|[+-]\d{2}:?\d{2}$/.test(c)?c:c+"Z",d=new Date(f);return isNaN(d.getTime())?n:d.toLocaleString("es-CO",{dateStyle:"short",timeStyle:"short"})}function Rr({label:n,done:c,pending:f,total:d,failed:y,color:p}){const g=d>0?d:c+f,w=g>0?Math.round(c/g*100):0;return e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:10,padding:"12px 14px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",marginBottom:6,flexWrap:"wrap",gap:6},children:[e.jsxs("div",{children:[e.jsx("span",{style:{fontSize:13,fontWeight:700,color:"var(--text-primary)"},children:n}),e.jsxs("span",{style:{marginLeft:8,fontSize:11,color:"var(--text-muted)"},children:[c.toLocaleString("es-CO")," de ",g.toLocaleString("es-CO")," subidas"]})]}),e.jsxs("span",{style:{fontSize:13,fontWeight:800,color:p},children:[w,"%"]})]}),e.jsx("div",{style:{height:8,background:"var(--bg-tertiary)",borderRadius:4,overflow:"hidden",marginBottom:6},children:e.jsx("div",{style:{width:`${w}%`,height:"100%",background:p,transition:"width 0.4s ease"}})}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",display:"flex",gap:12,flexWrap:"wrap"},children:[e.jsxs("span",{children:["â ",e.jsx("strong",{style:{color:"#10B981"}
1,children:c.toLocaleString("es-CO")})," subidas"]}),f>0&&e.jsxs("span",{children:["â³ ",e.jsx("strong",{style:{color:"#3B82F6"},children:f.toLocaleString("es-CO")})," faltan"]}),y>0&&e.jsxs("span",{children:["â ",e.jsx("strong",{style:{color:"#EF4444"},children:y.toLocaleString("es-CO")})," con error (se reintentan)"]})]})]})}function Ar(n,c,f=!1){return{padding:"8px 14px",fontSize:12.5,fontWeight:700,fontFamily:"inherit",background:f?"transparent":n,color:f?n:"#fff",border:f?`1px solid ${n}40`:"none",borderRadius:8,cursor:c?"not-allowed":"pointer",opacity:c?.5:1}}function Qr({adId:n,advertiserId:c,adName:f,onClose:d,onSuccess:y}){const p=ct(),[g,w]=i.useState(null),[T,x]=i.useState(!0),[v,m]=i.useState(""),[F,r]=i.useState(!1),[l,z]=i.useState(null);i.useEffect(()=>{let b=!1;return p(`/api/tiktok-direct/ad/review-info?advertiser_id=${encodeURIComponent(c)}&ad_ids=${encodeURIComponent(n)}`).then(k=>k.json()).then(k=>{if(b)return;const S=Array.isArray(k.review_info)?k.review_info[0]:null;w(S||null)}).catch(()=>{}).finally(()=>{b||x(!1)}),()=>{b=!0}},[n,c,p]),i.useEffect(()=>{const b=k=>{k.key==="Escape"&&d()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[d]);const M=async()=>{const b=v.trim();if(b.length<10){z({ok:!1,text:"Escribe al menos 10 caracteres explicando por qué tu anuncio cumple con las polÃticas."});return}r(!0),z(null);try{const k=await p(`/api/tiktok-direct/ad/${n}/appeal`,{method:"POST",body:JSON.stringify({advertiser_id:c,reason:b})}),S=await k.json();if(!k.ok){z({ok:!1,text:(S==null?void 0:S.message)||(S==null?void 0:S.error)||"Error enviando appeal"});return}z({ok:!0,text:"â Apelación enviada. TikTok revisará el ad en las próximas 24-48 horas. Te notificarán por email cuando haya respuesta."}),y&&y()}catch(k){z({ok:!1,text:(k==null?void 0:k.message)||"Error de red"})}finally{r(!1)}};return Mr.createPortal(e.jsx("div",{onClick:d,style:{position:"fixed",inset:0,background:"rgba(8,22,42,0.75)",zIndex:1e5,display:"flex",alignItems:"center",justifyContent:"center",padding:16},children:e.jsxs("div",{onClick:b=>b.stopPropagation(),style:{width:"100%",maxWidth:520,background:"var(--bg-card)",borderRadius:14,padding:22,boxShadow:"0 20px 50px rgba(0,0,0,0.4)",maxHeight:"90vh",overflowY:"auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:12},children:[e.jsx("span",{style:{fontSize:22},children:"âï¸"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:800,fontSize:16,color:"var(--text-primary)"},children:"Apelar rechazo"}),e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f})]})]}),T?e.jsx("div",{style:{fontSize:12.5,color:"var(--text-muted)",textAlign:"center",padding:14},children:"Cargando razón del rechazoâ¦"}):g!=null&&g.reject_reason?e.jsxs("div",{style:{padding:"10px 12px",borderRadius:8,marginBottom:14,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)"},children:[e.jsx("div",{style:{fontSize:10.5,fontWeight:700,color:"#B91C1C",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"Razón del rechazo (TikTok)"}),e.jsx("div",{style:{fontSize:13,color:"var(--text-primary)",lineHeight:1.5},children:g.reject_reason}),g.reject_reason_detail&&e.jsx("div",{style:{fontSize:11.5,color:"var(--text-secondary)",marginTop:4,lineHeight:1.5},children:g.reject_reason_detail}),g.is_appealable===!1&&e.jsx("div",{style:{fontSize:11,color:"#B45309",marginTop:8,fontWeight:700},children:"â TikTok marca este rechazo como NO APELABLE. Si igualmente envÃas la apelación, probablemente sea rechazada automáticamente."}),g.appeal_status&&g.appeal_status!=="NONE"&&e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:6},children:["Apelación previa: ",g.appeal_status]})]}):null,e.jsx("label",{style:{display:"block",fontSize:11,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:"Tu argumento (por qué cumple las polÃticas)"}
1),e.jsx("textarea",{value:v,onChange:b=>m(b.target.value),placeholder:"Ejemplo: 'Mi anuncio promociona un producto cosmético aprobado por Invima. No hace claims médicos â solo menciona uso natural. Adjunto registro sanitario en el sitio web.'",maxLength:2e3,rows:6,style:{width:"100%",padding:"10px 12px",fontSize:13,fontFamily:"inherit",background:"var(--bg-tertiary)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text-primary)",resize:"vertical",boxSizing:"border-box",lineHeight:1.5}}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,color:"var(--text-muted)",marginTop:4,marginBottom:14},children:[e.jsx("span",{children:"MÃnimo 10, máximo 2000 caracteres"}),e.jsxs("span",{style:{color:v.length>2e3?"#EF4444":"inherit"},children:[v.length,"/2000"]})]}),l&&e.jsx("div",{style:{padding:"10px 12px",borderRadius:8,fontSize:12.5,marginBottom:14,lineHeight:1.5,background:l.ok?"rgba(16,185,129,0.10)":"rgba(239,68,68,0.10)",border:`1px solid ${l.ok?"rgba(16,185,129,0.30)":"rgba(239,68,68,0.30)"}`,color:l.ok?"#065F46":"#B91C1C"},children:l.text}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx("button",{onClick:d,style:{padding:"9px 16px",fontSize:13,fontWeight:600,fontFamily:"inherit",border:"1px solid var(--border)",background:"transparent",borderRadius:8,color:"var(--text-primary)",cursor:"pointer"},children:"Cerrar"}),l!=null&&l.ok?null:e.jsx("button",{onClick:M,disabled:F||v.trim().length<10,style:{padding:"9px 18px",fontSize:13,fontWeight:700,fontFamily:"inherit",background:"#FE2C55",color:"#fff",border:"none",borderRadius:8,cursor:F||v.trim().length<10?"not-allowed":"pointer",opacity:F||v.trim().length<10?.5:1},children:F?"Enviandoâ¦":"Enviar apelación"})]}),e.jsxs("div",{style:{marginTop:16,paddingTop:14,borderTop:"1px dashed var(--border)",fontSize:11,color:"var(--text-muted)",lineHeight:1.5},children:[e.jsx("strong",{style:{color:"var(--text-secondary)"},children:"¿Te suspendieron la cuenta?"})," Las suspensiones de cuenta NO se pueden apelar via API â solo desde el Ads Manager de TikTok. ",e.jsx("a",{href:"https://ads.tiktok.com/help/article/account-suspensions",target:"_blank",rel:"noopener noreferrer",style:{color:"#FE2C55"},children:"Más info"}),"."]})]})}),document.body)}const Er="tiktok_appeals_panel_open_v1";function zo({collapsible:n=!0}={}){const c=ct(),{getQueryParams:f}=Pr(),[d,y]=i.useState(()=>{try{const k=localStorage.getItem(Er);return k===null?!0:k==="1"}catch{return!0}});i.useEffect(()=>{try{localStorage.setItem(Er,d?"1":"0")}catch{}},[d]);const[p,g]=i.useState([]),[w,T]=i.useState(!1),[x,v]=i.useState(null),[m,F]=i.useState(null),[r,l]=i.useState(0),{caja:z,visto:M}=Jr(d);i.useEffect(()=>{if(!d||!M)return;let k=!1;return T(!0),v(null),c(`/api/tiktok/ads?${f()}&status=all`).then(S=>S.json()).then(S=>{if(k)return;if(S.error){v(S.error);return}const I=Array.isArray(S.data)?S.data:[];g(I)}).catch(S=>{k||v(String(S))}).finally(()=>{k||T(!1)}),()=>{k=!0}},[d,M,f,c,r]);const b=i.useMemo(()=>p.filter(k=>k.isRejected===!0),[p]);return e.jsxs("div",{ref:z,style:{background:b.length>0?"linear-gradient(135deg, rgba(239,68,68,0.04), rgba(239,68,68,0.01))":"var(--bg-card)",border:`1px solid ${b.length>0?"rgba(239,68,68,0.25)":"var(--border)"}`,borderRadius:12,padding:"14px 18px",marginBottom:14},children:[e.jsxs("button",{type:"button",onClick:n?()=>y(k=>!k):void 0,style:{all:"unset",display:"flex",alignItems:"center",gap:10,cursor:n?"pointer":"default",width:"100%"},children:[n&&e.jsx("span",{style:{transform:d?"rotate(90deg)":"none",transition:"transform 0.15s",color:"var(--text-muted)",fontSize:11},children:"â¶"}),e.jsx("span",{style:{fontSize:18},children:"âï¸"}),e.jsxs("div",{style:{flex:1},children:[e.jsxs("div",{style:{fontWeight:700,fontSize:14,color:"var(--text-primary)"},children:["Anuncios rechazados ",b.length>0&&e.jsxs("span",{style:{color:"#EF4444"},children:["(",b.length,")"]})]}),e.jsx("div",{style:{fontSize:11.5,color:"var(--text-muted)",marginTop:2},children:b.length===0?"Sin rechazos detectados en este perÃodo. â":`${b.length} ${b.length===1?"anuncio rechazado por TikTok":"anuncios rechazados por TikTok"} â apela desde aquÃ.`})]}),b.length>0&&e.jsx("span",{style:{fontSize:10,fontWeight:800,color:"#EF4444",background:"rgba(239,68,68,0.12)",padding:"4px 9px",borderRadius:6,letterSpacing:"0.04em"},children:"REVISAR"})]}),d&&e.jsxs("div",{style:{marginTop:12},children:[w&&b.length===0?e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",textAlign:"center",padding:20},children:"Cargandoâ¦"}):x?e.jsxs("div",{style:{fontSize:12,color:"#EF4444",padding:10},children:["Error: ",x]}):b.length===0?e.jsx("div",{style:{padding:14,borderRadius:8,background:"rgba(16,185,129,0.06)",border:"1px solid rgba(16,185,129,0.20)",fontSize:12.5,color:"#065F46",textAlign:"center"},children:"â Sin anuncios rechazados en este perÃodo. Si TikTok rechaza alguno aparecerá aquà automáticamente."}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:b.map(k=>{const S=k.videoCoverUrl||k.imageUrl;return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 12px",borderRadius:8,background:"var(--bg-card)",border:"1px solid rgba(239,68,68,0.20)",flexWrap:"wrap"},children:[S?e.jsx("img",{src:S,alt:"",style:{width:48,height:60,objectFit:"cover",borderRadius:6,flexShrink:0},onError:I=>
1{I.currentTarget.style.display="none"}}):e.jsx("div",{style:{width:48,height:60,background:"#0F172A",borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:20},children:"ð"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{className:"censor-blur",style:{fontSize:13,fontWeight:700,color:"var(--text-primary)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:k.name}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2,display:"flex",gap:6,flexWrap:"wrap"},children:[e.jsx("span",{className:"censor-blur",children:k.accountName}),k.parentCampaign&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{className:"censor-blur",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:k.parentCampaign})]}),k.secondaryStatus&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{style:{color:"#EF4444"},children:k.secondaryStatus})]})]})]}),e.jsx("button",{onClick:()=>F(k),disabled:!k.id||!k.advertiser_id,style:{padding:"7px 14px",fontSize:12.5,fontWeight:700,fontFamily:"inherit",background:"#EF4444",color:"#fff",border:"none",borderRadius:8,cursor:!k.id||!k.advertiser_id?"not-allowed":"pointer",opacity:!k.id||!k.advertiser_id?.5:1,flexShrink:0},children:"âï¸ Apelar"})]},k.id)})}),e.jsxs("div",{style:{marginTop:12,paddingTop:10,borderTop:"1px dashed var(--border)",fontSize:10.5,color:"var(--text-muted)",lineHeight:1.5},children:["ð¡ ",e.jsx("strong",{children:"¿Te suspendieron toda la cuenta?"})," Las suspensiones de cuenta NO se pueden apelar vÃa API â solo desde el Ads Manager de TikTok. ",e.jsx("a",{href:"https://ads.tiktok.com/help/article/account-suspensions",target:"_blank",rel:"noopener noreferrer",style:{color:"#FE2C55"},children:"Más info"}),"."]})]}),m&&m.id&&m.advertiser_id&&e.jsx(Qr,{adId:m.id,advertiserId:m.advertiser_id,adName:m.name,onClose:()=>F(null),onSuccess:()=>{l(k=>k+1)}})]})}const Fo={AGE_13_17:"13-17",AGE_18_24:"18-24",AGE_25_34:"25-34",AGE_35_44:"35-44",AGE_45_54:"45-54",AGE_55_100:"55+",UNKNOWN:"Sin dato"},Io=["AGE_13_17","AGE_18_24","AGE_25_34","AGE_35_44","AGE_45_54","AGE_55_100","UNKNOWN"],Po={MALE:"Hombres",FEMALE:"Mujeres",None:"Sin dato",NONE:"Sin dato",UNKNOWN:"Sin dato"};function Wo({selectedAccounts:n,statusFilter:c="active",collapsible:f=!1,campaignIds:d=""}={}){const y=i.useMemo(()=>{const p=new URLSearchParams;n&&n.length>0&&p.set("accounts",n.join(",")),p.set("status",c),d&&p.set("campaigns",d);const g=p.toString();return{title:"¿A quién le vendes?",subtitleTemplate:w=>`Quién te compró en los últimos ${w} dÃas`,endpoint:`/api/tiktok/demographics?${g}`,emptyHint:"TikTok AUDIENCE necesita dÃas para clasificar conversiones. Si seleccionaste 3d, prueba 7d o 15d.",sections:[{key:"gender",title:"Género",icon:"â§",dataField:"byGender",labelMap:Po},{key:"age",title:"Edad",icon:"ð",dataField:"byAge",labelMap:Fo,order:Io},{key:"province",title:"Departamento",icon:"ð",dataField:"byProvince",childrenField:"byCity",labelMap:Qn}]}},[n==null?void 0:n.join(","),c,d]);return e.jsx(Xn,{config:y,collapsible:f,collapseKey:"tiktok-demographics"})}function No(n){if(n.length<2)return"";if(n.length===2)return`M ${n[0].x} ${n[0].y} L ${n[1].x} ${n[1].y}`;let c=`M ${n[0].x.toFixed(2)} ${n[0].y.toFixed(2)}`;for(let f=0;f<n.length-1;f++){const d=n[f-1]||n[f],y=n[f],p=n[f+1],g=n[f+2]||p,w=y.x+(p.x-d.x)/6,T=y.y+(p.y-d.y)/6,x=p.x-(g.x-y.x)/6,v=p.y-(g.y-y.y)/6;c+=` C ${w.toFixed(2)} ${T.toFixed(2)}, ${x.toFixed(2)} ${v.toFixed(2)}, ${p.x.toFixed(2)} ${p.y.toFixed(2)}`}return c}function Oo({data:n,width:c=64,height:f=28,color:d="#1877F2",showDot:y=!0}){const p=i.useId().replace(/:/g,"");if(!n.length||n.every(k=>k===0)||n.length===1)return null;const g=3,w=2,T=Math.min(...n),v=Math.max(...n)-T||1,m=n.map((k,S)=>{const I=w+S/(n.length-1)*(c-w*2),$=f-g-(k-T)/v*(f-g*2);return{x:I,y:$}}),F=No(m),r=`${F} L ${m[m.length-1].x.toFixed(2)} ${f} L ${m[0].x.toFixed(2)} ${f} Z`,l=n[0],z=n[n.length-1],M=z>l?"#10B981":z<l?"#EF4444":d,b=m[m.length-1];return e.jsxs("svg",{width:c,height:f,viewBox:`0 0 ${c} ${f}`,className:"sparkline",style:{display:"block",flexShrink:0,overflow:"visible"},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:`spark-fill-${p}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:M,stopOpacity:"0.28"}),e.jsx("stop",{offset:"100%",stopColor:M,stopOpacity:"0"})]})}),e.jsx("path",{d:r,fill:`url(#spark-fill-${p})`,stroke:"none"}),e.jsx("path",{d:F,fill:"none",stroke:M,strokeWidth:1.75,strokeLinecap:"round",strokeLinejoin:"round"}),y&&b&&e.jsxs(e.Fragment,{children:[e.jsx("circle",{cx:b.x,cy:b.y,r:3.5,fill:M,opacity:.25}),e.jsx("circle",{cx:b.x,cy:b.y,r:2,fill:M,stroke:"#fff",strokeWidth:1})]})]})}class Mo extends Kn.Component{constructor(c){super(c),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(c){console.error("[TikTokEntityActions crash]",c)}render(){return this.state.hasError?e.jsx("span",{style:{fontSize:14,color:"var(--text-muted)"},title:"Error en botón de acciones â recarga",children:"â "}):this.props.children}}function Lo({colKey:n,label:c,encabezado:f,width:d,align:y,isFirst:p,sortKey:g,sortDir:w,onSort:T,accentColor:x,customWidth:v,onResize:m,onResetWidth:F}){const{attributes:r,listeners:l,setNodeRef:z,transform:M,transition:b,isDragging:k}=Qs({id:n,disabled:p}),S=i.useRef(null),I=H=>{S.current=H,z(H)},$=v||d,Q={transform:Xs.Transform.toString(M),transition:b,textAlign:y||"left",padding:"10px",color:"var(--text-muted)",fontWeight:600,fontSize:11,textTransform:"uppercase",letterSpacing:"0.04em",borderBottom:"1px solid var(--border)",whiteSpace:"nowrap",background:k?`${x}25`:"var(--bg-tertiary)",width:$,minWidth:v,maxWidth:v,userSelect:"none",position:"relative",opacity:k?.7:1,zIndex:k?10:"auto",cursor:p?"default":"grab",touchAction:p?"auto":"none",overflow:"hidden",textOverflow:"ellipsis"},V=p?{}:{...r,...l};return e.jsxs("th",{ref:I,style:Q,...V,onClick:T,children:[f??c,g===n&&e.jsx("span",{style:{marginLeft:4,color:x}
1,children:w==="asc"?"â":"â"}),m&&!p&&e.jsx(hs,{getCurrentWidth:()=>{var H;return((H=S.current)==null?void 0:H.getBoundingClientRect().width)||$||100},onResize:m,onReset:F,highlightColor:x})]})}function X(n){let c=0,f=0,d=0,y=0,p=0,g=0,w=0,T=0,x=0,v=0;for(const m of n)c+=m.spend,f+=m.impressions,d+=m.clicks,y+=m.conversions,p+=m.conversionValue,g+=m.video_watched_2s,w+=m.video_watched_6s,T+=m.webConversions,v+=m.pageviews,x+=m.budget;return{spend:c,impressions:f,clicks:d,conversions:y,conversionValue:p,v2s:g,v6s:w,webConv:T,pageviews:v,budget:x,ctr:f>0?d/f*100:0,cpc:d>0?c/d:0,cpm:f>0?c/f*1e3:0,cpa:y>0?c/y:0,roas:c>0?p/c:0,webConvRate:d>0?T/d*100:0,landingRate:d>0?v/d*100:0}}const zr="tiktok_tab_col_order",st="tiktok_tab_hidden_cols";function Fr(n,c){try{const f=localStorage.getItem(n);return f?JSON.parse(f):c}catch{return c}}const h={tiktokCyan:"#FE2C55",tiktokPink:"#EC4899",green:"#10B981",blue:"#3b82f6",yellow:"#F59E0B",red:"#EF4444",muted:"#64748B"},Rt={spend:{label:"Gasto",unit:"cop",benchmark:null},cpm:{label:"CPM",unit:"cop",benchmark:7500},conversions:{label:"Conversiones",unit:"num",benchmark:null},cpa:{label:"CPA",unit:"cop",benchmark:15e3},reach:{label:"Alcance",unit:"num",benchmark:null},impressions:{label:"Impresiones",unit:"num",benchmark:null},cpc:{label:"CPC",unit:"cop",benchmark:1e3},clicks:{label:"Clicks al destino",unit:"num",benchmark:null},landingRate:{label:"% de carga",unit:"pct",benchmark:null},webConvRate:{label:"% conversión web",unit:"pct",benchmark:null}};function Ve(n){return n>=1e6?`$${(n/1e6).toFixed(1)}M`:n>=1e3?`$${(n/1e3).toFixed(0)}K`:`$${n.toFixed(0)}`}function Y(n){return n.toLocaleString("es-CO")}function Bo(n){const c=e.jsx("span",{style:{color:"var(--text-muted)"},children:"â"}),f=[{key:"lumy_orders",label:"Pedidos Lumy",encabezado:Tt("Pedidos Lumy"),width:110,align:"right",render:d=>{const y=_t(d);return y?e.jsx(xs,{agg:y}):c},sortValue:d=>{var y;return((y=_t(d))==null?void 0:y.orders)??-1},footer:d=>e.jsx("span",{style:{fontWeight:800},children:d.reduce((y,p)=>{var g;return y+(((g=_t(p))==null?void 0:g.orders)||0)},0)})}];for(const d of As)d.soloCampana&&n!=="campaigns"||f.push({key:d.key,label:d.label,encabezado:Tt(d.label),width:120,align:"right",render:y=>{var g;const p=(g=fr(y))==null?void 0:g[d.campo];return p==null?c:e.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:xr(p,d.formato,D)})},sortValue:y=>{var g;const p=(g=fr(y))==null?void 0:g[d.campo];return p==null?-1:Number(p)},footer:y=>e.jsx("span",{style:{fontWeight:800,fontVariantNumeric:"tabular-nums"},children:xr(Es(d,y,p=>Number(p.spend)||0),d.formato,D)})});return n==="ads"&&f.push({key:"lumy_destino",label:"Destino",encabezado:Tt("Destino"),width:130,align:"left",render:d=>fs(yr(d),ys),sortValue:d=>{var y;return((y=yr(d))==null?void 0:y.tipo)||""}}),f}function Do(n,c,f,d,y=[],p=1,g,w,T,x=!1){const v=ls([]),m=y.map(r=>({key:`cm_${r.id}`,label:r.name,width:120,align:"right",render:l=>cs(mr(r,l,v),r.format),sortValue:l=>mr(r,l,v)})),F=n==="campaigns"?"campaign":n==="adgroups"?"adgroup":"ad";return[{key:"status",label:"Estado",width:90,render:r=>e.jsx("span",{style:{fontSize:10,fontWeight:700,color:r.status==="active"?h.green:h.muted,background:r.status==="active"?`${h.green}15`:"var(--bg-tertiary)",border:`1px solid ${r.status==="active"?h.green+"35":"var(--border)"}`,padding:"2px 8px",borderRadius:20,whiteSpace:"nowrap"},children:r.status==="active"?"â Activa":"â Inactiva"}),sortValue:r=>r.status,footer:()=>e.jsx("span",{style:{fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:"TOTAL"})},{key:"name",label:"Nombre",width:320,render:r=>{const l=n==="ads",z=r.tiktokItemId?`https://www.tiktok.com/@_/video/${r.tiktokItemId}`:void 0,M=r.id&&r.advertiser_id?`https://ads.tiktok.com/i18n/perf/ad?aadvid=${r.advertiser_id}&keyword=${r.id}`:void 0;return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[l&&e.jsx(ds,{platform:"tiktok",adName:r.name,thumbnailUrl:r.videoCoverUrl||r.imageUrl,videoId:r.videoId,permalink:z,adsManagerUrl:M}),e.jsx("span",{className:"censor-blur",style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.name}
1),r.id&&r.advertiser_id&&e.jsx(Vn,{entityId:r.id,entityName:r.name,advertiserId:r.advertiser_id,level:F})]})},sortValue:r=>r.name,footer:r=>e.jsxs("span",{style:{fontWeight:700,color:"var(--text-primary)"},children:[r.length," ",r.length===1?"entidad":"entidades"]})},{key:"account",label:"Cuenta",width:160,render:r=>e.jsx("span",{className:"censor-blur",style:{fontSize:11,color:"var(--text-primary)",fontWeight:600},children:r.accountName}),sortValue:r=>r.accountName},{key:"type",label:"Tipo",width:95,align:"center",render:r=>r.isSmartPlus?e.jsx("span",{title:"Para editar esta campaña, ve al Ads Manager de TikTok. Por ahora solo podemos editar Manual. Trabajamos para poderlo hacer más adelante.",style:{fontSize:10,fontWeight:700,color:"#7C3AED",background:"rgba(124,58,237,0.10)",border:"1px solid rgba(124,58,237,0.30)",padding:"2px 8px",borderRadius:4,letterSpacing:.3},children:"⨠Smart+"}):r.campaignType==="smart"?e.jsx("span",{title:"Smart bidding â TikTok ajusta la puja automática. Editable desde el panel.",style:{fontSize:10,fontWeight:700,color:h.tiktokCyan,background:`${h.tiktokCyan}15`,border:`1px solid ${h.tiktokCyan}35`,padding:"2px 8px",borderRadius:4},children:"â¡ Smart"}):e.jsx("span",{title:"Manual â control total. Editable desde el panel.",style:{fontSize:10,fontWeight:700,color:"var(--text-muted)",background:"var(--bg-tertiary)",border:"1px solid var(--border)",padding:"2px 8px",borderRadius:4},children:"Manual"}),sortValue:r=>r.isSmartPlus?"a-smartplus":r.campaignType==="smart"?"b-smart":"c-manual"},{key:"spend",label:"Gasto",width:110,align:"right",sensitive:!0,render:r=>e.jsx("span",{style:{color:U(r.spend>=2e4?h.green:h.red),fontWeight:700},children:D(r.spend)}),sortValue:r=>r.spend,footer:r=>{const l=X(r);return e.jsx("span",{style:{color:U(l.spend>=2e4?h.green:h.red),fontWeight:800},children:D(l.spend)})}},{key:"impressions",label:"Impr.",width:90,align:"right",render:r=>e.jsx("span",{style:{color:"var(--text-secondary)"},children:Y(r.impressions)}),sortValue:r=>r.impressions,footer:r=>e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:Y(X(r).impressions)})},{key:"clicks",label:"Clicks",width:80,align:"right",render:r=>e.jsx("span",{style:{color:"var(--text-secondary)"},children:Y(r.clicks)}),sortValue:r=>r.clicks,footer:r=>e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:Y(X(r).clicks)})},{key:"ctr",label:"CTR",width:80,align:"right",render:r=>e.jsxs("span",{style:{color:U(r.ctr>=1.5?h.green:r.ctr>=.8?h.yellow:h.red),fontWeight:600},children:[r.ctr.toFixed(2),"%"]}),sortValue:r=>r.ctr,footer:r=>{const l=X(r);return e.jsxs("span",{style:{color:U(l.ctr>=1.5?h.green:l.ctr>=.8?h.yellow:h.red),fontWeight:800},children:[l.ctr.toFixed(2),"%"]})}},...n==="ads"?[{key:"fatigue_score",label:"Fatiga",width:110,align:"left",render:r=>{const l=vr(r.frequency||0,r.ctr||0,r.impressions||0,r.createdTime,p),z=no(l.score),M=ro(l.score),b=[`Frecuencia: ${l.frequency.toFixed(1)} â +${Math.round(l.frequencyPart)}`,l.daysOld!==void 0?`Edad: ${Math.round(l.daysOld)}d â +${Math.round(l.agePart)}`:"Edad: sin data",`CTR: ${l.ctr.toFixed(2)}% â +${Math.round(l.ctrPart)}`].join(` 2`);return e.jsxs("span",{title:b,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"2px 8px",borderRadius:999,background:`color-mix(in srgb, ${z} 14%, transparent)`,color:z,fontWeight:700,fontSize:11.5,cursor:"help"},children:[l.score," · ",M]})},sortValue:r=>vr(r.frequency||0,r.ctr||0,r.impressions||0,r.createdTime,p).score}
2]:[],{key:"cpc",label:"CPC",width:90,align:"right",sensitive:!0,render:r=>e.jsx("span",{style:{color:lt(r.cpc)},children:D(r.cpc)}),sortValue:r=>r.cpc,footer:r=>{const l=X(r).cpc;return e.jsx("span",{style:{fontWeight:800,color:lt(l)},children:D(l)})}},{key:"cpm",label:"CPM",width:90,align:"right",sensitive:!0,render:r=>e.jsx("span",{style:{color:U(r.cpm>7500?h.red:r.cpm>5500?h.yellow:"var(--text-primary)")},children:D(r.cpm)}),sortValue:r=>r.cpm,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:U(l.cpm>7500?h.red:l.cpm>5500?h.yellow:"var(--text-primary)")},children:D(l.cpm)})}},{key:"conversions",label:"Conv.",width:80,align:"right",render:r=>e.jsx("span",{style:{color:wr(r.conversions),fontWeight:600},children:r.conversions>0?Y(r.conversions):"â"}),sortValue:r=>r.conversions,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:wr(l.conversions)},children:l.conversions>0?Y(l.conversions):"â"})}},{key:"cpa",label:"CPA",width:90,align:"right",sensitive:!0,render:r=>e.jsx("span",{style:{color:it(r.cpa)},children:r.cpa>0?D(r.cpa):"â"}),sortValue:r=>r.cpa,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:it(l.cpa)},children:l.cpa>0?D(l.cpa):"â"})}},{key:"roas",label:"ROAS",width:80,align:"right",render:r=>e.jsx("span",{style:{color:U(r.roas>=3.5?h.green:r.roas>=1.5?h.yellow:r.roas>0?h.red:"var(--text-muted)"),fontWeight:700},children:r.roas>0?`${r.roas.toFixed(2)}x`:"â"}),sortValue:r=>r.roas,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:U(l.roas>=3.5?h.green:l.roas>=1.5?h.yellow:l.roas>0?h.red:"var(--text-muted)")},children:l.roas>0?`${l.roas.toFixed(2)}x`:"â"})}},{key:"conv_rate",label:"Conv. rate",width:90,align:"right",render:r=>e.jsx("span",{style:{color:"var(--text-secondary)"},children:r.clicks>0?`${(r.conversions/r.clicks*100).toFixed(2)}%`:"â"}),sortValue:r=>r.clicks>0?r.conversions/r.clicks*100:0,footer:r=>{const l=X(r),z=l.clicks>0?l.conversions/l.clicks*100:0;return e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:z>0?`${z.toFixed(2)}%`:"â"})}},{key:"video_2s",label:"Video 2s",width:90,align:"right",render:r=>e.jsx("span",{style:{color:"var(--text-secondary)"},children:Y(r.video_watched_2s)}),sortValue:r=>r.video_watched_2s,footer:r=>e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:Y(X(r).v2s)})},{key:"video_6s",label:"Video 6s",width:90,align:"right",render:r=>e.jsx("span",{style:{color:"var(--text-secondary)"},children:Y(r.video_watched_6s)}),sortValue:r=>r.video_watched_6s,footer:r=>e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:Y(X(r).v6s)})},{key:"hook_rate",label:"Hook rate",width:90,align:"right",render:r=>e.jsx("span",{style:{color:"var(--text-secondary)"},children:r.impressions>0?`${(r.video_watched_2s/r.impressions*100).toFixed(1)}%`:"â"}),sortValue:r=>r.impressions>0?r.video_watched_2s/r.impressions*100:0,footer:r=>{const l=X(r),z=l.impressions>0?l.v2s/l.impressions*100:0;return e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:z>0?`${z.toFixed(1)}%`:"â"})}},{key:"hold_rate",label:"Hold rate",width:90,align:"right",render:r=>e.jsx("span",{style:{color:"var(--text-secondary)"},children:r.video_watched_2s>0?`${(r.video_watched_6s/r.video_watched_2s*100).toFixed(1)}%`:"â"}),sortValue:r=>r.video_watched_2s>0?r.video_watched_6s/r.video_watched_2s*100:0,footer:r=>{const l=X(r),z=l.v2s>0?l.v6s/l.v2s*100:0;return e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:z>0?`${z.toFixed(1)}%`:"â"})}},{key:"pageviews",label:"Pageviews",width:100,align:"right",render:r=>e.jsx("span",{style:{color:r.pageviews>0?"var(--text-primary)":"var(--text-muted)",fontWeight:600},children:r.pageviews>0?Y(r.pageviews):"â"}),sortValue:r=>r.pageviews,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:l.pageviews>0?Y(l.pageviews):"â"})}},{key:"landing_rate",label:"Landing rate",width:110,align:"right",render:r=>e.jsx("span",{style:{color:U(r.landingRate>=70?h.green:r.landingRate>=40?h.yellow:r.landingRate>0?h.red:"var(--text-muted)")},children:r.landingRate>0?`${r.landingRate.toFixed(0)}%`:"â"}),sortValue:r=>
2r.landingRate,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:U(l.landingRate>=70?h.green:l.landingRate>=40?h.yellow:l.landingRate>0?h.red:"var(--text-muted)")},children:l.landingRate>0?`${l.landingRate.toFixed(0)}%`:"â"})}},{key:"web_conv",label:"Compras",width:90,align:"right",render:r=>e.jsx("span",{style:{color:U(r.webConversions>0?h.green:"var(--text-muted)"),fontWeight:600},children:r.webConversions>0?Y(r.webConversions):"â"}),sortValue:r=>r.webConversions,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:U(l.webConv>0?h.green:"var(--text-muted)")},children:l.webConv>0?Y(l.webConv):"â"})}},{key:"web_rate",label:"Tasa compra",width:110,align:"right",render:r=>e.jsx("span",{style:{color:U(r.webConvRate>=3?h.green:r.webConvRate>=1.5?h.yellow:r.webConvRate>0?h.red:"var(--text-muted)")},children:r.webConvRate>0?`${r.webConvRate.toFixed(2)}%`:"â"}),sortValue:r=>r.webConvRate,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:U(l.webConvRate>=3?h.green:l.webConvRate>=1.5?h.yellow:l.webConvRate>0?h.red:"var(--text-muted)")},children:l.webConvRate>0?`${l.webConvRate.toFixed(2)}%`:"â"})}},{key:"budget",label:"Presupuesto",width:145,align:"right",sensitive:!0,render:r=>{const l=r.id&&r.advertiser_id&&F!=="ad";return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,justifyContent:"flex-end"},children:[e.jsx("span",{style:{color:"var(--text-secondary)"},children:r.budget>0?D(r.budget):"â"}),l&&e.jsx(Hn,{entityId:r.id,advertiserId:r.advertiser_id,level:F,currentBudget:r.budget})]})},sortValue:r=>r.budget,footer:r=>{const l=X(r);return e.jsx("span",{style:{fontWeight:800,color:"var(--text-primary)"},children:l.budget>0?D(l.budget):"â"})}},{key:"trend",label:"Tendencia 7d",width:90,align:"center",render:r=>{if(!c||!r.id)return e.jsx("span",{style:{color:"var(--text-muted)"},children:"â"});const l=c[r.id];if(!l||l.length===0||l.every(b=>b===0))return e.jsx("span",{style:{color:"var(--text-muted)",fontSize:11},children:"â"});const z=l.reduce((b,k)=>b+k,0),M=l.map((b,k)=>`${`D${k-l.length+1===0?"hoy":k-l.length+1}`}: ${D(b)}`).join(` 3`);return e.jsx("div",{title:`Spend 7d: ${D(z)} 4${M}`,style:{display:"flex",justifyContent:"center"},children:e.jsx(Oo,{data:l,width:64,height:24,showDot:!0})})},sortValue:r=>{if(!c||!r.id)return 0;const l=c[r.id];return!l||l.length<2?0:l[l.length-1]-l[0]}},...n==="campaigns"&&d?[{key:"shopify_orders",label:"Compras Shopify",width:130,align:"right",render:r=>{const l=d.get(r.name);if(!l)return e.jsx("span",{style:{color:"var(--text-muted)"},children:"â"});const z=l.orders-l.cancelled;return e.jsx("span",{style:{fontWeight:700,color:U(h.green)},children:z})},sortValue:r=>{const l=d.get(r.name);return l?l.orders-l.cancelled:-1}},{key:"shopify_aov",label:"AOV Real",width:110,align:"right",sensitive:!0,render:r=>{const l=d.get(r.name);return!l||l.aov===0?e.jsx("span",{style:{color:"var(--text-muted)"},children:"â"}):e.jsx("span",{children:D(l.aov)})},sortValue:r=>{var l;return((l=d.get(r.name))==null?void 0:l.aov)||0}},{key:"shopify_cancel_rate",label:"% Cancelación",width:130,align:"right",render:r=>{const l=d.get(r.name);if(!l||l.orders===0)return e.jsx("span",{style:{color:"var(--text-muted)"},children:"â"});const z=l.cancelled/l.orders*100,M=U(z>=25?h.red:z>=12?h.yellow:h.green);return e.jsxs("span",{style:{color:M,fontWeight:600},children:[z.toFixed(1),"%"]})},sortValue:r=>{const l=d.get(r.name);return!l||l.orders===0?-1:l.cancelled/l.orders*100}}]:[],...x?Bo(n):[],...m,{key:"actions",label:"Acciones",width:130,align:"center",render:r=>{if(!r.id||!r.advertiser_id)return e.jsx("span",{title:"No se puede gestionar â reconecta la cuenta por OAuth con permiso de management",style:{fontSize:16,color:"var(--text-muted)"},children:"â"});const l=n==="adgroups"||n==="ads";return e.jsxs("div",{onClick:z=>z.stopPropagation(),style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(Mo,{children:e.jsx(Gn,{entityId:r.id,entityName:r.name,advertiserId:r.advertiser_id,currentStatus:r.status,level:F,spend:r.spend,roas:r.roas,budget:r.budget})}),n==="ads"&&r.isRejected&&T&&e.jsx("button",{onClick:z=>{z.stopPropagation(),T(r)}
4,title:"Apelar este rechazo de TikTok",style:{padding:"4px 8px",border:"1px solid rgba(239,68,68,0.40)",background:"rgba(239,68,68,0.08)",borderRadius:6,fontSize:11,fontWeight:700,cursor:"pointer",color:"#EF4444",fontFamily:"inherit",display:"inline-flex",alignItems:"center",gap:3,flexShrink:0},children:"âï¸ Apelar"}),l&&e.jsxs("button",{onClick:z=>{z.stopPropagation(),g==null||g(r),w==null||w(n)},title:"Ver resumen detallado",style:{padding:"4px 8px",border:"1px solid var(--border)",background:"var(--bg-card)",borderRadius:6,fontSize:11,fontWeight:600,cursor:"pointer",color:"#FE2C55",fontFamily:"inherit",display:"inline-flex",alignItems:"center",gap:3,flexShrink:0},children:[e.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M3 3v18h18"}),e.jsx("path",{d:"m19 9-5 5-4-4-3 3"})]}),"Resumen"]})]})},sortValue:r=>r.status}]}const Vo={background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:8,fontSize:"0.82em"},Ir={fontSize:10,fill:"var(--text-muted)"};function Xr(n,c,f){if(c===-1)return{covered:n,locked:[]};if(c<=0)return{covered:[],locked:n};const d=(f||[]).filter(Boolean);if(d.length===0)return n.length<=c?{covered:n,locked:[]}:{covered:[],locked:n};const y=new Set(d),p=g=>y.has(g.accountName)||!!g.advertiserId&&y.has(g.advertiserId);return{covered:n.filter(p),locked:n.filter(g=>!p(g))}}function Ho({centros:n,elegido:c,onChange:f}){const[d,y]=i.useState(!1),p=i.useRef(null);At(d,()=>y(!1)),i.useEffect(()=>{if(!d)return;function x(m){p.current&&!p.current.contains(m.target)&&y(!1)}const v=setTimeout(()=>document.addEventListener("mousedown",x),0);return()=>{clearTimeout(v),document.removeEventListener("mousedown",x)}},[d]);const g=n.find(x=>x.id===c),w=g?`${g.nombre} · ${g.cuentas.length} cuenta${g.cuentas.length===1?"":"s"}`:"Todos los centros",T=(x,v,m)=>{const F=c===x;return e.jsxs("button",{onClick:()=>{f(x),y(!1)},style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"7px 8px",cursor:"pointer",borderRadius:4,fontSize:12,border:"none",textAlign:"left",background:F?`${h.tiktokCyan}12`:"transparent",fontFamily:"inherit",color:"var(--text-primary)",fontWeight:F?700:500},children:[e.jsx("span",{style:{width:14,flexShrink:0,color:h.tiktokCyan,fontWeight:800},children:F?"â":""}),e.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v}),m!==null&&e.jsxs("span",{style:{fontSize:10,color:"var(--text-muted)",flexShrink:0},children:[m," cuenta",m===1?"":"s"]})]},x||"todos")};return e.jsxs("div",{ref:p,style:{position:"relative",minWidth:0},children:[e.jsxs("button",{onClick:()=>y(x=>!x),"aria-label":"Centro de Negocios de TikTok",style:{padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:600,border:"1px solid var(--border)",background:"var(--bg-card)",color:"var(--text-primary)",cursor:"pointer",fontFamily:"inherit",display:"flex",alignItems:"center",gap:8,minWidth:180,maxWidth:"100%"},children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:h.tiktokCyan,strokeWidth:"2.2",style:{flexShrink:0},children:e.jsx("path",{d:"M3 21h18M5 21V7l7-4 7 4v14M9 9h.01M9 13h.01M9 17h.01M15 9h.01M15 13h.01M15 17h.01"})}),e.jsx("span",{style:{flex:1,textAlign:"left",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w}),e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",style:{flexShrink:0,transform:d?"rotate(180deg)":"none",transition:"transform 0.15s"},children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),d&&e.jsxs("div",{style:{position:"absolute",top:"100%",left:0,marginTop:4,background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:8,padding:6,minWidth:240,maxWidth:"calc(100vw - 24px)",maxHeight:320,overflowY:"auto",zIndex:50,boxShadow:"var(--shadow-md)"},children:[T("","Todos los centros",null),n.map(x=>T(x.id,x.nombre,x.cuentas.length))]})]})}const Go=n=>{const c=qs(n);return c.length?c:Ur(n)};function qo({valor:n,opciones:c,onChange:f}){return e.jsx(us,{etiqueta:"Campaña",valor:n,opciones:c,onChange:f,acento:h.tiktokCyan,anchoMin:160,icono:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:h.tiktokCyan,strokeWidth:"2.2",style:{flexShrink:0},children:[e.jsx("path",{d:"M3 11l18-5v12L3 13v-2z"}),e.jsx("path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6"})]})})}function Ko({accounts:n,selected:c,onChange:f,centrosPorCuenta:d={}}){const{limits:y,selected:p}=Nr(),{covered:g,locked:w}=Xr(n,y.tiktok.limit,p.tiktok);new Set(w.map(b=>b.accountName));const{isHidden:T}=Wr(),[x,v]=i.useState(!1);i.useEffect(()=>{const b=k=>{const S=k.detail;(S==null?void 0:S.tipo)!=="cuentas-anuncios"||S.plataforma!=="tiktok"||(v(!0),S.consumido=!0)};return window.addEventListener("lumy:guia-ir",b),()=>window.removeEventListener("lumy:guia-ir",b)},[]);const m=i.useRef(null);At(x,()=>v(!1)),i.useEffect(()=>{if(!x)return;function b(S){m.current&&!m.current.contains(S.target)&&v(!1)}const k=setTimeout(()=>document.addEventListener("mousedown",b),0);return()=>{clearTimeout(k),document.removeEventListener("mousedown",b)}},[x]);const F=c.length===0?"Todas las cuentas":c.length===1?Or(c[0],T):`${c.length} cuentas`,r=b=>{f(c.includes(b)?c.filter(k=>k!==b):[...c,b])},l=i.useMemo(()=>{const b=new Map,k=[];for(const I of g){const $=I.advertiserId?d[String(I.advertiserId)]:void 0;if(!$){k.push(I);continue}const Q=b.get($.id)||{nombre:$.nombre,cuentas:[]};
4Q.cuentas.push(I),b.set($.id,Q)}if(b.size<2)return null;const S=[...b.entries()].map(([I,$])=>({id:I,nombre:$.nombre,cuentas:$.cuentas}));return S.sort((I,$)=>$.cuentas.length-I.cuentas.length||I.nombre.localeCompare($.nombre,"es")),k.length>0&&S.push({id:"__sueltas__",nombre:"Sin centro de negocios",cuentas:k}),S},[g,d]),z=b=>{const k=b.map($=>$.accountName);if(!k.every($=>c.includes($))){f([...new Set([...c,...k])]);return}const I=c.filter($=>!k.includes($));f(I.length>0?I:[...new Set(g.map($=>$.accountName).filter($=>!k.includes($)))])},M=b=>{const k=c.includes(b.accountName);return e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",cursor:"pointer",borderRadius:4,fontSize:12},children:[e.jsx("input",{type:"checkbox",checked:k,onChange:()=>r(b.accountName),style:{accentColor:h.tiktokCyan}}),e.jsx("span",{className:"censor-blur",style:{flex:1,color:"var(--text-primary)",fontWeight:k?600:500},children:b.accountName}),e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)"},children:Ve(b.spend)})]},b.accountName)};return e.jsxs("div",{ref:m,style:{position:"relative"},children:[e.jsxs("button",{onClick:()=>v(b=>!b),style:{padding:"6px 12px",borderRadius:8,fontSize:12,fontWeight:600,border:"1px solid var(--border)",background:"var(--bg-card)",color:"var(--text-primary)",cursor:"pointer",fontFamily:"inherit",display:"flex",alignItems:"center",gap:8,minWidth:180},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:h.tiktokCyan,strokeWidth:"2.2",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),e.jsx("span",{style:{flex:1,textAlign:"left",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:F}),e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",style:{transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),x&&e.jsxs("div",{style:{position:"absolute",top:"100%",right:0,marginTop:4,background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:8,padding:6,minWidth:260,maxWidth:"calc(100vw - 24px)",maxHeight:320,overflowY:"auto",zIndex:50,boxShadow:"var(--shadow-md)"},children:[n.length===0&&e.jsx("div",{style:{padding:10,fontSize:12,color:"var(--text-muted)",textAlign:"center"},children:"No hay cuentas conectadas"}),l?l.map(b=>{const k=b.cuentas.every(S=>c.includes(S.accountName));return e.jsxs("div",{style:{marginBottom:4},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px"},children:[e.jsxs("span",{style:{fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[b.nombre," · ",b.cuentas.length]}),e.jsx("button",{onClick:()=>z(b.cuentas),style:{border:"none",background:"transparent",color:h.tiktokCyan,fontSize:10.5,fontWeight:700,cursor:"pointer",fontFamily:"inherit",padding:"2px 4px",flexShrink:0},children:k?"Quitar":"Todas"})]}),b.cuentas.map(M)]},b.id)}):g.map(M),w.length>0&&e.jsxs("div",{style:{marginTop:6,paddingTop:6,borderTop:"1px dashed var(--border)"},children:[e.jsxs("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",padding:"2px 8px",marginBottom:2},children:["Plan no cubre · ",w.length]}),w.map(b=>e.jsxs("button",{onClick:()=>Ls("TikTok"),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",cursor:"pointer",borderRadius:4,fontSize:12,border:"none",background:"transparent",textAlign:"left",fontFamily:"inherit",opacity:.55},title:"Tu plan actual no cubre esta cuenta. Click para actualizar.",children:[e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",style:{flexShrink:0,color:"var(--text-muted)"},children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2"}),e.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),e.jsx("span",{className:"censor-blur",style:{flex:1,color:"var(--text-secondary)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.accountName}),e.jsx("span",{style:{fontSize:9,fontWeight:700,color:"#A855F7",textTransform:"uppercase",letterSpacing:"0.06em",flexShrink:0},children:"Upgrade"})]},b.accountName))]}),g.length>0&&e.jsxs("div",{style:{borderTop:"1px solid var(--border)",marginTop:4,paddingTop:4,display:"flex",gap:4},children:[e.jsxs("button",{onClick:()=>f(g.map(b=>b.accountName)),style:{flex:1,padding:"4px 6px",fontSize:11,background:"transparent",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-secondary)",cursor:"pointer",fontFamily:"inherit"},children:["Todas",w.length>0?` (${g.length})`:""]}),e.jsx("button",{onClick:()=>f([]),style:{flex:1,padding:"4px 6px",fontSize:11,background:"transparent",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-secondary)",cursor:"pointer",fontFamily:"inherit"},children:"Ninguna"})]})]})]})}function Ca(){var lr,cr;const n=Nn(),{getQueryParams:c,datePreset:f,setDatePreset:d,customRange:y,setCustomRange:p}=Pr();ws();const{refreshKey:g}=On(),{isHidden:w}=Wr(),T=w?"sensitive-hidden":"sensitive-visible",{setContext:x}=Mn(),[v,m]=i.useState([]),[F,r]=i.useState(!1),[l,z]=i.useState([]),M=i.useMemo(()=>
4{if(v.length===0)return l;const o=new Map(l.map(s=>[s.accountName,s.spend]));return v.map(s=>({...s,spend:o.get(s.accountName)??0}))},[v,l]),[b,k]=i.useState({}),[S,I]=i.useState(()=>{try{return localStorage.getItem("tiktok_centro_elegido")||""}catch{return""}}),$=i.useMemo(()=>{const o=new Map;for(const s of M){const t=s.advertiserId?b[String(s.advertiserId)]:void 0;if(!t)continue;const u=o.get(t.id)||{id:t.id,nombre:t.nombre,cuentas:[]};u.cuentas.push(s),o.set(t.id,u)}return[...o.values()].sort((s,t)=>t.cuentas.length-s.cuentas.length||s.nombre.localeCompare(t.nombre,"es"))},[M,b]),Q=i.useMemo(()=>{if(!S)return M;const o=$.find(s=>s.id===S);return o!=null&&o.cuentas.length?o.cuentas:M},[M,S,$]),V=o=>{I(o);try{localStorage.setItem("tiktok_centro_elegido",o)}catch{}const s=$.find(t=>t.id===o);oe(s?[...new Set(s.cuentas.map(t=>t.accountName))]:[])},[H,oe]=i.useState(()=>{try{const o=localStorage.getItem("tiktok_dash_selected_names");if(o)return JSON.parse(o)}catch{}return[]});i.useEffect(()=>{try{localStorage.setItem("tiktok_dash_selected_names",JSON.stringify(H))}catch{}},[H]),i.useEffect(()=>{const o=v.map(s=>s.accountName);oe(s=>ko(s,o,F))},[v,F]),i.useEffect(()=>{v.length===1&&!F&&oe(o=>o.length===0?[v[0].accountName]:o)},[v,F]);const re=Nr(),{user:ne}=Ln(),de=(ne==null?void 0:ne.role)==="admin"||!!(ne!=null&&ne.landing_access)||!re.loading&&!!((cr=(lr=re.limits)==null?void 0:lr.landing)!=null&&cr.enabled),ue=Is(de,"tiktok"),N=Zn(de),G=i.useMemo(()=>{const{covered:o}=Xr(M,re.limits.tiktok.limit,re.selected.tiktok),s=new Set(o.map(t=>t.accountName));return H.filter(t=>s.has(t))},[M,H,re.limits.tiktok.limit,re.selected.tiktok]),[j,W]=i.useState(null),[R,Z]=i.useState(null),[ie,Se]=i.useState(7),[Ce,dt]=i.useState([]),[K,Zr]=i.useState([]),[Et,en]=i.useState({}),[zt,Ft]=i.useState({}),[pt,tn]=i.useState(0),[Yo,rn]=i.useState(0),[Jo,nn]=i.useState(0),[q,It]=i.useState(null),[we,Pt]=i.useState(!1),[Wt,Ge]=i.useState(null),[se,sn]=i.useState("active"),Nt=qn(),on=(()=>{if(typeof window>"u")return"campaigns";const o=new URLSearchParams(window.location.search).get("level");return o==="campaigns"||o==="adgroups"||o==="ads"?o:"campaigns"})(),[A,qe]=i.useState(on);i.useEffect(()=>{const o=s=>{const t=s.detail;(t==null?void 0:t.tipo)!=="nivel-anuncios"||t.plataforma!=="tiktok"||(qe(t.nivel),t.consumido=!0)};return window.addEventListener("lumy:guia-ir",o),()=>window.removeEventListener("lumy:guia-ir",o)},[]);const{widths:Ot,setWidth:an,resetWidth:ln}=es(`tiktok_${A}`);i.useEffect(()=>{const o=new URLSearchParams(Nt.search).get("level");(o==="campaigns"||o==="adgroups"||o==="ads")&&o!==A&&qe(o)},[Nt.search]);const[ut,cn]=i.useState("spend"),[gt,Mt]=i.useState(""),[pe,Pe]=i.useState(0),[We,mt]=i.useState(!1);Un("tiktok",we||We);const Te=i.useRef(-1),he=pe>0&&pe===Te.current,_e=So(!!q,he?pe:null),[dn,Lt]=i.useState(!1),{metrics:Ke}=ts(),[pn,un]=i.useState(null),[Ue,ht]=i.useState(!1),Bt=rs(),Dt=to(f,y),[gn,Vt]=i.useState(null),[mn,hn]=i.useState("campaigns"),[$e,Ht]=i.useState(null),le=i.useMemo(()=>Do(A,Et,zt,Bt,Ke,Dt,Vt,hn,Ht,de),[A,Et,zt,Bt,Ke,Dt,de]),[Ye,Gt]=i.useState(()=>{const s=Fr(zr,[]).filter(u=>le.some(a=>a.key===u)),t=le.map(u=>u.key).filter(u=>!s.includes(u));return[...s,...t]});i.useEffect(()=>{const o=le.map(s=>s.key);Gt(s=>{const t=s.filter(a=>o.includes(a)),u=o.filter(a=>!t.includes(a));return u.length===0&&t.length===s.length?s:[...t,...u]})},[le]);const[be,xn]=i.useState(()=>{const o=new Set(Fr(st,["video_2s","video_6s","hook_rate","hold_rate","conv_rate","roas","lumy_orders",...hr]));try{if(!localStorage.getItem(st+"_lumy_v1")){for(const s of["lumy_orders",...hr])o.add(s);localStorage.setItem(st+"_lumy_v1","1")}}catch{}return o}),[ve,Je]=i.useState(!1),{ref:qt,ampliada:xe,girada:Kt,alternar:fn,estilo:yn,marca:bn,enCelular:vn}=Ts(),xt=o=>{const s=qt.current;s&&(o?s.setAttribute("data-arrastrando","1"):s.removeAttribute("data-arrastrando"))},[Qe,kn]=i.useState(""),[Xe,jn]=i.useState(""),Ut=(o,s)=>{kn(o),jn(s),o&&s&&o<=s&&p({since:o,until:s})},Ze=[{key:"yesterday",label:"Ayer",days:1},{key:"last_3d",label:"3 dÃas",days:3},{key:"last_7d",label:"7 dÃas",days:7},{key:"last_15d",label:"15 dÃas",days:15},{key:"last_30d",label:"30 dÃas",days:30}],[ke,ft]=i.useState(()=>{try{return JSON.parse(localStorage.getItem("tiktok_compare_items")||"null")||Ze}catch{return Ze}});i.useEffect(()=>{try{localStorage.setItem("tiktok_compare_items",JSON.stringify(ke))}catch{}},[ke]);const[Yt,yt]=i.useState(!1);At(Yt,()=>yt(!1));const[Re,Jt]=i.useState(""),[Ae,Qt]=i.useState(""),Sn=i.useRef(null),[Ee,bt]=i.useState("spend"),[Ne,et]=i.useState("desc"),[je,Oe]=i.useState(null),B=Bs(),fe=Bn(769),vt=ot("tiktok-alertas",!1);ot("tiktok-comparativo",!1);const kt=ot("tiktok-tendencia",!1),[Xt,jt]=i.useState(null),Cn=i.useMemo(()=>({activationConstraint:{delay:450,tolerance:8}}),[]),wn=Ds($t(Js,{activationConstraint:{distance:4}}),$t(Ys,Cn),$t(Us,{coordinateGetter:Ks}));i.useEffect(()=>{localStorage.setItem(zr,JSON.stringify(Ye))},[Ye]),i.useEffect(()=>{localStorage.setItem(st,JSON.stringify([...be]))},[be]),i.useEffect(()=>{let o=!0,s=0,t=null;const u=()=>{s++,t=setTimeout(a,5e3*s)};function a(){fetch("/api/tiktok/status").then(C=>C.json()).then(C=>{o&&(It(!!C.connected),C.accounts&&m(C.accounts),r(!!C.parcial),C.parcial&&s<3&&u())}).catch(()=>{o&&(s<3?u():It(!1))})}return a(),()=>{o=!1,t&&clearTimeout(t)}},[]);const Tn=v.map(o=>o.advertiserId||o.accountName).join(",");i.useEffect(()=>{if(!q||v.length<2){k({});return}let o=!0;return fetch("/api/tiktok/business-centers").then(s=>s.json()).then(s=>{o&&k((s==null?void 0:s.porCuenta)||{})}).catch(()=>{}),()=>{o=!1}},[q,Tn]),i.useEffect(()=>{q&&fetch(`/api/tiktok/accounts?${c()}`).then(o=>o.json()).then(o=>{o.accounts&&z(o.accounts)}).catch(()=>{})},[q,c,g,_e]);const Zt=i.useRef(!1),St=i.useRef(""),er=i.useRef(null);i.useEffect(()=>{var C;if(!q)return;(C=er.current)==null||C.abort();const o=new AbortController;er.current=o;const s=`${c()}|${H.join(",")}|${se}|${A}`,t=St.current!==""&&St.current!==s;St.current=s,t&&mt(!0),Zt.current||Pt(!0),Ge(null);const u=new URLSearchParams(c());G.length>0&&u.set("accounts",G.join(",")),he&&u.set("fresh","true"),u.set("status",se),B.size>0&&u.set("campaigns",[...B.selected].join(","));const a=async P=>{const _=[0,1e3,2e3,4e3];let E;for(let L=0;L<_.length;L++){if(o.signal.aborted)throw Object.assign(new Error("Aborted"),{name:"AbortError"});_[L]>0&&await new Promise(O=>setTimeout(O,_[L]));try{const O=await fetch(P,{signal:o.signal});if(O.ok)return O.json();if(O.status>=400&&O.status<500){const te=await O.text().catch(()=>""),ge=new Error(`HTTP ${O.status} ${O.statusText}${te?": "+te.slice(0,140):""}`);throw ge.status=O.status,ge}const ce=await O.text().catch(()=>"");E=Object.assign(new Error(`HTTP ${O.status}: ${ce.slice(0,140)||O.statusText}`),{status:O.status}),console.warn(`[tiktok] ${P} HTTP ${O.status} (intento ${L+1}/${_.length})`)}catch(O){if((O==null?void 0:O.name)==="AbortError"||O!=null&&O.status&&O.status>=400&&O.status<500)throw O;E=O,console.warn(`[tiktok] ${P} network err (intento ${L+1}/${_.length}):`,(O==null?void 0:O.message)||O)}}throw E||new Error("Fetch falló sin razón conocida")};Promise.allSettled([a(`/api/tiktok/overview?${u}`),a(`/api/tiktok/${A}?${u}`)]).then(([P,_])=>{var dr,pr;if(o.signal.aborted)return;P.status==="rejected"&&console.error("[tiktok] /overview FAILED:",((dr=P.reason)==null?void 0:dr.message)||P.reason),_.status==="rejected"&&console.error(`[tiktok] /${A} FAILED:`,((pr=_.reason)==null?void 0:pr.message)||_.reason);const E=P.status==="fulfilled"?P.value:null,L=_.status==="fulfilled"?_.value:null;if(!E&&!L){const Le=[P,_].filter(me=>me.status==="rejected").map(me=>{var ur;return((ur=me.reason)==null?void 0:ur.message)||String(me.reason)}),In=Le.some(me=>me.includes("HTTP 401")||me.includes("HTTP 403")),Pn=Le.some(me=>me.includes("HTTP 429")),Wn=In?"Tu cuenta de TikTok Ads necesita reconectarse":Pn?"TikTok limitó las consultas, espera unos segundos":`TikTok no respondió: ${Le[0]}`;Ge(Wn);return}(E==null?void 0:E.error)==="all_failed"&&console.warn(`[tiktok] /overview: server reportó all_failed â ${E.failedAccounts}/${E.accounts} cuentas fallaron`),(E==null?void 0:E.error)==="partial_failure"&&console.warn(`[tiktok] /overview: server reportó partial_failure â ${E.failedAccounts}/${E.accounts} cuentas fallaron`),E||console.warn(`[tiktok] /overview falló pero /${A} respondió â render parcial con la lista`),L||console.warn(`[tiktok] /${A} falló pero /overview respondió â render parcial con KPIs`);const O=(L==null?void 0:L.data)||[],ce=E!=null&&j!=null&&j.spend>0&&((E==null?void 0:E.spend)||0)===0&&((E==null?void 0:E.impressions)||0)===0,te=L!=null&&K.length>0&&O.length===0,ge=(E==null?void 0:E.error)==="partial_failure"||(E==null?void 0:E.error)==="all_failed",J=L==null?void 0:L._warnings,Me=Array.isArray(J)?J.length>0:Number((J==null?void 0:J.failedAccounts)||0)>0,Fn=j!=null||K.length>0;if(!t&&(ce||te||(ge||Me)&&Fn)){const Le=ce&&te?"overview+entities":ce?"overview (spend=0)":te?"entities (lista vacÃa)":ge?`overview partial (${E==null?void 0:E.failedAccounts}/${E==null?void 0:E.accounts} cuentas)`:"entities partial";console.log(`[tiktok] anti-flash atómico: skip (${Le}) â mantengo prev sincronizado`)}else E&&W(E),L&&(Zr(O),O.length>0&&tn(L.total||0)),(L||E)&&un(new Date)}
4).catch(P=>{(P==null?void 0:P.name)!=="AbortError"&&(console.error("[tiktok] fetch unexpected error:",P),Ge(P!=null&&P.message?String(P.message):"Error desconocido en TikTok"))}).finally(()=>{o.signal.aborted||(Pt(!1),mt(!1),ht(!1),Zt.current=!0)})},[q,c,g,pe,G.join(","),se,A,B.selected]),i.useEffect(()=>{if(!q)return;const o=new AbortController,s=new URLSearchParams(c());return G.length>0&&s.set("accounts",G.join(",")),he&&s.set("fresh","true"),Promise.all([fetch(`/api/tiktok/${A}?${s}&status=active`,{signal:o.signal}).then(t=>t.json()),fetch(`/api/tiktok/${A}?${s}&status=inactive`,{signal:o.signal}).then(t=>t.json())]).then(([t,u])=>{var a,C;o.signal.aborted||(rn(((a=t.data)==null?void 0:a.length)||0),nn(((C=u.data)==null?void 0:C.length)||0))}).catch(()=>{}),()=>o.abort()},[q,c,g,pe,G.join(","),A]),i.useEffect(()=>{if(!q)return;const o=new AbortController,s=new URLSearchParams;return s.set("days",String(ie)),G.length>0&&s.set("accounts",G.join(",")),he&&s.set("fresh","true"),fetch(`/api/tiktok/timeseries?${s}`,{signal:o.signal}).then(t=>t.json()).then(t=>{o.signal.aborted||t.error||dt(t.byDay||[])}).catch(()=>{}),()=>o.abort()},[q,ie,G.join(","),g,_e]),i.useEffect(()=>{if(!q)return;fetch(`/api/tiktok/sparklines?level=${A==="campaigns"?"campaign":A==="adgroups"?"adgroup":"ad"}`).then(s=>s.json()).then(s=>{s.error||en(s.data||{})}).catch(()=>{})},[q,A,g,_e]),i.useEffect(()=>{if(!q||A!=="ads"){Ft({});return}fetch("/api/tiktok/fatigue").then(o=>o.json()).then(o=>{o.error||Ft(o.data||{})}).catch(()=>{})},[q,A,g,_e]),i.useEffect(()=>{if(!q)return;const o=new AbortController,s=new URLSearchParams;return G.length>0&&s.set("accounts",G.join(",")),s.set("status",se),he&&s.set("fresh","true"),B.size>0&&s.set("campaigns",[...B.selected].join(",")),fetch(`/api/tiktok/overview-multi?${s}`,{signal:o.signal}).then(t=>t.json()).then(t=>{if(o.signal.aborted||t.error)return;const u=(t._warnings||[]).length>0;Z(a=>u&&a?(console.log(`[tiktok] overview-multi anti-flash: skip (${t._warnings.length} warnings) â mantengo prev`),a):t)}).catch(()=>{}),()=>o.abort()},[q,g,_e,G.join(","),se,B.selected]);const[_n,$n]=i.useState({});i.useEffect(()=>{if(!q)return;const o=ke.filter(t=>t.since&&t.until);if(o.length===0)return;const s=new AbortController;return o.forEach(t=>{const u=new URLSearchParams;u.set("since",t.since),u.set("until",t.until),u.set("status",se),G.length>0&&u.set("accounts",G.join(",")),he&&u.set("fresh","true"),fetch(`/api/tiktok/overview?${u}`,{signal:s.signal}).then(a=>a.json()).then(a=>{s.signal.aborted||a.error||$n(C=>({...C,[t.key]:{since:t.since,until:t.until,spend:a.spend||0,impressions:a.impressions||0,clicks:a.clicks||0,ctr:a.ctr||0,cpc:a.cpc||0,cpm:a.cpm||0,conversions:a.conversions||0,conversionValue:a.conversionValue||0,cpa:a.cpa||0,roas:a.roas||0,pageviews:a.pageviews||0,landingRate:a.clicks>0?(a.pageviews||0)/a.clicks*100:0}}))}).catch(()=>{})}),()=>s.abort()},[q,ke,g,_e,G.join(","),se]);const tr=Kr(3e4,!!q);i.useEffect(()=>{!q||tr===0||Pe(o=>o+1)},[tr,q]),i.useEffect(()=>{he&&(Te.current=-1)},[he,pe]);const[ze,rr]=i.useState(null),[Qo,nr]=i.useState(null);function Ct(o,s){try{const t=o.trim();if(/\s+AND\s+/i.test(t))return t.split(/\s+AND\s+/i).every(C=>Ct(C,s));if(/\s+OR\s+/i.test(t))return t.split(/\s+OR\s+/i).some(C=>Ct(C,s));const u=t.match(/^(\w+)\s+contains\s+"?([^"]+)"?$/i);if(u){const C=u[1].toLowerCase(),P=u[2].toLowerCase();return(C==="campaign"?s.name||"":String(s[C]??"")).toLowerCase().includes(P)}const a=t.match(/^(\w+)\s*(>=|<=|>|<|=|!=)\s*([\d.]+)$/);if(a){const C=a[1].toLowerCase(),P=a[2],_=parseFloat(a[3]),L={spend:s.spend,clicks:s.clicks,impressions:s.impressions,ctr:s.ctr,cpc:s.cpc,cpm:s.cpm,compras:s.conversions,conversions:s.conversions,cpa:s.cpa,roas:s.roas}[C]??0;switch(P){case">":return L>_;case"<":return L<_;case">=":return L>=_;case"<=":return L<=_;case"=":return L===_;case"!=":return L!==_}}return!0}catch{return!0}}const wt=i.useMemo(()=>{if(!de)return K;const o=new Set(N);return _s(K,{pedidos:s=>A==="campaigns"?Ws(ue.indice,{campaign_id:s.id,campaign_name:s.name}):A==="adgroups"?Ns(ue.indice,{adset_id:s.id}):Os(ue.indice,{ad_id:s.id}),gasto:s=>Number(s.spend)||0,visitas:A==="campaigns"?s=>Ps(ue.indice,{campaign_id:s.id,campaign_name:s.name}):void 0,destino:A==="ads"?s=>ps(s.landingPageUrl?[s.landingPageUrl]:[],"",o):void 0})},[K,de,A,ue.indice,N]),ee=i.useMemo(()=>{const o=gt.trim().toLowerCase();let s=o?wt.filter(a=>(a.name||"").toLowerCase().includes(o)||(a.accountName||"").toLowerCase().includes(o)):wt;je&&A!=="campaigns"&&(s=s.filter(a=>a.parentCampaign===je)),B.size>0&&A!=="campaigns"&&(s=s.filter(a=>a.parentCampaignId&&B.has(String(a.parentCampaignId)))),ze&&(s=s.filter(a=>Ct(ze,a)));const t=le.find(a=>a.key===Ee);if(!t)return s;const u=Ne==="asc"?1:-1;return[...s].sort((a,C)=>{const P=t.sortValue(a),_=t.sortValue(C);return typeof P=="number"&&typeof _=="number"?(P-_)*u:String(P).localeCompare(String(_))*u})},[wt,gt,Ee,Ne,le,je,A,ze,B.selected]);i.useEffect(()=>{if(A!=="campaigns"||B.size===0||!K.length)return;const o=new Set(K.map(t=>
4String(t.id||"")).filter(Boolean)),s=B.reconcile(o);if(s>0){jt(`Se removieron ${s} ${s===1?"campaña":"campañas"} que no tienen data en este perÃodo`);const t=setTimeout(()=>jt(null),5e3);return()=>clearTimeout(t)}},[K,A]);const Fe=i.useMemo(()=>{const o=[];if(!R)return o;const s=R.today,t=R.yesterday,u=R.last_7d;s&&t&&t.spend>0&&s.spend/t.spend>1.5&&o.push({severity:"warning",title:`Gasto subió ${Math.round((s.spend/t.spend-1)*100)}% vs ayer`,desc:`Hoy: ${new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(s.spend)} · Ayer: ${new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(t.spend)}. Asegúrate de tener los presupuestos bajo control.`,action:"Revisa presupuestos por campaña y pausa las que no estén entregando ROAS ⥠2x",metric:`+${Math.round((s.spend/t.spend-1)*100)}%`}),u&&u.cpa>15e3&&u.conversions>0&&o.push({severity:"critical",title:"CPA arriba del lÃmite ($15K COP)",desc:`CPA 7d: ${new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(u.cpa)}. Con este costo no hay margen rentable en COD Colombia.`,action:"Pausa campañas con peor CPA y lanza Smart+ con Lookalike de compradores",metric:`CPA $${(u.cpa/1e3).toFixed(0)}K`}),u&&u.ctr>0&&u.ctr<.7&&o.push({severity:"warning",title:"CTR muy bajo en 7 dÃas",desc:`CTR: ${u.ctr.toFixed(2)}% â benchmark TikTok Colombia es 1-3%. El creative no está enganchando.`,action:"Refresca los hooks de los primeros 3 segundos. Prueba videos UGC, testimonios o demostración del producto",metric:`${u.ctr.toFixed(2)}%`}),u&&u.spend>1e5&&u.conversions===0&&o.push({severity:"critical",title:"Sin conversiones tracked en 7 dÃas",desc:`Gastaste ${new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(u.spend)} sin registrar ninguna conversión. Posible problema con el pixel TikTok o Events API.`,action:"Verifica el pixel TikTok y configura Events API (server-side)",metric:"0 conv."}),u&&u.ctr>1.5&&u.spend<2e5&&o.push({severity:"opportunity",title:`Oportunidad de escalar â CTR ${u.ctr.toFixed(2)}%`,desc:`CTR 7d ${u.ctr.toFixed(2)}% es excelente pero solo gastaste ${new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(u.spend)}. Hay espacio para aumentar presupuesto.`,action:"Sube presupuesto 20% cada 3 dÃas en las campañas con mejor CTR (no pases del 25% por vez)",metric:"+20% budget"}),s&&t&&t.cpm>0&&s.cpm>t.cpm*1.3&&s.cpm>5e3&&o.push({severity:"warning",title:`CPM subió ${Math.round((s.cpm/t.cpm-1)*100)}% hoy`,desc:`CPM: ${new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(s.cpm)} (ayer ${new Intl.NumberFormat("es-CO",{style:"currency",currency:"COP",maximumFractionDigits:0}).format(t.cpm)}). Señal de audiencia saturándose o mayor competencia.`,action:"Rota creativos, amplÃa audiencia con Lookalike 3-5% o activa Smart+ audience",metric:`CPM +${Math.round((s.cpm/t.cpm-1)*100)}%`});const a={critical:0,warning:1,opportunity:2,info:3};return o.sort((C,P)=>(a[C.severity]??3)-(a[P.severity]??3)),o},[R]),Ie=i.useMemo(()=>{if(!(R!=null&&R.last_7d))return null;const o=R.last_7d;let s=50;return o.ctr>=1.5?s+=25:o.ctr>=.8?s+=15:o.ctr>0&&(s+=5),o.cpa>0&&o.cpa<=1e4?s+=25:o.cpa>0&&o.cpa<=15e3?s+=15:o.cpa>0&&o.cpa<=2e4?s+=5:o.conversions===0&&(s-=20),o.conversions>=20?s+=15:o.conversions>=5?s+=8:o.conversions>0&&(s+=3),o.spend>5e5&&o.conversions===0?s-=15:o.spend>1e5&&o.conversions>0&&(s+=5),Math.max(0,Math.min(100,s))},[R]);i.useEffect(()=>{if(!j){x("");return}const o=D,s=[];if(s.push("=== DASHBOARD TIKTOK ADS â SNAPSHOT EN VIVO ==="),s.push(`Fecha: ${new Date().toISOString().slice(0,10)}`),s.push(`Cuentas conectadas (${M.length}): ${M.map(t=>t.accountName).join(", ")}`),s.push(`Cuentas seleccionadas en filtro: ${H.length===0?"TODAS":H.join(", ")}`),s.push(`Filtro de estado: ${se==="active"?"Solo ACTIVAS":se==="inactive"?"Solo INACTIVAS":"TODAS"}`),s.push(`Periodo del gráfico/tabla: ${f} (${j.since} â ${j.until})`),R!=null&&R.today){const t=R.today;s.push(""),s.push("ââ MÃTRICAS DE HOY ââ"),s.push(`Gasto: ${o(t.spend)}
4 | Clicks: ${t.clicks.toLocaleString("es-CO")} | CTR: ${t.ctr.toFixed(2)}% | CPC: ${o(t.cpc)} | CPM: ${o(t.cpm)}`),s.push(`Conversiones: ${t.conversions} | CPA: ${t.cpa>0?o(t.cpa):"N/A"} | Impresiones: ${t.impressions.toLocaleString("es-CO")}`)}if(R){s.push(""),s.push("ââ COMPARATIVO POR PERIODO ââ");const t=[["Ayer","yesterday"],["3 dÃas","last_3d"],["7 dÃas","last_7d"],["15 dÃas","last_15d"],["1 mes","last_30d"]];for(const[u,a]of t){const C=R[a];C&&s.push(`${u}: ${o(C.spend)} | ${C.clicks.toLocaleString("es-CO")} clicks | CTR ${C.ctr.toFixed(2)}% | ${C.conversions} conv | CPA ${C.cpa>0?o(C.cpa):"N/A"} | CPM ${o(C.cpm)}`)}}if(Ie!==null){s.push(""),s.push("ââ SALUD DE LA CUENTA ââ"),s.push(`Calificación: ${Ie}/100 (${Ie>=80?"Excelente":Ie>=65?"Buena":Ie>=45?"Regular":"CrÃtica"})`);const t=K.reduce((a,C)=>a+(C.budget||0),0),u=K.filter(a=>a.status==="active").reduce((a,C)=>a+(C.budget||0),0);s.push(`Presupuesto activo: ${o(u)} de ${o(t)} total`),s.push(`Campañas activas: ${K.filter(a=>a.status==="active").length} de ${K.length} | Smart+: ${K.filter(a=>a.isSmartPlus).length} | Smart: ${K.filter(a=>!a.isSmartPlus&&a.campaignType==="smart").length} | Manual: ${K.filter(a=>!a.isSmartPlus&&a.campaignType==="manual").length}`)}if(Fe.length>0){s.push(""),s.push("ââ ALERTAS DETECTADAS ââ");for(const t of Fe)s.push(`[${t.severity.toUpperCase()}] ${t.title}: ${t.desc} â ${t.action}`)}if(K.length>0){const t=A==="campaigns"?"CAMPAÃAS":A==="adgroups"?"GRUPOS":"ANUNCIOS";s.push(""),s.push(`ââ TOP 15 ${t} POR GASTO ââ`);const u=[...K].sort((a,C)=>C.spend-a.spend).slice(0,15);for(const a of u){const C=a.status==="active"?"[ACT]":"[INA]",P=a.isSmartPlus?"Smart+":a.campaignType==="smart"?"Smart":"Manual";s.push(`${C} ${P} ${a.accountName} | "${a.name}": ${o(a.spend)}, ${a.clicks}clk, CTR ${a.ctr.toFixed(2)}%, ${a.conversions}conv, CPA ${a.cpa>0?o(a.cpa):"N/A"}, CPM ${o(a.cpm)}, ${a.pageviews}pv, ${a.webConversions}compras(${a.webConvRate.toFixed(2)}%)`)}K.length>15&&s.push(`... y ${K.length-15} más en la tabla`)}s.push(""),s.push("ââ BENCHMARKS COLOMBIA COD ââ"),s.push("ROAS min rentable: 3.5x | CPA máx: $20K COP | CTR TikTok: 1-3% | CPM: <$7.5K COP | Tasa compra: 1.5-3%+"),x(s.join(` 5`))},[j,R,K,M,H,se,f,A,Fe,Ie,x]);const ye=i.useMemo(()=>{const o=le.find(t=>t.key==="actions"),s=Ye.filter(t=>t!=="actions").map(t=>le.find(u=>u.key===t)).filter(t=>t&&!be.has(t.key));return o?[o,...s]:s},[Ye,be,le]),sr=(o,s)=>{o!==s&&Gt(t=>{const u=t.indexOf(o),a=t.indexOf(s);return u<0||a<0?t:Zs(t,u,a)})},Rn=(o,s)=>{const t=ye.findIndex(a=>a.key===o),u=ye[t+s];t<0||!u||sr(o,u.key)};if(q===null)return e.jsx(Yn,{platform:"tiktok"});const An=q===!1,or=Ce.map(o=>({...o,fecha:o.date.slice(5),value:o[ut]})),ae=Rt[ut],En=(()=>{const o=new Date;return`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`})(),zn=Ce.length>0&&Ce[Ce.length-1].date===En,ar=e.jsx(e.Fragment,{children:e.jsxs("div",{style:{display:"flex",gap:6,marginBottom:14,alignItems:"center",flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)"},children:"Periodo:"}),e.jsx("div",{className:"date-filter-pill",children:[{key:"today",label:"Hoy"},{key:"yesterday",label:"Ayer"},{key:"last_3d",label:"3 dÃas"},{key:"last_7d",label:"7 dÃas"},{key:"last_15d",label:"15 dÃas"},{key:"last_30d",label:"30 dÃas"}].map(o=>{const s=!y&&f===o.key;return e.jsx("button",{onClick:()=>d(o.key),className:`date-pill-btn${s?" active":""}`,children:o.label},o.key)})}),e.jsx("div",{className:"date-filter-pill",children:e.jsx("button",{onClick:()=>Je(!0),className:`date-pill-btn${y||ve?" active":""}`,children:y?`${tt(Qe)} â ${tt(Xe)}`:"Personalizado"})}),(ve||y)&&e.jsx(br,{desde:Qe,hasta:Xe,onChange:Ut,abierto:ve,onCerrar:()=>Je(!1)}),e.jsxs("button",{onClick:()=>{mt(!0),Te.current=pe+1,Pe(o=>o+1)},disabled:we,className:"tk-refrescar-periodo",style:{marginLeft:"auto",background:"transparent",border:"1px solid var(--border)",borderRadius:20,padding:"5px 12px",fontSize:12,color:"var(--text-primary)",cursor:we?"default":"pointer",display:"flex",alignItems:"center",gap:6,fontFamily:"inherit",fontWeight:600},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",className:We?"icono-girando":void 0,children:[e.jsx("polyline",{points:"23 4 23 10 17 10"}),e.jsx("polyline",{points:"1 20 1 14 7 14"}),e.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]}),"Refrescar"]})]})}),ir=e.jsx("div",{className:"tiktok-levels-row",style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:10,marginBottom:14,padding:"0 8px",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",overflowX:"auto",WebkitOverflowScrolling:"touch"},children:e.jsx("div",{className:"level-switcher-row",style:{display:"flex",gap:0,minWidth:"max-content"},children:["campaigns","adgroups","ads"].map(o=>{const s={campaigns:"Campañas",adgroups:"Conjuntos de anuncios",ads:"Anuncios"},t=A===o;return e.jsx("button",{className:`level-switcher-tab${t?" level-switcher-tab--active level-switcher-tab--active-tiktok":""}`,onClick:()=>
5{qe(o),o==="campaigns"&&Oe(null)},style:{padding:"14px 20px 12px",border:"none",background:"transparent",fontSize:13.5,fontWeight:t?700:500,color:t?h.tiktokCyan:"var(--text-secondary)",cursor:"pointer",fontFamily:"inherit",borderBottom:`3px solid ${t?h.tiktokCyan:"transparent"}`,marginBottom:-1,transition:"color 0.15s",letterSpacing:"0.01em",display:"flex",alignItems:"center",gap:6,whiteSpace:"nowrap",flexShrink:0},onMouseEnter:u=>{t||(u.currentTarget.style.color="var(--text-primary)")},onMouseLeave:u=>{t||(u.currentTarget.style.color="var(--text-secondary)")},children:s[o]},o)})})});return e.jsxs("div",{style:{paddingBottom:48,position:"relative"},children:[e.jsx(zs,{tab:"tiktok",position:"top"}),An&&e.jsx(Ms,{platform:"tiktok"}),(We||we)&&e.jsx("div",{style:{position:"sticky",top:0,zIndex:90,height:2,marginBottom:-2,overflow:"hidden",background:"transparent"},children:e.jsx("div",{style:{height:"100%",background:`linear-gradient(90deg, transparent, ${h.tiktokCyan}, ${h.tiktokPink}, transparent)`,backgroundSize:"40% 100%",backgroundRepeat:"no-repeat",animation:"progress-slide 1.2s linear infinite"}})}),e.jsx(Dn,{platform:"tiktok",subtitle:e.jsxs("span",{children:["Campañas, grupos y anuncios de TikTok",j&&e.jsxs("span",{style:{display:"block",fontSize:11,opacity:.85,marginTop:2},children:["del ",e.jsx("b",{children:j.since})," al ",e.jsx("b",{children:j.until})]})]})}),Wt&&e.jsxs("div",{style:{padding:14,background:`${h.red}10`,border:`1px solid ${h.red}35`,borderRadius:10,color:U(h.red),fontSize:13,marginBottom:16,display:"flex",justifyContent:"space-between",alignItems:"center",gap:12,flexWrap:"wrap"},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:700,marginBottom:2},children:Wt}),e.jsx("div",{style:{fontSize:11.5,color:"var(--text-muted)"},children:"Si persiste, abre la pestaña Network del navegador y envÃame la respuesta del endpoint que falla."})]}),e.jsx("button",{onClick:()=>{Ge(null),Te.current=pe+1,Pe(o=>o+1)},style:{padding:"7px 14px",fontSize:12,fontWeight:600,background:h.red,color:"#fff",border:"none",borderRadius:6,cursor:"pointer",fontFamily:"inherit"},children:"Reintentar"})]}),(()=>{const s=j||{spend:0,impressions:0,clicks:0,ctr:0,cpc:0,cpm:0,conversions:0,cpa:0,pageviews:0,webConversions:0,webConvRate:0};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:fe?{display:"flex",flexDirection:"column"}:{display:"contents"},children:[e.jsxs("div",{style:fe?{order:2}:{display:"contents"},children:[!xe&&ar,(()=>{const t=s;return f==="today"||f==="yesterday"||f==="last_3d"||f==="last_7d"||f==="last_15d"||f==="last_30d"||y&&`${y.since}${y.until}`,e.jsxs(e.Fragment,{children:[(we||We)&&e.jsx("div",{style:{marginBottom:10,display:"flex"},children:e.jsx(Fs,{platform:"tiktok"})}),(()=>{const u=t.pageviews||0,a=t.clicks>0?u/t.clicks*100:0,C=t.webConversions||0,P=t.webConvRate??(t.clicks>0?C/t.clicks*100:0),_=R==null?void 0:R.yesterday,E=(_==null?void 0:_.pageviews)||0,L=(_==null?void 0:_.webConversions)||0;_&&_.clicks>0&&E/_.clicks*100,_&&(_.webConvRate??(_.clicks>0&&L/_.clicks*100));const ce=[{id:"spend",label:"Gasto",value:D(t.spend),sub:"periodo seleccionado",sensitive:!0,borderColor:h.tiktokCyan,ev:kr("gasto",t.spend)},{id:"cpa",label:"Costo por resultado",value:t.cpa>0?D(t.cpa):"â",sub:t.cpa>0?"gasto ÷ conversiones":"sin conversiones",sensitive:!0,borderColor:it(t.cpa),ev:t.cpa>0?rt(it(t.cpa),"CPA"):void 0},{id:"ctr",label:"CTR",value:t.ctr>0?`${t.ctr.toFixed(2)}%`:"â",sub:t.impressions>0?`${Y(t.clicks)} clics`:"sin impresiones",borderColor:h.tiktokCyan,ev:void 0},{id:"cpc",label:"CPC",value:D(t.cpc),sub:"por click",sensitive:!0,borderColor:lt(t.cpc),valueColor:lt(t.cpc),ev:void 0},{id:"cpm",label:"CPM",value:D(t.cpm),sub:"por mil impr.",sensitive:!0,borderColor:jr(t.cpm),ev:t.cpm>0?rt(jr(t.cpm),"CPM"):void 0},{id:"conversions",label:"Conversiones",value:Y(t.conversions),sub:t.spend>0?D(t.spend)+" gastado":"sin gasto",borderColor:h.tiktokPink,ev:kr("pedidos",t.conversions,{promedio7d:E>0?_.conversions:0})},{id:"carga",label:"% de carga",value:u>0?`${a.toFixed(1)}%`:"â",sub:u>0?`${Y(u)} de ${Y(t.clicks)} clicks`:"sin pageviews",borderColor:Sr(a),ev:a>0?rt(Sr(a),"% carga"):void 0},{id:"convWeb",label:"% conversión web",value:t.clicks>0?`${P.toFixed(2)}%`:"â",sub:t.clicks>0?`${Y(C)} de ${Y(t.clicks)}`:"sin clicks",borderColor:Cr(P),ev:P>0?rt(Cr(P),"CVR"):void 0}].map(te=>({id:te.id,node:e.jsxs(oo,{borderColor:te.borderColor,evaluacion:te.ev,children:[e.jsx(ao,{children:te.label}),e.jsx(io,{className:te.sensitive?T:"",color:te.valueColor,children:te.value}),e.jsx(lo,{children:te.sub})]})}));return e.jsx(co,{items:ce,storageKey:"tiktok_kpi_order",brandColor:h.tiktokCyan,customCreatorTab:"tiktok"})})()]})})()]}),A!=="rules"&&e.jsxs("div",{className:"tiktok-accounts-row",style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"12px 16px",marginBottom:12,display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[$.length>=2&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[e.jsx("span",{style:{fontSize:11,fontWeight:700,color:"var(--text-muted)",letterSpacing:"0.06em",textTransform:"uppercase",whiteSpace:"nowrap",flexShrink:0},children:fe?"Centro":"Centro de negocios"}),e.jsx(Ho,{centros:$,elegido:S,onChange:V})]}),e.jsx("span",{style:{fontSize:11,fontWeight:700,color:"var(--text-muted)",letterSpacing:"0.06em",textTransform:"uppercase"},children:"Filtro por cuenta"}),e.jsx(Ko,{accounts:Q,selected:H,onChange:oe,centrosPorCuenta:S?{}:b})]}),A!=="rules"&&e.jsxs("div",{className:"tiktok-period-row",style:{display:"flex",gap:6,alignItems:"center",flexWrap:fe&&!(ve||y)?"nowrap":"wrap",overflowX:fe?"auto":"visible",WebkitOverflowScrolling:"touch",padding:"10px 14px",marginBottom:10,background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:10},children:[!fe&&e.jsx("span",{style:{fontSize:11,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em",marginRight:4},children:"PerÃodo"}),e.jsx("div",{className:"date-filter-pill",children:[{key:"today",label:"Hoy"},{key:"yesterday",label:"Ayer"},{key:"last_3d",label:"3 dÃas"},{key:"last_7d",label:"7 dÃas"},{key:"last_15d",label:"15 dÃas"},{key:"last_30d",label:"1 mes"}].filter(t=>!fe||!["last_15d","last_30d"].includes(t.key)||t.key===f).map(t=>{const u=!y&&f===t.key;return e.jsx("button",{onClick:()=>{d(t.key)},className:`date-pill-btn${u?" active":""}`,children:t.label},t.key)})}),e.jsx("div",{className:"date-filter-pill",children:e.jsx("button",{onClick:()=>Je(!0),className:`date-pill-btn${y||ve?" active":""}`,children:y?`${tt(Qe)} â ${tt(Xe)}`:"Personalizado"})}),(ve||y)&&e.jsx(br,{desde:Qe,hasta:Xe,onChange:Ut,abierto:ve,onCerrar:()=>Je(!1)})]}),ir,e.jsxs("div",{ref:qt,...bn,className:"tk-card-tabla",style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"16px 18px",marginBottom:14,display:"flex",flexDirection:"column",minHeight:0,...yn}
5,children:[xe&&e.jsxs("div",{className:"tk-cabecera-ampliada",style:{flexShrink:0},children:[e.jsx("div",{children:ir}),e.jsx("div",{className:"periodo-en-tabla",children:ar})]}),A!=="rules"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"tk-controles",children:[e.jsxs("div",{className:"tk-fila-estado",style:{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap",marginBottom:10},children:[e.jsx("div",{style:{display:"flex",gap:4,alignItems:"center",flexWrap:"wrap",background:"var(--bg-tertiary)",borderRadius:8,padding:"3px",width:"fit-content"},children:[{key:"all",label:"Todas",dot:null},{key:"active",label:"Activas",dot:e.jsx("span",{style:{display:"inline-block",width:7,height:7,borderRadius:"50%",background:"#10B981"}})},{key:"inactive",label:"Pausadas",dot:e.jsx("span",{style:{display:"inline-block",width:7,height:7,borderRadius:"50%",border:"1.5px solid var(--text-muted)"}})}].map(t=>{const u=se===t.key;return e.jsxs("button",{onClick:()=>sn(t.key),style:{padding:"5px 12px",borderRadius:6,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit",border:"none",background:u?"var(--bg-card)":"transparent",color:u?"var(--text-primary)":"var(--text-muted)",display:"flex",alignItems:"center",gap:6,boxShadow:u?"0 1px 2px rgba(0,0,0,0.08)":"none",transition:"background 0.15s"},children:[t.dot,t.label]},t.key)})}),e.jsxs("button",{onClick:()=>{ht(!0),Te.current=pe+1,Pe(t=>t+1),setTimeout(()=>ht(!1),1500)},disabled:Ue,title:"Forzar actualización de datos (ignora caché)",style:{padding:"6px 12px",fontSize:12,fontWeight:700,cursor:Ue?"default":"pointer",fontFamily:"inherit",border:`1px solid ${h.tiktokCyan}`,background:`${h.tiktokCyan}15`,borderRadius:8,color:h.tiktokCyan,display:"flex",alignItems:"center",gap:5},children:[e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",className:Ue?"icono-girando":void 0,children:[e.jsx("polyline",{points:"23 4 23 10 17 10"}),e.jsx("polyline",{points:"1 20 1 14 7 14"}),e.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]}),e.jsx("span",{className:"mobile-icon-only-text",children:Ue?"Actualizando...":"Actualizar datos"})]})]}),e.jsxs("div",{className:"tk-fila-botones",style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",marginBottom:8},children:[je&&A!=="campaigns"&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,padding:"5px 10px",borderRadius:8,background:`${h.tiktokCyan}12`,border:`1px solid ${h.tiktokCyan}40`,color:"var(--text-primary)"},children:[e.jsx("span",{style:{color:"var(--text-muted)"},children:"Filtrado por campaña:"}),e.jsx("span",{className:"censor-blur",style:{fontWeight:700,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:je}),e.jsx("button",{onClick:()=>Oe(null),style:{border:"1px solid var(--border)",background:"var(--bg-card)",color:U(h.red),cursor:"pointer",fontSize:16,lineHeight:1,marginLeft:6,fontFamily:"inherit",width:24,height:24,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},title:"Quitar filtro","aria-label":"Quitar filtro",children:"Ã"})]}),B.size>0&&A!=="campaigns"&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,padding:"5px 10px",borderRadius:8,background:`${h.tiktokCyan}12`,border:`1px solid ${h.tiktokCyan}40`,color:"var(--text-primary)"},children:[e.jsx("span",{style:{color:"var(--text-muted)"},children:"Filtrado por:"}),e.jsxs("span",{style:{fontWeight:700},children:[B.size," ",B.size===1?"campaña":"campañas"]}),e.jsx("button",{onClick:()=>B.clear(),style:{border:"1px solid var(--border)",background:"var(--bg-card)",color:U(h.red),cursor:"pointer",fontSize:16,lineHeight:1,marginLeft:6,fontFamily:"inherit",width:24,height:24,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},title:"Limpiar selección","aria-label":"Limpiar selección",children:"Ã"})]}),B.size>0&&A==="campaigns"&&e.jsxs("button",{onClick:()=>B.clear(),style:{display:"flex",alignItems:"center",gap:6,fontSize:12,fontWeight:600,padding:"5px 10px",borderRadius:8,background:"transparent",border:`1px solid ${h.tiktokCyan}40`,color:h.tiktokCyan,cursor:"pointer",fontFamily:"inherit"},title:"Quitar todas las marcas",children:["Limpiar selección (",B.size,")"]}),Xt&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11.5,padding:"5px 10px",borderRadius:8,background:"rgba(245,158,11,0.10)",border:"1px solid rgba(245,158,11,0.35)",color:"#D97706"},children:[e.jsxs("span",{children:["â ï¸ ",Xt]}),e.jsx("button",{onClick:()=>jt(null),style:{border:"1px solid var(--border)",background:"var(--bg-card)",color:"#D97706",cursor:"pointer",fontSize:16,lineHeight:1,marginLeft:6,fontFamily:"inherit",width:24,height:24,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},title:"Cerrar aviso","aria-label":"Cerrar aviso",children:"Ã"})]}),(A==="adgroups"||A==="ads")&&e.jsx(qo,{valor:je||"",onChange:t=>Oe(t||null),opciones:Array.from(new Set(K.map(t=>t.parentCampaign).filter(t=>!!t))).sort().map(t=>({id:t,texto:w?Or(t,w):t}))}),e.jsxs("div",{className:"tk-filtro-movil",style:{position:"relative",flex:1,minWidth:180,maxWidth:280},children:[e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-muted)",pointerEvents:"none"},children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),e.jsx("input",{type:"search",placeholder:A==="campaigns"?"Buscar campaña...":A==="adgroups"?"Buscar conjunto...":"Bu
5scar anuncio...",value:gt,onChange:t=>Mt(t.target.value),style:{width:"100%",padding:"6px 10px 6px 30px",borderRadius:8,border:"1px solid var(--border)",background:"var(--bg-tertiary)",fontSize:12,fontFamily:"inherit",color:"var(--text-primary)"}})]}),!fe&&e.jsxs("div",{style:{fontSize:11,fontWeight:700,color:"var(--text-muted)",letterSpacing:"0.06em",textTransform:"uppercase",marginLeft:"auto",whiteSpace:"nowrap"},children:[ee.length," de ",pt," ",A==="campaigns"?"campañas":A==="adgroups"?"grupos":"anuncios"]}),e.jsxs("div",{className:"table-toolbar-actions",children:[e.jsxs("button",{className:"table-toolbar-btn",onClick:()=>Lt(!0),title:"Crear métricas personalizadas combinando variables",children:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12 20V10"}),e.jsx("path",{d:"M18 20V4"}),e.jsx("path",{d:"M6 20v-6"})]}),e.jsxs("span",{className:"table-toolbar-btn-label",children:["Métricas",Ke.length>0?` (${Ke.length})`:""]})]}),e.jsx(Uo,{allCols:le,hiddenCols:be,setHiddenCols:xn,accentColor:h.tiktokCyan,columnasALaVista:ye.map(t=>({key:t.key,label:t.label})),moverUnPuesto:Rn}),(vn||xe)&&e.jsx(e.Fragment,{children:e.jsxs("button",{className:`table-toolbar-btn${xe?" boton-salir-ampliada":""}`,"aria-label":xe?"Salir de pantalla completa":"Ver la tabla a pantalla completa",title:xe?"Salir de pantalla completa":"Ver la tabla a pantalla completa",onClick:fn,children:[e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:xe?e.jsx("path",{d:"M9 3v6H3M15 3v6h6M9 21v-6H3M15 21v-6h6"}):e.jsx("path",{d:"M3 9V3h6M21 9V3h-6M3 15v6h6M21 15v6h-6"})}),e.jsx("span",{className:"table-toolbar-btn-label",children:xe?"Salir":"Ampliar"})]})}),e.jsxs("button",{className:"table-toolbar-btn",onClick:()=>{const t=le.filter(u=>!be.has(u.key)&&u.key!=="actions");po({columns:t.map(u=>({label:u.label,getValue:a=>u.sortValue?u.sortValue(a):""})),rows:ee,filename:`tiktok-${A}`})},disabled:ee.length===0,title:"Exportar CSV",style:{opacity:ee.length===0?.5:1,cursor:ee.length===0?"not-allowed":"pointer"},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e.jsx("polyline",{points:"7 10 12 15 17 10"}),e.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),e.jsx("span",{className:"table-toolbar-btn-label",children:"CSV"})]})]})]})]}),e.jsx(ns,{desde:pn,fuente:"TikTok Business API en tiempo real",color:h.green}),e.jsx("div",{className:"hide-on-mobile",style:{fontSize:11,color:"var(--text-muted)",marginBottom:8},children:"Toca un encabezado para ordenar · En «Columnas» se muestran, se ocultan y se acomodan"}),e.jsxs("div",{className:"tk-zona-tabla",style:{overflowX:"auto",position:"relative"},children:[(We||we&&K.length>0)&&e.jsx(eo,{platform:"tiktok"}),e.jsxs("table",{className:"tiktok-entity-table",style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[e.jsx("thead",{children:e.jsx(Vs,{sensors:wn,collisionDetection:Kt?Go:Ur,modifiers:Kt?[ss]:void 0,autoScroll:!1,onDragStart:()=>xt(!0),onDragCancel:()=>xt(!1),onDragEnd:t=>{xt(!1);const{active:u,over:a}=t;!a||u.id===a.id||sr(String(u.id),String(a.id))},children:e.jsx(Hs,{items:ye.map(t=>t.key),strategy:Gs,children:e.jsxs("tr",{style:{background:"var(--bg-tertiary)"},children:[A==="campaigns"&&(()=>{const t=ee.length>0&&ee.every(a=>B.has(String(a.id||""))),u=ee.some(a=>B.has(String(a.id||"")));return e.jsx("th",{style:{width:32,padding:"8px 4px 8px 10px",textAlign:"center",borderBottom:"1px solid var(--border)"},children:e.jsx("input",{type:"checkbox",checked:t,ref:a=>{a&&(a.indeterminate=!t&&u)},onChange:()=>{t||u?B.clear():B.selectMany(ee.map(a=>String(a.id||"")).filter(Boolean))},style:{cursor:"pointer",accentColor:h.tiktokCyan},"aria-label":t?"Desmarcar todas":"Marcar todas las visibles"})})})(),ye.map((t,u)=>e.jsx(Lo,{colKey:t.key,label:t.label,encabezado:t.encabezado,width:t.width,align:t.align,isFirst:u===0,sortKey:Ee,sortDir:Ne,onSort:()=>{Ee===t.key?et(a=>
5a==="asc"?"desc":"asc"):(bt(t.key),et("desc"))},accentColor:h.tiktokCyan,customWidth:Ot[t.key],onResize:a=>an(t.key,a),onResetWidth:()=>ln(t.key)},t.key))]})})})}),e.jsxs("tbody",{children:[ee.length===0&&(()=>{const t=je!=null||B.size>0&&A!=="campaigns";return e.jsx("tr",{children:e.jsxs("td",{colSpan:ye.length+(A==="campaigns"?1:0),style:{padding:32,textAlign:"center"},children:[e.jsx("div",{style:{fontSize:13,fontWeight:700,color:"var(--text-primary)",marginBottom:6},children:"Sin datos para los filtros aplicados"}),e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:12,maxWidth:480,margin:"0 auto 12px"},children:t?`Tienes un filtro de campaña activo. QuÃtalo para ver todos los ${A==="adgroups"?"conjuntos":"anuncios"} del perÃodo, o cambia la fecha si buscas otro rango.`:"Prueba cambiar el filtro de fecha, estado, cuentas o búsqueda."}),e.jsxs("div",{style:{display:"inline-flex",gap:8,flexWrap:"wrap",justifyContent:"center"},children:[t&&e.jsx("button",{onClick:()=>{B.clear(),Oe(null)},style:{padding:"8px 16px",borderRadius:20,fontSize:12.5,fontWeight:700,cursor:"pointer",fontFamily:"inherit",border:"none",background:h.tiktokCyan,color:"#fff"},children:"Limpiar filtro de campañas"}),f==="today"&&[{key:"yesterday",label:"Ayer"},{key:"last_3d",label:"3 dÃas"},{key:"last_7d",label:"7 dÃas"}].map(u=>e.jsxs("button",{onClick:()=>d(u.key),style:{padding:"8px 14px",borderRadius:20,fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:"inherit",border:`1px solid ${h.tiktokCyan}`,background:`${h.tiktokCyan}15`,color:h.tiktokCyan},children:["Ver ",u.label]},u.key))]})]})})})(),ee.map((t,u)=>{const a=t.status==="active",C=A==="campaigns";let P={},_=a?h.green:h.muted,E="";a&&(t.spend>0&&t.conversions===0?(_="#EF4444",P={background:"rgba(239,68,68,0.06)",boxShadow:"inset 4px 0 12px rgba(239,68,68,0.20)"}):t.cpa>15e3?(_="#EF4444",P={background:"rgba(239,68,68,0.06)",boxShadow:"inset 4px 0 12px rgba(239,68,68,0.20)"}):t.cpa>1e4?(_="#F59E0B",P={background:"rgba(245,158,11,0.05)",boxShadow:"inset 4px 0 12px rgba(245,158,11,0.18)"}):t.cpa>0&&t.cpa<=1e4&&(E="row-excellent-gold"));const O=a?P.background||"transparent":"rgba(100,116,139,0.03)",ce=C?()=>{Oe(t.name),qe("adgroups")}:void 0,te=C?"Click para ver grupos de esta campaña":void 0,ge=C;return e.jsxs("tr",{className:E,onClick:ce,title:te,style:{borderBottom:"1px solid var(--border)",borderLeft:E?void 0:`3px solid ${_}`,background:E?void 0:O,boxShadow:E?void 0:P.boxShadow,cursor:ge?"pointer":"default",transition:"background 0.1s"},onMouseEnter:ge&&!E?J=>{J.currentTarget.style.background=`${h.tiktokCyan}08`}:void 0,onMouseLeave:ge&&!E?J=>{J.currentTarget.style.background=O}:void 0,children:[A==="campaigns"&&e.jsx("td",{style:{width:38,padding:"4px"},onClick:J=>J.stopPropagation(),children:e.jsx("label",{onClick:J=>J.stopPropagation(),style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"8px 6px",cursor:"pointer"},"aria-label":`Seleccionar ${t.name}`,children:e.jsx("input",{type:"checkbox",checked:B.has(String(t.id||"")),onChange:()=>B.toggle(String(t.id||"")),style:{cursor:"pointer",accentColor:h.tiktokCyan,width:18,height:18}})})}),ye.map(J=>{const Me=Ot[J.key];return e.jsx("td",{className:J.sensitive?T:"",style:{padding:"8px 10px",textAlign:J.align||"left",color:"var(--text-primary)",whiteSpace:"nowrap",width:Me,maxWidth:Me||(J.width?J.width+50:void 0),minWidth:Me,overflow:"hidden",textOverflow:"ellipsis"},children:J.render(t)},J.key)})]},t.id||`${t.name}-${u}`)})]}),ee.length>0&&e.jsx("tfoot",{children:e.jsxs("tr",{style:{background:"var(--bg-tertiary)",borderTop:`2px solid ${h.tiktokCyan}`},children:[A==="campaigns"&&e.jsx("td",{style:{width:32}}),ye.map(t=>e.jsx("td",{className:t.sensitive?T:"",style:{padding:"10px",textAlign:t.align||"left",fontSize:12,whiteSpace:"nowrap"},children:t.footer?t.footer(ee):""},t.key))]})})]})]})]})]}),e.jsx(Wo,{selectedAccounts:G,statusFilter:se,collapsible:!0,campaignIds:B.size>0?[...B.selected].join(","):""})]}),e.jsx(os,{platform:"tiktok",collapsible:!0}),Fe.length>0&&e.jsxs("div",{style:{marginBottom:14},children:[e.jsxs("button",{type:"button",onClick:vt.toggle,style:{all:"unset",cursor:"pointer",marginBottom:10,display:"flex",alignItems:"center",gap:8},children:[e.jsx(at,{open:vt.open}),e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:h.tiktokCyan,strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M12 8v4l3 3"})]}),e.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:2},children:[e.jsxs("span",{style:{fontWeight:800,fontSize:13.5,color:"var(--text-primary)"},children:["Alertas y recomendaciones TikTok",e.jsxs("span",{style:{fontSize:11,fontWeight:400,color:"var(--text-muted)"},children:[" · ",Fe.length," basadas en tu data"]})]}),e.jsx("span",{style:{fontSize:11.5,color:"var(--text-muted)",fontWeight:500},children:"Lo que hay que revisar hoy, sacado de tus propias cifras"})]})]}),e.jsx("div",{style:{display:vt.open?"grid":"none",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 330px), 1fr))",gap:10},children:Fe.map((t,u)=>{const a={critical:{color:U(h.red),bg:`${h.red}10`,badge:"CRÃTICO"},warning:{color:U(h.yellow),bg:`${h.yellow}10`,badge:"ATENCIÃN"},opportunity:{color:U(h.green),bg:`${h.green}10`,badge:"OPORTUNIDAD"},info:{color:h.blue,bg:`${h.blue}10`,badge:"INFO"}}[t.severity];return e.jsxs("div",{style:{background:a.bg,borderRadius:10,border:"1px solid var(--border)",padding:"12px 14px"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",ga
5p:8,marginBottom:6},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontSize:9,fontWeight:800,color:a.color,background:`${a.color}20`,padding:"2px 7px",borderRadius:4,letterSpacing:"0.05em"},children:a.badge}),e.jsx("span",{style:{fontWeight:700,fontSize:12.5,color:"var(--text-primary)"},children:t.title})]}),t.metric&&e.jsx("span",{style:{fontSize:10.5,fontWeight:700,color:a.color,whiteSpace:"nowrap"},children:t.metric})]}),e.jsx("div",{style:{fontSize:11.5,color:"var(--text-secondary)",lineHeight:1.55,marginBottom:8},children:t.desc}),e.jsxs("div",{style:{fontSize:11.5,color:a.color,fontWeight:700},children:["â ",t.action]})]},u)})})]}),e.jsxs("div",{style:{marginBottom:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Comparativo por periodo"}),!1]}),Yt&&e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:()=>yt(!1),style:{position:"fixed",inset:0,zIndex:49,background:"transparent"},"aria-hidden":"true"}),e.jsxs("div",{onClick:t=>t.stopPropagation(),style:{position:"relative",zIndex:50,background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:10,padding:"12px 14px",marginBottom:10,boxShadow:"var(--shadow-md)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,color:"var(--text-secondary)"},children:"Periodos visibles"}),e.jsx("button",{onClick:()=>yt(!1),"aria-label":"Cerrar",style:{background:"transparent",border:"none",cursor:"pointer",padding:4,color:"var(--text-muted)",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:[ke.map(t=>e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 9px",background:"var(--bg-tertiary)",borderRadius:14,fontSize:11,color:"var(--text-primary)"},children:[t.label,t.since&&e.jsxs("span",{style:{fontSize:9,color:"var(--text-muted)"},children:["(",t.since.slice(5),"â",t.until.slice(5),")"]}),e.jsx("button",{onClick:()=>ft(u=>u.filter(a=>a.key!==t.key)),style:{border:"none",background:"transparent",color:U(h.red),cursor:"pointer",fontSize:14,lineHeight:1,padding:0,fontFamily:"inherit"},children:"Ã"})]},t.key)),ke.length<Ze.length&&e.jsx("button",{onClick:()=>ft(Ze),style:{padding:"4px 9px",borderRadius:14,fontSize:11,fontFamily:"inherit",border:"1px dashed var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:"Restaurar defaults"})]}),e.jsx("div",{style:{fontSize:11,fontWeight:700,color:"var(--text-secondary)",marginBottom:6},children:"Agregar periodo personalizado"}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"flex-end"},children:[e.jsxs("label",{style:{fontSize:10,color:"var(--text-muted)"},children:["Desde",e.jsx("input",{type:"date",value:Re,onChange:t=>Jt(t.target.value),style:{display:"block",marginTop:2,padding:"5px 8px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-tertiary)",fontSize:12,fontFamily:"inherit",color:"var(--text-primary)"}})]}),e.jsxs("label",{style:{fontSize:10,color:"var(--text-muted)"},children:["Hasta",e.jsx("input",{type:"date",value:Ae,onChange:t=>Qt(t.target.value),style:{display:"block",marginTop:2,padding:"5px 8px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-tertiary)",fontSize:12,fontFamily:"inherit",color:"var(--text-primary)"}})]}),e.jsx("button",{disabled:!Re||!Ae,onClick:()=>{const t=`custom_${Date.now()}`,u=C=>C.slice(8,10)+"/"+C.slice(5,7),a=`${u(Re)} â ${u(Ae)}`;ft(C=>
5[...C,{key:t,label:a,since:Re,until:Ae}]),Jt(""),Qt("")},style:{padding:"6px 12px",borderRadius:6,fontSize:11,fontWeight:700,fontFamily:"inherit",border:"none",background:h.tiktokCyan,color:"#fff",cursor:Re&&Ae?"pointer":"default",opacity:Re&&Ae?1:.5},children:"Agregar"})]})]})]}),e.jsx("div",{ref:Sn,style:{display:"flex",gap:10,overflowX:"auto",scrollSnapType:"x mandatory",paddingBottom:4},children:[...ke].sort((t,u)=>{const a=t.key===f?-1:0,C=u.key===f?-1:0;return a-C}).map(t=>{const u={spend:0,clicks:0,ctr:0,cpa:0,pageviews:0},C=(t.since?_n[t.key]:R==null?void 0:R[t.key])||u,P=C.pageviews||0,_=C.clicks>0?P/C.clicks*100:0,E=({label:L,value:O,color:ce})=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",fontSize:11,color:"var(--text-muted)"},children:[e.jsx("span",{children:L}),e.jsx("b",{style:{color:ce||"var(--text-primary)"},children:O})]});return e.jsxs("div",{style:{flex:"0 0 200px",scrollSnapAlign:"start",background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:10,padding:"12px 14px"},children:[e.jsx("div",{style:{fontSize:10.5,fontWeight:800,color:h.tiktokCyan,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:8,paddingBottom:6,borderBottom:"1px solid var(--border)"},children:t.label}),e.jsxs("div",{style:{marginBottom:8},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:2},children:"Gasto"}),e.jsx("div",{className:T,style:{fontSize:17,fontWeight:800,color:"var(--text-primary)",lineHeight:1},children:Ve(C.spend)})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[e.jsx(E,{label:"% de carga",value:P>0?`${_.toFixed(1)}%`:"â",color:_>=75?h.green:_>=50?h.yellow:h.red}),e.jsx(E,{label:"CTR",value:`${C.ctr.toFixed(2)}%`,color:C.ctr>=1.5?h.green:C.ctr>=.8?h.yellow:h.red}),e.jsx(E,{label:"CPA",value:C.cpa>0?Ve(C.cpa):"â",color:C.cpa>0&&C.cpa<=15e3?h.green:C.cpa>0?h.red:"var(--text-muted)"})]})]},t.key)})})]}),or.length>1&&e.jsxs("div",{style:{background:"var(--bg-card)",border:"1px solid var(--border)",borderRadius:12,padding:"18px 20px",marginBottom:14},children:[e.jsxs("div",{style:{marginBottom:14,display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:10,flexWrap:"wrap"},children:[e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:kt.toggle,style:{all:"unset",cursor:"pointer",display:"flex",alignItems:"center",gap:6,fontWeight:700,fontSize:13.5,color:"var(--text-primary)"},children:[e.jsx(at,{open:kt.open}),"Tendencia de métrica"]}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)"},children:["Evolución diaria · últimos ",ie," dÃas · todas las cuentas y estados",zn&&e.jsx("span",{children:" · hoy es parcial (atribución COD en curso)"})]})]}),e.jsx("div",{style:{display:"flex",gap:4,background:"var(--bg-tertiary)",borderRadius:6,padding:2},children:[7,15,30].map(t=>e.jsxs("button",{onClick:()=>Se(t),style:{padding:"5px 10px",fontSize:11.5,fontWeight:600,background:ie===t?"var(--bg-card)":"transparent",color:ie===t?"var(--text-primary)":"var(--text-muted)",border:"none",borderRadius:4,cursor:"pointer",fontFamily:"inherit",boxShadow:ie===t?"0 1px 2px rgba(0,0,0,0.08)":"none"},children:[t,"d"]},t))})]}),kt.open&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:14},children:Object.keys(Rt).map(t=>{const u=Rt[t],a=ut===t;return e.jsx("button",{onClick:()=>cn(t),style:{padding:"5px 13px",borderRadius:20,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit",border:`1px solid ${a?h.tiktokCyan:"var(--border)"}`,background:a?`${h.tiktokCyan}15`:"transparent",color:a?h.tiktokCyan:"var(--text-muted)"},children:u.label},t)})}),e.jsx(Lr,{width:"100%",height:220,children:e.jsxs(Br,{data:or,margin:{top:6,right:20,bottom:0,left:10},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"tkGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:h.tiktokCyan,stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:h.tiktokCyan,stopOpacity:0})]})}),e.jsx(Dr,{strokeDasharray:"3 3",stroke:"var(--border)"}),e.jsx(Vr,{dataKey:"fecha",tick:Ir}),e.jsx(Hr,{tickFormatter:t=>ae.unit==="cop"?Ve(t):ae.unit==="pct"?`${t.toFixed(1)}%`:Y(t),tick:Ir,width:72}),ae.benchmark&&e.jsx(Cs,{y:ae.benchmark,stroke:h.red,strokeDasharray:"5 3",strokeOpacity:.7,label:{value:`LÃm ${ae.unit==="cop"?Ve(ae.benchmark):ae.unit==="pct"?`${ae.benchmark}%`:ae.benchmark}`,fill:h.red,fontSize:10,position:"insideTopRight"}}),e.jsx(Gr,{formatter:t=>[ae.unit==="cop"?D(t):ae.unit==="pct"?`${t.toFixed(2)}%`:Y(t),ae.label],contentStyle:Vo}),e.jsx(qr,{type:"monotone",dataKey:"value",stroke:h.tiktokCyan,strokeWidth:2.5,fill:"url(#tkGrad)",dot:{r:3,fill:h.tiktokCyan},activeDot:{r:5}})]})})]})]}),e.jsx(zo,{}),e.jsx(To,{collapsible:!0}),e.jsx($o,{}),e.jsx(as,{platform:"tiktok",brandColor:h.tiktokCyan,collapsible:!0}),e.jsx(Ro,{}),A!=="rules"&&e.jsx(bo,{entities:K,level:A}),e.jsx($s,{platform:"tiktok"})]})})(),n&&e.jsx("div",{style:{marginTop:14}
5,children:e.jsx(so,{scope:"tiktok",notebookStyle:!0,title:"¿Te ayudo a entender?",subtitle:`Dime qué quieres ver en tus ${A==="campaigns"?"campañas":A==="adgroups"?"grupos":"anuncios"} â filtros, orden, insights`,rotatingHints:["Muéstrame solo las que gastaron más de 50.000","Ordéname por CPA ascendente","Filtra las que tienen ROAS mayor a 3","¿Cuáles deberÃa pausar?",'Campañas con nombre que contenga "saturno"',"Dame las 5 con mejor CTR","Restaurar vista original","Recomiéndame qué escalar"],context:(()=>{var u;const o=A==="campaigns"?"Campañas":A==="adgroups"?"Grupos de anuncios":"Anuncios",s=ee.slice(0,15).map(a=>{const C=a.conversions>0?a.spend/a.conversions:0,P=a.campaignType==="smart"?" [SMART+]":"",_=[];a.frequency&&a.frequency>1&&_.push(`Frecuencia ${a.frequency.toFixed(2)}`),a.video_watched_2s>0&&a.impressions>0&&_.push(`Video 2s ${(a.video_watched_2s/a.impressions*100).toFixed(1)}%`),a.video_watched_6s>0&&a.impressions>0&&_.push(`Video 6s ${(a.video_watched_6s/a.impressions*100).toFixed(1)}%`),a.pageviews>0&&_.push(`Pageviews ${a.pageviews.toLocaleString("es-CO")}`),a.landingRate>0&&_.push(`Landing rate ${a.landingRate.toFixed(1)}%`),a.webConversions>0&&_.push(`Conv web ${a.webConversions}`),a.webConvRate>0&&_.push(`Conv web % ${a.webConvRate.toFixed(2)}%`),a.budget>0&&_.push(`Budget ${D(a.budget)}`),a.objective&&_.push(`Objetivo: ${a.objective}`),a.optimizationGoal&&_.push(`Optim: ${a.optimizationGoal}`);const E=`${a.name}${P} (${a.status}) · Gasto ${D(a.spend)} · Impr ${a.impressions.toLocaleString("es-CO")} · Clicks ${a.clicks.toLocaleString("es-CO")} · CTR ${a.ctr.toFixed(2)}% · CPC ${D(a.cpc)} · CPM ${D(a.cpm)} · Compras ${a.conversions} · CPA ${a.conversions>0?D(C):"n/a"} · ROAS ${a.roas.toFixed(2)}x`;return _.length>0?`${E} · ${_.join(" · ")}`:E}),t=ee.length-s.length;return[`Pestaña: TikTok Ads · Nivel: ${o}`,`Cuentas seleccionadas: ${H.length===0?"todas":H.join(", ")}`,`Filtro status: ${se}${ze?` · Filtro IA: ${ze}`:""}`,`Orden: ${Ee} ${Ne}`,`Total ${o.toLowerCase()}: ${pt} · Mostrando ${ee.length} en la tabla`,j?`Totales del periodo: Gasto ${D(j.spend)} · Compras ${j.conversions||0} · ROAS ${((u=j.roas)==null?void 0:u.toFixed(2))||"0.00"}x`:"","",`ââ FILAS VISIBLES (top ${s.length} por orden actual) ââ`,...s,t>0?`⦠y ${t} fila${t>1?"s":""} más en la tabla.`:"","",'IMPORTANTE: solo responde sobre los datos de ESTA tabla TikTok. Si te preguntan algo no derivable de las filas/columnas de arriba, di "eso no está en esta tabla" en una lÃnea. Manten respuestas en 1-3 lÃneas.','Si te piden GRAFICAR (tendencia, evolución diaria, comparar métricas en gráfica) â 1 lÃnea: "para gráficas ve al Home (Comparación general) â ahà está la gráfica grande con selector de métrica". NO grafiques aquÃ.','Si te piden análisis cross-platform (TikTok + Meta juntos, Shopify, Dropi) â 1 lÃnea: "eso lo ves en el Home o pÃdeselo a la burbuja flotante, que tiene la data completa".'].filter(Boolean).join(` 6`)})(),tableContext:`Tabla actual: ${ee.length} ${A} visibles de ${pt}. Columnas disponibles: spend, clicks, impressions, ctr, cpc, cpm, compras (conversions), cpa, roas. Nombre de columna para sort/filter debe matchear una de esas. Para filtro por texto en nombre: "campaign contains NOMBRE". Para numéricos: "spend>50000", "roas<2", "cpa>=15000" (también AND/OR).`,tableModified:!!ze||Ee!=="spend"||Ne!=="desc",onTableAction:(o,s)=>{var t,u;if(o==="reset"){rr(null),nr(null),bt("spend"),et("desc"),Mt("");return}if(o==="filter"){rr(s);return}if(o==="sort"){const a=s.split(":"),C=(t=a[0])==null?void 0:t.trim().toLowerCase(),P=(u=a[1])==null?void 0:u.trim().toLowerCase(),_={spend:"spend",clicks:"clicks",impressions:"impressions",ctr:"ctr",cpc:"cpc",cpm:"cpm",compras:"conversions",conversions:"conversions",cpa:"cpa",roas:"roas"};_[C]&&["asc","desc"].includes(P)&&(bt(_[C]),et(P));return}if(o==="metric"){const[a,...C]=s.split(":");a&&C.length>0&&nr({name:a.trim(),formula:C.join(":").trim()});return}}})}),e.jsx(yo,{entity:gn,level:mn,hiddenCols:be,onClose:()=>Vt(null)}),e.jsx(is,{open:dn,onClose:()=>Lt(!1)}),$e&&$e.id&&$e.advertiser_id&&e.jsx(Qr,{adId:$e.id,advertiserId:$e.advertiser_id,adName:$e.name,onClose:()=>Ht(null),onSuccess:()=>{Te.current=pe+1,Pe(o=>o+1)}})]})}function Uo({allCols:n,hiddenCols:c,setHiddenCols:f,accentColor:d,c
6olumnasALaVista:y,moverUnPuesto:p}){const g=i.useRef(null),w=i.useRef(null),[T,x]=i.useState(!1),[v,m]=i.useState(null),F="tiktok_col_accordion",[r,l]=i.useState(()=>{try{const S=localStorage.getItem(F);if(!S)return new Set(Be);const I=JSON.parse(S);return new Set(Array.isArray(I)?I:Be)}catch{return new Set(Be)}});i.useEffect(()=>{localStorage.setItem(F,JSON.stringify([...r]))},[r]);const z=()=>{if(g.current){const S=g.current.getBoundingClientRect();m({top:S.bottom+4,right:window.innerWidth-S.right})}x(!0)};i.useEffect(()=>{if(!T)return;const S=V=>{const H=V.target;w.current&&w.current.contains(H)||g.current&&g.current.contains(H)||x(!1)},I=V=>{V.key==="Escape"&&x(!1)},$=()=>{if(g.current){const V=g.current.getBoundingClientRect();m({top:V.bottom+4,right:window.innerWidth-V.right})}},Q=setTimeout(()=>document.addEventListener("mousedown",S),0);return document.addEventListener("keydown",I),window.addEventListener("resize",$),window.addEventListener("scroll",$,!0),()=>{clearTimeout(Q),document.removeEventListener("mousedown",S),document.removeEventListener("keydown",I),window.removeEventListener("resize",$),window.removeEventListener("scroll",$,!0)}},[T]);const M=S=>{l(I=>{const $=new Set(I);return $.has(S)?$.delete(S):$.add(S),$})},b=i.useMemo(()=>{const S=new Map;for(const I of Be)S.set(I,[]);for(const I of n){if(I.key==="actions")continue;const $=gs(I.key);S.get($).push(I)}return S},[n]),k=S=>{f(I=>{const $=new Set(I);return $.has(S)?$.delete(S):$.add(S),$})};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{ref:g,className:"table-toolbar-btn","aria-label":"Mostrar/ocultar columnas",onClick:()=>T?x(!1):z(),style:{padding:"6px 10px",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit",border:"1px solid var(--border)",background:"transparent",borderRadius:8,color:"var(--text-primary)",display:"flex",alignItems:"center",gap:5},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"7"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"7"}),e.jsx("rect",{x:"3",y:"14",width:"7",height:"7"}),e.jsx("rect",{x:"14",y:"14",width:"7",height:"7"})]}),e.jsx("span",{className:"table-toolbar-btn-label",children:"Columnas"})]}),T&&v&&Mr.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"column-picker-backdrop","data-menu-flotante":"bloquea",onClick:()=>x(!1)}),e.jsxs("div",{ref:w,className:"column-picker","data-menu-flotante":"",style:{position:"fixed",top:v.top,right:v.right,accentColor:d,maxHeight:Math.max(220,window.innerHeight-v.top-12)},children:[e.jsxs("div",{className:"column-picker-header",children:[e.jsx("span",{className:"column-picker-title",children:"Mostrar columnas"}),e.jsx("button",{className:"column-picker-close",onClick:()=>x(!1),"aria-label":"Cerrar",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsxs("div",{className:"column-picker-body",children:[e.jsx(Rs,{columnas:y,mover:p}),Be.map(S=>{const I=b.get(S)||[];if(I.length===0)return null;const $=r.has(S),Q=I.filter(V=>!c.has(V.key)).length;return e.jsxs("div",{className:"column-picker-cat",children:[e.jsxs("button",{className:"column-picker-cat-header",onClick:()=>M(S),type:"button",children:[e.jsx("span",{className:`column-picker-cat-chevron${$?" open":""}`,children:"â¶"}),e.jsx("span",{className:"column-picker-cat-label",children:ms[S]}),e.jsxs("span",{className:"column-picker-cat-count",children:[Q,"/",I.length]})]}),$&&e.jsx("div",{className:"column-picker-cat-body",children:I.map(V=>e.jsxs("label",{className:"column-picker-item",children:[e.jsx("input",{type:"checkbox",checked:!c.has(V.key),onChange:()=>k(V.key),style:{accentColor:d}}),e.jsx("span",{children:V.label})]},V.key))})]},S)})]})]})]}),document.body)]})}
6export{Ca as TiktokTab};
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.