PageSourceSearch

https://behonest.com.br/system/assets/AdminPage-ByEmtuOn.js

js behonest.com.br collected 2026-10-01 14:26:19 UTC 300,953 bytes, 42 lines download raw bytes

1import{r as x,c as re,j as t,g as le,A as wa,f as tn,b as sn,h as rn,u as an,a as nn}from"./index-XbtVPFmq.js";import{N as on}from"./Navbar-DjvrelRM.js";import{P as ln}from"./PageHeader-B0aK47Nc.js";import{M as mt}from"./Modal-Dy38jz6c.js";import{E as Et}from"./EmptyState-B2mQuo7W.js";import{b as nr,f as cn}from"./formatters-CZBK15sA.js";import{t as Qt,T as Ks,S as dn,a as mn,c as Ys,d as un,e as Zr}from"./tenants-B3d4NQt3.js";import{R as Zt,C as es,X as ts,Y as ss,T as rs}from"./CartesianChart--ahFU3v6.js";import{A as Xs,a as kt}from"./AreaChart-D3iI8aoD.js";import{L as pn}from"./Legend-7WPHRULZ.js";import{B as xn}from"./BarChart-DdxBhAU4.js";import{B as hn}from"./Bar-By3DPK-5.js";import"./DateFilterButton-DiyNo9Ms.js";import"./getRadiusAndStrokeWidthFromDot-DJno5CSx.js";const Qs="https://behonest.com.br";function Zs(){return{Authorization:`Bearer ${localStorage.getItem("auth_token")||""}`,"Content-Type":"application/json"}}async function er(s,e){try{return(await s.json())?.error||e}catch{return e}}function gn(s){const[e,r]=x.useState(null),[o,l]=x.useState(!1),[i,n]=x.useState(null),[m,d]=x.useState(null),u=x.useCallback(async()=>{if(!s){r(null);return}l(!0),d(null);try{const c=await fetch(`${Qs}/api/admin/users/${s}/permissions`,{headers:Zs()});if(!c.ok)throw new Error(await er(c,"Falha ao carregar permissões"));r(await c.json())}catch(c){d(c instanceof Error?c.message:"Falha ao carregar permissões"),r(null)}finally{l(!1)}},[s]);x.useEffect(()=>{u()},[u]);const p=x.useCallback(async c=>{if(!s)return"Usuário não definido";n(c.permission_key);try{const g=await fetch(`${Qs}/api/admin/users/${s}/permissions`,{method:"POST",headers:Zs(),body:JSON.stringify(c)});return g.ok?(await u(),null):await er(g,"Falha ao salvar a permissão")}catch(g){return g instanceof Error?g.message:"Falha ao salvar a permissão"}finally{n(null)}},[s,u]),y=x.useCallback(async c=>{if(!s)return"Usuário não definido";n(c);try{const g=await fetch(`${Qs}/api/admin/users/${s}/permissions/${encodeURIComponent(c)}`,{method:"DELETE",headers:Zs()});return g.ok?(await u(),null):await er(g,"Falha ao revogar a permissão")}catch(g){return g instanceof Error?g.message:"Falha ao revogar a permissão"}finally{n(null)}},[s,u]);return{data:e,loading:o,saving:i,error:m,refresh:u,grant:p,revoke:y}}const fn="https://behonest.com.br";function ea(){return{Authorization:`Bearer ${localStorage.getItem("auth_token")||""}`,"Content-Type":"application/json"}}async function ta(s,e){try{return(await s.json())?.error||e}catch{return e}}function yn(s){const[e,r]=x.useState(null),[o,l]=x.useState(!1),[i,n]=x.useState(null),[m,d]=x.useState(null),u=`${fn}/api/admin/users/${s}/projeto-visualizacoes`,p=x.useCallback(async()=>{if(!s){r(null);return}l(!0),d(null);try{const c=await fetch(u,{headers:ea()});if(!c.ok)throw new Error(await ta(c,"Falha ao carregar visualizações"));r(await c.json())}catch(c){d(c instanceof Error?c.message:"Falha ao carregar visualizações"),r(null)}finally{l(!1)}},[s,u]);x.useEffect(()=>{p()},[p]);const y=x.useCallback(async c=>{if(!s||!e)return"Usuário não definido";const g=e.rows.filter(h=>h.id===c?!h.granted:h.granted).map(h=>h.id);n(c);try{const h=await fetch(u,{method:"PUT",headers:ea(),body:JSON.stringify({viz_ids:g})});return h.ok?(r(await h.json()),null):await ta(h,"Falha ao salvar a visualização")}catch(h){return h instanceof Error?h.message:"Falha ao salvar a visualização"}finally{n(null)}},[s,u,e]);return{data:e,loading:o,saving:i,error:m,refresh:p,toggle:y}}function bn(s){const e=re.c(25),{viz:r,busy:o,readOnly:l,onToggle:i}=s,n=r.granted?"rgba(var(--secondary-rgb), 0.08)":"transparent",m=l?"default":"pointer",d=o?.6:1;let u;e[0]!==n||e[1]!==m||e[2]!==d?(u={display:"flex",gap:"10px",alignItems:"flex-start",padding:"10px",borderRadius:"var(--radius-sm)",border:"1px solid var(--glass-border)",background:n,cursor:m,opacity:d},e[0]=n,e[1]=m,e[2]=d,e[3]=u):u=e[3];const p=l||o;let y;e[4]===Symbol.for("react.memo_cache_sentinel")?(y={marginTop:"2px"},e[4]=y):y=e[4];let c;e[5]!==i||e[6]!==p||e[7]!==r.granted?(c=t.jsx("input",{type:"checkbox",checked:r.granted,disabled:p,onChange:i,style:y}),e[5]=i,e[6]=p,e[7]=r.granted,e[8]=c):c=e[8];let g,h;e[9]===Symbol.for("react.memo_cache_sentinel")?(g={minWidth:0,flex:1},h={fontSize:"13px",fontWeight:600},e[9]=g,e[10]=h):(g=e[9],h=e[10]);let f;e[11]!==r.name?(f=t.jsx("div",{style:h,children:r.name}),e[11]=r.name,e[12]=f):f=e[12];let $;e[13]===Symbol.for("react.memo_cache_sentinel")?($={fontSize:"11px",color:"var(--text-muted)",marginTop:"2px"},e[13]=$):$=e[13];let S;e[14]!==r.areas?(S=r.areas.length===0?"Sem áreas — libera a página, mas o quadro fica vazio.":`${r.areas.length} área${r.areas.length===1?"":"s"}: ${r.areas.join(" · ")}`,e[14]=r.areas,e[15]=S):S=e[15];let z;e[16]!==S?(z=t.jsx("div",{style:$,children:S}),e[16]=S,e[17]=z):z=e[17];let v;e[18]!==f||e[19]!==z?(v=t.jsxs("div",{style:g,children:[f,z]}),e[18]=f,e[19]=z,e[20]=v):v=e[20];let k;return e[21]!==v||e[22]!==u||e[23]!==c?(k=t.jsxs("label",{style:u,children:[c,v]}),e[21]=v,e[22]=u,e[23]=c,e[24]=k):k=e[24],k}function vn(s){const e=re.c(27),{userId:r,readOnly:o,onToast:l}=s,{data:i,loading:n,saving:m,error:d,toggle:u}=yn(r);if(n&&!i){let C;return e[0]===Symbol.for("react.memo_cache_sentinel")?(C=t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)"},children:"Carregando visualizações…"}),e[0]=C):C=e[0],C}if(d){let C;e[1]===Symbol.for("react.memo_cache_sentinel")?(C={fontSize:"12px",color:"#ff6b6b"},e[1]=C):C=e[1];let N;return e[2]!==d?(N=t.jsx("div",{style:C,children:d}),e[2]=d,e[3]=N):N=e[3],N}if(!i)return null;let p;e[4]!==l||e[5]!==u?(p=async C=>{const N=await u(C.id);N?l("error",N):l(C.granted?"info":"success",`${C.granted?"Removida":"Liberada"}: ${C.name}`)},e[4]=l,e[5]=u,e[6]=p):p=e[6];const y=p;let c;e[7]!==i.rows?(c=i.rows.filter(jn),e[7]=i.rows,e[8]=c):c=e[8];const g=c.length;let h;e[9]===Symbol.for("react.memo_cache_sentinel")?(h={marginBottom:"1.25rem"},e[9]=h):h=e[9];let f,$;e[10]===Symbol.for("react.memo_cache_sentinel")?(f=t.jsx("h4",{className:"admin-section-title",style:{marginBottom:"0.35rem"},children:"Painel · Visualizações de Projetos"}),$={fontSize:"11px",color:"var(--text-muted)",marginBottom:"0.6rem"}
1,e[10]=f,e[11]=$):(f=e[10],$=e[11]);const S=i.restricted?"Este usuário não vê nada em /system/painel/projetos até que uma visualização seja liberada. O que ele enxerga fica limitado às áreas marcadas aqui.":"O cargo já dá o quadro completo de Projetos — marcar aqui não muda o que este usuário vê.";let z;e[12]!==S?(z=t.jsx("div",{style:$,children:S}),e[12]=S,e[13]=z):z=e[13];let v;e[14]!==i.rows||e[15]!==y||e[16]!==o||e[17]!==m?(v=i.rows.length===0?t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)"},children:"Nenhuma visualização criada ainda. Crie em Painel → Projetos → aba Geral."}):t.jsx("div",{style:{display:"grid",gap:"8px"},children:i.rows.map(C=>t.jsx(bn,{viz:C,busy:m===C.id,readOnly:o,onToggle:()=>{y(C)}},C.id))}),e[14]=i.rows,e[15]=y,e[16]=o,e[17]=m,e[18]=v):v=e[18];let k;e[19]!==i.restricted||e[20]!==i.rows.length||e[21]!==g?(k=i.restricted&&g===0&&i.rows.length>0&&t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"8px"},children:'🔒 Nenhuma liberada — o usuário vê a tela de "Sem acesso" em Projetos.'}),e[19]=i.restricted,e[20]=i.rows.length,e[21]=g,e[22]=k):k=e[22];let A;return e[23]!==z||e[24]!==v||e[25]!==k?(A=t.jsxs("div",{style:h,children:[f,z,v,k]}),e[23]=z,e[24]=v,e[25]=k,e[26]=A):A=e[26],A}function jn(s){return s.granted}const Sn={role:{text:"herdado do cargo",color:"var(--text-muted)"},grant:{text:"liberado p/ este usuário",color:"var(--secondary)"},deny:{text:"negado p/ este usuário",color:"#ff6b6b"},legacy:{text:"liberado por flag de app",color:"var(--text-muted)"},scope:{text:"liberado por uma visualização",color:"var(--secondary)"},none:{text:"sem acesso",color:"var(--text-muted)"}};function sa(s){if(!s)return"";try{return new Date(s).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})}catch{return s}}function _n(s){const e=re.c(40),{item:r,effect:o,busy:l,onCancel:i,onConfirm:n}=s,[m,d]=x.useState(""),[u,p]=x.useState("");let y;e[0]!==r.sensitive||e[1]!==m?(y=r.sensitive&&!m.trim(),e[0]=r.sensitive,e[1]=m,e[2]=y):y=e[2];const c=y;let g,h,f;e[3]===Symbol.for("react.memo_cache_sentinel")?(g={marginTop:"8px",padding:"10px",borderRadius:"var(--radius-sm)",background:"rgba(255,255,255,0.04)",border:"1px solid var(--glass-border)",display:"flex",flexWrap:"wrap",gap:"8px",alignItems:"flex-end"},h={flex:"1 1 200px",minWidth:0},f={fontSize:"10px",color:"var(--text-muted)",display:"block"},e[3]=g,e[4]=h,e[5]=f):(g=e[3],h=e[4],f=e[5]);const $=r.sensitive?"(obrigatório)":"(opcional)";let S;e[6]!==$?(S=t.jsxs("label",{style:f,children:["Motivo ",$]}),e[6]=$,e[7]=S):S=e[7];let z;e[8]===Symbol.for("react.memo_cache_sentinel")?(z=H=>d(H.target.value),e[8]=z):z=e[8];const v=o==="deny"?"por que remover o acesso":"por que liberar";let k;e[9]===Symbol.for("react.memo_cache_sentinel")?(k={width:"100%",fontSize:"12px",padding:"6px 8px"},e[9]=k):k=e[9];let A;e[10]!==m||e[11]!==v?(A=t.jsx("input",{type:"text",value:m,onChange:z,autoFocus:!0,placeholder:v,style:k}),e[10]=m,e[11]=v,e[12]=A):A=e[12];let C;e[13]!==A||e[14]!==S?(C=t.jsxs("div",{style:h,children:[S,A]}),e[13]=A,e[14]=S,e[15]=C):C=e[15];let N,W;e[16]===Symbol.for("react.memo_cache_sentinel")?(N={flex:"0 1 150px"},W=t.jsx("label",{style:{fontSize:"10px",color:"var(--text-muted)",display:"block"},children:"Validade (opcional)"}),e[16]=N,e[17]=W):(N=e[16],W=e[17]);let T,B;e[18]===Symbol.for("react.memo_cache_sentinel")?(T=H=>p(H.target.value),B={width:"100%",fontSize:"12px",padding:"6px 8px"},e[18]=T,e[19]=B):(T=e[18],B=e[19]);let w;e[20]!==u?(w=t.jsxs("div",{style:N,children:[W,t.jsx("input",{type:"date",value:u,onChange:T,style:B})]}),e[20]=u,e[21]=w):w=e[21];const D=l||c,q=c?"Permissão sensível: informe o motivo":"";let P;e[22]!==u||e[23]!==n||e[24]!==m?(P=()=>n(m.trim(),u),e[22]=u,e[23]=n,e[24]=m,e[25]=P):P=e[25];let L;e[26]===Symbol.for("react.memo_cache_sentinel")?(L={fontSize:"12px",padding:"6px 12px"},e[26]=L):L=e[26];const R=l?"...":o==="deny"?"Negar":"Liberar";let O;e[27]!==D||e[28]!==q||e[29]!==P||e[30]!==R?(O=t.jsx("button",{type:"button",className:"btn btn-primary",disabled:D,title:q,onClick:P,style:L,children:R}),e[27]=D,e[28]=q,e[29]=P,e[30]=R,e[31]=O):O=e[31];let G;e[32]===Symbol.for("react.memo_cache_sentinel")?(G={fontSize:"12px",padding:"6px 12px"},e[32]=G):G=e[32];let E;e[33]!==i?(E=t.jsx("button",{type:"button",className:"btn btn-secondary",onClick:i,style:G,children:"Cancelar"}),e[33]=i,e[34]=E):E=e[34];let M;return e[35]!==C||e[36]!==w||e[37]!==O||e[38]!==E?(M=t.jsxs("div",{style:g,children:[C,w,O,E]}),e[35]=C,e[36]=w,e[37]=O,e[38]=E,e[39]=M):M=e[39],M}function kn(s){const e=re.c(51),{item:r,busy:o,readOnly:l,onPick:i,onRevoke:n,pending:m,onCancelPending:d,onConfirmPending:u}=s,p=Sn[r.origin],y=r.origin==="role"||r.origin==="legacy"||r.origin==="scope"||r.origin==="none";let c;e[0]!==o?(c=(O,G,E,M)=>t.jsx("button",{type:"button",onClick:E,disabled:M||o,style:{fontSize:"11px",padding:"4px 9px",borderRadius:"var(--radius-sm)",cursor:M?"not-allowed":"pointer",border:`1px solid ${G?"var(--secondary)":"rgba(255,255,255,0.15)"}`,background:G?"rgba(var(--secondary-rgb), 0.18)":"transparent",color:G?"var(--secondary)":"var(--text-muted)",opacity:M?.45:1,whiteSpace:"nowrap"},children:O}),e[0]=o,e[1]=c):c=e[1];const g=c,h=`1px solid ${r.origin==="deny"?"rgba(255,107,107,0.35)":"var(--glass-border)"}`,f=r.effective?"rgba(var(--secondary-rgb), 0.06)":"transparent";let $;e[2]!==h||e[3]!==f?($={padding:"10px",borderRadius:"var(--radius-sm)",border:h,background:f},e[2]=h,e[3]=f,e[4]=$):$=e[4];let S,z;e[5]===Symbol.for("react.memo_cache_sentinel")?(S={display:"flex",flexWrap:"wrap",gap:"8px",alignItems:"baseline"},z={fontSize:"13px",fontWeight:600},e[5]=S,e[6]=z):(S=e[5],z=e[6]);const v=r.effective?"✓":"✕";let k;e[7]!==r.label||e[8]!==v?(k=t.jsxs("span",{style:z,children:[v," ",r.label]}),e[7]=r.label,e[8]=v,e[9]=k):k=e[9];let A;
1e[10]!==r.sensitive?(A=r.sensitive&&t.jsx("span",{style:{fontSize:"9px",color:"#ffb454",border:"1px solid rgba(255,180,84,0.4)",borderRadius:"3px",padding:"1px 4px"},children:"sensível"}),e[10]=r.sensitive,e[11]=A):A=e[11];let C;e[12]!==p.color?(C={fontSize:"10px",color:p.color},e[12]=p.color,e[13]=C):C=e[13];let N;e[14]!==p.text||e[15]!==C?(N=t.jsx("span",{style:C,children:p.text}),e[14]=p.text,e[15]=C,e[16]=N):N=e[16];let W;e[17]===Symbol.for("react.memo_cache_sentinel")?(W={fontSize:"10px",color:"var(--text-muted)",marginLeft:"auto"},e[17]=W):W=e[17];let T;e[18]!==r.min_role_label?(T=t.jsxs("span",{style:W,children:["padrão: ",r.min_role_label]}),e[18]=r.min_role_label,e[19]=T):T=e[19];let B;e[20]!==N||e[21]!==T||e[22]!==k||e[23]!==A?(B=t.jsxs("div",{style:S,children:[k,A,N,T]}),e[20]=N,e[21]=T,e[22]=k,e[23]=A,e[24]=B):B=e[24];let w;e[25]===Symbol.for("react.memo_cache_sentinel")?(w={fontSize:"11px",color:"var(--text-muted)",margin:"4px 0 8px"},e[25]=w):w=e[25];let D;e[26]!==r.description?(D=t.jsx("div",{style:w,children:r.description}),e[26]=r.description,e[27]=D):D=e[27];let q;e[28]!==r.grant?(q=r.grant&&t.jsxs("div",{style:{fontSize:"10px",color:"var(--text-muted)",marginBottom:"8px"},children:[r.grant.effect==="deny"?"Negado":"Liberado"," por ",r.grant.granted_by_name||"—"," em ",sa(r.grant.granted_at),r.grant.expires_at?` · expira ${sa(r.grant.expires_at)}`:" · sem validade",r.grant.reason?` · "${r.grant.reason}"`:""]}),e[28]=r.grant,e[29]=q):q=e[29];let P;e[30]!==y||e[31]!==r.grantable||e[32]!==r.origin||e[33]!==i||e[34]!==n||e[35]!==l||e[36]!==g?(P=r.grantable?l?null:t.jsxs("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[g("Herdado",y,n,y),g("Liberar",r.origin==="grant",()=>i("grant"),r.origin==="grant"),g("Negar",r.origin==="deny",()=>i("deny"),r.origin==="deny")]}):t.jsx("div",{style:{fontSize:"10px",color:"var(--text-muted)"},children:"🔒 Definida pelo cargo — não é concedível individualmente."}),e[30]=y,e[31]=r.grantable,e[32]=r.origin,e[33]=i,e[34]=n,e[35]=l,e[36]=g,e[37]=P):P=e[37];let L;e[38]!==o||e[39]!==r||e[40]!==d||e[41]!==u||e[42]!==m?(L=m&&t.jsx(_n,{item:r,effect:m,busy:o,onCancel:d,onConfirm:u}),e[38]=o,e[39]=r,e[40]=d,e[41]=u,e[42]=m,e[43]=L):L=e[43];let R;return e[44]!==B||e[45]!==D||e[46]!==q||e[47]!==P||e[48]!==L||e[49]!==$?(R=t.jsxs("div",{style:$,children:[B,D,q,P,L]}),e[44]=B,e[45]=D,e[46]=q,e[47]=P,e[48]=L,e[49]=$,e[50]=R):R=e[50],R}function wn(s){const e=re.c(48),{userId:r,onToast:o}=s,{data:l,loading:i,saving:n,error:m,grant:d,revoke:u}=gn(r),[p,y]=x.useState(null);if(i&&!l){let L;return e[0]===Symbol.for("react.memo_cache_sentinel")?(L=t.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"var(--text-muted)"},children:"Carregando permissões…"}),e[0]=L):L=e[0],L}if(m){let L;e[1]===Symbol.for("react.memo_cache_sentinel")?(L={padding:"2rem",textAlign:"center",color:"#ff6b6b"},e[1]=L):L=e[1];let R;return e[2]!==m?(R=t.jsx("div",{style:L,children:m}),e[2]=m,e[3]=R):R=e[3],R}if(!l)return null;const c=l.user.role==="admin";let g;e[4]!==d||e[5]!==o?(g=async(L,R,O,G)=>{const E=await d({permission_key:L.key,effect:R,reason:O||void 0,expires_at:G?`${G}T23:59:59`:void 0});y(null),E?o("error",E):o("success",`${R==="deny"?"Negado":"Liberado"}: ${L.label}`)},e[4]=d,e[5]=o,e[6]=g):g=e[6];const h=g;let f;e[7]!==o||e[8]!==u?(f=async L=>{const R=await u(L.key);R?o("error",R):o("info",`${L.label} volta ao padrão do cargo`)},e[7]=o,e[8]=u,e[9]=f):f=e[9];const $=f;let S,z,v;e[10]===Symbol.for("react.memo_cache_sentinel")?(S={maxHeight:"75vh",overflowY:"auto",paddingRight:"4px"},z={display:"flex",flexWrap:"wrap",gap:"10px",alignItems:"center",padding:"10px 12px",marginBottom:"1rem",borderRadius:"var(--radius-md)",background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)"},v={fontSize:"12px"},e[10]=S,e[11]=z,e[12]=v):(S=e[10],z=e[11],v=e[12]);let k;e[13]===Symbol.for("react.memo_cache_sentinel")?(k={color:"var(--secondary)"},e[13]=k):k=e[13];let A;e[14]!==l.user.role_label?(A=t.jsxs("span",{style:v,children:["Nível: ",t.jsx("strong",{style:k,children:l.user.role_label})]}),e[14]=l.user.role_label,e[15]=A):A=e[15];let C;e[16]===Symbol.for("react.memo_cache_sentinel")?(C={fontSize:"12px",color:"var(--text-muted)"},e[16]=C):C=e[16];const N=l.permissions.length===1?"m":"s",W=l.permissions.length===1?"":"s";let T;e[17]!==l.permissions.length||e[18]!==W||e[19]!==N?(T=t.jsxs("span",{style:C,children:[l.permissions.length," permissõe",N," efetiva",W]}),e[17]=l.permissions.length,e[18]=W,e[19]=N,e[20]=T):T=e[20];let B;e[21]===Symbol.for("react.memo_cache_sentinel")?(B=t.jsx("span",{style:{fontSize:"11px",color:"var(--text-muted)",flex:"1 1 260px"},children:"O cargo define o padrão; aqui você libera ou nega item a item, sem promover o usuário."}),e[21]=B):B=e[21];let w;e[22]!==T||e[23]!==A?(w=t.jsxs("div",{style:z,children:[A,T,B]}),e[22]=T,e[23]=A,e[24]=w):w=e[24];let D;e[25]!==c?(D=c&&t.jsx("div",{style:{padding:"10px 12px",marginBottom:"1rem",borderRadius:"var(--radius-md)",background:"rgba(var(--secondary-rgb), 0.1)",border:"1px solid var(--secondary)",fontSize:"12px"},children:"👑 Administrador tem acesso total e ignora concessões individuais. Para restringir, mude o cargo."}),e[25]=c,e[26]=D):D=e[26];let q;if(e[27]!==l.categories||e[28]!==h||e[29]!==$||e[30]!==c||e[31]!==o||e[32]!==p||e[33]!==n||e[34]!==r){let L;e[36]!==h||e[37]!==$||e[38]!==c||e[39]!==o||e[40]!==p||e[41]!==n||e[42]!==r?(L=R=>t.jsxs("div",{style:{marginBottom:"1.25rem"},children:[t.jsx("h4",{className:"admin-section-title",style:{marginBottom:"0.5rem"},children:R.category_label}),t.jsx("div",{style:{display:"grid",gap:"8px"},children:R.permissions.map(O=>t.jsx(kn,{item:O,busy:n===O.key,readOnly:c,pending:p?.key===O.key?p.effect:null,onPick:G=>y({key:O.key,effect:G}),onRevoke:()=>{$(O)},onCancelPending:()=>y(null),onConfirmPending:(G,E)=>{h(O,p.effect,G,E)}}
1,O.key))}),R.category==="painel_estrategia"&&t.jsx("div",{style:{marginTop:"1rem"},children:t.jsx(vn,{userId:r,readOnly:c,onToast:o})})]},R.category),e[36]=h,e[37]=$,e[38]=c,e[39]=o,e[40]=p,e[41]=n,e[42]=r,e[43]=L):L=e[43],q=l.categories.map(L),e[27]=l.categories,e[28]=h,e[29]=$,e[30]=c,e[31]=o,e[32]=p,e[33]=n,e[34]=r,e[35]=q}else q=e[35];let P;return e[44]!==w||e[45]!==D||e[46]!==q?(P=t.jsxs("div",{style:S,children:[w,D,q]}),e[44]=w,e[45]=D,e[46]=q,e[47]=P):P=e[47],P}function Ca(s){const e=re.c(29),{isOpen:r,title:o,message:l,confirmLabel:i,cancelLabel:n,variant:m,onConfirm:d,onCancel:u,busy:p}=s,y=i===void 0?"Confirmar":i,c=n===void 0?"Cancelar":n,g=m===void 0?"danger":m,h=p===void 0?!1:p,f=x.useRef(null);let $,S;e[0]!==r?($=()=>{if(r){const q=setTimeout(()=>f.current?.focus(),50);return()=>clearTimeout(q)}},S=[r],e[0]=r,e[1]=$,e[2]=S):($=e[1],S=e[2]),x.useEffect($,S);const z=g==="danger"?"⚠️":g==="warning"?"❗":"ℹ️";let v;e[3]!==h||e[4]!==c||e[5]!==u?(v=t.jsx("button",{ref:f,type:"button",className:"btn btn-secondary",onClick:u,disabled:h,children:c}),e[3]=h,e[4]=c,e[5]=u,e[6]=v):v=e[6];const k=`btn btn-${g==="danger"?"danger":g==="warning"?"warning":"primary"}`,A=h?"Aguarde…":y;let C;e[7]!==h||e[8]!==d||e[9]!==k||e[10]!==A?(C=t.jsx("button",{type:"button",className:k,onClick:d,disabled:h,children:A}),e[7]=h,e[8]=d,e[9]=k,e[10]=A,e[11]=C):C=e[11];let N;e[12]!==C||e[13]!==v?(N=t.jsxs(t.Fragment,{children:[v,C]}),e[12]=C,e[13]=v,e[14]=N):N=e[14];const W=`confirm-dialog-icon ${g}`;let T;e[15]!==W||e[16]!==z?(T=t.jsx("div",{className:W,"aria-hidden":"true",children:z}),e[15]=W,e[16]=z,e[17]=T):T=e[17];let B;e[18]!==l?(B=t.jsx("p",{className:"confirm-dialog-message",children:l}),e[18]=l,e[19]=B):B=e[19];let w;e[20]!==T||e[21]!==B?(w=t.jsxs("div",{className:"confirm-dialog-body",children:[T,B]}),e[20]=T,e[21]=B,e[22]=w):w=e[22];let D;return e[23]!==r||e[24]!==u||e[25]!==N||e[26]!==w||e[27]!==o?(D=t.jsx(mt,{isOpen:r,onClose:u,title:o,size:"sm",footer:N,children:w}),e[23]=r,e[24]=u,e[25]=N,e[26]=w,e[27]=o,e[28]=D):D=e[28],D}function ra(s){const e=re.c(3),{tabs:r,activeTab:o,onTabChange:l}=s,i=x.useRef(null),n=(c,g)=>{if(c.key!=="ArrowRight"&&c.key!=="ArrowLeft"&&c.key!=="Home"&&c.key!=="End")return;c.preventDefault();let h=g;c.key==="ArrowRight"?h=(g+1)%r.length:c.key==="ArrowLeft"?h=(g-1+r.length)%r.length:c.key==="Home"?h=0:c.key==="End"&&(h=r.length-1),i.current?.querySelectorAll("button.nav-tab-btn")[h]?.focus(),l(r[h].id)},m="nav-tabs-container",d="nav-tabs",u="tablist",p=r.map((c,g)=>{const h=o===c.id;return t.jsxs("button",{role:"tab","aria-selected":h,tabIndex:h?0:-1,onClick:()=>l(c.id),onKeyDown:f=>n(f,g),className:`nav-tab-btn ${h?"active":""}`,children:[t.jsx("span",{className:"tab-icon",children:c.icon}),t.jsx("span",{children:c.label}),typeof c.count=="number"&&t.jsx("span",{className:"tab-count","aria-label":`${c.count} itens`,children:c.count})]},c.id)});let y;return e[0]!==i||e[1]!==p?(y=t.jsx("div",{className:m,children:t.jsx("div",{className:d,role:u,ref:i,children:p})}),e[0]=i,e[1]=p,e[2]=y):y=e[2],y}function Cn(s){const e=re.c(78),{initialRole:r,onSave:o,onCancel:l,readOnly:i}=s,n=i===void 0?!1:i,[m,d]=x.useState(r?.name||""),[u,p]=x.useState(r?.level||0);let y;e[0]!==r?.permissions?(y=r?.permissions||{view_admin:!1,manage_users:!1,manage_roles:!1,manage_stores:!1,all_access:!1},e[0]=r?.permissions,e[1]=y):y=e[1];const[c,g]=x.useState(y);let h;e[2]!==n?(h=de=>{n||g(je=>({...je,[de]:!je[de]}))},e[2]=n,e[3]=h):h=e[3];const f=h;let $;e[4]!==r||e[5]!==u||e[6]!==m||e[7]!==o||e[8]!==c||e[9]!==n?($=de=>{de.preventDefault(),!n&&o({...r,name:m,level:u,permissions:c})},e[4]=r,e[5]=u,e[6]=m,e[7]=o,e[8]=c,e[9]=n,e[10]=$):$=e[10];const S=$;let z;e[11]===Symbol.for("react.memo_cache_sentinel")?(z=t.jsx("label",{children:"Nome do Cargo"}),e[11]=z):z=e[11];let v;e[12]===Symbol.for("react.memo_cache_sentinel")?(v=de=>d(de.target.value),e[12]=v):v=e[12];let k;e[13]!==m||e[14]!==n?(k=t.jsxs("div",{className:"form-group",children:[z,t.jsx("input",{type:"text",value:m,onChange:v,placeholder:"ex: gerente",required:!0,disabled:n})]}),e[13]=m,e[14]=n,e[15]=k):k=e[15];let A;e[16]===Symbol.for("react.memo_cache_sentinel")?(A=t.jsx("label",{children:"Nível (Hierarquia)"}),e[16]=A):A=e[16];let C;e[17]===Symbol.for("react.memo_cache_sentinel")?(C=de=>p(Number(de.target.value)),e[17]=C):C=e[17];let N;e[18]!==u||e[19]!==n?(N=t.jsx("input",{type:"number",value:u,onChange:C,placeholder:"0-100",disabled:n}),e[18]=u,e[19]=n,e[20]=N):N=e[20];let W;e[21]===Symbol.for("react.memo_cache_sentinel")?(W=t.jsx("small",{children:"Níveis mais altos têm prioridade visual."}),e[21]=W):W=e[21];let T;e[22]!==N?(T=t.jsxs("div",{className:"form-group",children:[A,N,W]}),e[22]=N,e[23]=T):T=e[23];let B;e[24]===Symbol.for("react.memo_cache_sentinel")?(B=t.jsx("label",{children:"Permissões"}),e[24]=B):B=e[24];let w;e[25]===Symbol.for("react.memo_cache_sentinel")?(w={display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.5rem"},e[25]=w):w=e[25];let D;e[26]!==f?(D=()=>f("view_admin"),e[26]=f,e[27]=D):D=e[27];let q;e[28]!==c.view_admin||e[29]!==n||e[30]!==D?(q=t.jsxs("label",{className:"checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:c.view_admin,onChange:D,disabled:n}),"Ver Admin"]}),e[28]=c.view_admin,e[29]=n,e[30]=D,e[31]=q):q=e[31];let P;e[32]!==f?(P=()=>f("manage_users"),e[32]=f,e[33]=P):P=e[33];let L;e[34]!==c.manage_users||e[35]!==n||e[36]!==P?(L=t.jsxs("label",{className:"checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:c.manage_users,onChange:P,disabled:n}),"Gerenciar Usuários"]}),e[34]=c.manage_users,e[35]=n,e[36]=P,e[37]=L):L=e[37];let R;e[38]!==f?(R=()=>f("manage_stores"),e[38]=f,e[39]=R):R=e[39];let O;e[40]!==c.manage_stores||e[41]!==n||e[42]!==R?(O=t.jsxs("label",{className:"checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:c.manage_stores,onChange:R,disabled:n}),"Gerenciar Lojas"]}),e[40]=c.manage_stores,e[41]=n,e[42]=R,e[43]=O):O=e[43];let G;e[44]!==f?(G=()=>f("manage_roles"),e[44]=f,e[45]=G):G=e[45];let E;e[46]!==c.manage_roles||e[47]!==n||e[48]!==G?(E=t.jsxs("label",{className:"checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:c.manage_roles,onChange:G,disabled:n}),"Gerenciar Cargos"]}),e[46]=c.manage_roles,e[47]=n,e[48]=G,e[49]=E):E=e[49];let M;e[50]===Symbol.for("react.memo_cache_sentinel")?(M={color:"#ef4444"},e[50]=M):M=e[50];let H;e[51]!==f?(H=()=>f("all_access"),e[51]=f,e[52]=H):H=e[52];let X;e[53]!==c.all_access||e[54]!==n||e[55]!==H?(X=t.jsxs("label",{className:"checkbox-label",style:M,children:[t.jsx("input",{type:"checkbox",checked:c.all_access,onChange:H,disabled:n}),"Acesso Total (Super Admin)"]}),e[53]=c.all_access,e[54]=n,e[55]=H,e[56]=X):X=e[56];let J;e[57]!==q||e[58]!==L||e[59]!==O||e[60]!==E||e[61]!==X?(J=t.jsxs("div",{className:"form-group",children:[B,t.jsxs("div",{className:"permissions-grid",style:w,children:[q,L,O,E,X]})]}),e[57]=q,e[58]=L,e[59]=O,e[60]=E,e[61]=X,e[62]=J):J=e[62];let U;e[63]===Symbol.for("react.memo_cache_sentinel")?(U={marginTop:"1rem",display:"flex",justifyContent:"flex-end",gap:"0.5rem"},e[63]=U):U=e[63];const K=n?"Fechar":"Cancelar";let Y;e[64]!==l||e[65]!==K?(Y=t.jsx("button",{type:"button",className:"btn btn-secondary",onClick:l,children:K}),e[64]=l,e[65]=K,e[66]=Y):Y=e[66];let Q;e[67]!==n?(Q=!n&&t.jsx("button",{type:"submit",className:"btn btn-primary",children:"Salvar"}),e[67]=n,e[68]=Q):Q=e[68];let me;e[69]!==Y||e[70]!==Q?(me=t.jsxs("div",{className:"form-actions",style:U,children:[Y,Q]}),e[69]=Y,e[70]=Q,e[71]=me):me=e[71];let ue;return e[72]!==S||e[73]!==T||e[74]!==J||e[75]!==me||e[76]!==k?(ue=t.jsxs("form",{onSubmit:S,children:[k,T,J,me]}),e[72]=S,e[73]=T,e[74]=J,e[75]=me,e[76]=k,e[77]=ue):ue=e[77],ue}function $n(s){const e=re.c(62),{store:r,onSave:o,onCancel:l,readOnly:i}=s,n=i===void 0?!1:i;let m;e[0]!==r?(m={...r},e[0]=r,e[1]=m):m=e[1];const[d,u]=x.useState(m);let p;e[2]!==n?(p=X=>{if(n)return;const{name:J,value:U}=X.target;u(K=>({...K,[J]:J==="lat"||J==="lng"?parseFloat(U):U}))},e[2]=n,e[3]=p):p=e[3];const y=p;let c;e[4]!==d||e[5]!==o||e[6]!==n?(c=X=>{X.preventDefault(),!n&&o(d)},e[4]=d,e[5]=o,e[6]=n,e[7]=c):c=e[7];const g=c;let h,f;e[8]===Symbol.for("react.memo_cache_sentinel")?(h={maxWidth:"140px"},f=t.jsx("label",{children:"Unique ID"}),e[8]=h,e[9]=f):(h=e[8],f=e[9]);const $=d.unique_id||"";let S;e[10]!==$?(S=t.jsxs("div",{className:"form-group",style:h,children:[f,t.jsx("input",{type:"text",value:$,disabled:!0})]}),e[10]=$,e[11]=S):S=e[11];let z;e[12]===Symbol.for("react.memo_cache_sentinel")?(z=t.jsx("label",{children:"Nome da Loja"}),e[12]=z):z=e[12];let v;e[13]!==d.name||e[14]!==y||e[15]!==n?(v=t.jsxs("div",{className:"form-group",children:[z,t.jsx("input",{name:"name",type:"text",value:d.name,onChange:y,required:!0,disabled:n})]}),e[13]=d.name,e[14]=y,e[15]=n,e[16]=v):v=e[16];let k;e[17]!==v||e[18]!==S?(k=t.jsxs("div",{className:"form-row",children:[S,v]}),e[17]=v,e[18]=S,e[19]=k):k=e[19];let A;e[20]===Symbol.for("react.memo_cache_sentinel")?(A=t.jsx("label",{children:"Cidade"}),e[20]=A):A=e[20];let C;e[21]!==d.city||e[22]!==y||e[23]!==n?(C=t.jsxs("div",{className:"form-group",children:[A,t.jsx("input",{name:"city",type:"text",value:d.city,onChange:y,disabled:n})]}),e[21]=d.city,e[22]=y,e[23]=n,e[24]=C):C=e[24];let N;e[25]===Symbol.for("react.memo_cache_sentinel")?(N=t.jsx("label",{children:"Estado (Sigla)"}),e[25]=N):N=e[25];let W;e[26]===Symbol.for("react.memo_cache_sentinel")?(W={textTransform:"uppercase"},e[26]=W):W=e[26];let T;e[27]!==d.state||e[28]!==y||e[29]!==n?(T=t.jsxs("div",{className:"form-group",children:[N,t.jsx("input",{name:"state",type:"text",value:d.state,onChange:y,maxLength:2,
1style:W,disabled:n})]}),e[27]=d.state,e[28]=y,e[29]=n,e[30]=T):T=e[30];let B;e[31]!==C||e[32]!==T?(B=t.jsxs("div",{className:"form-row",children:[C,T]}),e[31]=C,e[32]=T,e[33]=B):B=e[33];let w;e[34]===Symbol.for("react.memo_cache_sentinel")?(w=t.jsx("label",{children:"Latitude"}),e[34]=w):w=e[34];let D;e[35]!==d.lat||e[36]!==y||e[37]!==n?(D=t.jsxs("div",{className:"form-group",children:[w,t.jsx("input",{name:"lat",type:"number",step:"any",value:d.lat,onChange:y,disabled:n})]}),e[35]=d.lat,e[36]=y,e[37]=n,e[38]=D):D=e[38];let q;e[39]===Symbol.for("react.memo_cache_sentinel")?(q=t.jsx("label",{children:"Longitude"}),e[39]=q):q=e[39];let P;e[40]!==d.lng||e[41]!==y||e[42]!==n?(P=t.jsxs("div",{className:"form-group",children:[q,t.jsx("input",{name:"lng",type:"number",step:"any",value:d.lng,onChange:y,disabled:n})]}),e[40]=d.lng,e[41]=y,e[42]=n,e[43]=P):P=e[43];let L;e[44]!==D||e[45]!==P?(L=t.jsxs("div",{className:"form-row",children:[D,P]}),e[44]=D,e[45]=P,e[46]=L):L=e[46];let R;e[47]===Symbol.for("react.memo_cache_sentinel")?(R={marginTop:"1rem",display:"flex",justifyContent:"flex-end",gap:"0.5rem"},e[47]=R):R=e[47];const O=n?"Fechar":"Cancelar";let G;e[48]!==l||e[49]!==O?(G=t.jsx("button",{type:"button",className:"btn btn-secondary",onClick:l,children:O}),e[48]=l,e[49]=O,e[50]=G):G=e[50];let E;e[51]!==n?(E=!n&&t.jsx("button",{type:"submit",className:"btn btn-primary",children:"Salvar Alterações"}),e[51]=n,e[52]=E):E=e[52];let M;e[53]!==G||e[54]!==E?(M=t.jsxs("div",{className:"form-actions",style:R,children:[G,E]}),e[53]=G,e[54]=E,e[55]=M):M=e[55];let H;return e[56]!==g||e[57]!==k||e[58]!==B||e[59]!==L||e[60]!==M?(H=t.jsxs("form",{onSubmit:g,children:[k,B,L,M]}),e[56]=g,e[57]=k,e[58]=B,e[59]=L,e[60]=M,e[61]=H):H=e[61],H}function zn(s){const e=re.c(8),{toasts:r,onRemove:o}=s;let l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l={position:"fixed",top:"20px",right:"20px",zIndex:"var(--z-toast, 9999)",display:"flex",flexDirection:"column",gap:"10px"},e[0]=l):l=e[0];let i;if(e[1]!==o||e[2]!==r){let m;e[4]!==o?(m=d=>t.jsx(An,{toast:d,onRemove:o},d.id),e[4]=o,e[5]=m):m=e[5],i=r.map(m),e[1]=o,e[2]=r,e[3]=i}else i=e[3];let n;return e[6]!==i?(n=t.jsx("div",{className:"toast-container",style:l,children:i}),e[6]=i,e[7]=n):n=e[7],n}function An(s){const e=re.c(19),{toast:r,onRemove:o}=s;let l,i;e[0]!==o||e[1]!==r.id?(l=()=>{const f=setTimeout(()=>{o(r.id)},5e3);return()=>clearTimeout(f)},i=[r.id,o],e[0]=o,e[1]=r.id,e[2]=l,e[3]=i):(l=e[2],i=e[3]),x.useEffect(l,i);let n;e[4]===Symbol.for("react.memo_cache_sentinel")?(n={success:"#10B981",error:"#EF4444",info:"#3B82F6"},e[4]=n):n=e[4];const d=n[r.type];let u;e[5]!==d?(u={backgroundColor:d,color:"white",padding:"12px 20px",borderRadius:"8px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",minWidth:"250px",maxWidth:"400px",animation:"slideIn 0.3s ease-out",display:"flex",justifyContent:"space-between",alignItems:"center"},e[5]=d,e[6]=u):u=e[6];let p;e[7]!==r.message?(p=t.jsx("span",{children:r.message}),e[7]=r.message,e[8]=p):p=e[8];let y;e[9]!==o||e[10]!==r.id?(y=()=>o(r.id),e[9]=o,e[10]=r.id,e[11]=y):y=e[11];let c;e[12]===Symbol.for("react.memo_cache_sentinel")?(c={background:"transparent",border:"none",color:"white",marginLeft:"10px",cursor:"pointer",fontSize:"18px"},e[12]=c):c=e[12];let g;e[13]!==y?(g=t.jsx("button",{onClick:y,style:c,children:"×"}),e[13]=y,e[14]=g):g=e[14];let h;return e[15]!==u||e[16]!==p||e[17]!==g?(h=t.jsxs("div",{style:u,children:[p,g]}),e[15]=u,e[16]=p,e[17]=g,e[18]=h):h=e[18],h}function Rn(s,e=1440*60*1e3){const r=n=>`${s}_${n}`;function o(n){try{const m=r(n),d=localStorage.getItem(m);if(d){const{data:u}=JSON.parse(d);return u}}catch{}return null}function l(n){try{const m=r(n),d=localStorage.getItem(m);if(d){const{timestamp:u}=JSON.parse(d);return Date.now()-u>=e}}catch{}return!0}function i(n,m){try{const d=r(n);localStorage.setItem(d,JSON.stringify({data:m,timestamp:Date.now()}))}catch{}}return{getCacheKey:r,getFromCache:o,saveToCache:i,isStale:l}}const as="https://behonest.com.br",Ie="#edb125";function Tn({storeId:s,storeName:e,userCount:r,onClose:o}){const[l,i]=x.useState(""),[n,m]=x.useState(""),[d,u]=x.useState(""),[p,y]=x.useState(!1),[c,g]=x.use
1State(!1),[h,f]=x.useState(!1),[$,S]=x.useState(null),[z,v]=x.useState("info"),[k,A]=x.useState(null),C=x.useRef(null),[N,W]=x.useState([]),[T,B]=x.useState(!0),[w,D]=x.useState(0),[q,P]=x.useState(r),L=N.length||r,R=q-w,O=x.useCallback(()=>({Authorization:`Bearer ${le()}`,"Content-Type":"application/json"}),[]);x.useEffect(()=>()=>{C.current&&clearInterval(C.current)},[]),x.useEffect(()=>{(async()=>{try{const Y=await(await fetch(`${as}/api/admin/contact-info/contacts?store_id=${s}`,{headers:O()})).json();Y.success&&Y.contacts&&(W(Y.contacts),P(Y.contacts.length))}catch{}finally{B(!1)}})()},[s,O]);const G=x.useCallback(async()=>{if(!l.trim()||!n.trim()||!d.trim()){S("Preencha assunto, HTML e email de teste"),v("error");return}f(!0),S("Enviando email de teste..."),v("info");try{const U=await fetch(`${as}/api/admin/contact-info/send-test-email`,{method:"POST",headers:O(),body:JSON.stringify({subject:l,html_body:n,test_email:d})}),K=await U.json();U.ok&&K.success?(S(`✅ Test email enviado para ${d}`),v("success")):(S(`❌ Falha: ${K.error||"Erro desconhecido"}`),v("error"))}catch{S("❌ Erro de conexão"),v("error")}finally{f(!1)}},[l,n,d,O]),E=x.useCallback(U=>{C.current&&clearInterval(C.current),C.current=setInterval(async()=>{try{const Y=await(await fetch(`${as}/api/admin/contact-info/blast-status?job_id=${U}`,{headers:O()})).json();if(!Y.success)return;const{status:Q,sent:me,failed:ue,total:de}=Y;A({sent:me,failed:ue,total:de}),S(`📧 Enviando ${me+ue}/${de}... (${me} ✅ ${ue} ❌)`),v("info"),(Q==="done"||Q==="error")&&(C.current&&clearInterval(C.current),C.current=null,g(!1),Q==="done"?(S(`✅ Concluído! ${me} enviados, ${ue} falhas de ${de} total`),v("success")):(S(`❌ Erro: ${me} enviados, ${ue} falhas. ${Y.errors?.[0]||""}`),v("error")))}catch{}},1e3)},[O]),M=x.useCallback(async()=>{if(!l.trim()||!n.trim()){S("Preencha assunto e HTML"),v("error");return}if(window.confirm(`Enviar email para ${R} de ${L} usuário(s) da loja "${e}"?
2
3Usuários ${w+1} a ${q} da lista.
4Esta ação não pode ser desfeita.`)){g(!0),A(null),S(`📧 Iniciando envio para ${R} usuários...`),v("info");try{const K=await fetch(`${as}/api/admin/contact-info/send-email`,{method:"POST",headers:O(),body:JSON.stringify({store_id:s,subject:l,html_body:n,start_index:w,end_index:q})}),Y=await K.json();K.ok&&Y.success&&Y.job_id?(A({sent:0,failed:0,total:Y.total||R}),E(Y.job_id)):(S(`❌ Falha: ${Y.error||"Erro desconhecido"}`),v("error"),g(!1))}catch{S("❌ Erro de conexão"),v("error"),g(!1)}}},[l,n,s,e,L,R,w,q,O,E]),H=z==="success"?"#22c55e":z==="error"?"#ef4444":Ie,X=L>0?w/L*100:0,J=L>0?q/L*100:100;return t.jsx("div",{onClick:o,style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.6)",backdropFilter:"blur(4px)",display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsxs("div",{onClick:U=>U.stopPropagation(),style:{background:"#1a1a2e",borderRadius:"16px",border:`1px solid ${Ie}40`,width:"90%",maxWidth:"700px",maxHeight:"90vh",overflowY:"auto",padding:"1.5rem",boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[t.jsxs("h3",{style:{margin:0,color:"var(--text-primary)",fontSize:"1.1rem"},children:["📧 Enviar Email — ",e]}),t.jsx("button",{onClick:o,style:{background:"none",border:"none",color:"var(--text-muted)",fontSize:"1.3rem",cursor:"pointer"},title:"Fechar",children:"✕"})]}),t.jsxs("div",{style:{padding:"0.75rem",borderRadius:"10px",background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.08)",marginBottom:"0.75rem"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.4rem"},children:[t.jsx("label",{style:{fontSize:"0.78rem",color:"var(--text-muted)"},children:"📊 Destinatários"}),t.jsxs("span",{style:{fontSize:"0.72rem",color:Ie,fontWeight:600},children:[R," de ",L," selecionados",L>0&&` (${w+1}–${q})`]})]}),L>1&&t.jsxs("div",{style:{position:"relative",height:"32px",marginBottom:"0.5rem"},children:[t.jsx("div",{style:{position:"absolute",top:"14px",left:0,right:0,height:"4px",borderRadius:"2px",background:"rgba(255,255,255,0.1)"}}),t.jsx("div",{style:{position:"absolute",top:"14px",height:"4px",borderRadius:"2px",background:Ie,left:`${X}%`,width:`${J-X}%`}}),t.jsx("input",{type:"range",min:0,max:L,value:w,onChange:U=>{const K=parseInt(U.target.value);K<q&&D(K)},className:"range-slider-thumb",style:{position:"absolute",top:0,left:0,width:"100%",height:"32px",appearance:"none",WebkitAppearance:"none",background:"transparent",pointerEvents:"none",zIndex:3}}),t.jsx("input",{type:"range",min:0,max:L,value:q,onChange:U=>{const K=parseInt(U.target.value);K>w&&P(K)},className:"range-slider-thumb",style:{position:"absolute",top:0,left:0,width:"100%",height:"32px",appearance:"none",WebkitAppearance:"none",background:"transparent",pointerEvents:"none",zIndex:4}})]}),T?t.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-muted)",textAlign:"center",padding:"0.5rem"},children:"Carregando contatos..."}):N.length>0?t.jsx("div",{style:{maxHeight:"140px",overflowY:"auto",borderRadius:"8px",background:"rgba(0,0,0,0.2)",padding:"0.25rem"},children:N.map((U,K)=>{const Y=K>=w&&K<q;return t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.25rem 0.5rem",borderRadius:"4px",fontSize:"0.72rem",opacity:Y?1:.3,background:Y?`${Ie}08`:"transparent",color:Y?"var(--text-primary)":"var(--text-muted)",transition:"opacity 0.15s, background 0.15s"},children:[t.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:[K+1,". ",U.name]}),t.jsx("span",{style:{color:Y?Ie:"var(--text-muted)",marginLeft:"0.5rem",flexShrink:0,fontSize:"0.7rem"},children:U.email})]},K)})}):t.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-muted)",textAlign:"center",padding:"0.5rem"},children:["👥 ",r," usuário(s)"]}),t.jsx("style",{children:`
5                        .range-slider-thumb::-webkit-slider-thumb {
6                            -webkit-appearance: none; appearance: none;
7                            width: 18px; height: 18px; border-radius: 50%;
8                            background: ${Ie}; border: 2px solid #1a1a2e;
9                            cursor: pointer; pointer-events: all;
10                            box-shadow: 0 2px 6px rgba(0,0,0,0.4);
11                        }
12                        .range-slider-thumb::-moz-range-thumb {
13                            width: 18px; height: 18px; border-radius: 50%;
14                            background: ${Ie}; border: 2px solid #1a1a2e;
15                            cursor: pointer; pointer-events: all;
16                            box-shadow: 0 2px 6px rgba(0,0,0,0.4);
17                        }
18                    `})]}),t.jsxs("div",{style:{padding:"0.35rem 0.75rem",borderRadius:"8px",background:`${Ie}10`,border:`1px solid ${Ie}30`,fontSize:"0.72rem",color:Ie,marginBottom:"0.75rem"},children:["💡 Use ",t.jsx("code",{style:{background:"rgba(255,255,255,0.1)",padding:"0.1rem 0.3rem",borderRadius:"4px"},children:"{nome}"})," no assunto ou corpo para personalizar"]}),t.jsx("label",{style:{fontSize:"0.8rem",color:"var(--text-muted)",marginBottom:"0.25rem",display:"block"}
18,children:"Assunto"}),t.jsx("input",{type:"text",className:"admin-input",placeholder:"Ex: Novidades da sua loja",value:l,onChange:U=>i(U.target.value),style:{width:"100%",padding:"0.6rem 0.85rem",borderRadius:"10px",fontSize:"0.85rem",marginBottom:"0.75rem"}}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.25rem"},children:[t.jsx("label",{style:{fontSize:"0.8rem",color:"var(--text-muted)"},children:"Corpo HTML"}),t.jsx("button",{onClick:()=>y(!p),style:{background:p?`${Ie}20`:"transparent",border:`1px solid ${Ie}40`,borderRadius:"6px",color:Ie,fontSize:"0.72rem",padding:"0.2rem 0.6rem",cursor:"pointer"},children:p?"✏️ Editor":"👁️ Preview"})]}),p?t.jsx("iframe",{srcDoc:n||'<p style="color:#999;text-align:center;">Nenhum HTML</p>',sandbox:"",style:{width:"100%",height:"260px",borderRadius:"10px",border:"1px solid rgba(255,255,255,0.1)",background:"#fff",marginBottom:"0.75rem"},title:"Email Preview"}):t.jsx("textarea",{className:"admin-input",placeholder:"<div>Cole seu HTML aqui...</div>",value:n,onChange:U=>m(U.target.value),rows:8,style:{width:"100%",padding:"0.6rem 0.85rem",borderRadius:"10px",fontSize:"0.8rem",fontFamily:'"Fira Code", "Consolas", monospace',resize:"vertical",marginBottom:"0.75rem",lineHeight:1.5}}),t.jsxs("div",{style:{padding:"0.75rem",borderRadius:"10px",background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.08)",marginBottom:"0.75rem"},children:[t.jsx("label",{style:{fontSize:"0.78rem",color:"var(--text-muted)",marginBottom:"0.3rem",display:"block"},children:"🧪 Enviar Teste"}),t.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[t.jsx("input",{type:"email",className:"admin-input",placeholder:"[email protected]",value:d,onChange:U=>u(U.target.value),style:{flex:1,padding:"0.5rem 0.75rem",borderRadius:"8px",fontSize:"0.82rem"}}),t.jsx("button",{className:"btn btn-primary",onClick:G,disabled:h||c,style:{fontSize:"0.78rem",padding:"0.5rem 1rem",whiteSpace:"nowrap",opacity:h||c?.6:1},children:h?"⏳...":"🧪 Testar"})]})]}),$&&t.jsxs("div",{style:{padding:"0.5rem 0.75rem",borderRadius:"8px",background:`${H}15`,border:`1px solid ${H}40`,fontSize:"0.78rem",color:H,marginBottom:"0.75rem"},children:[$,k&&k.total>0&&c&&t.jsx("div",{style:{marginTop:"0.4rem",background:"rgba(255,255,255,0.1)",borderRadius:"4px",height:"6px",overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",borderRadius:"4px",background:`linear-gradient(90deg, #22c55e, ${Ie})`,width:`${(k.sent+k.failed)/k.total*100}%`,transition:"width 0.3s ease"}})})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem"},children:[t.jsx("button",{onClick:o,disabled:c,style:{background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"10px",color:"var(--text-muted)",fontSize:"0.82rem",padding:"0.5rem 1.25rem",cursor:"pointer"},children:"Cancelar"}),t.jsx("button",{className:"btn btn-primary",onClick:M,disabled:c||h||!l.trim()||!n.trim()||R===0,style:{fontSize:"0.82rem",padding:"0.5rem 1.25rem",display:"flex",alignItems:"center",gap:"0.4rem",opacity:c||!l.trim()||!n.trim()||R===0?.6:1},children:c?"⏳ Enviando...":`📧 Enviar para ${R} usuários`})]})]})})}const aa="https://behonest.com.br",it="#edb125";function Nn({stores:s}){const[e,r]=x.useState(null),[o,l]=x.useState(null),[i,n]=x.useState(!1),[m,d]=x.useState(!1),[u,p]=x.useState(""),[y,c]=x.useState(!1),g=x.useCallback(()=>({Authorization:`Bearer ${le()}`,"Content-Type":"application/json"}),[]),h=x.useCallback(async v=>{if(e===v){r(null),l(null);return}r(v),l(null),n(!0);try{const k=await fetch(`${aa}/api/stores/${v}/users-count`,{headers:g()});if(k.ok){const A=await k.json();l(A.count??A.unique_users??0)}}catch(k){console.error("Error fetching user count:",k)}finally{n(!1)}},[e,g]),f=x.useCallback(async()=>{if(e){d(!0);try{const v=await fetch(`${aa}/api/admin/contact-info/export?store=${e}`,{headers:g()});if(v.ok){const k=await v.blob(),A=window.URL.createObjectURL(k),C=document.createElement("a");C.href=A,C.download=`contatos_${e}.csv`,document.body.appendChild(C),C.click(),C.remove(),window.URL.revokeObjectURL(A)}}catch(v){console.error("Error downloading CSV:",v)}finally{d(!1)}}},[e,g]),$=v=>v.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim(),S=s.filter(v=>{if(!u.trim())return!0;const k=$(u);return $(v.name||"").includes(k)||$(v.unique_id||"").includes(k)||$(v.city||"").includes(k)}),z=v=>({padding:"0.75rem 1rem",borderRadius:"12px",cursor:"pointer",border:`1px solid ${v?it+"60":"rgba(255,255,255,0.08)"}`,background:v?`${it}08`:"rgba(255,255,255,0.02)",display:"flex",alignItems:"center",gap:"0.75rem",transition:"border-color 0.2s, background 0.2s"});return t.jsxs("div",{children:[t.jsxs("div",{style:{marginBottom:"1rem"},children:[t.jsx("h3",{style:{margin:0,color:"var(--text-primary)",fontSize:"1rem"},children:"📋 Contact Info"}),t.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.82rem",color:"var(--text-muted)"},children:"Selecione uma loja para ver o número de usuários e baixar os contatos."})]}),t.jsxs("div",{className:"search-input-wrap",style:{width:"100%",marginBottom:"0.75rem"},children:[t.jsx("input",{type:"text",placeholder:"Buscar loja por nome, cidade ou ID…",value:u,onChange:v=>p(v.target.value),className:"admin-input search-input",style:{width:"100%",padding:"0.6rem 0.85rem",borderRadius:"10px",fontSize:"0.85rem"}}),u&&t.jsx("button",{type:"button",className:"search-clear","aria-label":"Limpar busca",onClick:()=>p(""),children:"✕"})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.4rem",maxHeight:"400px",overflowY:"auto"},children:S.length===0?t.jsx("p",{style:{textAlign:"center",color:"var(--text-muted)",padding:"2rem"},children:u?`Nenhuma loja corresponde a "${u}"`:"Nenhuma loja disponível"}):S.map(v=>{const k=v.unique_id,A=e===k;return t.jsxs("div",{onClick:()=>h(k),style:z(A),children:[t.jsx("span",{style:{fontSize:"1.1rem"},children:A?"☑️":"⬜"}),t.jsxs("span",{style:{flex:1,color:"var(--text-primary)",fontSize:"0.85rem",fontWeight:A?600:400},children:["🏪 ",v.name]}),A&&t.jsx("span",{style:{fontSize:"0.75rem",padding:"0.15rem 0.6rem",borderRadius:"20px",fontWeight:700,background:`${it}18`,color:it},children:i?"...":`👥 ${o??0} usuários`})]},k)})}),e&&o!==null&&!i&&t.jsxs("div",{style:{marginTop:"1.25rem",padding:"1rem",borderRadius:"12px",background:`${it}06`,border:`1px solid ${it}30`,display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:"0.75rem"},children:[t.jsxs("div",{children:[t.jsx("p",{style:{margin:0,fontSize:"0.88rem",fontWeight:600,color:"var(--text-primary)"},children:s.find(v=>v.unique_id===e)?.name}),t.jsxs("p",{style:{margin:"0.15rem 0 0",fontSize:"0.78rem",color:"var(--text-muted)"},children:[o," usuário",o!==1?"s":""," encontrado",o!==1?"s":""]})]}),t.jsx("button",{className:"btn btn-primary",onClick:f,disabled:m||o===0,style:{fontSize:"0.82rem",padding:"0.5rem 1.25rem",display:"flex",alignItems:"center",gap:"0.4rem"},children:m?"⏳ Baixando...":"📥 Download CSV"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>c(!0),disabled:o===0,style:{fontSize:"0.82rem",padding:"0.5rem 1.25rem",display:"flex",alignItems:"center",gap:"0.4rem",background:"rgba(237,177,37,0.12)",border:`1px solid ${it}50`,color:it,borderRadius:"10px",cursor:o===0?"not-allowed":"pointer",opacity:o===0?.5:1},children:"📧 Enviar Email"})]}),y&&e&&o!==null&&t.jsx(Tn,{storeId:e,storeName:s.find(v=>v.unique_id===e)?.name||e,userCount:o,onClose:()=>c(!1)})]})}
18function En(){const s=re.c(15),[e,r]=x.useState(null),[o,l]=x.useState(!1);let i;s[0]===Symbol.for("react.memo_cache_sentinel")?(i=z=>new Promise(v=>{r({...z,resolve:v})}),s[0]=i):i=s[0];const n=i;let m;s[1]!==e?(m=()=>{e&&(l(!0),e.resolve(!0),r(null),l(!1))},s[1]=e,s[2]=m):m=s[2];const d=m;let u;s[3]!==e?(u=()=>{e&&(e.resolve(!1),r(null))},s[3]=e,s[4]=u):u=s[4];const p=u,y=!!e,c=e?.title||"",g=e?.message||"",h=e?.confirmLabel,f=e?.cancelLabel,$=e?.variant;let S;return s[5]!==o||s[6]!==p||s[7]!==d||s[8]!==y||s[9]!==c||s[10]!==g||s[11]!==h||s[12]!==f||s[13]!==$?(S={confirm:n,dialog:t.jsx(Ca,{isOpen:y,title:c,message:g,confirmLabel:h,cancelLabel:f,variant:$,busy:o,onConfirm:d,onCancel:p})},s[5]=o,s[6]=p,s[7]=d,s[8]=y,s[9]=c,s[10]=g,s[11]=h,s[12]=f,s[13]=$,s[14]=S):S=s[14],S}const tr="https://behonest.com.br",ct="#edb125";function Ln(){const[s,e]=x.useState([]),[r,o]=x.useState(!0),[l,i]=x.useState(!1),[n,m]=x.useState(null),[d,u]=x.useState(null),[p,y]=x.useState(""),[c,g]=x.useState(""),[h,f]=x.useState(""),[$,S]=x.useState(""),[z,v]=x.useState(""),{confirm:k,dialog:A}=En(),C=x.useCallback(()=>({Authorization:`Bearer ${le()}`,"Content-Type":"application/json"}),[]),N=x.useCallback(async()=>{try{const R=await fetch(`${tr}/api/admin/redirects`,{headers:C()});if(R.ok){const O=await R.json();e(Array.isArray(O)?O:[])}}catch(R){console.error("Error fetching redirect links:",R)}finally{o(!1)}},[C]);x.useEffect(()=>{N()},[N]);const W=async()=>{if(!p.trim()){S("URL de destino é obrigatória");return}S(""),i(!0);try{const R=await fetch(`${tr}/api/admin/redirects`,{method:"POST",headers:C(),body:JSON.stringify({destination_url:p.trim(),slug:c.trim()||void 0,label:h.trim()||void 0})}),O=await R.json();R.ok?(y(""),g(""),f(""),N()):S(O.error||"Erro ao criar link")}catch(R){console.error("Error creating redirect:",R),S("Erro de conexão")}finally{i(!1)}},T=async R=>{if(await k({title:"Remover link",message:"Remover este link e todos os registros de visita? Esta ação não pode ser desfeita.",confirmLabel:"Remover",variant:"danger"}))try{(await fetch(`${tr}/api/admin/redirects/${R}`,{method:"DELETE",headers:C()})).ok&&N()}catch(G){console.error("Error deleting redirect:",G)}},B=R=>{const O=`${window.location.origin}/r/${R.slug}`;navigator.clipboard.writeText(O).then(()=>{m(R.id),setTimeout(()=>m(null),2e3)})},w=R=>R?new Date(R).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit"}):"—",D=R=>{const O=`${window.location.origin}/r/${R}`;return`https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=${encodeURIComponent(O)}`},q=R=>{window.open(D(R.slug),"_blank")},P=x.useMemo(()=>{const R=z.trim().toLowerCase();return R?s.filter(O=>O.slug.toLowerCase().includes(R)||O.destination_url.toLowerCase().includes(R)||(O.label||"").toLowerCase().includes(R)):s},[s,z]),L={width:"100%",padding:"0.6rem 0.85rem",borderRadius:"10px",fontSize:"0.85rem",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",color:"var(--text-primary)",outline:"none",fontFamily:"inherit"};return t.jsxs("div",{children:[t.jsxs("div",{style:{marginBottom:"1rem",display:"flex",justifyContent:"space-between",alignItems:"flex-end",gap:"1rem",flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsxs("h3",{style:{margin:0,color:"var(--text-primary)",fontSize:"1rem"},children:["🔗 Redirect Links",t.jsx("span",{className:"text-muted",style:{fontSize:"0.82rem",fontWeight:400,marginLeft:"0.5rem"},children:P.length===s.length?`${s.length}`:`${P.length} de ${s.length}`})]}),t.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.82rem",color:"var(--text-muted)"},children:"Crie links de redirecionamento rastreados. Cada visita registra o IP do visitante."})]}),s.length>0&&t.jsxs("div",{className:"search-input-wrap",children:[t.jsx("input",{type:"text",placeholder:"Buscar slug, destino ou label…",value:z,onChange:R=>v(R.target.value),className:"search-input",style:{...L,minWidth:"260px"}}),z&&t.jsx("button",{type:"button",className:"search-clear","aria-label":"Limpar busca",onClick:()=>v(""),children:"✕"})]})]}),t.jsxs("div",{style:{padding:"1rem",borderRadius:"12px",background:`${ct}06`,border:`1px solid ${ct}25`,marginBottom:"1.25rem",display:"flex",flexDirection:"column",gap:"0.6rem"},children:[t.jsx("div",{style:{fontWeight:600,fontSize:"0.88rem",color:"var(--text-primary)",marginBottom:"0.25rem"},children:"➕ Novo Link"}),t.jsx("input",{type:"url",placeholder:"URL de destino (ex: https://exemplo.com/pagina)",value:p,onChange:R=>y(R.target.value),style:L,id:"redirect-dest-url"}),t.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[t.jsx("input",{type:"text",placeholder:"Slug personalizado (opcional)",value:c,onChange:R=>g(R.target.value.replace(/[^a-zA-Z0-9-_]/g,"").toLowerCase()),style:{...L,flex:1},id:"redirect-slug"}),t.jsx("input",{type:"text",placeholder:"Label (opcional)",value:h,onChange:R=>f(R.target.value),style:{...L,flex:1},id:"redirect-label"})]}),$&&t.jsxs("p",{style:{margin:0,fontSize:"0.78rem",color:"#dc3545"},children:["⚠️ ",$]}),t.jsx("button",{className:"btn btn-primary",onClick:W,disabled:l,style:{fontSize:"0.82rem",padding:"0.5rem 1.25rem",alignSelf:"flex-start",display:"flex",alignItems:"center",gap:"0.4rem"},id:"redirect-create-btn",children:l?"⏳ Criando...":"🔗 Criar Link"})]}),r?t.jsx("div",{style:{padding:"0.5rem"},children:[1,2,3,4].map(R=>t.jsx("div",{className:"skeleton",style:{height:"52px",borderRadius:"12px",marginBottom:"0.5rem"}},R))}):s.length===0?t.jsx(Et,{icon:"🔗",title:"Nenhum link criado ainda",subtitle:"Use o formulário acima para criar seu primeiro link rastreado."}):P.length===0?t.jsx(Et,{icon:"🔍",title:"Nenhum link corresponde à busca",subtitle:`Nada corresponde a "${z}". Limpe a busca ou tente outro termo.`}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",maxHeight:"400px",overflowY:"auto"},children:P.map(R=>t.jsxs("div",{style:{padding:"0.75rem 1rem",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.08)",background:"rgba(255,255,255,0.02)",display:"flex",alignItems:"center",gap:"0.75rem",flexWrap:"wrap"},children:[t.jsxs("span",{style:{fontSize:"0.8rem",fontWeight:700,fontFamily:"'Poppins', monospace",color:ct,background:`${ct}15`,padding:"0.2rem 0.6rem",borderRadius:"6px",whiteSpace:"nowrap"},children:["/r/",R.slug]}),t.jsxs("div",{style:{flex:1,minWidth:"150px"},children:[R.label&&t.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--text-primary)"},children:R.label}),t.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"300px"},children:["→ ",R.destination_url]})]}),t.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"center",flexShrink:0},children:[t.jsxs("span",{style:{fontSize:"0.75rem",padding:"0.15rem 0.6rem",borderRadius:"20px",fontWeight:700,background:`${ct}18`,color:ct,whiteSpace:"nowrap"},children:["👤 ",R.unique_ips," IP",R.unique_ips!==1?"s":""]}),t.jsxs("span",{style:{fontSize:"0.72rem",color:"var(--text-muted)",whiteSpace:"nowrap"},children:[R.total_visits," visita",R.total_visits!==1?"s":""]}),t.jsx("span",{style:{fontSize:"0.72rem",color:"var(--text-muted)",whiteSpace:"nowrap"},children:w(R.created_at)}),t.jsx("button",{onClick:()=>B(R),title:"Copiar link",style:{background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",color:n===R.id?"#28a745":"var(--text-muted)",borderRadius:"6px",padding:"0.3rem 0.5rem",fontSize:"0.75rem",cursor:"pointer",transition:"all 0.15s"},children:n===R.id?"✓":"📋"}),t.jsx("button",{onClick:()=>u(R),title:"Gerar QR Code",style:{background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",color:"var(--text-muted)",borderRadius:"6px",padding:"0.3rem 0.5rem",fontSize:"0.75rem",cursor:"pointer",transition:"all 0.15s"},children:"📱"}),t.jsx("button",{onClick:()=>T(R.id),title:"Remover link",style:{background:"rgba(220,53,69,0.08)",border:"1px solid rgba(220,53,69,0.2)",color:"#dc3545",borderRadius:"6px",padding:"0.3rem 0.5rem",fontSize:"0.75rem",cursor:"pointer",transition:"all 0.15s"},children:"🗑️"})]})]},R.id))}),d&&t.jsx("div",{onClick:()=>u(null),style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,backdropFilter:"blur(4px)"},children:t.jsxs("div",{onClick:R=>R.stopPropagation(),style:{background:"var(--card-bg, #1a1d2e)",borderRadius:"16px",padding:"1.5rem",border:`1px solid ${ct}30`,textAlign:"center",maxWidth:"340px",width:"90%"},children:[t.jsx("h4",{style:{margin:"0 0 0.25rem",color:"var(--text-primary)",fontSize:"0.95rem"},children:"QR Code"}),t.jsx("p",{style:{margin:"0 0 1rem",fontSize:"0.78rem",color:"var(--text-muted)"},children:d.label||`/r/${d.slug}`}),t.jsx("img",{src:D(d.slug),alt:`QR Code for /r/${d.slug}`,style:{width:"200px",height:"200px",borderRadius:"8px",background:"#fff",padding:"8px",marginBottom:"1rem"}}),t.jsxs("p",{style:{margin:"0 0 1rem",fontSize:"0.72rem",color:ct,fontWeight:600,wordBreak:"break-all"},children:[window.location.origin,"/r/",d.slug]}),t.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"center"},children:[t.jsx("button",{className:"btn btn-primary",onClick:()=>q(d),style:{fontSize:"0.8rem",padding:"0.45rem 1rem",display:"flex",alignItems:"center",gap:"0.3rem"},children:"📥 Baixar PNG"}),t.jsx("button",{onClick:()=>u(null),style:{fontSize:"0.8rem",padding:"0.45rem 1rem",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.15)",color:"var(--text-muted)",borderRadius:"8px",cursor:"pointer"},children:"Fechar"})]})]})}),A]})}function Bn(s){return s==="/system"?"/":s.startsWith("/system/")?s.slice(7):s}const na={"/":"Hub do Sistema","/login":"Login","/forgot-password":"Esqueci a Senha","/reset-password":"Redefinir Senha","/set-password":"Definir Senha","/main":"Dashboard","/main/map":"Dashboard: Mapa de Lojas","/admin":"Admin Panel","/search":"Busca","/products":"Relatórios","/franquia":"Franquia","/swagger":"API Docs","/mix":"Mix de Produtos","/mix/combos":"Mix: Combos","/mix/bulk":"Mix: Edição em Massa","/clients":"Clientes","/pedidos":"Pedidos","/prospeccao":"Prospecção","/ruptura":"Ruptura","/relatorio-semanal":"Relatórios (legado)","/relatorios":"Relatórios","/reconciliacao":"Reconciliação","/promotions":"Promoções","/tools":"Ferramentas","/ferramentas/itemprices":"Ferramentas: Preços de Itens","/ferramentas/cdromie":"Ferramentas: CD ROMIE","/ferramentas/missed-sales":"Ferramentas: Vendas Perdidas","/ferramentas/product-sync":"Ferramentas: Sync de Produtos","/ferramentas/planograma":"Ferramentas: Planograma","/ferramentas/comparacao-produtos":"Ferramentas: Comparação de Produtos","/simulador-detalhado":"Simulador Detalhado","/fornecedor":"Fornecedor: Dashboard","/privacy":"Privacidade","/terms":"Termos","/system/logistica":"🚚 LOG: Logística","/system/bi-opr":"📊 BI-OPR: Business Intelligence","/system/painel":"🛡️ PAI: Painel Administrativo","/system/content-generator":"✍️ CGN: Content Generator","/system/comercial":"📋 CRM: Comercial","/system/marketing":"📢 Marketing: Dashboard","/system/marketing/instagram":"📢 Marketing: Instagram","/system/marketing/blog":"📢 Marketing: Blog","/system/marketing/youtube":"📢 Marketing: YouTube","/system/growth/meta-ads/geral":"🚀 Growth: Meta Ads","/system/growth/meta-ads/funil":"🚀 Growth: Funil","/system/growth/meta-ads/meio-funil":"🚀 Growth: Meio Funil","/system/growth/meta-ads/criativos":"🚀 Growth: Criativos","/system/growth/meta-ads/metas":"🚀 Growth: Metas","/system/growth/google-ads/geral":"🚀 Growth: Google Ads","/system/growth/crm":"🚀 Growth: CRM"},In=[{test:/^\/r\/[^/]+$/,label:"Redirect Link"},{test:/^\/users\/[^/]+$/,label:"Detalhe de Usuário"},{test:/^\/store\/[^/]+\/user\/[^/]+$/,label:"Usuário em Loja"},{test:/^\/[^/]+\/store\/[^/]+\/insights$/,label:"Loja: Insights"},{test:/^\/[^/]+\/store\/[^/]+$/,label:"Loja: Detalhe"},{test:/^\/clients\/cluster\/[^/]+\/[^/]+$/,label:"Clientes: Cluster"},{test:/^\/mix\/item\/[^/]+$/,label:"Mix: Item"},{test:/^\/promotions\/resultados\/[^/]+$/,label:"Promoções: Resultado"},{test:/^\/fornecedor\/item\/[^/]+$/,label:"Fornecedor: Item"}];function we(s){for(const e of[s,Bn(s)]){if(na[e])return na[e];for(const{test:r,label:o}of In)if(r.test(e))return o}return s}function Wn(s){return we(s)!==s}const oa=[{key:"page_views",label:"Views",cor:"#3b82f6"},{key:"clicks",label:"Cliques",cor:"#a855f7"},{key:"total_time_ms",label:"Tempo",cor:"#edb125"},{key:"unique_users",label:"Usuários",cor:"#22c55e"}],Pn=12;function Dn(s){if(!s||s<=0)return"—";const e=Math.floor(s/1e3);if(e<60)return`${e}s`;const r=Math.floor(e/3600),o=Math.floor(e%3600/60);return r>0?`${r}h ${o}min`:`${o}min`}function cs(s,e){return s[e]||0}
18function la(s,e){return e==="total_time_ms"?Dn(s):s.toLocaleString("pt-BR")}function $a(s,e){const o=`${s.real_path||s.path} ${s.label||""} ${we(s.real_path||s.path)}`.toLowerCase().includes(e),l=s.children.map(i=>$a(i,e)).filter(i=>i!==null);return!o&&l.length===0?null:{...s,children:o?s.children:l}}function Mn(s){const r=s.split("/").filter(Boolean).slice(2);return r.length?`/system/${r.join("/")}`:"/system"}function or(s,e=[]){return e.push(s.path),s.children.forEach(r=>or(r,e)),e}function Fn(s){const e=re.c(48),{root:r,busca:o,onDetalhar:l}=s,[i,n]=x.useState("page_views");let m;e[0]!==r?.children?(m=()=>new Set(["/system",...(r?.children||[]).map(Un)]),e[0]=r?.children,e[1]=m):m=e[1];const[d,u]=x.useState(m),[p,y]=x.useState(On);let c;e[2]!==o?(c=o.trim().toLowerCase(),e[2]=o,e[3]=c):c=e[3];const g=c;let h;e:{if(!r){h=null;break e}let J;e[4]!==r||e[5]!==g?(J=g?$a(r,g):r,e[4]=r,e[5]=g,e[6]=J):J=e[6],h=J}const f=h;let $;e:{if(!g||!f){$=d;break e}let J;e[7]!==f?(J=new Set(or(f)),e[7]=f,e[8]=J):J=e[8],$=J}const S=$;let z;e[9]!==i?(z=oa.find(J=>J.key===i)?.cor||"#3b82f6",e[9]=i,e[10]=z):z=e[10];const v=z;let k;e[11]!==f||e[12]!==i?(k=f?cs(f,i):0,e[11]=f,e[12]=i,e[13]=k):k=e[13];const A=k;let C;e[14]===Symbol.for("react.memo_cache_sentinel")?(C=J=>u(U=>{const K=new Set(U);return K.has(J)?K.delete(J):K.add(J),K}),e[14]=C):C=e[14];const N=C;if(!f){let J;e[15]===Symbol.for("react.memo_cache_sentinel")?(J={...ia,textAlign:"center",color:"var(--text-muted)"},e[15]=J):J=e[15];const U=r?"Nenhuma página corresponde à busca.":"Nenhum dado de uso encontrado para o período selecionado.";let K;return e[16]!==U?(K=t.jsx("div",{style:J,children:U}),e[16]=U,e[17]=K):K=e[17],K}let W,T,B;e[18]===Symbol.for("react.memo_cache_sentinel")?(T={display:"flex",flexDirection:"column",gap:"0.75rem"},B={display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},W=t.jsx("span",{style:{fontSize:"12px",color:"var(--text-muted)"},children:"Acumular por:"}),e[18]=W,e[19]=T,e[20]=B):(W=e[18],T=e[19],B=e[20]);let w;e[21]!==i?(w=oa.map(J=>t.jsx("button",{onClick:()=>n(J.key),style:sr(i===J.key,J.cor),children:J.label},J.key)),e[21]=i,e[22]=w):w=e[22];let D,q;e[23]===Symbol.for("react.memo_cache_sentinel")?(D=t.jsx("div",{style:{flex:1}}),q=sr(!1,"var(--text-muted)"),e[23]=D,e[24]=q):(D=e[23],q=e[24]);let P;e[25]!==f?(P=t.jsx("button",{style:q,onClick:()=>u(new Set(or(f))),children:"⤢ Expandir tudo"}),e[25]=f,e[26]=P):P=e[26];let L;e[27]===Symbol.for("react.memo_cache_sentinel")?(L=sr(!1,"var(--text-muted)"),e[27]=L):L=e[27];let R;e[28]!==f.children?(R=t.jsx("button",{style:L,onClick:()=>u(new Set(["/system",...f.children.map(qn)])),children:"⤡ Recolher"}),e[28]=f.children,e[29]=R):R=e[29];let O;e[30]!==w||e[31]!==P||e[32]!==R?(O=t.jsxs("div",{style:B,children:[W,w,D,P,R]}),e[30]=w,e[31]=P,e[32]=R,e[33]=O):O=e[33];let G;e[34]===Symbol.for("react.memo_cache_sentinel")?(G={fontSize:"11px",color:"var(--text-muted)"},e[34]=G):G=e[34];let E,M;e[35]===Symbol.for("react.memo_cache_sentinel")?(E=t.jsxs("div",{style:G,children:["Cada nó soma o uso de tudo que está abaixo dele — a fatia é sobre o total do período. Caminho gravado sem o prefixo ",t.jsx("code",{children:"/system"})," (o hub roda com basename) entra no mesmo ramo."]}),M={...ia,padding:"0.5rem 0.75rem"},e[35]=E,e[36]=M):(E=e[35],M=e[36]);let H;e[37]!==S||e[38]!==f||e[39]!==v||e[40]!==i||e[41]!==l||e[42]!==A||e[43]!==p?(H=t.jsx("div",{style:M,children:t.jsx(za,{no:f,metrica:i,cor:v,total:A,totalPai:A,abertos:S,alternar:N,verTudo:p,setVerTudo:y,onDetalhar:l})}),e[37]=S,e[38]=f,e[39]=v,e[40]=i,e[41]=l,e[42]=A,e[43]=p,e[44]=H):H=e[44];let X;return e[45]!==O||e[46]!==H?(X=t.jsxs("div",{style:T,children:[O,E,H]}),e[45]=O,e[46]=H,e[47]=X):X=e[47],X}function qn(s){return s.path}function On(){return new Set}function Un(s){return s.path}function za(s){const e=re.c(105),{no:r,metrica:o,cor:l,total:i,totalPai:n,abertos:m,alternar:d,verTudo:u,setVerTudo:p,onDetalhar:y}=s;let c;e[0]!==m||e[1]!==r.path?(c=m.has(r.path),e[0]=m,e[1]=r.path,e[2]=c):c=e[2];const g=c,h=r.children.length>0;let f;if(e[3]!==g||e[4]!==m||e[5]!==d||e[6]!==l||e[7]!==o||e[8]!==r||e[9]!==y||e[10]!==p||e[11]!==h||e[12]!==i||e[13]!==n||e[14]!==u){const $=cs(r,o),S=i>0?$/i*100:0,z=n>0?$/n*100:0,v=!!r.real_path&&(r.self_page_views>
180||r.self_clicks>0),k=r.path==="/system",A=r.depth===2;let C;e[16]!==r.label||e[17]!==r.real_path||e[18]!==r.segment?(C=r.label||(r.real_path&&Wn(r.real_path)?we(r.real_path):r.segment),e[16]=r.label,e[17]=r.real_path,e[18]=r.segment,e[19]=C):C=e[19];const N=C,W=r.real_path;let T;e[20]!==o?(T=($e,at)=>cs(at,o)-cs($e,o),e[20]=o,e[21]=T):T=e[21];const B=[...r.children].sort(T),D=u.has(r.path)?B:B.slice(0,Pn),q=B.length-D.length;let P;e[22]!==d||e[23]!==r.path||e[24]!==h?(P=()=>h&&d(r.path),e[22]=d,e[23]=r.path,e[24]=h,e[25]=P):P=e[25];const L=h?"pointer":"default",R=k||A?"rgba(255,255,255,0.04)":"transparent";let O;e[26]!==L||e[27]!==R?(O={display:"flex",alignItems:"center",gap:"0.6rem",padding:"7px 8px",borderRadius:"8px",cursor:L,background:R,transition:"background 0.15s"},e[26]=L,e[27]=R,e[28]=O):O=e[28];let G;e[29]!==A||e[30]!==k?(G=$e=>$e.currentTarget.style.background=k||A?"rgba(255,255,255,0.04)":"transparent",e[29]=A,e[30]=k,e[31]=G):G=e[31];let E;e[32]===Symbol.for("react.memo_cache_sentinel")?(E={width:"14px",flexShrink:0,color:"var(--text-muted)",fontSize:"10px"},e[32]=E):E=e[32];const M=h?g?"▼":"▶":"";let H;e[33]!==M?(H=t.jsx("span",{style:E,children:M}),e[33]=M,e[34]=H):H=e[34];let X,J;e[35]===Symbol.for("react.memo_cache_sentinel")?(X={flex:1,minWidth:0},J={display:"flex",alignItems:"baseline",gap:"0.5rem",flexWrap:"wrap"},e[35]=X,e[36]=J):(X=e[35],J=e[36]);const U=k||A?700:600,K=k||A?"14px":"13px",Y=v||r.depth===0?"var(--text-primary)":"var(--text-muted)";let Q;e[37]!==U||e[38]!==K||e[39]!==Y?(Q={fontWeight:U,fontSize:K,color:Y},e[37]=U,e[38]=K,e[39]=Y,e[40]=Q):Q=e[40];let me;e[41]!==N||e[42]!==Q?(me=t.jsx("span",{style:Q,children:N}),e[41]=N,e[42]=Q,e[43]=me):me=e[43];let ue;e[44]!==W||e[45]!==k?(ue=W&&!k&&t.jsx("span",{style:{fontSize:"11px",color:"var(--text-muted)"},children:W}),e[44]=W,e[45]=k,e[46]=ue):ue=e[46];let de;e[47]!==r.pages||e[48]!==h?(de=h&&t.jsxs("span",{style:{fontSize:"11px",color:"var(--text-muted)"},children:[r.pages," ",r.pages===1?"página":"páginas"]}),e[47]=r.pages,e[48]=h,e[49]=de):de=e[49];let je;e[50]!==o||e[51]!==r||e[52]!==h||e[53]!==v?(je=h&&v&&t.jsxs("span",{style:{fontSize:"11px",color:"var(--text-muted)"},children:["· própria: ",la(Hn(r,o),o)]}),e[50]=o,e[51]=r,e[52]=h,e[53]=v,e[54]=je):je=e[54];let fe;e[55]!==me||e[56]!==ue||e[57]!==de||e[58]!==je?(fe=t.jsxs("div",{style:J,children:[me,ue,de,je]}),e[55]=me,e[56]=ue,e[57]=de,e[58]=je,e[59]=fe):fe=e[59];let _e;e[60]===Symbol.for("react.memo_cache_sentinel")?(_e={maxWidth:"420px",marginTop:"3px"},e[60]=_e):_e=e[60];let ke;e[61]!==l||e[62]!==S?(ke=t.jsx("div",{style:_e,children:t.jsx(Vn,{pct:S,cor:l})}),e[61]=l,e[62]=S,e[63]=ke):ke=e[63];let Be;e[64]!==fe||e[65]!==ke?(Be=t.jsxs("div",{style:X,children:[fe,ke]}),e[64]=fe,e[65]=ke,e[66]=Be):Be=e[66];let te,ge;e[67]===Symbol.for("react.memo_cache_sentinel")?(te={textAlign:"right",minWidth:"120px",flexShrink:0},ge={fontWeight:700,fontSize:"13px"},e[67]=te,e[68]=ge):(te=e[67],ge=e[68]);const Re=la($,o);let xe;e[69]!==Re?(xe=t.jsx("div",{style:ge,children:Re}),e[69]=Re,e[70]=xe):xe=e[70];let ye;e[71]===Symbol.for("react.memo_cache_sentinel")?(ye={fontSize:"10px",color:"var(--text-muted)"},e[71]=ye):ye=e[71];let pe;e[72]!==S?(pe=S.toFixed(1),e[72]=S,e[73]=pe):pe=e[73];let Ce;e[74]!==k||e[75]!==z?(Ce=!k&&` · ${z.toFixed(0)}% do pai`,e[74]=k,e[75]=z,e[76]=Ce):Ce=e[76];let De;e[77]!==pe||e[78]!==Ce?(De=t.jsxs("div",{style:ye,children:[pe,"% do total",Ce]}),e[77]=pe,e[78]=Ce,e[79]=De):De=e[79];let Me;e[80]!==xe||e[81]!==De?(Me=t.jsxs("div",{style:te,children:[xe,De]}),e[80]=xe,e[81]=De,e[82]=Me):Me=e[82];let rt;e[83]===Symbol.for("react.memo_cache_sentinel")?(rt={minWidth:"70px",textAlign:"right",flexShrink:0,fontSize:"11px",color:"var(--text-muted)"},e[83]=rt):rt=e[83];const Ve=r.unique_users===1?"usuário":"usuários";let Je;e[84]!==r.unique_users||e[85]!==Ve?(Je=t.jsxs("div",{style:rt,children:[r.unique_users," ",Ve]}),e[84]=r.unique_users,e[85]=Ve,e[86]=Je):Je=e[86];let Ke;e[87]===Symbol.for("react.memo_cache_sentinel")?(Ke={width:"90px",flexShrink:0,textAlign:"right"},e[87]=Ke):Ke=e[87];let Ge;e[88]!==r.path||e[89]!==r.real_path||e[90]!==y||e[91]!==h||e[92]!==v?(Ge=(v||h)&&t.jsx("button",{onClick:$e=>{$e.stopPropagation();const at=r.real_path||Mn(r.path);y(at,h?"ramo":"pagina")},style:{padding:"3px 10px",borderRadius:"6px",fontSize:"11px",cursor:"pointer",border:"1px solid var(--glass-border)",background:"var(--glass-highlight)",color:"var(--text-primary)"},children:"Detalhar →"}),e[88]=r.path,e[89]=r.real_path,e[90]=y,e[91]=h,e[92]=v,e[93]=Ge):Ge=e[93];let Fe;e[94]!==Ge?(Fe=t.jsx("div",{style:Ke,children:Ge}),e[94]=Ge,e[95]=Fe):Fe=e[95];let be;e[96]!==H||e[97]!==Be||e[98]!==Me||e[99]!==Je||e[100]!==Fe||e[101]!==P||e[102]!==O||e[103]!==G?(be=t.jsxs("div",{onClick:P,style:O,onMouseEnter:Gn,onMouseLeave:G,children:[H,Be,Me,Je,Fe]}),e[96]=H,e[97]=Be,e[98]=Me,e[99]=Je,e[100]=Fe,e[101]=P,e[102]=O,e[103]=G,e[104]=be):be=e[104],f=t.jsxs("div",{children:[be,g&&h&&t.jsxs("div",{style:{marginLeft:"18px",borderLeft:"1px solid var(--glass-border)",paddingLeft:"8px"},children:[D.map($e=>t.jsx(za,{no:$e,metrica:o,cor:l,total:i,totalPai:$,abertos:m,alternar:d,verTudo:u,setVerTudo:p,onDetalhar:y},$e.path)),q>0&&t.jsxs("button",{onClick:()=>{const $e=new Set(u);$e.add(r.path),p($e)},style:{margin:"4px 0 8px 22px",padding:"3px 10px",borderRadius:"6px",fontSize:"11px",cursor:"pointer",border:"1px dashed var(--glass-border)",background:"transparent",color:"var(--text-muted)"},children:["+ ver mais ",q]})]})]}),e[3]=g,e[4]=m,e[5]=d,e[6]=l,e[7]=o,e[8]=r,e[9]=y,e[10]=p,e[11]=h,e[12]=i,e[13]=n,e[14]=u,e[15]=f}else f=e[15];return f}function Gn(s){return s.currentTarget.style.background="rgba(255,255,255,0.05)"}function Hn(s,e){switch(e){case"page_views":return s.self_page_views;case"clicks":return s.self_clicks;case"total_time_ms":return s.self_time_ms;case"unique_users":return s.self_unique_users}}function Vn(s){const e=re.c(4),{pct:r,cor:o}=s,l=Math.max(1.5,Math.min(100,r));let i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={height:"4px",background:"rgba(255,255,255,0.05)",borderRadius:"999px",overflow:"hidden"},e[0]=i):i=e[0];const n=`${l}%`,m=`linear-gradient(90deg, ${o}aa, ${o})`;let d;return e[1]!==n||e[2]!==m?(d=t.jsx("div",{style:i,children:t.jsx("div",{style:{height:"100%",width:n,borderRadius:"999px",background:m,transition:"width 0.4s cubic-bezier(0.22, 1, 0.36, 1)"}})}),e[1]=n,e[2]=m,e[3]=d):d=e[3],d}const ia={background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)",padding:"1.5rem"},sr=(s,e)=>({padding:"0.35rem 0.8rem",borderRadius:"999px",cursor:"pointer",fontSize:"12px",border:`1px solid ${s?e:"var(--glass-border)"}`,background:s?`${e}22`:"rgba(255,255,255,0.03)",color:s?e:"var(--text-primary)",fontWeight:s?700:400,transition:"all 0.2s"}),ca=[{key:"page_views",label:"Views",cor:"#3b82f6"},{key:"clicks",label:"Cliques",cor:"#a855f7"},{key:"total_time_ms",label:"Tempo",cor:"#edb125"},{key:"unique_users",label:"Usuários",cor:"#22c55e"}];function ms(s){if(!s||s<=0)return"—";const e=Math.floor(s/1e3);if(e<60)return`${e}s`;const r=Math.floor(e/3600),o=Math.floor(e%3600/60);return r>0?`${r}h ${o}min`:`${o}min`}
18function Jn(s,e){return e==="total_time_ms"?ms(s):s.toLocaleString("pt-BR")}function Kn(s,e){const r=new Date(s),o=r.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});if(e==="mês"){const n=r.toLocaleDateString("pt-BR",{month:"long",year:"numeric"});return n.charAt(0).toUpperCase()+n.slice(1)}if(e==="dia")return`${r.toLocaleDateString("pt-BR",{weekday:"short"}).replace(".","")}, ${o}`;const l=e==="2 dias"?1:e==="semana"?6:13,i=new Date(r.getTime()+l*864e5);return`${o} – ${i.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}`}function Yn(s){const e=re.c(70),{dados:r,carregando:o}=s,[l,i]=x.useState("page_views"),[n,m]=x.useState(eo);if(o){let U;return e[0]===Symbol.for("react.memo_cache_sentinel")?(U=t.jsx("div",{style:{...ns,color:"var(--text-muted)"},children:"Carregando linha do tempo…"}),e[0]=U):U=e[0],U}if(!r||r.buckets.length===0){let U;return e[1]===Symbol.for("react.memo_cache_sentinel")?(U=t.jsx("div",{style:{...ns,color:"var(--text-muted)",textAlign:"center"},children:"Sem atividade registrada nesta página no período."}),e[1]=U):U=e[1],U}let d;e[2]!==l?(d=ca.find(U=>U.key===l)?.cor||"#3b82f6",e[2]=l,e[3]=d):d=e[3];const u=d;let p;if(e[4]!==r.buckets||e[5]!==l){let U;e[7]!==l?(U=K=>K[l]||0,e[7]=l,e[8]=U):U=e[8],p=Math.max(...r.buckets.map(U),1),e[4]=r.buckets,e[5]=l,e[6]=p}else p=e[6];const y=p;let c;e[9]===Symbol.for("react.memo_cache_sentinel")?(c=U=>m(K=>{const Y=new Set(K);return Y.has(U)?Y.delete(U):Y.add(U),Y}),e[9]=c):c=e[9];const g=c;let h,f,$;e[10]===Symbol.for("react.memo_cache_sentinel")?(h={display:"flex",flexDirection:"column",gap:"0.75rem"},f={display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},$={fontSize:"12px",color:"var(--text-muted)"},e[10]=h,e[11]=f,e[12]=$):(h=e[10],f=e[11],$=e[12]);let S;e[13]===Symbol.for("react.memo_cache_sentinel")?(S={color:"var(--text-primary)"},e[13]=S):S=e[13];let z;e[14]!==r.bucket_label?(z=t.jsx("strong",{style:S,children:r.bucket_label}),e[14]=r.bucket_label,e[15]=z):z=e[15];const v=r.escopo==="ramo"?"esta página e tudo abaixo dela":"só esta página";let k;e[16]!==z||e[17]!==v?(k=t.jsxs("span",{style:$,children:["Por ",z," ·"," ",v]}),e[16]=z,e[17]=v,e[18]=k):k=e[18];let A;e[19]===Symbol.for("react.memo_cache_sentinel")?(A=t.jsx("div",{style:{flex:1}}),e[19]=A):A=e[19];let C;e[20]!==l?(C=ca.map(U=>t.jsx("button",{onClick:()=>i(U.key),style:to(l===U.key,U.cor),children:U.label},U.key)),e[20]=l,e[21]=C):C=e[21];let N;e[22]!==k||e[23]!==C?(N=t.jsxs("div",{style:f,children:[k,A,C]}),e[22]=k,e[23]=C,e[24]=N):N=e[24];let W;e[25]===Symbol.for("react.memo_cache_sentinel")?(W={display:"flex",gap:"1.25rem",flexWrap:"wrap",...ns,padding:"0.9rem 1.2rem"},e[25]=W):W=e[25];let T;e[26]!==r.total.page_views?(T=r.total.page_views.toLocaleString("pt-BR"),e[26]=r.total.page_views,e[27]=T):T=e[27];let B;e[28]!==T?(B=t.jsx(Ft,{label:"Views",valor:T}),e[28]=T,e[29]=B):B=e[29];let w;e[30]!==r.total.clicks?(w=r.total.clicks.toLocaleString("pt-BR"),e[30]=r.total.clicks,e[31]=w):w=e[31];let D;e[32]!==w?(D=t.jsx(Ft,{label:"Cliques",valor:w}),e[32]=w,e[33]=D):D=e[33];let q;e[34]!==r.total.interactions?(q=r.total.interactions.toLocaleString("pt-BR"),e[34]=r.total.interactions,e[35]=q):q=e[35];let P;e[36]!==q?(P=t.jsx(Ft,{label:"Digitação/envios",valor:q}),e[36]=q,e[37]=P):P=e[37];let L;e[38]!==r.total.total_time_ms?(L=ms(r.total.total_time_ms),e[38]=r.total.total_time_ms,e[39]=L):L=e[39];let R;e[40]!==L?(R=t.jsx(Ft,{label:"Tempo",valor:L}),e[40]=L,e[41]=R):R=e[41];const O=String(r.total.unique_users);let G;e[42]!==O?(G=t.jsx(Ft,{label:"Usuários",valor:O}),e[42]=O,e[43]=G):G=e[43];let E;e[44]!==B||e[45]!==D||e[46]!==P||e[47]!==R||e[48]!==G?(E=t.jsxs("div",{style:W,children:[B,D,P,R,G]}),e[44]=B,e[45]=D,e[46]=P,e[47]=R,e[48]=G,e[49]=E):E=e[49];let M;e[50]===Symbol.for("react.memo_cache_sentinel")?(M={...ns,padding:"0.5rem 0.75rem"},e[50]=M):M=e[50];let H;if(e[51]!==n||e[52]!==u||e[53]!==r.bucket_label||e[54]!==r.buckets||e[55]!==y||e[56]!==l){let U;e[58]!==n||e[59]!==u||e[60]!==r.bucket_label||e[61]!==y||e[62]!==l?(U=K=>{const Y=n.has(K.inicio),Q=K[l]||0,me=Math.max(1.5,Q/y*100);return t.jsxs("div",{children:[t.jsxs("div",{onClick:()=>g(K.inicio),style:{display:"flex",alignItems:"center",gap:"0.7rem",padding:"8px",borderRadius:"8px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:Zn,onMouseLeave:Qn,children:[t.jsx("span",{style:{width:"14px",flexShrink:0,fontSize:"10px",color:"var(--text-muted)"},children:Y?"▼":"▶"}),t.jsx("span",{style:{width:"130px",flexShrink:0,fontSize:"13px",fontWeight:600},children:Kn(K.inicio,r.bucket_label)}),t.jsx("div",{style:{flex:1,minWidth:"80px"},children:t.jsx("div",{style:{height:"8px",background:"rgba(255,255,255,0.05)",borderRadius:"999px",overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${me}%`,borderRadius:"999px",background:`linear-gradient(90deg, ${u}aa, ${u})`,transition:"width 0.4s cubic-bezier(0.22, 1, 0.36, 1)"}})})}),t.jsx("span",{style:{width:"90px",textAlign:"right",fontWeight:700,fontSize:"13px"},children:Jn(Q,l)}),t.jsxs("span",{style:{width:"150px",textAlign:"right",fontSize:"11px",color:"var(--text-muted)"},children:[K.unique_users," ",K.unique_users===1?"usuário":"usuários"," · ",ms(K.total_time_ms)]})]}),Y&&t.jsx("div",{style:{margin:"0 0 10px 30px",borderLeft:"1px solid var(--glass-border)",paddingLeft:"10px"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"12px"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:wt,children:"Usuário"}),t.jsx("th",{style:{...wt,textAlign:"right",width:"70px"},children:"Views"}),t.jsx("th",{style:{...wt,textAlign:"right",width:"70px"},children:"Cliques"}),t.jsx("th",{style:{...wt,textAlign:"right",width:"80px"},children:"Digitação"}),t.jsx("th",{style:{...wt,textAlign:"right",width:"90px"},children:"Tempo"}),t.jsx("th",{style:{...wt,textAlign:"right",width:"80px"},children:"Páginas"})]})}),t.jsx("tbody",{children:K.usuarios.map(Xn)})]})})]},K.inicio)}
18,e[58]=n,e[59]=u,e[60]=r.bucket_label,e[61]=y,e[62]=l,e[63]=U):U=e[63],H=r.buckets.map(U),e[51]=n,e[52]=u,e[53]=r.bucket_label,e[54]=r.buckets,e[55]=y,e[56]=l,e[57]=H}else H=e[57];let X;e[64]!==H?(X=t.jsx("div",{style:M,children:H}),e[64]=H,e[65]=X):X=e[65];let J;return e[66]!==N||e[67]!==E||e[68]!==X?(J=t.jsxs("div",{style:h,children:[N,E,X]}),e[66]=N,e[67]=E,e[68]=X,e[69]=J):J=e[69],J}function Xn(s){return t.jsxs("tr",{children:[t.jsx("td",{style:Ct,children:s.user_name}),t.jsx("td",{style:{...Ct,textAlign:"right",fontWeight:600},children:s.page_views}),t.jsx("td",{style:{...Ct,textAlign:"right"},children:s.clicks}),t.jsx("td",{style:{...Ct,textAlign:"right"},children:s.interactions}),t.jsx("td",{style:{...Ct,textAlign:"right",color:"var(--secondary)"},children:ms(s.total_time_ms)}),t.jsx("td",{style:{...Ct,textAlign:"right",color:"var(--text-muted)"},children:s.pages})]},s.user_id)}function Qn(s){return s.currentTarget.style.background="transparent"}function Zn(s){return s.currentTarget.style.background="rgba(255,255,255,0.05)"}function eo(){return new Set}function Ft(s){const e=re.c(9),{label:r,valor:o}=s;let l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l={fontSize:"11px",color:"var(--text-muted)"},e[0]=l):l=e[0];let i;e[1]!==r?(i=t.jsx("div",{style:l,children:r}),e[1]=r,e[2]=i):i=e[2];let n;e[3]===Symbol.for("react.memo_cache_sentinel")?(n={fontSize:"16px",fontWeight:700},e[3]=n):n=e[3];let m;e[4]!==o?(m=t.jsx("div",{style:n,children:o}),e[4]=o,e[5]=m):m=e[5];let d;return e[6]!==i||e[7]!==m?(d=t.jsxs("div",{children:[i,m]}),e[6]=i,e[7]=m,e[8]=d):d=e[8],d}const ns={background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)",padding:"1.2rem"},wt={textAlign:"left",padding:"6px 8px",fontSize:"11px",fontWeight:700,color:"var(--secondary)",borderBottom:"1px solid rgba(255,255,255,0.1)"},Ct={padding:"5px 8px",borderBottom:"1px solid rgba(255,255,255,0.05)",whiteSpace:"nowrap"},to=(s,e)=>({padding:"0.3rem 0.75rem",borderRadius:"999px",cursor:"pointer",fontSize:"12px",border:`1px solid ${s?e:"var(--glass-border)"}`,background:s?`${e}22`:"rgba(255,255,255,0.03)",color:s?e:"var(--text-primary)",fontWeight:s?700:400,transition:"all 0.2s"}),so={background:"none",border:0,padding:0,margin:0,font:"inherit",color:"inherit",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:"4px"};function ce(s){const e=re.c(19),{column:r,sort:o,children:l,style:i,firstDir:n}=s,m=n===void 0?"desc":n,d=o.key===r,u=d?o.dir==="asc"?"ascending":"descending":"none";let p;e[0]!==i?(p={textAlign:"center",cursor:"pointer",userSelect:"none",...i},e[0]=i,e[1]=p):p=e[1];let y;e[2]!==r||e[3]!==m||e[4]!==o?(y=()=>o.toggle(r,m),e[2]=r,e[3]=m,e[4]=o,e[5]=y):y=e[5];const c=d?1:.35;let g;e[6]!==c?(g={opacity:c,fontSize:"0.85em"},e[6]=c,e[7]=g):g=e[7];const h=d?o.dir==="desc"?"▼":"▲":"↕";let f;e[8]!==g||e[9]!==h?(f=t.jsx("span",{"aria-hidden":"true",style:g,children:h}),e[8]=g,e[9]=h,e[10]=f):f=e[10];let $;e[11]!==l||e[12]!==y||e[13]!==f?($=t.jsxs("button",{type:"button",style:so,onClick:y,children:[l,f]}),e[11]=l,e[12]=y,e[13]=f,e[14]=$):$=e[14];let S;return e[15]!==u||e[16]!==p||e[17]!==$?(S=t.jsx("th",{style:p,"aria-sort":u,children:$}),e[15]=u,e[16]=p,e[17]=$,e[18]=S):S=e[18],S}function os(s){return s==null||s===""}function ro(s,e){return typeof s=="number"&&typeof e=="number"?s-e:String(s).localeCompare(String(e),"pt-BR",{numeric:!0,sensitivity:"base"})}function Rt(s,e,r={}){const o=r[e.key]??(i=>i[e.key]),l=e.dir==="asc"?1:-1;return[...s].sort((i,n)=>{const m=o(i),d=o(n);return os(m)||os(d)?Number(os(m))-Number(os(d)):l*ro(m,d)})}function Tt(s,e){const r=re.c(6),o="desc";let l;r[0]!==o||r[1]!==s?(l={key:s,dir:o},r[0]=o,r[1]=s,r[2]=l):l=r[2];const[i,n]=x.useState(l);let m;r[3]===Symbol.for("react.memo_cache_sentinel")?(m=(p,y)=>{const c=y===void 0?"desc":y;n(g=>g.key===p?{key:p,dir:g.dir==="desc"?"asc":"desc"}:{key:p,dir:c})},r[3]=m):m=r[3];const d=m;let u;return r[4]!==i?(u={...i,toggle:d},r[4]=i,r[5]=u):u=r[5],u}const Le=s=>({padding:"0.6rem 1.2rem",borderRadius:"8px",cursor:"pointer",fontSize:"0.9rem",border:s?"1px solid var(--secondary)":"1px solid var(--glass-border)",background:s?"rgba(var(--secondary-rgb), 0.15)":"rgba(255,255,255,0.03)",color:s?"var(--secondary)":"var(--text-primary)",fontWeight:s?"bold":"normal",transition:"all 0.2s"}),ae={padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",fontSize:"13px",whiteSpace:"nowrap"},oe={...ae,fontWeight:"bold",color:"var(--secondary)",borderBottom:"1px solid rgba(255,255,255,0.12)"},Ne={background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)",padding:"1.5rem"},He=s=>({display:"inline-block",padding:"2px 8px",borderRadius:"12px",fontSize:"11px",fontWeight:"bold",background:`${s}22`,color:s,border:`1px solid ${s}44`});function ds(s){if(!s)return"—";const e=Math.floor((Date.now()-new Date(s).getTime())/1e3);return e<60?`${e}s atrás`:e<3600?`${Math.floor(e/60)}min atrás`:e<86400?`${Math.floor(e/3600)}h atrás`:`${Math.floor(e/86400)}d atrás`}function We(s){if(!s||s<=0)return"—";const e=Math.floor(s/1e3);if(e<60)return`${e}s`;const r=Math.floor(e/3600),o=Math.floor(e%3600/60),l=e%60;return r>0?`${r}h ${o}min`:o>0&&l>0&&o<10?`${o}min ${l}s`:`${o}min`}function yt(s){const e=re.c(18),{icon:r,value:o,label:l,color:i,style:n}=s;let m;e[0]!==n?(m={...Ne,padding:"1rem",textAlign:"center",...n},e[0]=n,e[1]=m):m=e[1];let d;e[2]===Symbol.for("react.memo_cache_sentinel")?(d={fontSize:"1.4rem"},e[2]=d):d=e[2];let u;e[3]!==r?(u=t.jsx("div",{style:d,"aria-hidden":"true",children:r}),e[3]=r,e[4]=u):u=e[4];let p;e[5]!==i?(p={fontSize:"1.3rem",fontWeight:"bold",color:i},e[5]=i,e[6]=p):p=e[6];let y;e[7]!==p||e[8]!==o?(y=t.jsx("div",{style:p,children:o}),e[7]=p,e[8]=o,e[9]=y):y=e[9];let c;e[10]===Symbol.for("react.memo_cache_sentinel")?(c={fontSize:"11px",color:"var(--text-muted)",marginTop:"2px"},e[10]=c):c=e[10];let g;e[11]!==l?(g=t.jsx("div",{style:c,children:l}),e[11]=l,e[12]=g):g=e[12];let h;return e[13]!==m||e[14]!==u||e[15]!==y||e[16]!==g?(h=t.jsxs("div",{style:m,children:[u,y,g]}),e[13]=m,e[14]=u,e[15]=y,e[16]=g,e[17]=h):h=e[17],h}const qt=25;function ao(s){const e=re.c(39),{rows:r,totals:o}=s,l=Tt("views"),{key:i,dir:n}=l;let m;e[0]!==n||e[1]!==i||e[2]!==r?(m=Rt(r,{key:i,dir:n}),e[0]=n,e[1]=i,e[2]=r,e[3]=m):m=e[3];const d=m;let u;e[4]!==d?(u={n:0,of:d},e[4]=d,e[5]=u):u=e[5];const[p,y]=x.useState(u);let c;e[6]!==d?(c=N=>y({n:N,of:d}),e[6]=d,e[7]=c):c=e[7];const g=c,h=Math.max(1,Math.ceil(d.length/qt)),f=Math.min(p.of===d?p.n:0,h-1),$=f*qt;let S,z,v,k;
18if(e[8]!==$||e[9]!==r.length||e[10]!==l||e[11]!==d||e[12]!==o){const N=d.slice($,$+qt);let W,T,B;e[17]===Symbol.for("react.memo_cache_sentinel")?(S={...Ne,padding:"1.25rem"},T={display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"1rem"},B=t.jsx("h3",{style:{margin:0,fontSize:"1rem"},children:"📝 Páginas de Conteúdo"}),W={fontSize:"12px",color:"var(--text-muted)"},e[17]=W,e[18]=S,e[19]=T,e[20]=B):(W=e[17],S=e[18],T=e[19],B=e[20]);const w=r.length===1?"conteúdo":"conteúdos";e[21]!==r.length||e[22]!==w?(z=t.jsxs("div",{style:T,children:[B,t.jsxs("span",{style:W,children:[r.length," ",w]})]}),e[21]=r.length,e[22]=w,e[23]=z):z=e[23],e[24]!==r.length||e[25]!==o?(v=o&&r.length>0&&t.jsx(oo,{t:o}),e[24]=r.length,e[25]=o,e[26]=v):v=e[26],k=r.length===0?t.jsxs("div",{style:{color:"var(--text-muted)",fontSize:"13px",textAlign:"center",padding:"2rem"},children:["Nenhum conteúdo cadastrado ainda. Gere um em ",t.jsx("code",{children:"/system/criacao-de-conteudo/admin"}),"."]}):t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx(ce,{column:"content_id",sort:l,style:oe,children:"#"}),t.jsx(ce,{column:"title",sort:l,style:oe,firstDir:"asc",children:"Título"}),t.jsx(ce,{column:"status",sort:l,style:oe,firstDir:"asc",children:"Status"}),t.jsx(ce,{column:"views",sort:l,style:oe,children:"Acessos"}),t.jsx(ce,{column:"unique_visitors",sort:l,style:oe,children:"Únicos"}),t.jsx(ce,{column:"clicks",sort:l,style:oe,children:"Cliques"}),t.jsx(ce,{column:"total_time_ms",sort:l,style:oe,children:"Tempo total"}),t.jsx(ce,{column:"last_view",sort:l,style:oe,children:"Último acesso"}),t.jsx("th",{style:oe,children:"Link"})]})}),t.jsx("tbody",{children:N.map(no)})]})}),e[8]=$,e[9]=r.length,e[10]=l,e[11]=d,e[12]=o,e[13]=S,e[14]=z,e[15]=v,e[16]=k}else S=e[13],z=e[14],v=e[15],k=e[16];let A;e[27]!==f||e[28]!==$||e[29]!==g||e[30]!==d.length||e[31]!==h?(A=d.length>qt&&t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"1rem",marginTop:"1rem"},children:[t.jsx("button",{style:{...Le(!1),opacity:f<=0?.4:1,cursor:f<=0?"not-allowed":"pointer"},disabled:f<=0,onClick:()=>g(Math.max(0,f-1)),children:"← Anterior"}),t.jsxs("span",{style:{fontSize:"12px",color:"var(--text-muted)"},children:[$+1,"–",Math.min($+qt,d.length)," de ",d.length]}),t.jsx("button",{style:{...Le(!1),opacity:f>=h-1?.4:1,cursor:f>=h-1?"not-allowed":"pointer"},disabled:f>=h-1,onClick:()=>g(Math.min(h-1,f+1)),children:"Próximo →"})]}),e[27]=f,e[28]=$,e[29]=g,e[30]=d.length,e[31]=h,e[32]=A):A=e[32];let C;return e[33]!==S||e[34]!==z||e[35]!==v||e[36]!==k||e[37]!==A?(C=t.jsxs("div",{style:S,children:[z,v,k,A]}),e[33]=S,e[34]=z,e[35]=v,e[36]=k,e[37]=A,e[38]=C):C=e[38],C}function no(s){return t.jsx(io,{c:s},s.content_id)}function oo(s){const e=re.c(36),{t:r}=s;let o;e[0]!==r.views?(o=r.views.toLocaleString("pt-BR"),e[0]=r.views,e[1]=o):o=e[1];let l;e[2]!==o?(l={icon:"👁️",value:o,label:"Acessos",color:"#a855f7"},e[2]=o,e[3]=l):l=e[3];let i;e[4]!==r.unique_visitors?(i=r.unique_visitors.toLocaleString("pt-BR"),e[4]=r.unique_visitors,e[5]=i):i=e[5];let n;e[6]!==i?(n={icon:"👥",value:i,label:"Visitantes únicos",color:"#14b8a6"},e[6]=i,e[7]=n):n=e[7];let m;e[8]!==r.clicks?(m=r.clicks.toLocaleString("pt-BR"),e[8]=r.clicks,e[9]=m):m=e[9];let d;e[10]!==m?(d={icon:"🖱️",value:m,label:"Cliques",color:"#3b82f6"},e[10]=m,e[11]=d):d=e[11];let u;e[12]!==r.total_time_ms?(u=We(r.total_time_ms),e[12]=r.total_time_ms,e[13]=u):u=e[13];let p;e[14]!==u?(p={icon:"⏱️",value:u,label:"Tempo total",color:"#22c55e"},e[14]=u,e[15]=p):p=e[15];let y;e[16]!==r.avg_time_per_view_ms?(y=We(r.avg_time_per_view_ms),e[16]=r.avg_time_per_view_ms,e[17]=y):y=e[17];let c;e[18]!==y?(c={icon:"⌛",value:y,label:"Tempo médio por acesso",color:"#0ea5e9"},e[18]=y,e[19]=c):c=e[19];let g;e[20]!==r.contents_viewed?(g=r.contents_viewed.toLocaleString("pt-BR"),e[20]=r.contents_viewed,e[21]=g):g=e[21];let h;
18e[22]!==r.contents_total?(h=r.contents_total.toLocaleString("pt-BR"),e[22]=r.contents_total,e[23]=h):h=e[23];const f=`${g} de ${h}`;let $;e[24]!==f?($={icon:"📝",value:f,label:"Conteúdos acessados",color:"#f59e0b"},e[24]=f,e[25]=$):$=e[25];let S;e[26]!==c||e[27]!==$||e[28]!==l||e[29]!==n||e[30]!==d||e[31]!==p?(S=[l,n,d,p,c,$],e[26]=c,e[27]=$,e[28]=l,e[29]=n,e[30]=d,e[31]=p,e[32]=S):S=e[32];const z=S;let v;e[33]===Symbol.for("react.memo_cache_sentinel")?(v={display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1rem"},e[33]=v):v=e[33];let k;return e[34]!==z?(k=t.jsx("div",{style:v,children:z.map(lo)}),e[34]=z,e[35]=k):k=e[35],k}function lo(s){return t.jsx(yt,{icon:s.icon,value:s.value,label:s.label,color:s.color},s.label)}function io(s){const e=re.c(55),{c:r}=s;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={...ae,color:"var(--text-muted)",textAlign:"center"},e[0]=o):o=e[0];let l;e[1]!==r.content_id?(l=t.jsx("td",{style:o,children:r.content_id}),e[1]=r.content_id,e[2]=l):l=e[2];let i;e[3]===Symbol.for("react.memo_cache_sentinel")?(i={...ae,maxWidth:"420px",overflow:"hidden",textOverflow:"ellipsis"},e[3]=i):i=e[3];let n;e[4]===Symbol.for("react.memo_cache_sentinel")?(n={fontWeight:600},e[4]=n):n=e[4];let m;e[5]!==r.title?(m=t.jsx("div",{style:n,children:r.title}),e[5]=r.title,e[6]=m):m=e[6];let d;e[7]===Symbol.for("react.memo_cache_sentinel")?(d={fontSize:"11px",color:"var(--text-muted)"},e[7]=d):d=e[7];let u;e[8]!==r.kind?(u=t.jsx("div",{style:d,children:r.kind}),e[8]=r.kind,e[9]=u):u=e[9];let p;e[10]!==r.title||e[11]!==m||e[12]!==u?(p=t.jsxs("td",{style:i,title:r.title,children:[m,u]}),e[10]=r.title,e[11]=m,e[12]=u,e[13]=p):p=e[13];let y;e[14]===Symbol.for("react.memo_cache_sentinel")?(y={...ae,textAlign:"center"},e[14]=y):y=e[14];const c=r.status==="published"?"#22c55e":"#94a3b8";let g;e[15]!==c?(g=He(c),e[15]=c,e[16]=g):g=e[16];const h=r.status==="published"?"publicado":"rascunho";let f;e[17]!==g||e[18]!==h?(f=t.jsx("td",{style:y,children:t.jsx("span",{style:g,children:h})}),e[17]=g,e[18]=h,e[19]=f):f=e[19];let $;e[20]===Symbol.for("react.memo_cache_sentinel")?($={...ae,textAlign:"right",fontWeight:600,color:"var(--secondary)"},e[20]=$):$=e[20];let S;e[21]!==r.views?(S=t.jsx("td",{style:$,children:r.views}),e[21]=r.views,e[22]=S):S=e[22];let z;e[23]===Symbol.for("react.memo_cache_sentinel")?(z={...ae,textAlign:"right"},e[23]=z):z=e[23];let v;e[24]!==r.unique_visitors?(v=t.jsx("td",{style:z,children:r.unique_visitors}),e[24]=r.unique_visitors,e[25]=v):v=e[25];let k;e[26]===Symbol.for("react.memo_cache_sentinel")?(k={...ae,textAlign:"right"},e[26]=k):k=e[26];let A;e[27]!==r.clicks?(A=t.jsx("td",{style:k,children:r.clicks}),e[27]=r.clicks,e[28]=A):A=e[28];let C;e[29]===Symbol.for("react.memo_cache_sentinel")?(C={...ae,textAlign:"right"},e[29]=C):C=e[29];let N;e[30]!==r.total_time_ms?(N=We(r.total_time_ms),e[30]=r.total_time_ms,e[31]=N):N=e[31];let W;e[32]!==N?(W=t.jsx("td",{style:C,children:N}),e[32]=N,e[33]=W):W=e[33];let T;e[34]===Symbol.for("react.memo_cache_sentinel")?(T={...ae,textAlign:"right",color:"var(--text-muted)"},e[34]=T):T=e[34];let B;e[35]!==r.last_view?(B=ds(r.last_view),e[35]=r.last_view,e[36]=B):B=e[36];let w;e[37]!==B?(w=t.jsx("td",{style:T,children:B}),e[37]=B,e[38]=w):w=e[38];let D;e[39]===Symbol.for("react.memo_cache_sentinel")?(D={...ae,textAlign:"center"},e[39]=D):D=e[39];let q;e[40]!==r.content_id||e[41]!==r.status?(q=r.status==="published"?t.jsx("a",{href:`/conteudo/${r.content_id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--secondary)",textDecoration:"none",fontSize:"12px"},children:"↗ abrir"}):"—",e[40]=r.content_id,e[41]=r.status,e[42]=q):q=e[42];let P;e[43]!==q?(P=t.jsx("td",{style:D,children:q}),e[43]=q,e[44]=P):P=e[44];let L;return e[45]!==f||e[46]!==S||e[47]!==v||e[48]!==A||e[49]!==l||e[50]!==W||e[51]!==w||e[52]!==P||e[53]!==p?(L=t.jsxs("tr",{children:[l,p,f,S,v,A,W,w,P]}),e[45]=f,e[46]=S,e[47]=v,e[48]=A,e[49]=l,e[50]=W,e[51]=w,e[52]=P,e[53]=p,e[54]=L):L=e[54],L}const co={ia:"#a855f7",busca_ia:"#3b82f6",busca:"#14b8a6",preview:"#f59e0b",anuncios:"#ec4899",seo:"#94a3b8",outro:"#64748b"},bt=s=>
18s.toLocaleString("pt-BR");function mo(s){return s.filter(e=>e.categoria==="ia"||e.categoria==="busca_ia").reduce((e,r)=>e+r.acessos,0)}function uo(s){const e=re.c(46),{dados:r}=s,o=Tt("acessos"),{key:l,dir:i}=o,n=r?.robos;let m;e[0]!==i||e[1]!==l||e[2]!==n?(m=Rt(n??[],{key:l,dir:i}),e[0]=i,e[1]=l,e[2]=n,e[3]=m):m=e[3];const d=m;if(!r)return null;const u=r.totais;let p,y,c;e[4]===Symbol.for("react.memo_cache_sentinel")?(p={...Ne,padding:"1.25rem"},y={display:"flex",alignItems:"baseline",justifyContent:"space-between",flexWrap:"wrap",gap:"0.5rem",marginBottom:"1rem"},c=t.jsx("h3",{style:{margin:0,fontSize:"1rem"},children:"🤖 Robôs que acessaram os conteúdos"}),e[4]=p,e[5]=y,e[6]=c):(p=e[4],y=e[5],c=e[6]);let g;e[7]!==r.log_ate||e[8]!==r.log_desde?(g=r.log_desde&&t.jsxs("span",{style:{fontSize:"12px",color:"var(--text-muted)"},children:["log do servidor de ",nr(r.log_desde)," a ",nr(r.log_ate??r.log_desde)]}),e[7]=r.log_ate,e[8]=r.log_desde,e[9]=g):g=e[9];let h;e[10]!==g?(h=t.jsxs("div",{style:y,children:[c,g]}),e[10]=g,e[11]=h):h=e[11];let f;e[12]===Symbol.for("react.memo_cache_sentinel")?(f={display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))",gap:"1rem",marginBottom:"1rem"},e[12]=f):f=e[12];let $;e[13]!==u.acessos_robos?($=bt(u.acessos_robos),e[13]=u.acessos_robos,e[14]=$):$=e[14];let S;e[15]!==u.pct_acessos_robos?(S=u.pct_acessos_robos.toLocaleString("pt-BR"),e[15]=u.pct_acessos_robos,e[16]=S):S=e[16];const z=`${$} · ${S}%`;let v;e[17]!==z?(v=t.jsx(yt,{icon:"🤖",value:z,label:"Acessos de robôs",color:"#a855f7"}),e[17]=z,e[18]=v):v=e[18];let k;e[19]!==r.robos?(k=bt(mo(r.robos)),e[19]=r.robos,e[20]=k):k=e[20];let A;e[21]!==k?(A=t.jsx(yt,{icon:"🧠",value:k,label:"Acessos de IA (inclui Google e Bing)",color:"#3b82f6"}),e[21]=k,e[22]=A):A=e[22];let C;e[23]!==u.acessos_navegador?(C=bt(u.acessos_navegador),e[23]=u.acessos_navegador,e[24]=C):C=e[24];let N;e[25]!==C?(N=t.jsx(yt,{icon:"👤",value:C,label:"Acessos de pessoas (navegador comum)",color:"#22c55e"}),e[25]=C,e[26]=N):N=e[26];let W;e[27]!==u.robos_distintos?(W=bt(u.robos_distintos),e[27]=u.robos_distintos,e[28]=W):W=e[28];let T;e[29]!==W?(T=t.jsx(yt,{icon:"🏷️",value:W,label:"Robôs diferentes",color:"#f59e0b"}),e[29]=W,e[30]=T):T=e[30];let B;e[31]!==v||e[32]!==A||e[33]!==N||e[34]!==T?(B=t.jsxs("div",{style:f,children:[v,A,N,T]}),e[31]=v,e[32]=A,e[33]=N,e[34]=T,e[35]=B):B=e[35];let w;e[36]!==d||e[37]!==o?(w=d.length===0?t.jsx("div",{style:{color:"var(--text-muted)",fontSize:"13px",textAlign:"center",padding:"1.5rem"},children:"Nenhum robô no período."}):t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx(ce,{column:"nome",sort:o,style:oe,firstDir:"asc",children:"Robô"}),t.jsx(ce,{column:"empresa",sort:o,style:oe,firstDir:"asc",children:"Empresa"}),t.jsx(ce,{column:"finalidade",sort:o,style:oe,firstDir:"asc",children:"Para quê"}),t.jsx(ce,{column:"categoria_rotulo",sort:o,style:oe,firstDir:"asc",children:"Tipo"}),t.jsx(ce,{column:"acessos",sort:o,style:oe,children:"Acessos"}),t.jsx(ce,{column:"conteudos",sort:o,style:oe,children:"Conteúdos"}),t.jsx(ce,{column:"views_js",sort:o,style:oe,children:"Com JS"}),t.jsx(ce,{column:"ultimo",sort:o,style:oe,children:"Último acesso"})]})}),t.jsx("tbody",{children:d.map(po)})]})}),e[36]=d,e[37]=o,e[38]=w):w=e[38];let D,q;e[39]===Symbol.for("react.memo_cache_sentinel")?(D={fontSize:"11px",color:"var(--text-muted)",margin:"0.75rem 0 0"},q=t.jsx("b",{children:"Acessos"}),e[39]=D,e[40]=q):(D=e[39],q=e[40]);let P;e[41]===Symbol.for("react.memo_cache_sentinel")?(P=t.jsxs("p",{style:D,children:[q," = log do servidor: toda vez que a página foi buscada, inclusive por robô que não roda JavaScript. ",t.jsx("b",{children:"Com JS"}),' = rastreador da página (histórico mais longo, mas só vê quem roda JavaScript). O Bing entra como "busca usada por IA": o índice dele é a base do Copilot e do ChatGPT Search. "Navegador em massa" = navegador comum, mas o mesmo IP abriu 20+ conteúdos no dia.']}),e[41]=P):P=e[41];let L;return e[42]!==B||e[43]!==w||e[44]!==h?(L=t.jsxs("div",{style:p,children:[h,B,w,P]}),e[42]=B,e[43]=w,e[44]=h,e[45]=L):L=e[45],L}function po(s){return t.jsx(xo,{r:s},s.chave)}function xo(s){const e=re.c(43),{r}=s;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={fontWeight:600},e[0]=o):o=e[0];let l;e[1]!==r.nome?(l=t.jsx("td",{style:ae,children:t.jsx("div",{style:o,children:r.nome})}),e[1]=r.nome,e[2]=l):l=e[2];let i;e[3]!==r.empresa?(i=t.jsx("td",{style:ae,children:r.empresa}),e[3]=r.empresa,e[4]=i):i=e[4];let n;e[5]===Symbol.for("react.memo_cache_sentinel")?(n={...ae,whiteSpace:"normal",minWidth:"220px",maxWidth:"360px"},e[5]=n):n=e[5];let m;e[6]!==r.finalidade?(m=t.jsx("td",{style:n,children:r.finalidade}),e[6]=r.finalidade,e[7]=m):m=e[7];let d;e[8]===Symbol.for("react.memo_cache_sentinel")?(d={...ae,textAlign:"center"},e[8]=d):d=e[8];const u=co[r.categoria]??"#64748b";let p;e[9]!==u?(p=He(u),e[9]=u,e[10]=p):p=e[10];let y;e[11]!==r.categoria_rotulo||e[12]!==p?(y=t.jsx("td",{style:d,children:t.jsx("span",{style:p,children:r.categoria_rotulo})}),e[11]=r.categoria_rotulo,e[12]=p,e[13]=y):y=e[13];let c;e[14]===Symbol.for("react.memo_cache_sentinel")?(c={...ae,textAlign:"right",fontWeight:600,color:"var(--secondary)"},e[14]=c):c=e[14];let g;e[15]!==r.acessos?(g=bt(r.acessos),e[15]=r.acessos,e[16]=g):g=e[16];let h;e[17]!==g?(h=t.jsx("td",{style:c,children:g}),e[17]=g,e[18]=h):h=e[18];let f;e[19]===Symbol.for("react.memo_cache_sentinel")?(f={...ae,textAlign:"right"},e[19]=f):f=e[19];let $;e[20]!==r.conteudos?($=bt(r.conteudos),e[20]=r.conteudos,e[21]=$):$=e[21];let S;e[22]!==$?(S=t.jsx("td",{style:f,children:$}),e[22]=$,e[23]=S):S=e[23];let z;e[24]===Symbol.for("react.memo_cache_sentinel")?(z={...ae,textAlign:"right"},e[24]=z):z=e[24];let v;e[25]!==r.views_js?(v=bt(r.views_js),e[25]=r.views_js,e[26]=v):v=e[26];let k;e[27]!==v?(k=t.jsx("td",{style:z,children:v}),e[27]=v,e[28]=k):k=e[28];let A;e[29]===Symbol.for("react.memo_cache_sentinel")?(A={...ae,textAlign:"right",color:"var(--text-muted)"},e[29]=A):A=e[29];let C;e[30]!==r.ultimo?(C=r.ultimo?nr(r.ultimo):"—",e[30]=r.ultimo,e[31]=C):C=e[31];let N;e[32]!==C?(N=t.jsx("td",{style:A,children:C}),e[32]=C,e[33]=N):N=e[33];let W;return e[34]!==h||e[35]!==S||e[36]!==k||e[37]!==l||e[38]!==N||e[39]!==i||e[40]!==m||e[41]!==y?(W=t.jsxs("tr",{children:[l,i,m,y,h,S,k,N]}),e[34]=h,e[35]=S,e[36]=k,e[37]=l,e[38]=N,e[39]=i,e[40]=m,e[41]=y,e[42]=W):W=e[42],W}const Oe="https://behonest.com.br",ho=[{label:"7d",value:7},{label:"14d",value:14},{label:"30d",value:30},{label:"90d",value:90},{label:"Tudo",value:0}],da={page_path:s=>we(s.page_path)},go={users:s=>s.users.length},fo={page_path:s=>we(s.page_path),element_text:s=>s.element_text||s.element_id};function ma(s,e){const r=s[e];return typeof r=="number"?r:s.total_clicks}function ua(s){switch(s){case"page_view":return"📄";case"page_leave":return"⏱️";case"click":return"🖱️";case"input":return"⌨️";case"submit":return"📨";default:return"•"}}function Ut(s){return s===1?{label:"🥇",color:"#facc15",isMedal:!0}:s===2?{label:"🥈",color:"#cbd5e1",isMedal:!0}:s===3?{label:"🥉",color:"#d97706",isMedal:!0}:{label:`#${s}`,color:"var(--text-muted)",isMedal:!1}}
18function ls(s){const e=re.c(9),{value:r,max:o,color:l,height:i}=s,n=i===void 0?6:i,m=o>0?Math.max(2,Math.min(100,r/o*100)):0,d=`${n}px`;let u;e[0]!==d?(u={position:"relative",height:d,background:"rgba(255,255,255,0.05)",borderRadius:"999px",overflow:"hidden"},e[0]=d,e[1]=u):u=e[1];const p=`${m}%`,y=`linear-gradient(90deg, ${l}aa, ${l})`,c=`0 0 12px ${l}55`;let g;e[2]!==p||e[3]!==y||e[4]!==c?(g=t.jsx("div",{style:{position:"absolute",inset:"0 auto 0 0",width:p,background:y,borderRadius:"999px",transition:"width 0.5s cubic-bezier(0.22, 1, 0.36, 1)",boxShadow:c}}),e[2]=p,e[3]=y,e[4]=c,e[5]=g):g=e[5];let h;return e[6]!==u||e[7]!==g?(h=t.jsx("div",{style:u,children:g}),e[6]=u,e[7]=g,e[8]=h):h=e[8],h}function pa(s){const e=re.c(31),{rank:r,title:o,subtitle:l,value:i,color:n}=s;let m;e[0]!==r?(m=Ut(r),e[0]=r,e[1]=m):m=e[1];const{label:d}=m;let u;e[2]===Symbol.for("react.memo_cache_sentinel")?(u={1:168,2:140,3:116},e[2]=u):u=e[2];const p=u;let y;e[3]===Symbol.for("react.memo_cache_sentinel")?(y={1:2,2:1,3:3},e[3]=y):y=e[3];const g=y[r],h=`linear-gradient(180deg, ${n}1a, transparent)`,f=`1px solid ${n}55`,$=`${p[r]}px`,S=r===1?`0 0 32px ${n}33`:"none";let z;e[4]!==g||e[5]!==h||e[6]!==f||e[7]!==$||e[8]!==S?(z={order:g,display:"flex",flexDirection:"column",alignItems:"center",gap:"6px",padding:"14px 10px",borderRadius:"var(--radius-md)",background:h,border:f,minHeight:$,justifyContent:"flex-end",boxShadow:S},e[4]=g,e[5]=h,e[6]=f,e[7]=$,e[8]=S,e[9]=z):z=e[9];const v=r===1?"2.4rem":"2rem";let k;e[10]!==v?(k={fontSize:v,lineHeight:1},e[10]=v,e[11]=k):k=e[11];let A;e[12]!==d||e[13]!==k?(A=t.jsx("div",{style:k,children:d}),e[12]=d,e[13]=k,e[14]=A):A=e[14];let C;e[15]===Symbol.for("react.memo_cache_sentinel")?(C={fontWeight:"bold",fontSize:"13px",textAlign:"center",color:"var(--text-primary)",maxWidth:"160px",overflow:"hidden",textOverflow:"ellipsis"},e[15]=C):C=e[15];let N;e[16]!==o?(N=t.jsx("div",{style:C,title:o,children:o}),e[16]=o,e[17]=N):N=e[17];let W;e[18]!==l?(W=l&&t.jsx("div",{style:{fontSize:"10px",color:"var(--text-muted)",maxWidth:"160px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:l,children:l}),e[18]=l,e[19]=W):W=e[19];let T;e[20]!==n?(T={fontSize:"15px",fontWeight:"bold",color:n},e[20]=n,e[21]=T):T=e[21];let B;e[22]!==T||e[23]!==i?(B=t.jsx("div",{style:T,children:i}),e[22]=T,e[23]=i,e[24]=B):B=e[24];let w;return e[25]!==A||e[26]!==N||e[27]!==W||e[28]!==B||e[29]!==z?(w=t.jsxs("div",{style:z,children:[A,N,W,B]}),e[25]=A,e[26]=N,e[27]=W,e[28]=B,e[29]=z,e[30]=w):w=e[30],w}function yo(){const[s,e]=x.useState("rank"),[r,o]=x.useState(7),[l,i]=x.useState(!1),[n,m]=x.useState(""),[d,u]=x.useState("clicks"),[p,y]=x.useState(null),[c,g]=x.useState([]),[h,f]=x.useState("day"),[$,S]=x.useState([]),[z,v]=x.useState(null),[k,A]=x.useState(null),[C,N]=x.useState("conteudos"),[W,T]=x.useState([]),[B,w]=x.useState("arvore"),[D,q]=x.useState(null),P=Tt("total_clicks"),L=Tt("total_time_ms"),R=Tt("click_count"),O=Tt("typing_events"),[G,E]=x.useState(""),[M,H]=x.useState([]),[X,J]=x.useState("pagina"),[U,K]=x.useState(null),[Y,Q]=x.useState(!1),[me,ue]=x.useState([]),[de,je]=x.useState([]),[fe,_e]=x.useState(null),[ke,Be]=x.useState([]),[te,ge]=x.useState([]),Re=x.useCallback(async()=>{try{const j=le(),F=await fetch(`${Oe}/api/admin/usage/engagement?days=${r}`,{headers:{Authorization:`Bearer ${j}`}});F.ok&&y(await F.json())}catch(j){console.error(j)}},[r]),xe=x.useCallback(async()=>{i(!0);try{const j=le(),F=await fetch(`${Oe}/api/admin/usage/summary?days=${r}`,{headers:{Authorization:`Bearer ${j}`}});F.ok&&T(await F.json())}catch(j){console.error(j)}finally{i(!1)}},[r]),ye=x.useCallback(async()=>{i(!0);try{const j=le(),F=await fetch(`${Oe}/api/admin/usage/tree?days=${r}`,{headers:{Authorization:`Bearer ${j}`}});F.ok&&q((await F.json()).root??null)}catch(j){console.error(j)}finally{i(!1)}}
18,[r]),pe=x.useCallback(async j=>{i(!0);try{const F=le(),Z=await fetch(`${Oe}/api/admin/usage/page-detail?page=${encodeURIComponent(j)}&days=${r}`,{headers:{Authorization:`Bearer ${F}`}});Z.ok&&H(await Z.json())}catch(F){console.error(F)}finally{i(!1)}},[r]),Ce=x.useCallback(async(j,F)=>{Q(!0);try{const Z=le(),ie=new URLSearchParams({page:j,days:String(r),escopo:F}),Se=await fetch(`${Oe}/api/admin/usage/page-timeline?${ie}`,{headers:{Authorization:`Bearer ${Z}`}});K(Se.ok?await Se.json():null)}catch(Z){console.error(Z),K(null)}finally{Q(!1)}},[r]),De=x.useCallback(async()=>{i(!0);try{const j={Authorization:`Bearer ${le()}`},[F,Z,ie]=await Promise.all([fetch(`${Oe}/api/admin/usage/content?days=${r}`,{headers:j}),fetch(`${Oe}/api/admin/usage/content/totals?days=${r}`,{headers:j}),fetch(`${Oe}/api/admin/usage/content/robots?days=${r}`,{headers:j})]);F.ok&&S(await F.json()),v(Z.ok?await Z.json():null),A(ie.ok?await ie.json():null)}catch(j){console.error(j)}finally{i(!1)}},[r]),Me=x.useCallback(async()=>{i(!0);try{const j=le(),F=await fetch(`${Oe}/api/admin/usage/timeseries?bucket=${h}`,{headers:{Authorization:`Bearer ${j}`}});F.ok&&g(await F.json())}catch(j){console.error(j)}finally{i(!1)}},[h]),rt=x.useCallback(async()=>{i(!0);try{const j=le(),F=await fetch(`${Oe}/api/admin/usage/typing?days=${r}`,{headers:{Authorization:`Bearer ${j}`}});F.ok&&ue(await F.json())}catch(j){console.error(j)}finally{i(!1)}},[r]),Ve=x.useCallback(async()=>{i(!0);try{const j=le(),F=await fetch(`${Oe}/api/admin/usage/active-users?days=${r}`,{headers:{Authorization:`Bearer ${j}`}});F.ok&&je(await F.json())}catch(j){console.error(j)}finally{i(!1)}},[r]),Je=x.useCallback(async j=>{i(!0);try{const F=le(),[Z,ie]=await Promise.all([fetch(`${Oe}/api/admin/usage/user-activity?user_id=${j}&days=${r}`,{headers:{Authorization:`Bearer ${F}`}}),fetch(`${Oe}/api/admin/usage/user-page-times?user_id=${j}&days=${r}`,{headers:{Authorization:`Bearer ${F}`}})]);Z.ok&&Be(await Z.json()),ie.ok&&ge(await ie.json())}catch(F){console.error(F)}finally{i(!1)}},[r]);x.useEffect(()=>{Re()},[r,Re]),x.useEffect(()=>{(s==="pages"||s==="time"||s==="detail")&&xe(),s==="pages"&&ye(),s==="users"&&Ve(),s==="typing"&&rt(),s==="content"&&De(),s==="rank"&&(xe(),Ve()),s==="stats"&&Me()},[s,r,xe,ye,Ve,rt,De,Me]),x.useEffect(()=>{s==="detail"&&G&&(pe(G),Ce(G,X))},[s,G,X,r,pe,Ce]),x.useEffect(()=>{fe!==null&&Je(fe)},[fe,r,Je]);const Ke=(j,F="pagina")=>{E(j),J(F),e("detail")},Ge=Rt(W.filter(j=>!n||we(j.page_path).toLowerCase().includes(n.toLowerCase())||j.page_path.toLowerCase().includes(n.toLowerCase())),P,da),Fe=p?[{label:"Tempo Total",value:We(p.total_time_ms),icon:"⏱️",color:"#22c55e"},{label:"Clicks",value:p.clicks.toLocaleString(),icon:"🖱️",color:"#3b82f6"},{label:"Page Views",value:p.page_views.toLocaleString(),icon:"📄",color:"#a855f7"},{label:"Digitações",value:p.typing_events.toLocaleString(),icon:"⌨️",color:"#f59e0b"},{label:"Submits",value:p.submits.toLocaleString(),icon:"📨",color:"#ec4899"},{label:"Usuários",value:p.active_users,icon:"👥",color:"#14b8a6"}]:[],be=p&&p.active_users>0?Math.floor(p.total_time_ms/p.active_users):0,$e=12,at={clicks:{label:"Clicks",pageColor:"#3b82f6",userColor:"#22c55e",format:j=>j.toLocaleString()},time:{label:"Tempo Total",pageColor:"#a855f7",userColor:"#ec4899",format:j=>We(j)},views:{label:"Page Views",pageColor:"#0ea5e9",userColor:"#14b8a6",format:j=>j.toLocaleString()}},qe=x.useMemo(()=>{const j=d==="clicks"?"total_clicks":d==="time"?"total_time_ms":"page_views";return[...W].map(F=>({...F,_metric:F[j]||0})).sort((F,Z)=>Z._metric-F._metric).slice(0,$e)},[W,d]),Qe=x.useMemo(()=>{const j=d==="clicks"?"clicks":d==="time"?"total_time_ms":"total_events";return[...de].map(F=>({...F,_metric:F[j]||0})).sort((F,Z)=>Z._metric-F._metric).slice(0,$e)},[de,d]),us=qe[0]?._metric||1,It=Qe[0]?._metric||1,ze=at[d],Ze=x.useMemo(()=>{let j=0;return c.map(F=>{j+=F.total_events;const Z=new Date(F.bucket+"T00:00:00"),ie=h==="month"?Z.toLocaleDateString("pt-BR",{month:"short",year:"2-digit"}):Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});return{...F,label:ie,time_hours:+(F.total_time_ms/36e5).toFixed(1),cumulative_events:j}})},[c,h]),Ye=x.useMemo(()=>
18{if(c.length<2)return null;const j=Math.min(7,Math.floor(c.length/2));if(j<1)return null;const F=Se=>Se.reduce((Ee,Wt)=>Ee+Wt.total_events,0),Z=F(c.slice(-j)),ie=F(c.slice(-2*j,-j));return ie===0?null:{pct:(Z-ie)/ie*100,window:j}},[c]),ht=x.useMemo(()=>c.reduce((j,F)=>({events:j.events+F.total_events,time_ms:j.time_ms+F.total_time_ms,clicks:j.clicks+F.clicks,views:j.views+F.page_views}),{events:0,time_ms:0,clicks:0,views:0}),[c]),lt={background:"#0E2050",border:"1px solid #edb125",borderRadius:"8px",fontSize:"12px"},ve=[{value:"day",label:"Dia"},{value:"week",label:"Semana"},{value:"month",label:"Mês"}];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:"1rem"},children:[t.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[t.jsx("button",{style:Le(s==="rank"),onClick:()=>e("rank"),children:"🏆 Ranking"}),t.jsx("button",{style:Le(s==="stats"),onClick:()=>e("stats"),children:"📈 Estatísticas"}),t.jsx("button",{style:Le(s==="pages"),onClick:()=>e("pages"),children:"📄 Páginas"}),t.jsx("button",{style:Le(s==="detail"),onClick:()=>e("detail"),children:"🔍 Detalhe"}),t.jsx("button",{style:Le(s==="time"),onClick:()=>e("time"),children:"⏱️ Tempo"}),t.jsx("button",{style:Le(s==="typing"),onClick:()=>e("typing"),children:"⌨️ Digitação"}),t.jsx("button",{style:Le(s==="users"),onClick:()=>e("users"),children:"👤 Usuários"}),t.jsx("button",{style:Le(s==="content"),onClick:()=>e("content"),children:"📝 Conteúdo"})]}),t.jsx("div",{style:{display:"flex",gap:"6px"},children:ho.map(j=>t.jsx("button",{onClick:()=>o(j.value),style:{padding:"6px 14px",borderRadius:"var(--radius-sm)",cursor:"pointer",fontWeight:"bold",transition:"all 0.15s",fontSize:"12px",background:r===j.value?"var(--secondary)":"var(--glass-highlight)",color:r===j.value?"var(--primary)":"var(--text-primary)",border:r===j.value?"1px solid var(--secondary)":"1px solid var(--glass-border)"},children:j.label},j.value))})]}),p&&t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 150px), 1fr))",gap:"0.75rem"},children:[Fe.map(j=>t.jsx(yt,{icon:j.icon,value:j.value,label:j.label,color:j.color},j.label)),t.jsx(yt,{icon:"📊",value:We(be),label:"Média/Usuário",color:"#0ea5e9"})]}),l&&t.jsx("div",{style:{textAlign:"center",padding:"2rem",color:"var(--text-muted)"},children:"⏳ Carregando..."}),s==="rank"&&!l&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap",alignItems:"center"},children:[t.jsx("span",{style:{fontSize:"12px",color:"var(--text-muted)",marginRight:"4px"},children:"Ranquear por:"}),["clicks","time","views"].map(j=>{const F=d===j,Z=at[j],ie=j==="clicks"?"🖱️":j==="time"?"⏱️":"📄";return t.jsxs("button",{onClick:()=>u(j),style:{padding:"6px 14px",borderRadius:"var(--radius-sm)",cursor:"pointer",fontSize:"12px",fontWeight:"bold",background:F?Z.pageColor:"var(--glass-highlight)",color:F?"#0b1e44":"var(--text-primary)",border:`1px solid ${F?Z.pageColor:"var(--glass-border)"}`,transition:"all 0.2s"},children:[ie," ",Z.label]},j)})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 380px), 1fr))",gap:"1.25rem"},children:[t.jsxs("div",{style:{...Ne,padding:"1.25rem"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"1rem"},children:[t.jsx("h3",{style:{margin:0,fontSize:"1rem"},children:"📄 Top Páginas"}),t.jsxs("span",{style:He(ze.pageColor),children:["por ",ze.label]})]}),qe.length>=3&&t.jsx("div",{style:{display:"flex",alignItems:"flex-end",justifyContent:"center",gap:"8px",marginBottom:"1.25rem"},children:qe.slice(0,3).map((j,F)=>t.jsx(pa,{rank:F+1,title:we(j.page_path),subtitle:j.page_path,value:ze.format(j._metric),color:ze.pageColor},j.page_path))}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[qe.length===0&&t.jsx("div",{style:{color:"var(--text-muted)",fontSize:"13px",textAlign:"center",padding:"1rem"},children:"Sem dados de páginas no período."}),qe.slice(qe.length>=3?3:0).map((j,F)=>{const Z=(qe.length>=3?4:1)+F,ie=Ut(Z);return t.jsxs("div",{onClick:()=>Ke(j.page_path),style:{display:"grid",gridTemplateColumns:"36px 1fr auto",gap:"10px",alignItems:"center",padding:"8px 10px",borderRadius:"8px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:Se=>Se.currentTarget.style.background="rgba(255,255,255,0.04)",onMouseLeave:Se=>Se.currentTarget.style.background="transparent",children:[t.jsx("div",{style:{textAlign:"center",fontWeight:"bold",color:ie.color,fontSize:ie.isMedal?"1.2rem":"12px"},children:ie.label}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:"13px",fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:we(j.page_path)}),t.jsx("div",{style:{marginTop:"4px"},children:t.jsx(ls,{value:j._metric,max:us,color:ze.pageColor})})]}),t.jsx("div",{style:{fontSize:"13px",fontWeight:"bold",color:ze.pageColor,whiteSpace:"nowrap"},children:ze.format(j._metric)})]},j.page_path)})]})]}),t.jsxs("div",{style:{...Ne,padding:"1.25rem"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"1rem"},children:[t.jsx("h3",{style:{margin:0,fontSize:"1rem"},children:"👤 Top Usuários"}),t.jsxs("span",{style:He(ze.userColor),children:["por ",ze.label]})]}),Qe.length>=3&&t.jsx("div",{style:{display:"flex",alignItems:"flex-end",justifyContent:"center",gap:"8px",marginBottom:"1.25rem"},children:Qe.slice(0,3).map((j,F)=>t.jsx(pa,{rank:F+1,title:j.user_name,subtitle:`#${j.user_id}`,value:ze.format(j._metric),color:ze.userColor}
18,j.user_id))}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[Qe.length===0&&t.jsx("div",{style:{color:"var(--text-muted)",fontSize:"13px",textAlign:"center",padding:"1rem"},children:"Sem usuários ativos no período."}),Qe.slice(Qe.length>=3?3:0).map((j,F)=>{const Z=(Qe.length>=3?4:1)+F,ie=Ut(Z);return t.jsxs("div",{onClick:()=>{_e(j.user_id),e("users")},style:{display:"grid",gridTemplateColumns:"36px 1fr auto",gap:"10px",alignItems:"center",padding:"8px 10px",borderRadius:"8px",cursor:"pointer",transition:"background 0.15s"},onMouseEnter:Se=>Se.currentTarget.style.background="rgba(255,255,255,0.04)",onMouseLeave:Se=>Se.currentTarget.style.background="transparent",children:[t.jsx("div",{style:{textAlign:"center",fontWeight:"bold",color:ie.color,fontSize:ie.isMedal?"1.2rem":"12px"},children:ie.label}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:"13px",fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.user_name}),t.jsxs("div",{style:{display:"flex",gap:"6px",fontSize:"10px",color:"var(--text-muted)",marginBottom:"2px"},children:[t.jsxs("span",{children:["🖱️ ",j.clicks.toLocaleString()]}),t.jsxs("span",{children:["⌨️ ",j.typing_events.toLocaleString()]}),t.jsxs("span",{children:["⏱️ ",We(j.total_time_ms)]})]}),t.jsx(ls,{value:j._metric,max:It,color:ze.userColor})]}),t.jsx("div",{style:{fontSize:"13px",fontWeight:"bold",color:ze.userColor,whiteSpace:"nowrap"},children:ze.format(j._metric)})]},j.user_id)})]})]})]})]}),s==="stats"&&!l&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:"1rem"},children:[t.jsxs("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[t.jsx("span",{style:{fontSize:"12px",color:"var(--text-muted)",marginRight:"4px"},children:"Agrupar por:"}),ve.map(j=>t.jsx("button",{onClick:()=>f(j.value),style:{padding:"6px 14px",borderRadius:"var(--radius-sm)",cursor:"pointer",fontWeight:"bold",fontSize:"12px",transition:"all 0.15s",background:h===j.value?"var(--secondary)":"var(--glass-highlight)",color:h===j.value?"var(--primary)":"var(--text-primary)",border:h===j.value?"1px solid var(--secondary)":"1px solid var(--glass-border)"},children:j.label},j.value))]}),c.length>0&&t.jsxs("span",{style:{fontSize:"12px",color:"var(--text-muted)"},children:["Desde ",new Date(c[0].bucket+"T00:00:00").toLocaleDateString("pt-BR")," — todos os dados registrados"]})]}),c.length===0?t.jsx("div",{style:{...Ne,textAlign:"center",padding:"3rem",color:"var(--text-muted)"},children:"Nenhum evento de uso registrado ainda."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 160px), 1fr))",gap:"0.75rem"},children:[[{label:"Eventos (total)",value:ht.events.toLocaleString(),icon:"📊",color:"#0ea5e9"},{label:"Clicks (total)",value:ht.clicks.toLocaleString(),icon:"🖱️",color:"#3b82f6"},{label:"Page Views (total)",value:ht.views.toLocaleString(),icon:"📄",color:"#a855f7"},{label:"Tempo (total)",value:We(ht.time_ms),icon:"⏱️",color:"#22c55e"}].map(j=>t.jsxs("div",{style:{...Ne,padding:"1rem",textAlign:"center"},children:[t.jsx("div",{style:{fontSize:"1.4rem"},children:j.icon}),t.jsx("div",{style:{fontSize:"1.3rem",fontWeight:"bold",color:j.color},children:j.value}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"2px"},children:j.label})]},j.label)),Ye&&t.jsxs("div",{style:{...Ne,padding:"1rem",textAlign:"center"},children:[t.jsx("div",{style:{fontSize:"1.4rem"},children:Ye.pct>=0?"📈":"📉"}),t.jsxs("div",{style:{fontSize:"1.3rem",fontWeight:"bold",color:Ye.pct>=0?"#22c55e":"#ef4444"},children:[Ye.pct>=0?"+":"",Ye.pct.toFixed(0),"%"]}),t.jsxs("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"2px"},children:["Tendência (últ. ",Ye.window," vs ",Ye.window," anteriores)"]})]})]}),t.jsxs("div",{style:Ne,children:[t.jsx("h3",{style:{margin:"0 0 1rem 0",fontSize:"1rem"},children:"📊 Atividade por tipo de evento"}),t.jsx(Zt,{width:"100%",height:280,children:t.jsxs(Xs,{data:Ze,children:[t.jsx(es,{strokeDasharray:"3 3",stroke:"rgba(255,255,255,0.1)"}),t.jsx(ts,{dataKey:"label",tick:{fill:"var(--text-muted)",fontSize:11},minTickGap:24}
18),t.jsx(ss,{tick:{fill:"var(--text-muted)",fontSize:11}}),t.jsx(rs,{contentStyle:lt}),t.jsx(pn,{wrapperStyle:{fontSize:"12px"}}),t.jsx(kt,{type:"monotone",dataKey:"clicks",name:"Clicks",stackId:"1",stroke:"#3b82f6",fill:"#3b82f655"}),t.jsx(kt,{type:"monotone",dataKey:"page_views",name:"Page Views",stackId:"1",stroke:"#a855f7",fill:"#a855f755"}),t.jsx(kt,{type:"monotone",dataKey:"typing_events",name:"Digitações",stackId:"1",stroke:"#f59e0b",fill:"#f59e0b55"}),t.jsx(kt,{type:"monotone",dataKey:"submits",name:"Submits",stackId:"1",stroke:"#ec4899",fill:"#ec489955"})]})})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 380px), 1fr))",gap:"1.25rem"},children:[t.jsxs("div",{style:Ne,children:[t.jsx("h3",{style:{margin:"0 0 1rem 0",fontSize:"1rem"},children:"👥 Usuários ativos"}),t.jsx(Zt,{width:"100%",height:240,children:t.jsxs(xn,{data:Ze,children:[t.jsx(es,{strokeDasharray:"3 3",stroke:"rgba(255,255,255,0.1)"}),t.jsx(ts,{dataKey:"label",tick:{fill:"var(--text-muted)",fontSize:11},minTickGap:24}),t.jsx(ss,{tick:{fill:"var(--text-muted)",fontSize:11},allowDecimals:!1}),t.jsx(rs,{contentStyle:lt}),t.jsx(hn,{dataKey:"active_users",name:"Usuários",fill:"#14b8a6",radius:[4,4,0,0]})]})})]}),t.jsxs("div",{style:Ne,children:[t.jsx("h3",{style:{margin:"0 0 1rem 0",fontSize:"1rem"},children:"⏱️ Tempo de uso (horas)"}),t.jsx(Zt,{width:"100%",height:240,children:t.jsxs(Xs,{data:Ze,children:[t.jsx(es,{strokeDasharray:"3 3",stroke:"rgba(255,255,255,0.1)"}),t.jsx(ts,{dataKey:"label",tick:{fill:"var(--text-muted)",fontSize:11},minTickGap:24}),t.jsx(ss,{tick:{fill:"var(--text-muted)",fontSize:11}}),t.jsx(rs,{contentStyle:lt,formatter:j=>[`${j??0}h`,"Tempo"]}),t.jsx(kt,{type:"monotone",dataKey:"time_hours",name:"Horas",stroke:"#22c55e",fill:"#22c55e33"})]})})]})]}),t.jsxs("div",{style:Ne,children:[t.jsx("h3",{style:{margin:"0 0 1rem 0",fontSize:"1rem"},children:"🚀 Crescimento acumulado (eventos desde o início)"}),t.jsx(Zt,{width:"100%",height:260,children:t.jsxs(Xs,{data:Ze,children:[t.jsx(es,{strokeDasharray:"3 3",stroke:"rgba(255,255,255,0.1)"}),t.jsx(ts,{dataKey:"label",tick:{fill:"var(--text-muted)",fontSize:11},minTickGap:24}),t.jsx(ss,{tick:{fill:"var(--text-muted)",fontSize:11}}),t.jsx(rs,{contentStyle:lt}),t.jsx(kt,{type:"monotone",dataKey:"cumulative_events",name:"Eventos acumulados",stroke:"#edb125",fill:"#edb12533"})]})})]})]})]}),s==="pages"&&!l&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"0.75rem"},children:[t.jsx("button",{style:Le(B==="arvore"),onClick:()=>w("arvore"),children:"🌳 Árvore"}),t.jsx("button",{style:Le(B==="lista"),onClick:()=>w("lista"),children:"📋 Lista"})]}),t.jsxs("div",{className:"search-input-wrap",style:{maxWidth:"350px",width:"100%",marginBottom:"0.75rem"},children:[t.jsx("input",{type:"text",placeholder:"Buscar página…",value:n,onChange:j=>m(j.target.value),className:"search-input",style:{padding:"0.6rem 1rem",borderRadius:"var(--radius-md)",border:"1px solid var(--glass-border)",background:"var(--glass-bg)",color:"var(--text-primary)",width:"100%"}}),n&&t.jsx("button",{type:"button",className:"search-clear","aria-label":"Limpar busca",onClick:()=>m(""),children:"✕"})]}),B==="arvore"&&t.jsx(Fn,{root:D,busca:n,onDetalhar:Ke}),t.jsx("div",{style:{overflowX:"auto",display:B==="lista"?"block":"none"},children:(()=>{const j=Math.max(1,...Ge.map(F=>ma(F,P.key)));return t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{...oe,width:"48px",textAlign:"center"},children:"#"}),t.jsx(ce,{column:"page_path",sort:P,style:oe,firstDir:"asc",children:"Página"}),t.jsx(ce,{column:"page_views",sort:P,style:oe,children:"Views"}),t.jsx(ce,{column:"total_clicks",sort:P,style:oe,children:"Clicks"}),t.jsx(ce,{column:"avg_time_ms",sort:P,style:oe,children:"Tempo médio"}),t.jsx(ce,{column:"unique_users",sort:P,style:oe,children:"Usuários"}),t.jsx(ce,{column:"last_activity",sort:P,style:oe,children:"Última Atividade"}),t.jsx("th",{style:oe})]})}),t.jsx("tbody",{children:Ge.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:8,style:{...ae,textAlign:"center",color:"var(--text-muted)",padding:"2rem"},children:"Nenhum dado de uso encontrado para o período selecionado."})}):Ge.map((F,Z)=>{const ie=Ut(Z+1),Se=ma(F,P.key);return t.jsxs("tr",{style:{transition:"background 0.15s"},onMouseEnter:Ee=>Ee.currentTarget.style.background="rgba(255,255,255,0.03)",onMouseLeave:Ee=>Ee.currentTarget.style.background="transparent",children:[t.jsx("td",{style:{...ae,textAlign:"center",color:ie.color,fontWeight:"bold",fontSize:ie.isMedal?"1.2rem":"12px"},children:ie.label}),t.jsxs("td",{style:ae,children:[t.jsx("div",{style:{fontWeight:"bold"},children:we(F.page_path)}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginBottom:"4px"},children:F.page_path}),t.jsx("div",{style:{maxWidth:"260px"},children:t.jsx(ls,{value:Se,max:j,color:"#3b82f6",height:4})})]}),t.jsx("td",{style:{...ae,textAlign:"right"}
18,children:F.page_views.toLocaleString()}),t.jsx("td",{style:{...ae,textAlign:"right"},children:t.jsx("span",{style:{fontWeight:"bold",fontSize:"14px"},children:F.total_clicks.toLocaleString()})}),t.jsx("td",{style:{...ae,textAlign:"right",color:"var(--secondary)"},children:We(F.avg_time_ms)}),t.jsx("td",{style:{...ae,textAlign:"right"},children:t.jsx("span",{style:He("#3b82f6"),children:F.unique_users})}),t.jsx("td",{style:ae,children:ds(F.last_activity)}),t.jsx("td",{style:ae,children:t.jsx("button",{onClick:()=>Ke(F.page_path),style:{padding:"4px 12px",borderRadius:"6px",border:"1px solid var(--glass-border)",background:"var(--glass-highlight)",color:"var(--text-primary)",cursor:"pointer",fontSize:"12px"},children:"Detalhar →"})})]},F.page_path)})})]})})()})]}),s==="detail"&&!l&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:Ne,children:[t.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold",fontSize:"14px"},children:"Selecionar Página"}),t.jsxs("select",{value:G,onChange:j=>{E(j.target.value),J("pagina")},style:{padding:"0.6rem 1rem",borderRadius:"var(--radius-md)",border:"1px solid var(--glass-border)",background:"var(--glass-bg)",color:"var(--text-primary)",width:"100%",maxWidth:"500px"},children:[t.jsx("option",{value:"",children:"— Selecione uma página —"}),W.map(j=>t.jsxs("option",{value:j.page_path,children:[we(j.page_path)," (",j.total_clicks," clicks)"]},j.page_path))]})]}),G&&t.jsxs(t.Fragment,{children:[t.jsxs("h3",{style:{margin:0},children:["📈 Uso ao longo do tempo · ",t.jsx("span",{style:{color:"var(--secondary)"},children:we(G)}),X==="ramo"&&t.jsx("span",{style:{fontSize:"12px",color:"var(--text-muted)"},children:" (ramo inteiro)"})]}),t.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[t.jsx("button",{style:Le(X==="pagina"),onClick:()=>J("pagina"),children:"📄 Só esta página"}),t.jsx("button",{style:Le(X==="ramo"),onClick:()=>J("ramo"),children:"🌳 Esta página + tudo abaixo"})]}),t.jsx(Yn,{dados:U,carregando:Y}),t.jsxs("h3",{style:{margin:0},children:["🔍 Interações em ",t.jsx("span",{style:{color:"var(--secondary)"},children:we(G)})]}),t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx(ce,{column:"event_type",sort:R,style:oe,firstDir:"asc",children:"Tipo"}),t.jsx(ce,{column:"element_tag",sort:R,style:oe,firstDir:"asc",children:"Elemento"}),t.jsx(ce,{column:"element_text",sort:R,style:oe,firstDir:"asc",children:"Texto"}),t.jsx(ce,{column:"element_id",sort:R,style:oe,firstDir:"asc",children:"ID"}),t.jsx(ce,{column:"click_count",sort:R,style:oe,children:"Eventos"}),t.jsx(ce,{column:"users",sort:R,style:oe,children:"Usuários"})]})}),t.jsx("tbody",{children:M.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:6,style:{...ae,textAlign:"center",color:"var(--text-muted)",padding:"2rem"},children:"Nenhuma interação registrada nesta página."})}):Rt(M,R,go).map((j,F)=>t.jsxs("tr",{children:[t.jsxs("td",{style:ae,children:[ua(j.event_type)," ",t.jsx("span",{style:{fontSize:"11px",color:"var(--text-muted)"},children:j.event_type})]}),t.jsx("td",{style:ae,children:t.jsx("span",{style:He("#a855f7"),children:j.element_tag||"—"})}),t.jsx("td",{style:{...ae,maxWidth:"300px",overflow:"hidden",textOverflow:"ellipsis"},children:j.element_text||"—"}),t.jsx("td",{style:ae,children:t.jsx("code",{style:{fontSize:"11px",opacity:.7},children:j.element_id||"—"})}),t.jsx("td",{style:{...ae,textAlign:"right",fontWeight:"bold"},children:j.click_count}),t.jsx("td",{style:ae,children:t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:[j.users.slice(0,5).map((Z,ie)=>t.jsx("span",{style:He("#22c55e"),children:Z},ie)),j.users.length>5&&t.jsxs("span",{style:{fontSize:"11px",color:"var(--text-muted)"},children:["+",j.users.length-5]})]})})]},F))})]})})]})]}),s==="time"&&!l&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{style:{margin:0},children:"⏱️ Tempo gasto por página"}),t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx(ce,{column:"page_path",sort:L,style:oe,firstDir:"asc",children:"Página"}),t.jsx(ce,{column:"total_time_ms",sort:L,style:oe,children:"Tempo Total"}),t.jsx(ce,{column:"avg_time_ms",sort:L,style:oe,children:"Tempo Médio"}),t.jsx(ce,{column:"page_views",sort:L,style:oe,children:"Visitas"}),t.jsx(ce,{column:"unique_users",sort:L,style:oe,children:"Usuários"})]})}),t.jsx("tbody",{children:(()=>{const j=Rt(W,L,da);return j.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:5,style:{...ae,textAlign:"center",color:"var(--text-muted)",padding:"2rem"},children:"Nenhum dado de tempo registrado ainda. Dados de tempo aparecem quando usuários saem de uma página."})}):j.map(F=>t.jsxs("tr",{children:[t.jsxs("td",{style:ae,children:[t.jsx("div",{style:{fontWeight:"bold"},children:we(F.page_path)}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)"},children:F.page_path})]}),t.jsx("td",{style:{...ae,textAlign:"right",fontWeight:"bold",color:"var(--secondary)"},children:We(F.total_time_ms)}),t.jsx("td",{style:{...ae,textAlign:"right"},children:We(F.avg_time_ms)}),t.jsx("td",{style:{...ae,textAlign:"right"}
18,children:F.page_views.toLocaleString()}),t.jsx("td",{style:{...ae,textAlign:"right"},children:t.jsx("span",{style:He("#3b82f6"),children:F.unique_users})})]},F.page_path))})()})]})})]}),s==="typing"&&!l&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{style:{margin:0},children:"⌨️ Campos mais digitados"}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)"},children:"Captura apenas a identidade do campo e a quantidade de caracteres digitados — nunca o conteúdo. Campos sensíveis (senha, CPF, cartão) são ignorados."}),t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx(ce,{column:"page_path",sort:O,style:oe,firstDir:"asc",children:"Página"}),t.jsx(ce,{column:"element_text",sort:O,style:oe,firstDir:"asc",children:"Campo"}),t.jsx(ce,{column:"element_tag",sort:O,style:oe,firstDir:"asc",children:"Tag"}),t.jsx(ce,{column:"typing_events",sort:O,style:oe,children:"Eventos"}),t.jsx(ce,{column:"total_chars",sort:O,style:oe,children:"Caracteres"}),t.jsx(ce,{column:"unique_users",sort:O,style:oe,children:"Usuários"}),t.jsx(ce,{column:"last_activity",sort:O,style:oe,children:"Última"})]})}),t.jsx("tbody",{children:me.length===0?t.jsx("tr",{children:t.jsx("td",{colSpan:7,style:{...ae,textAlign:"center",color:"var(--text-muted)",padding:"2rem"},children:"Nenhuma atividade de digitação registrada."})}):Rt(me,O,fo).map((j,F)=>t.jsxs("tr",{children:[t.jsxs("td",{style:ae,children:[t.jsx("div",{style:{fontWeight:"bold",fontSize:"12px"},children:we(j.page_path)}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)"},children:j.page_path})]}),t.jsxs("td",{style:ae,children:[t.jsx("div",{style:{fontSize:"13px"},children:j.element_text||j.element_id||"—"}),j.element_id&&t.jsx("code",{style:{fontSize:"10px",opacity:.6},children:j.element_id})]}),t.jsx("td",{style:ae,children:t.jsx("span",{style:He("#f59e0b"),children:j.element_tag})}),t.jsx("td",{style:{...ae,textAlign:"right",fontWeight:"bold"},children:j.typing_events}),t.jsx("td",{style:{...ae,textAlign:"right"},children:j.total_chars.toLocaleString()}),t.jsx("td",{style:{...ae,textAlign:"right"},children:t.jsx("span",{style:He("#3b82f6"),children:j.unique_users})}),t.jsx("td",{style:ae,children:ds(j.last_activity)})]},F))})]})})]}),s==="users"&&!l&&t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"300px 1fr",gap:"1.5rem"},children:[t.jsxs("div",{style:{...Ne,maxHeight:"700px",overflowY:"auto"},children:[t.jsx("h4",{style:{margin:"0 0 1rem 0",fontSize:"14px"},children:"🏆 Usuários Ativos"}),de.length===0&&t.jsx("div",{style:{color:"var(--text-muted)",fontSize:"13px"},children:"Nenhum usuário ativo no período."}),(()=>{const j=[...de].sort((Z,ie)=>ie.total_time_ms-Z.total_time_ms),F=j[0]?.total_time_ms||1;return j.map((Z,ie)=>{const Se=Ut(ie+1),Ee=fe===Z.user_id;return t.jsxs("div",{onClick:()=>_e(Z.user_id),style:{display:"grid",gridTemplateColumns:"32px 1fr",gap:"8px",padding:"10px 12px",borderRadius:"8px",cursor:"pointer",marginBottom:"4px",transition:"all 0.15s",background:Ee?"rgba(var(--secondary-rgb), 0.15)":"transparent",border:Ee?"1px solid var(--secondary)":"1px solid transparent",alignItems:"center"},children:[t.jsx("div",{style:{textAlign:"center",fontWeight:"bold",color:Se.color,fontSize:Se.isMedal?"1.2rem":"12px"},children:Se.label}),t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontWeight:"bold",fontSize:"13px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.user_name}),t.jsxs("div",{style:{fontSize:"11px",color:"var(--text-muted)",display:"flex",gap:"8px",flexWrap:"wrap",margin:"2px 0 4px"},children:[t.jsxs("span",{children:["⏱️ ",We(Z.total_time_ms)]}),t.jsxs("span",{children:["🖱️ ",Z.clicks]}),t.jsxs("span",{children:["⌨️ ",Z.typing_events]})]}),t.jsx(ls,{value:Z.total_time_ms,max:F,color:"#22c55e",height:4})]})]},Z.user_id)})})()]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:fe===null?t.jsxs("div",{style:{...Ne,textAlign:"center",padding:"3rem",color:"var(--text-muted)"},children:[t.jsx("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"},children:"👈"}),"Selecione um usuário para ver a atividade."]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:Ne,children:[t.jsxs("h4",{style:{margin:"0 0 0.75rem 0"},children:["Atividade de ",t.jsx("span",{style:{color:"var(--secondary)"},children:de.find(j=>j.user_id===fe)?.user_name||`#${fe}`})]}),te.length>0&&t.jsxs("div",{style:{marginBottom:"1rem"},children:[t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",marginBottom:"0.5rem"},children:"Tempo por página"}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"4px",maxHeight:"180px",overflowY:"auto"},children:te.slice(0,20).map(j=>t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px",fontSize:"12px",padding:"4px 8px",background:"rgba(255,255,255,0.02)",borderRadius:"4px"},children:[t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:we(j.page_path)}),t.jsx("span",{style:{flexShrink:0,color:"var(--secondary)",fontWeight:"bold"},children:We(j.total_time_ms)})]},j.page_path))})]})]}),t.jsxs("div",{style:Ne,children:[t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",marginBottom:"0.5rem"},children:"Linha do tempo"}),t.jsxs("div",{style:{maxHeight:"500px",overflowY:"auto"},children:[ke.length===0&&t.jsx("div",{style:{color:"var(--text-muted)",fontSize:"13px"},children:"Nenhuma atividade encontrada."}),ke.map((j,F)=>{const Z=j.metadata&&typeof j.metadata=="object"&&"chars"in j.metadata?Number(j.metadata.chars):null;return t.jsxs("div",{style:{display:"flex",gap:"12px",padding:"8px 0",borderBottom:"1px solid rgba(255,255,255,0.05)"},children:[t.jsx("div",{style:{flexShrink:0,width:"24px",textAlign:"center",fontSize:"14px"},children:ua(j.event_type)}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsxs("div",{style:{fontSize:"13px"},children:[j.event_type==="page_view"&&t.jsxs("span",{children:["Visitou ",t.jsx("strong",{children:we(j.page_path)})]}),j.event_type==="page_leave"&&t.jsxs("span",{children:["Saiu de ",t.jsx("strong",{children:we(j.page_path)})," após ",t.jsx("span",{style:{color:"var(--secondary)",fontWeight:"bold"},children:We(j.duration_ms)})]}),j.event_type==="click"&&t.jsxs("span",{children:["Clicou em ",t.jsx("span",{style:He("#a85
185f7"),children:j.element_tag})," ",t.jsx("strong",{children:j.element_text||j.element_id||"—"})," em ",we(j.page_path)]}),j.event_type==="input"&&t.jsxs("span",{children:["Digitou em ",t.jsx("span",{style:He("#f59e0b"),children:j.element_tag})," ",t.jsx("strong",{children:j.element_text||j.element_id||"—"}),Z!==null&&t.jsxs(t.Fragment,{children:[" — ",t.jsxs("em",{style:{color:"var(--text-muted)"},children:[Z," caracteres"]})]})]}),j.event_type==="submit"&&t.jsxs("span",{children:["Enviou formulário ",t.jsx("strong",{children:j.element_text||j.element_id||"—"})," em ",we(j.page_path)]})]}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)"},children:j.page_path})]}),t.jsx("div",{style:{flexShrink:0,fontSize:"11px",color:"var(--text-muted)",whiteSpace:"nowrap"},children:ds(j.created_at)})]},F)})]})]})]})})]}),s==="content"&&!l&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[t.jsx("button",{style:Le(C==="conteudos"),onClick:()=>N("conteudos"),children:"📝 Por conteúdo"}),t.jsx("button",{style:Le(C==="robos"),onClick:()=>N("robos"),children:"🤖 Robôs"})]}),C==="conteudos"?t.jsx(ao,{rows:$,totals:z}):t.jsx(uo,{dados:k})]})]})}const bo="https://behonest.com.br",xa="#edb125";function $t(s,e={}){const r=le();return fetch(`${bo}${s}`,{...e,headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},...e.headers||{}}})}function vo({onClose:s}){const[e,r]=x.useState([]),[o,l]=x.useState(""),[i,n]=x.useState([]),[m,d]=x.useState({}),[u,p]=x.useState(!1),[y,c]=x.useState(null),[g,h]=x.useState(""),[f,$]=x.useState(null),[S,z]=x.useState(""),[v,k]=x.useState(""),[A,C]=x.useState(!1),[N,W]=x.useState(null),[T,B]=x.useState(!1);x.useEffect(()=>{(async()=>{try{const E=await $t("/api/admin/build/env/targets");if(!E.ok)throw new Error(`${E.status}`);const M=await E.json();r(M.targets||[]),M.targets?.length&&l(M.targets[0].target)}catch(E){c(E instanceof Error?E.message:"Erro ao carregar alvos")}})()},[]),x.useEffect(()=>{const E=M=>{M.key==="Escape"&&s()};return window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E),d({})}},[s]);const w=x.useCallback(async E=>{if(E){p(!0),c(null),d({});try{const M=await $t(`/api/admin/build/env?target=${encodeURIComponent(E)}`);if(!M.ok)throw new Error(`${M.status} ${M.statusText}`);const H=await M.json();
18n(H.entries||[])}catch(M){c(M instanceof Error?M.message:"Erro ao carregar variáveis"),n([])}finally{p(!1)}}},[]);x.useEffect(()=>{w(o)},[o,w]);const D=async E=>{if(m[E]!==void 0){d(({[E]:M,...H})=>H);return}try{const M=await $t("/api/admin/build/env/reveal",{method:"POST",body:JSON.stringify({target:o,key:E})});if(!M.ok)throw new Error(`${M.status}`);const H=await M.json();d(X=>({...X,[E]:H.value}))}catch(M){c(M instanceof Error?M.message:"Erro ao revelar valor")}},q=async E=>{$(E),z(E),C(!0),c(null);try{const M=await $t("/api/admin/build/env/reveal",{method:"POST",body:JSON.stringify({target:o,key:E})});if(!M.ok)throw new Error(`${M.status}`);const H=await M.json();k(H.value||"")}catch(M){c(M instanceof Error?M.message:"Erro ao carregar valor para edição")}},P=()=>{$(""),z(""),k(""),C(!0),c(null)},L=()=>{C(!1),$(null),z(""),k("")},R=async()=>{const E=S.trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(E)){c("Chave inválida — letras, números e _, começando por letra ou _");return}B(!0);try{const M=await $t("/api/admin/build/env",{method:"POST",body:JSON.stringify({target:o,key:E,value:v})}),H=await M.json();if(!M.ok)throw new Error(H.error||`${M.status}`);L(),await w(o)}catch(M){c(M instanceof Error?M.message:"Erro ao salvar")}finally{B(!1)}},O=async E=>{B(!0);try{const M=await $t("/api/admin/build/env",{method:"DELETE",body:JSON.stringify({target:o,key:E})}),H=await M.json();if(!M.ok)throw new Error(H.error||`${M.status}`);W(null),await w(o)}catch(M){c(M instanceof Error?M.message:"Erro ao remover")}finally{B(!1)}},G=i.filter(E=>!g||E.key.toLowerCase().includes(g.toLowerCase()));return t.jsx("div",{onClick:s,style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)",zIndex:1e3,display:"flex",alignItems:"flex-start",justifyContent:"center",padding:"5vh 1rem"},children:t.jsxs("div",{onClick:E=>E.stopPropagation(),style:{background:"var(--glass-bg)",border:"1px solid var(--glass-border)",borderRadius:10,width:"100%",maxWidth:880,maxHeight:"90vh",display:"flex",flexDirection:"column",boxShadow:"0 20px 60px rgba(0,0,0,0.6)"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"14px 18px",borderBottom:"1px solid rgba(255,255,255,0.08)"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:"1.05rem",fontWeight:700,color:"var(--text-primary)"},children:"🔐 Variáveis de Ambiente"}),t.jsx("div",{style:{fontSize:"0.75rem",color:"#6b7280",marginTop:2},children:"Acesso restrito a admins. Toda revelação, criação, edição e remoção é auditada."})]}),t.jsx("button",{onClick:s,style:{background:"transparent",border:"none",color:"var(--text-muted)",fontSize:"1.5rem",cursor:"pointer",lineHeight:1},children:"×"})]}),t.jsxs("div",{style:{display:"flex",gap:10,padding:"12px 18px",borderBottom:"1px solid rgba(255,255,255,0.05)",flexWrap:"wrap",alignItems:"center"},children:[t.jsx("select",{value:o,onChange:E=>l(E.target.value),style:{background:"var(--glass-highlight)",color:"var(--text-primary)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:6,padding:"6px 10px",fontSize:"0.85rem",minWidth:220},children:e.map(E=>t.jsxs("option",{value:E.target,style:{background:"#0a1130",color:"#fff"},children:[E.label,E.exists?"":" (não existe)"]},E.target))}),t.jsx("input",{type:"text",placeholder:"🔍 Filtrar por chave…",value:g,onChange:E=>h(E.target.value),style:{flex:1,minWidth:180,background:"var(--glass-highlight)",color:"var(--text-primary)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:6,padding:"6px 10px",fontSize:"0.85rem"}}),t.jsx("button",{onClick:P,style:{background:xa,color:"#001f54",border:"none",borderRadius:6,padding:"7px 14px",fontWeight:700,cursor:"pointer",fontSize:"0.8rem"},children:"+ Adicionar Variável"})]}),y&&t.jsx("div",{style:{background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.4)",padding:"8px 14px",color:"#fca5a5",fontSize:"0.8rem"},children:y}),A&&t.jsxs("div",{style:{padding:"14px 18px",background:"rgba(237,177,37,0.05)",borderBottom:"1px solid rgba(237,177,37,0.2)",display:"grid",gridTemplateColumns:"1fr 2fr auto",gap:10,alignItems:"flex-end"},children:[t.jsxs("div",{children:[t.jsxs("label",{style:{fontSize:"0.7rem",color:"var(--text-muted)",display:"block",marginBottom:4},children:["CHAVE ",f?"(não editável)":""]}),t.jsx("input",{type:"text",value:S,onChange:E=>z(E.target.value.toUpperCase()),disabled:!!f,placeholder:"MY_API_KEY",spellCheck:!1,autoComplete:"off",style:{width:"100%",background:"rgba(0,0,0,0.3)",color:"var(--text-primary)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:6,padding:"7px 10px",fontSize:"0.85rem",fontFamily:"monospace",opacity:f?.6:1}})]}),t.jsxs("div",{children:[t.jsx("label",{style:{fontSize:"0.7rem",color:"var(--text-muted)",display:"block",marginBottom:4},children:"VALOR"}
18),t.jsx("input",{type:"text",value:v,onChange:E=>k(E.target.value),placeholder:"valor da variável",spellCheck:!1,autoComplete:"off",style:{width:"100%",background:"rgba(0,0,0,0.3)",color:"var(--text-primary)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:6,padding:"7px 10px",fontSize:"0.85rem",fontFamily:"monospace"}})]}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("button",{onClick:L,disabled:T,style:{background:"transparent",color:"var(--text-muted)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:6,padding:"7px 12px",cursor:T?"default":"pointer",fontSize:"0.8rem"},children:"Cancelar"}),t.jsx("button",{onClick:R,disabled:T||!S.trim(),style:{background:xa,color:"#001f54",border:"none",borderRadius:6,padding:"7px 14px",fontWeight:700,cursor:T||!S.trim()?"default":"pointer",fontSize:"0.8rem",opacity:T||!S.trim()?.5:1},children:T?"…":"Salvar"})]})]}),t.jsxs("div",{style:{overflowY:"auto",flex:1,padding:"10px 18px"},children:[u&&t.jsx("div",{style:{color:"var(--text-muted)",textAlign:"center",padding:20},children:"Carregando…"}),!u&&G.length===0&&t.jsx("div",{style:{color:"#6b7280",textAlign:"center",padding:30,fontSize:"0.85rem"},children:g?"Nenhuma variável corresponde ao filtro.":"Nenhuma variável encontrada para este alvo."}),!u&&G.map(E=>{const M=m[E.key],H=M!==void 0;return t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:10,padding:"10px 12px",borderBottom:"1px solid rgba(255,255,255,0.04)",alignItems:"center"},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[t.jsx("span",{style:{fontFamily:"monospace",fontSize:"0.85rem",fontWeight:700,color:"var(--text-primary)"},children:E.key}),E.secret&&t.jsx("span",{style:{fontSize:"0.65rem",color:"#fbbf24",background:"rgba(251,191,36,0.1)",border:"1px solid rgba(251,191,36,0.3)",padding:"1px 6px",borderRadius:4,letterSpacing:.5},children:"SECRET"}),t.jsxs("span",{style:{fontSize:"0.65rem",color:"#6b7280"},children:[E.length," chars"]})]}),t.jsx("div",{style:{fontFamily:"monospace",fontSize:"0.8rem",color:H?"#a7f3d0":"#9ca3af",background:"rgba(0,0,0,0.25)",padding:"5px 8px",borderRadius:4,wordBreak:"break-all",userSelect:H?"all":"none"},children:H?M||"(vazio)":E.preview||"(vazio)"})]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:()=>D(E.key),title:H?"Ocultar valor":"Revelar valor (auditado)",style:rr,children:H?"🙈":"👁"}),t.jsx("button",{onClick:()=>q(E.key),title:"Editar",style:rr,children:"✏️"}),t.jsx("button",{onClick:()=>W(E.key),title:"Remover",style:{...rr,color:"#fca5a5"},children:"🗑"})]})]},E.key)})]}),N&&t.jsxs("div",{style:{padding:"10px 18px",background:"rgba(239,68,68,0.08)",borderTop:"1px solid rgba(239,68,68,0.3)",display:"flex",justifyContent:"space-between",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsxs("div",{style:{fontSize:"0.8rem",color:"#fca5a5"},children:["Remover ",t.jsx("code",{style:{background:"rgba(0,0,0,0.3)",padding:"1px 6px",borderRadius:3},children:N}),"? Um backup do .env será gerado automaticamente."]}),t.jsxs("div",{style:{display:"flex",gap:6},children:[t.jsx("button",{onClick:()=>W(null),disabled:T,style:{background:"transparent",color:"var(--text-muted)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:6,padding:"5px 12px",cursor:T?"default":"pointer",fontSize:"0.75rem"},children:"Cancelar"}),t.jsx("button",{onClick:()=>O(N),disabled:T,style:{background:"#ef4444",color:"#fff",border:"none",borderRadius:6,padding:"5px 12px",fontWeight:700,cursor:T?"default":"pointer",fontSize:"0.75rem",opacity:T?.5:1},children:T?"…":"Remover"})]})]}),t.jsxs("div",{style:{padding:"8px 18px",borderTop:"1px solid rgba(255,255,255,0.05)",fontSize:"0.7rem",color:"#6b7280",display:"flex",justifyContent:"space-between"},children:[t.jsxs("span",{children:["Total: ",i.length," variável(is)"]}),t.jsx("span",{children:"⚠ Mudanças exigem redeploy do alvo para entrar em vigor."})]})]})})}const rr={background:"var(--glass-highlight)",border:"1px solid rgba(255,255,255,0.1)",color:"var(--text-primary)",borderRadius:6,padding:"4px 8px",cursor:"pointer",fontSize:"0.85rem",minWidth:30},jo="https://behonest.com.br",Gt="#edb125";function ha(s,e={}){const r=le();return fetch(`${jo}${s}`,{...e,headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{},...e.headers||{}}})}function So(s,e){return s==="done"?"#22c55e":s==="failed"||e==="failed"?"#ef4444":s==="running"?Gt:"#6b7280"}function ar(s){const e=re.c(13),{label:r,stage:o,jobStatus:l}=s;let i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={display:"flex",alignItems:"center",gap:6},e[0]=i):i=e[0];let n;e[1]!==l||e[2]!==o?(n=So(o,l),e[1]=l,e[2]=o,e[3]=n):n=e[3];const m=o==="running"?`0 0 8px ${Gt}`:"none";let d;e[4]!==n||e[5]!==m?(d=t.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:n,boxShadow:m,transition:"background 0.2s"}}),e[4]=n,e[5]=m,e[6]=d):d=e[6];let u;e[7]===Symbol.for("react.memo_cache_sentinel")?(u={fontSize:"0.75rem",color:"var(--text-muted)"},e[7]=u):u=e[7];let p;e[8]!==r?(p=t.jsx("span",{style:u,children:r}),e[8]=r,e[9]=p):p=e[9];let y;return e[10]!==d||e[11]!==p?(y=t.jsxs("div",{style:i,children:[d,p]}),e[10]=d,e[11]=p,e[12]=y):y=e[12],y}function _o(s){return s?s.status==="success"?`Deployed às ${new Date(s.finished_at||s.started_at||s.requested_at||"").toLocaleStr
18ing("pt-BR")}`:s.status==="failed"?`Falhou — ${s.error||"ver log"}`:s.status==="running"?"Em execução…":"Na fila":"nunca executado"}function ko(){const[s,e]=x.useState([]),[r,o]=x.useState(!0),[l,i]=x.useState(null),[n,m]=x.useState(null),[d,u]=x.useState(!1),p=x.useRef(null),y=x.useCallback(async()=>{try{const g=await ha("/api/admin/build/repos");if(!g.ok)throw new Error(`${g.status} ${g.statusText}`);const h=await g.json();e(h.rows||[]),i(null)}catch(g){i(g instanceof Error?g.message:"Erro ao carregar")}finally{o(!1)}},[]);x.useEffect(()=>{y()},[y]),x.useEffect(()=>{if(!s.some(h=>h.latest&&(h.latest.status==="queued"||h.latest.status==="running"))){p.current&&(window.clearInterval(p.current),p.current=null);return}if(!p.current)return p.current=window.setInterval(y,2500),()=>{p.current&&(window.clearInterval(p.current),p.current=null)}},[s,y]);async function c(g){try{const h=await ha("/api/admin/build/deploy",{method:"POST",body:JSON.stringify({target:g})});if(!h.ok)throw new Error(`${h.status} ${h.statusText}`);await y()}catch(h){i(h instanceof Error?h.message:"Falha ao enfileirar deploy")}}return r?t.jsxs("div",{style:{padding:"8px 0"},children:[t.jsx("div",{className:"skeleton",style:{height:28,width:220,borderRadius:6,marginBottom:8}}),t.jsx("div",{className:"skeleton",style:{height:14,width:380,borderRadius:4,marginBottom:20}}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 280px), 1fr))",gap:12},children:[1,2,3,4].map(g=>t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:8,padding:14},children:[t.jsx("div",{className:"skeleton",style:{height:18,width:"70%",borderRadius:4,marginBottom:10}}),t.jsx("div",{className:"skeleton",style:{height:12,width:"40%",borderRadius:4,marginBottom:14}}),t.jsx("div",{className:"skeleton",style:{height:14,width:"90%",borderRadius:4}})]},g))})]}):t.jsxs("div",{style:{padding:"8px 0"},children:[t.jsxs("div",{style:{marginBottom:16,display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:12,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx("h2",{style:{margin:0,color:"var(--text-primary)"},children:"🛠 Deploy Painel"}),t.jsx("div",{style:{color:"var(--text-muted)",fontSize:"0.85rem",marginTop:4},children:"Sincroniza commits do GitHub, instala dependências e rebuilda o bundle de produção."})]}),t.jsx("button",{onClick:()=>u(!0),title:"Gerenciar variáveis de ambiente",style:{background:"transparent",color:Gt,border:`1px solid ${Gt}`,borderRadius:6,padding:"8px 14px",fontWeight:700,cursor:"pointer",fontSize:"0.85rem",display:"inline-flex",alignItems:"center",gap:6},children:"🔐 Env"})]}),d&&t.jsx(vo,{onClose:()=>u(!1)}),l&&t.jsx("div",{style:{background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.4)",padding:10,borderRadius:6,color:"#fca5a5",marginBottom:12},children:l}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 280px), 1fr))",gap:12},children:s.map(g=>{const h=g.latest,f=h&&(h.status==="queued"||h.status==="running");return t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:8,padding:14},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)"},children:g.label}),t.jsx("div",{style:{fontSize:"0.7rem",color:"#6b7280"},children:g.target})]}),t.jsx("button",{onClick:()=>c(g.target),disabled:!!f,style:{background:f?"rgba(255,255,255,0.06)":Gt,color:f?"#9ca3af":"#001f54",border:"none",borderRadius:6,padding:"6px 12px",fontWeight:700,cursor:f?"default":"pointer",fontSize:"0.8rem"},children:f?"…":"Deploy"})]}),t.jsxs("div",{style:{display:"flex",gap:12,marginBottom:8},children:[t.jsx(ar,{label:"Sync",stage:h?.stage_sync??null,jobStatus:h?.status??null}),t.jsx(ar,{label:"Build",stage:h?.stage_build??null,jobStatus:h?.status??null}),t.jsx(ar,{label:"Deploy",stage:h?.stage_deploy??null,jobStatus:h?.status??null})]}),t.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-muted)",minHeight:18},children:_o(h)}),h&&t.jsx("button",{onClick:()=>m(n===h.id?null:h.id),style:{marginTop:8,background:"transparent",border:"1px solid rgba(255,255,255,0.12)",color:"var(--text-muted)",borderRadius:4,padding:"4px 8px",fontSize:"0.7rem",cursor:"pointer"},children:n===h.id?"Esconder log ▴":"Ver log ▾"}),h&&n===h.id&&t.jsx("pre",{style:{marginTop:8,padding:10,background:"#0a0e1a",border:"1px solid rgba(255,255,255,0.08)",borderRadius:4,color:"#cbd5e1",fontSize:"0.7rem",maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:h.output||"(sem saída ainda)"})]},g.target)})})]})}const wo="https://behonest.com.br",dt="#edb125";
18function Ue(s){return s==null?"—":s.toLocaleString("pt-BR")}function Co(s){if(!s)return"—";try{return new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})}catch{return s}}function ga(s){const[e,r]=s.split("-");return`${["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"][Math.max(0,Math.min(11,Number(r)-1))]}/${e.slice(2)}`}function $o(){const s=re.c(51),[e,r]=x.useState(null),[o,l]=x.useState(!0),[i,n]=x.useState(!1),[m,d]=x.useState(null),[u,p]=x.useState(null);let y;s[0]===Symbol.for("react.memo_cache_sentinel")?(y=function(ge){const Re=ge===void 0?!1:ge;Re?n(!0):l(!0);const xe=le();fetch(`${wo}/api/painel/repositorios/summary${Re?"?refresh=1":""}`,{headers:{...xe?{Authorization:`Bearer ${xe}`}:{}}}).then(No).then(ye=>{r(ye),d(null)}).catch(ye=>d(ye instanceof Error?ye.message:"Erro")).finally(()=>{l(!1),n(!1)})},s[0]=y):y=s[0];const c=y;let g,h;s[1]===Symbol.for("react.memo_cache_sentinel")?(g=()=>{c(!1)},h=[],s[1]=g,s[2]=h):(g=s[1],h=s[2]),x.useEffect(g,h);let f;s[3]!==e?.contributors?(f=e?.contributors||[],s[3]=e?.contributors,s[4]=f):f=s[4];let $;s[5]!==f?($=f.slice(0,10),s[5]=f,s[6]=$):$=s[6];const S=$;let z;e:{if(!e){let ge;s[7]===Symbol.for("react.memo_cache_sentinel")?(ge=[],s[7]=ge):ge=s[7],z=ge;break e}let te;if(s[8]!==u||s[9]!==e.timeline||s[10]!==S){const ge=new Map,Re=new Set(S.map(To));for(const xe of e.timeline){if(u){if(xe.email!==u)continue}else if(!Re.has(xe.email))continue;const ye=ge.get(xe.month)||{month:xe.month,insertions:0,deletions:0,commits:0};ye.insertions=ye.insertions+xe.insertions,ye.deletions=ye.deletions+xe.deletions,ye.commits=ye.commits+xe.commits,ge.set(xe.month,ye)}te=Array.from(ge.values()).sort(Ro),s[8]=u,s[9]=e.timeline,s[10]=S,s[11]=te}else te=s[11];z=te}const v=z,k=v.reduce(Ao,0);let A;s[12]===Symbol.for("react.memo_cache_sentinel")?(A={background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:8,padding:16},s[12]=A):A=s[12];const C=A;let N;s[13]===Symbol.for("react.memo_cache_sentinel")?(N={fontSize:11,letterSpacing:"0.12em",textTransform:"uppercase",color:"var(--text-muted)"},s[13]=N):N=s[13];const W=N;let T;s[14]===Symbol.for("react.memo_cache_sentinel")?(T={fontSize:28,fontWeight:800,fontVariantNumeric:"tabular-nums",marginTop:4},s[14]=T):T=s[14];const B=T;let w;s[15]===Symbol.for("react.memo_cache_sentinel")?(w={width:"100%",borderCollapse:"collapse",fontSize:13,color:"var(--text-primary)"},s[15]=w):w=s[15];const D=w;let q;s[16]===Symbol.for("react.memo_cache_sentinel")?(q={textAlign:"left",padding:"10px 12px",borderBottom:"1px solid rgba(255,255,255,0.10)",fontWeight:700,fontSize:11,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--text-secondary)"},s[16]=q):q=s[16];const P=q;let L;s[17]===Symbol.for("react.memo_cache_sentinel")?(L={padding:"10px 12px",borderBottom:"1px solid rgba(255,255,255,0.06)"},s[17]=L):L=s[17];const R=L;let O;s[18]===Symbol.for("react.memo_cache_sentinel")?(O={...R,textAlign:"right",fontVariantNumeric:"tabular-nums"},s[18]=O):O=s[18];const G=O;let E;s[19]===Symbol.for("react.memo_cache_sentinel")?(E={...P,textAlign:"right"},s[19]=E):E=s[19];const M=E;let H,X,J,U;s[20]===Symbol.for("react.memo_cache_sentinel")?(H={display:"flex",flexDirection:"column",gap:16},X={display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},J=t.jsx("h2",{style:{margin:0,fontSize:18,color:"var(--text-primary)"},children:"Repositórios"}),U={color:"var(--text-muted)",fontSize:13,marginTop:2},s[20]=H,s[21]=X,s[22]=J,s[23]=U):(H=s[20],X=s[21],J=s[22],U=s[23]);let K;s[24]!==e||s[25]!==o?(K=o?"Carregando estatísticas…":e?`${e.total_repos} repositórios · ${Ue(e.total_commits)} commits · ${Ue(e.total_insertions)} linhas adicionadas no total.`:"Sem dados disponíveis.",s[24]=e,s[25]=o,s[26]=K):K=s[26];let Y;s[27]!==K?(Y=t.jsxs("div",{children:[J,t.jsx("div",{style:U,children:K})]}),s[27]=K,s[28]=Y):Y=s[28];let Q;s[29]===Symbol.for("react.memo_cache_sentinel")?(Q=()=>c(!0),s[29]=Q):Q=s[29];const me=i?"default":"pointer";let ue;s[30]!==me?(ue={background:"var(--glass-highlight)",border:"1px solid rgba(255,255,255,0.12)",color:"var(--text-secondary)",padding:"6px 12px",borderRadius:6,fontSize:13,cursor:me},s[30]=me,s[31]=ue):ue=s[31];const de=i?"Recalculando…":"↻ Atualizar";let je;s[32]!==i||s[33]!==ue||s[34]!==de?(je=t.jsx("button",{type:"button",disabled:i,onClick:Q,style:ue,children:de}
18),s[32]=i,s[33]=ue,s[34]=de,s[35]=je):je=s[35];let fe;s[36]!==Y||s[37]!==je?(fe=t.jsxs("div",{style:X,children:[Y,je]}),s[36]=Y,s[37]=je,s[38]=fe):fe=s[38];let _e;s[39]!==m?(_e=m&&t.jsxs("div",{style:{...C,borderColor:"rgba(239,68,68,0.45)",background:"rgba(239,68,68,0.08)"},children:[t.jsx("strong",{style:{color:"#ef4444"},children:"Erro · "}),m]}),s[39]=m,s[40]=_e):_e=s[40];let ke;s[41]!==u||s[42]!==e||s[43]!==o||s[44]!==k||s[45]!==v?(ke=o?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 160px), 1fr))",gap:12},children:[1,2,3,4].map(te=>t.jsxs("div",{style:C,children:[t.jsx("div",{className:"skeleton",style:{height:12,width:"60%",borderRadius:4,marginBottom:12}}),t.jsx("div",{className:"skeleton",style:{height:28,width:"80%",borderRadius:6}})]},te))}),t.jsx("div",{style:C,children:[1,2,3,4,5,6].map(zo)})]}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 160px), 1fr))",gap:12},children:[t.jsxs("div",{style:C,children:[t.jsx("div",{style:W,children:"Repositórios"}),t.jsx("div",{style:{...B,color:dt},children:Ue(e.total_repos)})]}),t.jsxs("div",{style:C,children:[t.jsx("div",{style:W,children:"Commits"}),t.jsx("div",{style:{...B,color:dt},children:Ue(e.total_commits)})]}),t.jsxs("div",{style:C,children:[t.jsx("div",{style:W,children:"Linhas +"}),t.jsx("div",{style:{...B,color:"#22c55e"},children:Ue(e.total_insertions)})]}),t.jsxs("div",{style:C,children:[t.jsx("div",{style:W,children:"Linhas −"}),t.jsx("div",{style:{...B,color:"#ef4444"},children:Ue(e.total_deletions)})]})]}),t.jsxs("div",{style:C,children:[t.jsx("h3",{style:{margin:"0 0 12px",fontSize:14,color:dt},children:"Repositórios"}),t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:D,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:P,children:"Repositório"}),t.jsx("th",{style:M,children:"Commits"}),t.jsx("th",{style:P,children:"Último commit"}),t.jsx("th",{style:M,children:"Contribuidores"})]})}),t.jsx("tbody",{children:e.repos.map(te=>t.jsxs("tr",{children:[t.jsx("td",{style:R,children:t.jsx("strong",{children:te.name})}),t.jsx("td",{style:G,children:te.error?"—":Ue(te.commits)}),t.jsx("td",{style:R,children:te.error?t.jsx("span",{style:{color:"#ef4444"},children:te.error}):Co(te.last_commit)}),t.jsx("td",{style:G,children:te.error?"—":Ue(te.contributors)})]},te.name))})]})})]}),t.jsxs("div",{style:C,children:[t.jsx("h3",{style:{margin:"0 0 12px",fontSize:14,color:dt},children:"Contribuidores"}),t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:D,children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{...P,width:24}}),t.jsx("th",{style:P,children:"Autor"}),t.jsx("th",{style:M,children:"Commits"}),t.jsx("th",{style:{...M,color:"#22c55e"},children:"Linhas +"}),t.jsx("th",{style:{...M,color:"#ef4444"},children:"Linhas −"}),t.jsx("th",{style:P,children:"Volume relativo"})]})}),t.jsx("tbody",{children:e.contributors.map(te=>{const ge=e.contributors[0]?.insertions||1,Re=te.insertions/ge*100,xe=u===te.email;return t.jsxs("tr",{onClick:()=>p(xe?null:te.email),style:{cursor:"pointer",background:xe?"rgba(237,177,37,0.08)":void 0},title:"Clique para filtrar a linha do tempo abaixo por este autor",children:[t.jsx("td",{style:R,children:xe?"●":""}),t.jsx("td",{style:R,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[t.jsx("strong",{children:te.name}),t.jsx("span",{style:{fontSize:11,color:"var(--text-muted)"},children:te.email})]})}),t.jsx("td",{style:G,children:Ue(te.commits)}),t.jsxs("td",{style:{...G,color:"#22c55e"},children:["+",Ue(te.insertions)]}),t.jsxs("td",{style:{...G,color:"#ef4444"},children:["−",Ue(te.deletions)]}),t.jsx("td",{style:{...R,minWidth:140},children:t.jsx("div",{style:{height:8,background:"var(--glass-highlight)",borderRadius:4,overflow:"hidden"},children:t.jsx("div",{style:{height:"100%",width:`${Re}%`,background:`linear-gradient(90deg, ${dt}, rgba(237,177,37,0.5))`,transition:"width 0.3s ease"}})})})]},te.email)})})]})})]}),t.jsxs("div",{style:C,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[t.jsx("h3",{style:{margin:0,fontSize:14,color:dt},children:"Linhas adicionadas por mês"}),u&&t.jsx("button",{type:"button",onClick:()=>p(null),style:{background:"transparent",border:"1px solid rgba(255,255,255,0.15)",color:"var(--text-secondary)",padding:"4px 10px",borderRadius:6,fontSize:12,cursor:"pointer"},children:"Limpar filtro"})]}),t.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:8},children:u?`Filtrado: ${e.contributors.find(te=>te.email===u)?.name||u}`:"Soma dos top 10 contribuidores. Clique em uma linha da tabela acima para filtrar."}),v.length===0?t.jsx("div",{style:{color:"var(--text-muted)",fontSize:13,padding:20,textAlign:"center"},children:"Sem dados"}):t.jsx("div",{style:{display:"grid",gridAutoFlow:"column",gridAutoColumns:"minmax(36px, 1fr)",gap:6,alignItems:"end",height:220,padding:"8px 4px 0",overflowX:"auto"},children:v.map(te=>{const ge=k===0?0:te.insertions/k*100;return t.jsxs("div",{title:`${ga(te.month)} · +${Ue(te.insertions)} · ${Ue(te.commits)} commits`,style:{display:"flex",flexDirection:"column",gap:6,minWidth:36},children:[t.jsx("div",{style:{flex:1,display:"flex",alignItems:"flex-end",background:"rgba(255,255,255,0.04)",borderRadius:4,border:"1px solid rgba(255,255,255,0.06)",overflow:"hidden"},children:t.jsx("div",{style:{width:"100%",height:`${ge}%`,background:`linear-gradient(180deg, ${dt}, rgba(237,177,37,0.45))`,borderTop:`1px solid ${dt}`,transition:"height 0.4s cubic-bezier(0.4, 0, 0.2, 1)"}})}
18),t.jsx("div",{style:{fontSize:10,color:"var(--text-muted)",textAlign:"center",letterSpacing:"0.04em"},children:ga(te.month)})]},te.month)})})]})]}):null,s[41]=u,s[42]=e,s[43]=o,s[44]=k,s[45]=v,s[46]=ke):ke=s[46];let Be;return s[47]!==fe||s[48]!==_e||s[49]!==ke?(Be=t.jsxs("div",{style:H,children:[fe,_e,ke]}),s[47]=fe,s[48]=_e,s[49]=ke,s[50]=Be):Be=s[50],Be}function zo(s){return t.jsx("div",{className:"skeleton",style:{height:38,borderRadius:6,marginBottom:8}},s)}function Ao(s,e){return Math.max(s,e.insertions)}function Ro(s,e){return s.month.localeCompare(e.month)}function To(s){return s.email}async function No(s){if(!s.ok)throw new Error(`${s.status} ${s.statusText}`);return s.json()}const fa="https://behonest.com.br",Eo="#edb125";function Lo(s){if(!s)return"—";try{return new Date(s).toLocaleString("pt-BR")}catch{return s}}function Bo(s){const r={error:{bg:"rgba(239,68,68,0.18)",fg:"#fca5a5",border:"rgba(239,68,68,0.55)"},warn:{bg:"rgba(255,138,0,0.18)",fg:"#ffa94d",border:"rgba(255,138,0,0.55)"},info:{bg:"rgba(56,189,248,0.16)",fg:"#7dd3fc",border:"rgba(56,189,248,0.55)"}}[s]||{bg:"var(--glass-highlight)",fg:"var(--text-primary)",border:"rgba(255,255,255,0.15)"};return{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:999,fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.06em",background:r.bg,color:r.fg,border:`1px solid ${r.border}`}}function Io(){const[s,e]=x.useState([]),[r,o]=x.useState([]),[l,i]=x.useState(!0),[n,m]=x.useState(null),[d,u]=x.useState(""),[p,y]=x.useState(""),[c,g]=x.useState(""),[h,f]=x.useState(""),[$,S]=x.useState(""),[z,v]=x.useState(200),[k,A]=x.useState(new Set);function C(){i(!0);const w=le(),D=new URLSearchParams;d&&D.set("user_id",d),p.trim()&&D.set("email",p.trim()),c&&D.set("level",c),h&&D.set("source",h),$&&D.set("since",$),D.set("limit",String(z)),fetch(`${fa}/api/admin/logs/user-events?${D.toString()}`,{headers:{Authorization:`Bearer ${w}`}}).then(async q=>{if(!q.ok)throw new Error(`${q.status} ${q.statusText}`);return q.json()}).then(q=>{e(q.rows||[]),m(null)}).catch(q=>m(q instanceof Error?q.message:"Erro")).finally(()=>i(!1))}function N(){const w=le();fetch(`${fa}/api/admin/logs/user-events/users`,{headers:{Authorization:`Bearer ${w}`}}).then(D=>D.ok?D.json():Promise.reject(D.status)).then(D=>o(D.rows||[])).catch(()=>{})}x.useEffect(()=>{N(),C();const w=window.setInterval(C,3e4);return()=>window.clearInterval(w)},[d,p,c,h,$,z]);const W=x.useMemo(()=>{const w={error:0,warn:0,info:0};for(const D of s)D.level in w&&(w[D.level]+=1);return w},[s]),T={background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:8,padding:16},B={background:"var(--glass-highlight)",border:"1px solid rgba(255,255,255,0.12)",color:"var(--text-primary)",padding:"6px 10px",borderRadius:6,fontSize:13,minWidth:0};return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[t.jsx("h3",{style:{margin:0,fontSize:16,color:"var(--text-primary)"},children:"Logs por Usuário"}),t.jsxs("span",{style:{color:"var(--text-muted)",fontSize:12},children:["Auto-atualiza a cada 30s. ",s.length," eventos · ",W.error," erros, ",W.warn," warns, ",W.info," infos."]}),t.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:6},children:t.jsx("button",{type:"button",onClick:C,style:{background:"var(--glass-highlight)",border:"1px solid rgba(255,255,255,0.12)",color:"var(--text-secondary)",padding:"6px 12px",borderRadius:6,fontSize:13,cursor:"pointer"},children:"↻ Atualizar"})})]}),t.jsx("div",{style:T,children:t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 160px), 1fr))",gap:10},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"Usuário"}),t.jsxs("select",{value:d,onChange:w=>u(w.target.value),style:{...B,width:"100%"},children:[t.jsx("option",{value:"",children:"Todos os usuários"}),r.map(w=>t.jsxs("option",{value:w.user_id,children:[w.name||w.email||`#${w.user_id}`," · ",w.events]}
18,w.user_id))]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"Email contém"}),t.jsxs("div",{className:"search-input-wrap",style:{width:"100%"},children:[t.jsx("input",{type:"text",value:p,onChange:w=>y(w.target.value),placeholder:"ex.: @behonest",className:"search-input",style:{...B,width:"100%"}}),p&&t.jsx("button",{type:"button",className:"search-clear","aria-label":"Limpar",onClick:()=>y(""),children:"✕"})]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"Nível"}),t.jsxs("select",{value:c,onChange:w=>g(w.target.value),style:{...B,width:"100%"},children:[t.jsx("option",{value:"",children:"Todos"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"warn",children:"Warn"}),t.jsx("option",{value:"info",children:"Info"})]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"Origem"}),t.jsxs("select",{value:h,onChange:w=>f(w.target.value),style:{...B,width:"100%"},children:[t.jsx("option",{value:"",children:"Todas"}),t.jsx("option",{value:"frontend",children:"Frontend"}),t.jsx("option",{value:"backend",children:"Backend"})]})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"Desde"}),t.jsx("input",{type:"date",value:$,onChange:w=>S(w.target.value),style:{...B,width:"100%"}})]}),t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:"Limite"}),t.jsxs("select",{value:z,onChange:w=>v(Number(w.target.value)),style:{...B,width:"100%"},children:[t.jsx("option",{value:100,children:"100"}),t.jsx("option",{value:200,children:"200"}),t.jsx("option",{value:500,children:"500"}),t.jsx("option",{value:1e3,children:"1000"})]})]})]})}),n&&t.jsxs("div",{style:{...T,borderColor:"rgba(239,68,68,0.45)",background:"rgba(239,68,68,0.08)"},children:[t.jsx("strong",{style:{color:"#ef4444"},children:"Erro · "}),n]}),t.jsx("div",{style:T,children:l&&s.length===0?t.jsx("div",{style:{padding:"0.5rem"},children:[1,2,3,4,5].map(w=>t.jsx("div",{className:"skeleton",style:{height:"38px",borderRadius:"6px",marginBottom:"0.4rem"}},w))}):s.length===0?t.jsx(Et,{icon:"📭",title:"Nenhum evento",subtitle:"Ajuste os filtros ou aguarde novos eventos chegarem."}):t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13,color:"var(--text-primary)"},children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:zt,children:"Data"}),t.jsx("th",{style:zt,children:"Usuário"}),t.jsx("th",{style:zt,children:"Nível"}),t.jsx("th",{style:zt,children:"Origem"}),t.jsx("th",{style:zt,children:"Mensagem"}),t.jsx("th",{style:zt,children:"URL"})]})}),t.jsx("tbody",{children:s.map(w=>{const D=k.has(w.id);return t.jsxs(t.Fragment,{children:[t.jsxs("tr",{onClick:()=>{A(q=>{const P=new Set(q);return P.has(w.id)?P.delete(w.id):P.add(w.id),P})},style:{cursor:w.stack||w.meta?"pointer":"default",background:D?"rgba(237,177,37,0.06)":void 0},children:[t.jsx("td",{style:{...At,whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:Lo(w.created_at)}),t.jsx("td",{style:At,children:t.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[t.jsx("strong",{children:w.user_name||w.user_email||(w.user_id?`#${w.user_id}`:"—")}),w.user_email&&w.user_name&&t.jsx("span",{style:{fontSize:11,color:"var(--text-muted)"},children:w.user_email})]})}),t.jsx("td",{style:At,children:t.jsx("span",{style:Bo(w.level),children:w.level})}),t.jsx("td",{style:At,children:t.jsx("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:4,background:"var(--glass-highlight)",color:"var(--text-secondary)"},children:w.source})}),t.jsx("td",{style:{...At,maxWidth:480},children:t.jsx("span",{style:{fontFamily:"ui-monospace, monospace",fontSize:12},children:w.message})}),t.jsx("td",{style:{...At,fontSize:11,color:"var(--text-muted)",maxWidth:240,wordBreak:"break-all"},children:w.url||"—"})]},w.id),D&&(w.stack||w.meta)&&t.jsx("tr",{children:t.jsxs("td",{colSpan:6,style:{padding:"0 12px 12px",background:"rgba(0,0,0,0.18)"},children:[w.stack&&t.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-all",fontSize:11,color:"var(--text-secondary)",margin:"8px 0 0",padding:8,background:"rgba(0,0,0,0.4)",borderRadius:4},children:w.stack}),w.meta&&t.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:11,color:Eo,margin:"8px 0 0",padding:8,background:"rgba(0,0,0,0.4)",borderRadius:4},children:JSON.stringify(w.meta,null,2)})]})},`${w.id}-detail`)]})})})]})})})]})}const zt={textAlign:"left",padding:"8px 12px",borderBottom:"1px solid rgba(255,255,255,0.10)",fontWeight:700,fontSize:11,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--text-secondary)"},At={padding:"8px 12px",borderBottom:"1px solid rgba(255,255,255,0.06)",verticalAlign:"top"},Wo="https://behonest.com.br",Nt=s=>
18(s??0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),nt=s=>Math.round(s??0).toLocaleString("pt-BR"),Aa=s=>{if(!s)return"—";try{return new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return s}};function ya(s){const e=le();return fetch(`${Wo}${s}`,{headers:{...e?{Authorization:`Bearer ${e}`}:{}}}).then(async r=>{if(!r.ok)throw new Error(`${r.status} ${r.statusText}`);return r.json()})}const Po=[{label:"Tudo",value:0},{label:"7 dias",value:7},{label:"30 dias",value:30},{label:"90 dias",value:90}];function Do(){const s=re.c(47);let e;s[0]===Symbol.for("react.memo_cache_sentinel")?(e=[],s[0]=e):e=s[0];const[r,o]=x.useState(e),[l,i]=x.useState(null),[n,m]=x.useState(!0),[d,u]=x.useState(null),[p,y]=x.useState(0),[c,g]=x.useState(null);let h;s[1]===Symbol.for("react.memo_cache_sentinel")?(h=[],s[1]=h):h=s[1];const[f,$]=x.useState(h),[S,z]=x.useState(!1);let v;s[2]!==p?(v=function(){m(!0),ya(`/api/planogram/nivel-par-changes${p?`?days=${p}`:""}`).then(Q=>{o(Q.stores||[]),i(Q.totals),u(null)}).catch(Q=>u(Q instanceof Error?Q.message:"Erro")).finally(()=>m(!1))},s[2]=p,s[3]=v):v=s[3];const k=v;let A;s[4]!==k?(A=()=>{k()},s[4]=k,s[5]=A):A=s[5];let C;s[6]!==p?(C=[p],s[6]=p,s[7]=C):C=s[7],x.useEffect(A,C);let N;s[8]===Symbol.for("react.memo_cache_sentinel")?(N=function(Q){g(Q),z(!0),$([]),ya(`/api/planogram/nivel-par-changes/${encodeURIComponent(Q.store_unique_id)}`).then(me=>$(me.items||[])).catch(()=>$([])).finally(()=>z(!1))},s[8]=N):N=s[8];const W=N;let T;s[9]!==r?(T=[...r].sort(qo),s[9]=r,s[10]=T):T=s[10];const B=T;let w,D,q,P;s[11]===Symbol.for("react.memo_cache_sentinel")?(D={display:"flex",flexDirection:"column",gap:16},q={display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:12},P=t.jsxs("div",{children:[t.jsx("h2",{style:{margin:0},children:"📐 Alterações de Nível Par"}),t.jsx("p",{style:{margin:"4px 0 0",color:"var(--text-muted)",fontSize:13},children:"Mudanças de nível par feitas pelas lojas na página de Insights. Adições viram receita extra potencial; remoções viram economia de estoque."})]}),w={display:"flex",gap:6},s[11]=w,s[12]=D,s[13]=q,s[14]=P):(w=s[11],D=s[12],q=s[13],P=s[14]);let L;s[15]!==p?(L=Po.map(Y=>t.jsx("button",{onClick:()=>y(Y.value),className:p===Y.value?"btn btn-primary":"btn",style:{padding:"6px 12px",fontSize:13},children:Y.label},Y.value)),s[15]=p,s[16]=L):L=s[16];let R;s[17]!==L?(R=t.jsxs("div",{style:q,children:[P,t.jsx("div",{style:w,children:L})]}),s[17]=L,s[18]=R):R=s[18];let O;s[19]!==l?(O=l&&t.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[t.jsx(Ot,{label:"Lojas",value:nt(l.stores)}),t.jsx(Ot,{label:"Alterações",value:nt(l.changes)}),t.jsx(Ot,{label:"Itens alterados",value:nt(l.items_changed)}),t.jsx(Ot,{label:"Receita extra",value:Nt(l.value_up),tone:"up"}),t.jsx(Ot,{label:"Economia",value:Nt(l.value_down),tone:"down"})]}),s[19]=l,s[20]=O):O=s[20];let G;s[21]!==n?(G=n&&t.jsx("div",{style:{color:"var(--text-muted)"},children:"Carregando…"}),s[21]=n,s[22]=G):G=s[22];let E;s[23]!==d?(E=d&&t.jsxs("div",{style:{color:"var(--danger, #e5484d)"},children:["Erro: ",d]}),s[23]=d,s[24]=E):E=s[24];let M;s[25]!==d||s[26]!==n||s[27]!==B.length?(M=!n&&!d&&B.length===0&&t.jsx("div",{style:{color:"var(--text-muted)"},children:"Nenhuma alteração registrada ainda."}),s[25]=d,s[26]=n,s[27]=B.length,s[28]=M):M=s[28];let H;s[29]===Symbol.for("react.memo_cache_sentinel")?(H={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 240px), 1fr))",gap:14},s[29]=H):H=s[29];let X;if(s[30]!==B){let Y;s[32]===Symbol.for("react.memo_cache_sentinel")?(Y=Q=>t.jsxs("button",{onClick:()=>W(Q),style:{textAlign:"left",cursor:"pointer",background:"var(--surface, #1b1b1f)",border:"1px solid var(--border, rgba(255,255,255,0.08))",borderRadius:12,padding:16,color:"inherit",display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:8},children:[t.jsx("strong",{style:{fontSize:15},children:Q.store_name}),t.jsx("span",{style:{fontSize:11,color:"var(--text-muted)"},children:Q.store_unique_id})]}),t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",fontSize:12,color:"var(--text-muted)"},children:[t.jsxs("span",{children:[nt(Q.items_changed)," itens"]}),t.jsx("span",{children:"·"}),t.jsxs("span",{style:{color:"#3fb950"},children:["+",nt(Q.items_added)]}),t.jsxs("span",{style:{color:"#e5a04d"},children:["−",nt(Q.items_removed)]}),t.jsx("span",{children:"·"}),t.jsxs("span",{children:[Q.changes," edições"]})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx(ba,{label:"Receita extra",value:Nt(Q.value_up),tone:"up"}),t.jsx(ba,{label:"Economia",value:Nt(Q.value_down),tone:"down"})]}),t.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)"},children:["Última: ",Aa(Q.last_change)]})]},Q.store_unique_id),s[32]=Y):Y=s[32],X=B.map(Y),s[30]=B,s[31]=X}else X=s[31];let J;s[33]!==X?(J=t.jsx("div",{style:H,children:X}),s[33]=X,s[34]=J):J=s[34];let U;
18s[35]!==f||s[36]!==S||s[37]!==c?(U=c&&t.jsx("div",{onClick:()=>g(null),style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.55)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2e3,padding:20},children:t.jsxs("div",{onClick:Fo,style:{background:"var(--surface, #1b1b1f)",borderRadius:12,padding:20,maxWidth:820,width:"100%",maxHeight:"85vh",overflow:"auto",border:"1px solid var(--border, rgba(255,255,255,0.12))"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[t.jsxs("h3",{style:{margin:0},children:[c.store_name," ",t.jsxs("span",{style:{fontSize:12,color:"var(--text-muted)"},children:["(",c.store_unique_id,")"]})]}),t.jsx("button",{className:"btn",onClick:()=>g(null),style:{padding:"4px 10px"},children:"✕"})]}),S&&t.jsx("div",{style:{color:"var(--text-muted)"},children:"Carregando…"}),!S&&f.length===0&&t.jsx("div",{style:{color:"var(--text-muted)"},children:"Sem detalhes."}),!S&&f.length>0&&t.jsx("div",{style:{overflowX:"auto"},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{textAlign:"left",color:"var(--text-muted)"},children:[t.jsx("th",{style:{padding:"6px 8px"},children:"Produto"}),t.jsx("th",{style:{padding:"6px 8px"},children:"De → Para"}),t.jsx("th",{style:{padding:"6px 8px",textAlign:"right"},children:"Δ un."}),t.jsx("th",{style:{padding:"6px 8px",textAlign:"right"},children:"Preço un."}),t.jsx("th",{style:{padding:"6px 8px",textAlign:"right"},children:"Impacto"}),t.jsx("th",{style:{padding:"6px 8px"},children:"Quando"})]})}),t.jsx("tbody",{children:f.map(Mo)})]})})]})}),s[35]=f,s[36]=S,s[37]=c,s[38]=U):U=s[38];let K;return s[39]!==R||s[40]!==O||s[41]!==G||s[42]!==E||s[43]!==M||s[44]!==J||s[45]!==U?(K=t.jsxs("div",{style:D,children:[R,O,G,E,M,J,U]}),s[39]=R,s[40]=O,s[41]=G,s[42]=E,s[43]=M,s[44]=J,s[45]=U,s[46]=K):K=s[46],K}function Mo(s,e){const r=(s.delta_value??0)>0;return t.jsxs("tr",{style:{borderTop:"1px solid var(--border, rgba(255,255,255,0.06))"},children:[t.jsxs("td",{style:{padding:"6px 8px"},children:[s.product_name||s.product_code,t.jsx("div",{style:{fontSize:11,color:"var(--text-muted)"},children:s.product_code})]}),t.jsxs("td",{style:{padding:"6px 8px"},children:[nt(s.prev_par)," → ",nt(s.new_par)]}),t.jsxs("td",{style:{padding:"6px 8px",textAlign:"right",color:r?"#3fb950":"#e5a04d"},children:[(s.delta_units??0)>0?"+":"",nt(s.delta_units)]}),t.jsx("td",{style:{padding:"6px 8px",textAlign:"right"},children:s.unit_price!=null?Nt(s.unit_price):"—"}),t.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:r?"#3fb950":"#e5a04d"},children:s.delta_value!=null?`${r?"+":"−"}${Nt(Math.abs(s.delta_value))}`:"—"}),t.jsx("td",{style:{padding:"6px 8px",color:"var(--text-muted)"},children:Aa(s.created_at)})]},e)}function Fo(s){return s.stopPropagation()}function qo(s,e){return e.value_up+e.value_down-(s.value_up+s.value_down)}function Ot(s){const e=re.c(12),{label:r,value:o,tone:l}=s,i=l==="up"?"#3fb950":l==="down"?"#e5a04d":"inherit";let n,m;e[0]===Symbol.for("react.memo_cache_sentinel")?(n={background:"var(--surface, #1b1b1f)",border:"1px solid var(--border, rgba(255,255,255,0.08))",borderRadius:10,padding:"10px 16px",minWidth:120},m={fontSize:11,color:"var(--text-muted)"},e[0]=n,e[1]=m):(n=e[0],m=e[1]);let d;e[2]!==r?(d=t.jsx("div",{style:m,children:r}),e[2]=r,e[3]=d):d=e[3];let u;e[4]!==i?(u={fontSize:18,fontWeight:700,color:i},e[4]=i,e[5]=u):u=e[5];let p;e[6]!==u||e[7]!==o?(p=t.jsx("div",{style:u,children:o}),e[6]=u,e[7]=o,e[8]=p):p=e[8];let y;return e[9]!==d||e[10]!==p?(y=t.jsxs("div",{style:n,children:[d,p]}),e[9]=d,e[10]=p,e[11]=y):y=e[11],y}function ba(s){const e=re.c(13),{label:r,value:o,tone:l}=s,i=l==="up"?"#3fb950":"#e5a04d";let n,m;e[0]===Symbol.for("react.memo_cache_sentinel")?(n={flex:1,background:"rgba(255,255,255,0.03)",borderRadius:8,padding:"8px 10px"},m={fontSize:10,color:"var(--text-muted)"},e[0]=n,e[1]=m):(n=e[0],m=e[1]);const d=l==="up"?"↑ ":"↓ ";let u;e[2]!==r||e[3]!==d?(u=t.jsxs("div",{style:m,children:[d,r]}),e[2]=r,e[3]=d,e[4]=u):u=e[4];let p;e[5]!==i?(p={fontSize:14,fontWeight:700,color:i},e[5]=i,e[6]=p):p=e[6];let y;e[7]!==p||e[8]!==o?(y=t.jsx("div",{style:p,children:o}),e[7]=p,e[8]=o,e[9]=y):y=e[9];let c;return e[10]!==u||e[11]!==y?(c=t.jsxs("div",{style:n,children:[u,y]}),e[10]=u,e[11]=y,e[12]=c):c=e[12],c}async function vt(s,e={}){const r=le(),o=await fetch(`${wa}${s}`,{...e,headers:{...e.body?{"Content-Type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}}});if(!o.ok){const l=await o.json().catch(()=>({}));throw new Error(l.error||`Falha na requisição (${o.status})`)}return o.json()}const xt="/api/claude-whatsapp",Oo=()=>vt(`${xt}/acessos`),Uo=s=>vt(`${xt}/rag/usuarios/${s}`),Go=(s,e)=>vt(`${xt}/rag/usuarios/${s}/buscar?q=${encodeURIComponent(e)}`),Ho=s=>vt(`${xt}/rag/memorias/${s}`,{method:"DELETE"}),Vo=s=>vt(`${xt}/rag/reindexar`,{method:"POST",body:JSON.stringify(s?{user_id:s}:{})}),Jo=s=>vt(`${xt}/rag/consolidar`,{method:"POST",body:JSON.stringify({user_id:s})}),Ko=()=>vt(`${xt}/rag/importacoes`).then(s=>s.importacoes);async function Yo(s,e,r){const o=new FormData;o.append("arquivo",s),o.append("simular",e?"1":"0");const l=le(),i=await fetch(`${wa}${xt}/rag/importacoes`,{method:"POST",body:o,headers:l?{Authorization:`Bearer ${l}`}:{}}),n=await i.json().catch(()=>({}));if(!i.ok)throw new Error(n.error||`Falha no envio (${i.status})`);return n}const ut="#3fb950",ot="#e5a04d",tt="var(--secondary, #58a6ff)",st=s=>{if(!s)return"—";const e=new Date(s);
18return isNaN(e.getTime())?s:e.toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})};function Pe(s){const e=re.c(6),{texto:r,cor:o}=s,l=`1px solid ${o}`;let i;e[0]!==o||e[1]!==l?(i={fontSize:11,fontWeight:600,color:o,border:l,borderRadius:999,padding:"2px 8px",whiteSpace:"nowrap"},e[0]=o,e[1]=l,e[2]=i):i=e[2];let n;return e[3]!==i||e[4]!==r?(n=t.jsx("span",{style:i,children:r}),e[3]=i,e[4]=r,e[5]=n):n=e[5],n}function pt(s){const e=re.c(3),{texto:r}=s;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={border:"1px dashed var(--border, rgba(255,255,255,0.15))",borderRadius:12,padding:20,textAlign:"center",color:"var(--text-muted)",fontSize:13},e[0]=o):o=e[0];let l;return e[1]!==r?(l=t.jsx("div",{style:o,children:r}),e[1]=r,e[2]=l):l=e[2],l}function Bt(s){const e=re.c(3),{children:r}=s;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={background:"var(--surface, #1b1b1f)",border:"1px solid var(--border, rgba(255,255,255,0.08))",borderRadius:10,padding:12,display:"flex",flexDirection:"column",gap:6},e[0]=o):o=e[0];let l;return e[1]!==r?(l=t.jsx("div",{style:o,children:r}),e[1]=r,e[2]=l):l=e[2],l}const Ra={fontSize:12,color:"var(--text-muted)"},Xo={fontSize:11,wordBreak:"break-all",padding:"1px 6px",borderRadius:6,background:"var(--bg-secondary, rgba(127,127,127,0.14))",border:"1px solid var(--border, rgba(127,127,127,0.2))"},Qo=[{campo:"paginas",rotulo:"Páginas"},{campo:"rotas",rotulo:"Endpoints"},{campo:"arquivos",rotulo:"Arquivos"},{campo:"tabelas",rotulo:"Tabelas"}];function Zo(s){const e=re.c(12),{itens:r,onEsquecer:o}=s;let l,i;e[0]===Symbol.for("react.memo_cache_sentinel")?(l={display:"flex",flexDirection:"column",gap:8},i=t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"baseline",flexWrap:"wrap"},children:[t.jsx("h4",{style:{margin:0,fontSize:15},children:"Mapa de rotas e páginas"}),t.jsx("span",{style:Ra,children:"Como ele pede cada coisa e onde ela mora — aprendido dos pedidos concluídos."})]}),e[0]=l,e[1]=i):(l=e[0],i=e[1]);let n;e[2]!==r.length?(n=r.length===0&&t.jsx(pt,{texto:"Nenhum mapa ainda — nasce do próximo pedido que mexer no sistema."}),e[2]=r.length,e[3]=n):n=e[3];let m;if(e[4]!==r||e[5]!==o){let u;e[7]!==o?(u=p=>t.jsx(el,{item:p,onEsquecer:()=>o(p)},p.id),e[7]=o,e[8]=u):u=e[8],m=r.map(u),e[4]=r,e[5]=o,e[6]=m}else m=e[6];let d;return e[9]!==n||e[10]!==m?(d=t.jsxs("section",{style:l,children:[i,n,m]}),e[9]=n,e[10]=m,e[11]=d):d=e[11],d}function el(s){const e=re.c(33),{item:r,onEsquecer:o}=s,l=r.dados;if(!l)return null;let i,n;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={display:"flex",justifyContent:"space-between",gap:10,alignItems:"flex-start"},n={fontSize:13},e[0]=i,e[1]=n):(i=e[0],n=e[1]);let m;e[2]!==l.intencao?(m=t.jsx("strong",{style:n,children:l.intencao}),e[2]=l.intencao,e[3]=m):m=e[3];let d;e[4]===Symbol.for("react.memo_cache_sentinel")?(d={padding:"2px 8px",fontSize:11,flexShrink:0},e[4]=d):d=e[4];let u;e[5]!==o?(u=t.jsx("button",{className:"btn",onClick:o,"aria-label":"Esquecer mapa",style:d,children:"Esquecer"}),e[5]=o,e[6]=u):u=e[6];let p;e[7]!==m||e[8]!==u?(p=t.jsxs("div",{style:i,children:[m,u]}),e[7]=m,e[8]=u,e[9]=p):p=e[9];let y;e[10]!==l.termos?(y=l.termos.length>0&&t.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:l.termos.map(sl)}),e[10]=l.termos,e[11]=y):y=e[11];let c;e[12]!==l?(c=Qo.filter(C=>{const{campo:N}=C;return l[N]?.length}).map(C=>{const{campo:N,rotulo:W}=C;return t.jsxs("div",{style:{fontSize:12,display:"flex",gap:6,flexWrap:"wrap"},children:[t.jsx("span",{style:{color:"var(--text-muted)",minWidth:72},children:W}),l[N].map(tl)]},N)}),e[12]=l,e[13]=c):c=e[13];let g;e[14]===Symbol.for("react.memo_cache_sentinel")?(g={display:"flex",gap:10,flexWrap:"wrap",...Ra},e[14]=g):g=e[14];const h=`${l.frequencia} pedido${l.frequencia>1?"s":""}`;let f;e[15]!==h?(f=t.jsx(Pe,{texto:h,cor:ut}),e[15]=h,e[16]=f):f=e[16];const $=r.acessos;let S;e[17]!==r.criado_em?(S=st(r.criado_em),e[17]=r.criado_em,e[18]=S):S=e[18];let z;e[19]!==r.acessos||e[20]!==S?(z=t.jsxs("span",{children:["usado ",$,"× · atualizado ",S]}),e[19]=r.acessos,e[20]=S,e[21]=z):z=e[21];let v;e[22]!==l.fonte?(v=l.fonte==="resposta"&&t.jsx("span",{title:"Sem transcrição da sessão: saiu só do texto da resposta",children:"só da resposta"}),e[22]=l.fonte,e[23]=v):v=e[23];let k;e[24]!==f||e[25]!==z||e[26]!==v?(k=t.jsxs("div",{style:g,children:[f,z,v]}),e[24]=f,e[25]=z,e[26]=v,e[27]=k):k=e[27];let A;return e[28]!==k||e[29]!==p||e[30]!==y||e[31]!==c?(A=t.jsxs(Bt,{children:[p,y,c,k]}),e[28]=k,e[29]=p,e[30]=y,e[31]=c,e[32]=A):A=e[32],A}function tl(s){return t.jsx("code",{style:Xo,children:s},s)}function sl(s){return t.jsx(Pe,{texto:`“${s}”`,cor:tt},s)}const lr={fontSize:12,color:"var(--text-muted)"},rl=[{chave:"perfil",rotulo:"Perfil",cor:tt},{chave:"area",rotulo:"Áreas da memória",cor:tt},{chave:"conversa",rotulo:"Conversas",cor:ut},{chave:"projeto",rotulo:"Projetos",cor:ot},{chave:"arquivo",rotulo:"Arquivos de projeto",cor:ot},{chave:"artefato",rotulo:"Artefatos",cor:ot}];function al(s){const e=[];for(const r of rl){const o=s.filter(i=>i.categoria===r.chave);if(r.chave!=="conversa"){o.length&&e.push({chave:r.chave,rotulo:r.rotulo,cor:r.cor,itens:o});continue}const l=[...new Set(o.map(i=>i.dados?.tipo_conversa||"outros"))].sort();for(const i of l)e.push({chave:`conversa:${i}`,rotulo:`Conversas · ${i}`,cor:r.cor,itens:o.filter(n=>(n.dados?.tipo_conversa||"outros")===i)})}return e}function nl(s){const e=re.c(20),{itens:r,onEsquecer:o}=s;let l;e[0]!==r?(l=al(r),e[0]=r,e[1]=l):l=e[1];const i=l;let n;e[2]!==r?(n=r.filter(ll).reduce(ol,0),e[2]=r,e[3]=n):n=e[3];const m=n;let d,u,p;
18e[4]===Symbol.for("react.memo_cache_sentinel")?(d={display:"flex",flexDirection:"column",gap:8},u={display:"flex",gap:10,alignItems:"baseline",flexWrap:"wrap"},p=t.jsx("h4",{style:{margin:0,fontSize:15},children:"Acervo do claude.ai"}),e[4]=d,e[5]=u,e[6]=p):(d=e[4],u=e[5],p=e[6]);const y=r.length?`${r.length} itens · ${m} conversas resumidas por tipo`:"Importado da exportação de dados do claude.ai.";let c;e[7]!==y?(c=t.jsxs("div",{style:u,children:[p,t.jsx("span",{style:lr,children:y})]}),e[7]=y,e[8]=c):c=e[8];let g;e[9]!==r.length?(g=r.length===0&&t.jsx(pt,{texto:"Nada importado do claude.ai para este usuário."}),e[9]=r.length,e[10]=g):g=e[10];let h;if(e[11]!==i||e[12]!==o){let $;e[14]!==o?($=S=>t.jsxs("details",{children:[t.jsxs("summary",{style:{cursor:"pointer",display:"flex",gap:8,alignItems:"center",padding:"4px 0"},children:[t.jsx(Pe,{texto:`${S.itens.length}`,cor:S.cor}),t.jsx("span",{style:{fontSize:13,fontWeight:600},children:S.rotulo})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:6},children:S.itens.map(z=>t.jsx(il,{item:z,onEsquecer:()=>o(z)},z.id))})]},S.chave),e[14]=o,e[15]=$):$=e[15],h=i.map($),e[11]=i,e[12]=o,e[13]=h}else h=e[13];let f;return e[16]!==c||e[17]!==g||e[18]!==h?(f=t.jsxs("section",{style:d,children:[c,g,h]}),e[16]=c,e[17]=g,e[18]=h,e[19]=f):f=e[19],f}function ol(s,e){return s+(e.dados?.n||1)}function ll(s){return s.categoria==="conversa"}function il(s){const e=re.c(30),{item:r,onEsquecer:o}=s,l=r.dados;let i,n;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={display:"flex",justifyContent:"space-between",gap:10,alignItems:"flex-start"},n={...lr,fontStyle:"italic"},e[0]=i,e[1]=n):(i=e[0],n=e[1]);let m;e[2]!==r.contexto?(m=t.jsx("span",{style:n,children:r.contexto}),e[2]=r.contexto,e[3]=m):m=e[3];let d;e[4]===Symbol.for("react.memo_cache_sentinel")?(d={padding:"2px 8px",fontSize:11,flexShrink:0},e[4]=d):d=e[4];let u;e[5]!==o?(u=t.jsx("button",{className:"btn",onClick:o,"aria-label":"Esquecer item do acervo",style:d,children:"Esquecer"}),e[5]=o,e[6]=u):u=e[6];let p;e[7]!==m||e[8]!==u?(p=t.jsxs("div",{style:i,children:[m,u]}),e[7]=m,e[8]=u,e[9]=p):p=e[9];let y;e[10]===Symbol.for("react.memo_cache_sentinel")?(y={fontSize:13,whiteSpace:"pre-wrap",maxHeight:180,overflow:"auto"},e[10]=y):y=e[10];let c;e[11]!==r.texto?(c=t.jsx("div",{style:y,children:r.texto}),e[11]=r.texto,e[12]=c):c=e[12];let g;e[13]===Symbol.for("react.memo_cache_sentinel")?(g={display:"flex",gap:10,flexWrap:"wrap",...lr},e[13]=g):g=e[13];let h;e[14]!==l?(h=l?.n&&l.n>1&&t.jsx(Pe,{texto:`${l.n} conversas`,cor:ut}),e[14]=l,e[15]=h):h=e[15];let f;e[16]!==r.criado_em?(f=st(r.criado_em),e[16]=r.criado_em,e[17]=f):f=e[17];let $;e[18]!==f?($=t.jsx("span",{children:f}),e[18]=f,e[19]=$):$=e[19];let S;e[20]!==r.acessos?(S=t.jsxs("span",{children:["usado ",r.acessos,"×"]}),e[20]=r.acessos,e[21]=S):S=e[21];let z;e[22]!==h||e[23]!==$||e[24]!==S?(z=t.jsxs("div",{style:g,children:[h,$,S]}),e[22]=h,e[23]=$,e[24]=S,e[25]=z):z=e[25];let v;return e[26]!==z||e[27]!==p||e[28]!==c?(v=t.jsxs(Bt,{children:[p,c,z]}),e[26]=z,e[27]=p,e[28]=c,e[29]=v):v=e[29],v}const va={memoria:{texto:"Memória",cor:tt},conversa:{texto:"Conversa",cor:ut},rota:{texto:"Mapa de rota",cor:ot},acervo:{texto:"claude.ai",cor:tt}},Xe={fontSize:12,color:"var(--text-muted)"},cl=s=>s==null?"—":`${Math.round(s*100)}%`;function dl({usuario:s,onClose:e}){const[r,o]=x.useState(null),[l,i]=x.useState(null),[n,m]=x.useState(null),d=x.useCallback(()=>{Uo(s.user_id).then(o).catch(c=>i(c.message))},[s.user_id]);x.useEffect(d,[d]),x.useEffect(()=>{const c=g=>g.key==="Escape"&&e();return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e]);const u=async c=>{if(window.confirm(`Esquecer isto de ${s.nome}?
19
20${c.texto}`))try{await Ho(c.id),d()}catch(g){i(g.message)}},p=async()=>{m("Compactando (funde parecidos, resume conversas antigas, aplica o teto)…");try{m(`Compactado: ${ja(await Jo(s.user_id))}.`),d()}catch(c){m(null),i(c.message)}},y=async()=>{m("Indexando pedidos pendentes…");try{const c=await Vo(s.user_id);
20m(`${c.indexados} pedido(s) indexado(s)${c.falhas?`, ${c.falhas} com falha`:""}.`),d()}catch(c){m(null),i(c.message)}};return tn.createPortal(t.jsx("div",{onClick:e,style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.55)",zIndex:2e3,padding:16,display:"flex",alignItems:"center",justifyContent:"center"},children:t.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":`Memória de ${s.nome}`,onClick:c=>c.stopPropagation(),style:{background:"var(--bg-card, var(--surface, #1b1b1f))",borderRadius:12,padding:20,maxWidth:900,width:"100%",maxHeight:"88vh",overflow:"auto",border:"1px solid var(--border, rgba(255,255,255,0.12))",display:"flex",flexDirection:"column",gap:18},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12,alignItems:"flex-start",flexWrap:"wrap"},children:[t.jsxs("div",{style:{flex:"1 1 260px"},children:[t.jsxs("h3",{style:{margin:0},children:["🧠 Memória de ",s.nome]}),t.jsx("div",{style:Xe,children:r?`${r.resumo.memorias} memórias · ${r.resumo.rotas} mapas de rota · ${r.resumo.trechos} trechos de conversa · `+(r.resumo.acervo?`${r.resumo.acervo} do claude.ai · `:"")+`indexado em ${st(r.resumo.ultima_indexacao)}`:"Carregando…"})]}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsx("button",{className:"btn",onClick:p,style:{padding:"4px 10px",fontSize:12},children:"Compactar"}),t.jsx("button",{className:"btn",onClick:y,style:{padding:"4px 10px",fontSize:12},children:"Reindexar"}),t.jsx("button",{className:"btn",onClick:e,"aria-label":"Fechar",style:{padding:"4px 10px"},children:"✕"})]})]}),r?.ultima_consolidacao&&t.jsxs("div",{style:Xe,children:["Última compactação (",r.ultima_consolidacao.origem==="manual"?"manual":"automática",")"," ","em ",st(r.ultima_consolidacao.iniciado_em),": ",ja(r.ultima_consolidacao)]}),l&&t.jsxs("div",{style:{color:"var(--danger, #e5484d)",fontSize:13},children:["Erro: ",l]}),n&&t.jsx("div",{style:{...Xe,color:tt},children:n}),r&&t.jsx(ml,{itens:r.memorias,onEsquecer:u}),r&&t.jsx(Zo,{itens:r.rotas,onEsquecer:u}),r&&t.jsx(nl,{itens:r.acervo||[],onEsquecer:u}),t.jsx(ul,{userId:s.user_id}),r&&t.jsx(hl,{consultas:r.consultas})]})}),document.body)}function ja(s){if(!s.antes||!s.depois)return s.erro?`falhou (${s.erro})`:"em andamento";const e=m=>m.memoria+m.rota+m.conversa+(m.acervo||0),[r,o]=[e(s.antes),e(s.depois)],l=s.antes.caracteres?Math.round((1-s.depois.caracteres/s.antes.caracteres)*100):0,i=Object.values(s.detalhes||{}).filter(m=>typeof m=="object").length,n=r===o&&!l?"nada a compactar":`${r} → ${o} itens, texto −${l}%`;return i?`${n} (${i} etapa(s) com erro)`:n}function ir(s){const e=re.c(9),{texto:r,detalhe:o}=s;let l,i;e[0]===Symbol.for("react.memo_cache_sentinel")?(l={display:"flex",gap:10,alignItems:"baseline",flexWrap:"wrap"},i={margin:0,fontSize:15},e[0]=l,e[1]=i):(l=e[0],i=e[1]);let n;e[2]!==r?(n=t.jsx("h4",{style:i,children:r}),e[2]=r,e[3]=n):n=e[3];let m;e[4]!==o?(m=o&&t.jsx("span",{style:Xe,children:o}),e[4]=o,e[5]=m):m=e[5];let d;return e[6]!==n||e[7]!==m?(d=t.jsxs("div",{style:l,children:[n,m]}),e[6]=n,e[7]=m,e[8]=d):d=e[8],d}function ml(s){const e=re.c(12),{itens:r,onEsquecer:o}=s;let l,i;e[0]===Symbol.for("react.memo_cache_sentinel")?(l={display:"flex",flexDirection:"column",gap:8},i=t.jsx(ir,{texto:"Memórias",detalhe:"Fatos duráveis extraídos das conversas. Importância ≥ 4 entra em todo pedido."}),e[0]=l,e[1]=i):(l=e[0],i=e[1]);let n;e[2]!==r.length?(n=r.length===0&&t.jsx(pt,{texto:"Nenhuma memória ainda — ela nasce a cada pedido concluído."}),e[2]=r.length,e[3]=n):n=e[3];let m;if(e[4]!==r||e[5]!==o){let u;e[7]!==o?(u=p=>t.jsxs(Bt,{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"flex-start"},children:[t.jsx("span",{style:{fontSize:13},children:p.texto}),t.jsx("button",{className:"btn",onClick:()=>o(p),"aria-label":"Esquecer memória",style:{padding:"2px 8px",fontSize:11,flexShrink:0},children:"Esquecer"})]}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center",...Xe},children:[p.categoria&&t.jsx(Pe,{texto:p.categoria,cor:tt}),t.jsxs("span",{title:"Importância",children:["★".repeat(p.importancia),"☆".repeat(5-p.importancia)]}),t.jsxs("span",{children:["usada ",p.acessos,"×"]}),t.jsxs("span",{children:["desde ",st(p.criado_em)]})]})]}
20,p.id),e[7]=o,e[8]=u):u=e[8],m=r.map(u),e[4]=r,e[5]=o,e[6]=m}else m=e[6];let d;return e[9]!==n||e[10]!==m?(d=t.jsxs("section",{style:l,children:[i,n,m]}),e[9]=n,e[10]=m,e[11]=d):d=e[11],d}function ul({userId:s}){const[e,r]=x.useState(""),[o,l]=x.useState(null),[i,n]=x.useState(!1),[m,d]=x.useState(null),u=async p=>{if(p.preventDefault(),!!e.trim()){n(!0),d(null);try{l(await Go(s,e.trim()))}catch(y){d(y.message)}finally{n(!1)}}};return t.jsxs("section",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsx(ir,{texto:"Testar recuperação",detalhe:"Simula um pedido dele e mostra o que o Claude receberia (10–20 s)."}),t.jsxs("form",{onSubmit:u,style:{display:"flex",gap:8,flexWrap:"wrap"},children:[t.jsx("input",{value:e,onChange:p=>r(p.target.value),placeholder:"Ex.: qual foi o faturamento de ontem?","aria-label":"Pedido de teste",className:"admin-input",style:{flex:"1 1 260px",padding:"8px 10px"}}),t.jsx("button",{className:"btn btn-primary",disabled:i||!e.trim(),style:{padding:"8px 14px"},children:i?"Buscando…":"Buscar"})]}),m&&t.jsxs("div",{style:{color:"var(--danger, #e5484d)",fontSize:13},children:["Erro: ",m]}),o&&t.jsx(pl,{res:o})]})}function pl(s){const e=re.c(20),{res:r}=s;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={display:"flex",flexDirection:"column",gap:8},e[0]=o):o=e[0];const l=r.itens.length,i=r.ms/1e3;let n;e[1]!==i?(n=i.toFixed(1),e[1]=i,e[2]=n):n=e[2];let m;e[3]!==r.formulacoes.consulta?(m=r.formulacoes.consulta&&t.jsxs(t.Fragment,{children:[" · consulta reescrita: ",t.jsx("em",{children:r.formulacoes.consulta})]}),e[3]=r.formulacoes.consulta,e[4]=m):m=e[4];let d;e[5]!==r.itens.length||e[6]!==n||e[7]!==m?(d=t.jsxs("div",{style:Xe,children:[l," itens em ",n," s",m]}),e[5]=r.itens.length,e[6]=n,e[7]=m,e[8]=d):d=e[8];let u;e[9]!==r.itens.length?(u=r.itens.length===0&&t.jsx(pt,{texto:"Nada relevante na memória para esse pedido."}),e[9]=r.itens.length,e[10]=u):u=e[10];let p;e[11]!==r.itens?(p=r.itens.map(xl),e[11]=r.itens,e[12]=p):p=e[12];let y;e[13]!==r.contexto?(y=r.contexto&&t.jsxs("details",{children:[t.jsx("summary",{style:{cursor:"pointer",...Xe},children:"Ver o bloco exato enviado ao Claude"}),t.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:12,marginTop:8},children:r.contexto})]}),e[13]=r.contexto,e[14]=y):y=e[14];let c;return e[15]!==d||e[16]!==u||e[17]!==p||e[18]!==y?(c=t.jsxs("div",{style:o,children:[d,u,p,y]}),e[15]=d,e[16]=u,e[17]=p,e[18]=y,e[19]=c):c=e[19],c}function xl(s){return t.jsxs(Bt,{children:[t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[t.jsx(Pe,{texto:va[s.tipo].texto,cor:va[s.tipo].cor}),s.nucleo?t.jsx(Pe,{texto:"Núcleo (sempre)",cor:tt}):t.jsxs("span",{style:Xe,children:["relevância ",cl(s.rerank)," · score ",s.score?.toFixed(3)]}),t.jsx("span",{style:Xe,children:st(s.criado_em)})]}),s.contexto&&t.jsx("div",{style:{...Xe,fontStyle:"italic"},children:s.contexto}),t.jsx("div",{style:{fontSize:13,whiteSpace:"pre-wrap",maxHeight:160,overflow:"auto"},children:s.texto})]},s.id)}function hl(s){const e=re.c(9),{consultas:r}=s;let o,l;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={display:"flex",flexDirection:"column",gap:8},l=t.jsx(ir,{texto:"Últimas recuperações",detalhe:"O que o RAG entregou nos pedidos reais dele."}),e[0]=o,e[1]=l):(o=e[0],l=e[1]);let i;e[2]!==r.length?(i=r.length===0&&t.jsx(pt,{texto:"Nenhum pedido passou pelo RAG ainda."}),e[2]=r.length,e[3]=i):i=e[3];let n;e[4]!==r?(n=r.map(gl),e[4]=r,e[5]=n):n=e[5];let m;return e[6]!==i||e[7]!==n?(m=t.jsxs("section",{style:o,children:[l,i,n]}),e[6]=i,e[7]=n,e[8]=m):m=e[8],m}function gl(s){return t.jsxs(Bt,{children:[t.jsx("span",{style:{fontSize:13},children:s.consulta}),t.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap",...Xe},children:[t.jsx("span",{children:st(s.criado_em)}),t.jsxs("span",{children:[s.itens.length," itens (",s.itens.filter(fl).length," do núcleo)"]}),t.jsxs("span",{children:[(s.ms/1e3).toFixed(1)," s"]}),s.job_id&&t.jsxs("span",{children:["pedido #",s.job_id]})]})]},s.id)}function fl(s){return s.nucleo}const Lt={fontSize:12,color:"var(--text-muted)"},yl={rodando:tt,ok:ut,erro:"var(--danger, #e5484d)"},bl=1e4;function vl(){const[s,e]=x.useState([]),[r,o]=x.useState(null),[l,i]=x.useState(!1),[n,m]=x.useState(!1),d=x.useRef(null),u=x.useCallback(()=>
20{Ko().then(e).catch(c=>o(c.message))},[]);x.useEffect(u,[u]);const p=s.some(c=>c.status==="rodando");x.useEffect(()=>{if(!p)return;const c=setInterval(u,bl);return()=>clearInterval(c)},[p,u]);const y=async c=>{c.preventDefault();const g=d.current?.files?.[0];if(g){i(!0),o(null);try{await Yo(g,n),d.current&&(d.current.value=""),u()}catch(h){o(h.message)}finally{i(!1)}}};return t.jsxs("section",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:10,flexWrap:"wrap"},children:[t.jsx("h3",{style:{margin:0,fontSize:16},children:"Importar do claude.ai"}),t.jsx("span",{style:Lt,children:"Exportação de dados da organização (.zip) → RAG de cada usuário, casado pelo e-mail."})]}),t.jsxs("form",{onSubmit:y,style:{display:"flex",gap:10,flexWrap:"wrap",alignItems:"center"},children:[t.jsx("input",{ref:d,type:"file",accept:".zip,application/zip","aria-label":"Arquivo da exportação",style:{flex:"1 1 240px",fontSize:13}}),t.jsxs("label",{style:{...Lt,display:"flex",gap:6,alignItems:"center"},children:[t.jsx("input",{type:"checkbox",checked:n,onChange:c=>m(c.target.checked)})," Só simular"]}),t.jsx("button",{className:"btn btn-primary",disabled:l,style:{padding:"8px 14px"},children:l?"Enviando…":"Importar"})]}),r&&t.jsxs("div",{style:{color:"var(--danger, #e5484d)",fontSize:13},children:["Erro: ",r]}),s.length===0&&t.jsx(pt,{texto:"Nenhuma importação ainda."}),s.map(c=>t.jsx(jl,{imp:c},c.id))]})}function jl(s){const e=re.c(36),{imp:r}=s;let o;e[0]!==r.resultado?.sem_usuario?(o=r.resultado?.sem_usuario||[],e[0]=r.resultado?.sem_usuario,e[1]=o):o=e[1];const l=o;let i;e[2]===Symbol.for("react.memo_cache_sentinel")?(i={display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},e[2]=i):i=e[2];const n=yl[r.status];let m;e[3]!==r.status||e[4]!==n?(m=t.jsx(Pe,{texto:r.status,cor:n}),e[3]=r.status,e[4]=n,e[5]=m):m=e[5];let d;e[6]!==r.simulacao?(d=r.simulacao&&t.jsx(Pe,{texto:"simulação",cor:ot}),e[6]=r.simulacao,e[7]=d):d=e[7];let u;e[8]===Symbol.for("react.memo_cache_sentinel")?(u={fontSize:13,wordBreak:"break-all"},e[8]=u):u=e[8];let p;e[9]!==r.arquivo?(p=t.jsx("strong",{style:u,children:r.arquivo}),e[9]=r.arquivo,e[10]=p):p=e[10];let y;e[11]!==r.iniciado_em?(y=st(r.iniciado_em),e[11]=r.iniciado_em,e[12]=y):y=e[12];let c;e[13]!==r.finalizado_em?(c=r.finalizado_em?` → ${st(r.finalizado_em)}`:"",e[13]=r.finalizado_em,e[14]=c):c=e[14];let g;e[15]!==y||e[16]!==c?(g=t.jsxs("span",{style:Lt,children:[y,c]}),e[15]=y,e[16]=c,e[17]=g):g=e[17];let h;e[18]!==g||e[19]!==m||e[20]!==d||e[21]!==p?(h=t.jsxs("div",{style:i,children:[m,d,p,g]}),e[18]=g,e[19]=m,e[20]=d,e[21]=p,e[22]=h):h=e[22];let f;e[23]!==r.erro?(f=r.erro&&t.jsx("div",{style:{color:"var(--danger, #e5484d)",fontSize:12},children:r.erro}),e[23]=r.erro,e[24]=f):f=e[24];let $;e[25]!==r.usuarios?($=r.usuarios||[],e[25]=r.usuarios,e[26]=$):$=e[26];let S;e[27]!==$?(S=$.map(Sl),e[27]=$,e[28]=S):S=e[28];let z;e[29]!==l?(z=l.length>0&&t.jsxs("div",{style:{...Lt,color:ot},children:["Sem usuário no HRM (não importado): ",l.join(", ")]}),e[29]=l,e[30]=z):z=e[30];let v;return e[31]!==h||e[32]!==f||e[33]!==S||e[34]!==z?(v=t.jsxs(Bt,{children:[h,f,S,z]}),e[31]=h,e[32]=f,e[33]=S,e[34]=z,e[35]=v):v=e[35],v}function Sl(s){return t.jsx(_l,{u:s},s.conta)}function _l(s){const e=re.c(20),{u:r}=s;let o;e[0]!==r.itens?(o=r.itens?Object.entries(r.itens).filter(wl).map(kl).join(" · "):null,e[0]=r.itens,e[1]=o):o=e[1];const l=o;let i,n;e[2]===Symbol.for("react.memo_cache_sentinel")?(i={fontSize:12,display:"flex",gap:8,flexWrap:"wrap",alignItems:"baseline"},n={fontWeight:600},e[2]=i,e[3]=n):(i=e[2],n=e[3]);let m;e[4]!==r.nome?(m=t.jsx("span",{style:n,children:r.nome}),e[4]=r.nome,e[5]=m):m=e[5];const d=r.usuario_hrm||"sem usuário";let u;e[6]!==d||e[7]!==r.como||e[8]!==r.email?(u=t.jsxs("span",{style:Lt,children:[r.email," → ",d," (",r.como,")"]}),e[6]=d,e[7]=r.como,e[8]=r.email,e[9]=u):u=e[9];const p=l??`${r.bruto.conversas} conversas · ${r.bruto.projetos} projetos · ${r.bruto.artefatos} artefatos`,y=r.conversas?` · ${r.conversas.resumidas} conversas resumidas`:"";let c;e[10]!==p||e[11]!==y?(c=t.jsxs("span",{style:Lt,children:[p,y]}),e[10]=p,e[11]=y,e[12]=c):c=e[12];let g;e[13]!==r.erro?(g=r.erro&&t.jsxs("span",{style:{color:"var(--danger, #e5484d)"},children:["falhou: ",r.erro," (reimporte para retomar)"]}),e[13]=r.erro,e[14]=g):g=e[14];let h;return e[15]!==g||e[16]!==m||e[17]!==u||e[18]!==c?(h=t.jsxs("div",{style:i,children:[m,u,c,g]}),e[15]=g,e[16]=m,e[17]=u,e[18]=c,e[19]=h):h=e[19],h}function kl(s){const[e,r]=s;return`${r} ${e}`}function wl(s){const[,e]=s;return e}const Cl=s=>
20s.toLocaleString("pt-BR",{style:"currency",currency:"USD"}),$l=(s,e)=>Number(e.pode_usar)-Number(s.pode_usar)||(e.ultimo_pedido||"").localeCompare(s.ultimo_pedido||"")||s.nome.localeCompare(e.nome);function zl(){const s=re.c(29),[e,r]=x.useState(null),[o,l]=x.useState(null),[i,n]=x.useState(!0),[m,d]=x.useState(null);let u,p;s[0]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{Oo().then(r).catch(T=>l(T.message)).finally(()=>n(!1))},p=[],s[0]=u,s[1]=p):(u=s[0],p=s[1]),x.useEffect(u,p);let y,c;if(s[2]!==e?.usuarios){const T=[...e?.usuarios||[]].sort($l);y=T.filter(Rl),c=T.filter(Al),s[2]=e?.usuarios,s[3]=y,s[4]=c}else y=s[3],c=s[4];let g;s[5]!==y||s[6]!==c?(g={completos:y,limitados:c},s[5]=y,s[6]=c,s[7]=g):g=s[7];const{completos:h,limitados:f}=g;let $,S;s[8]===Symbol.for("react.memo_cache_sentinel")?($={display:"flex",flexDirection:"column",gap:20},S=t.jsxs("div",{children:[t.jsx("h2",{style:{margin:0},children:"🤖 Nest"}),t.jsx("p",{style:{margin:"4px 0 0",color:"var(--text-muted)",fontSize:13},children:"Quem pode pedir alterações ao Claude Code pelo WhatsApp. Só funciona para quem tem celular cadastrado."})]}),s[8]=$,s[9]=S):($=s[8],S=s[9]);let z;s[10]!==e?(z=e&&t.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[t.jsx(is,{label:"Com acesso",value:e.totais.com_acesso}),t.jsx(is,{label:"Podendo usar",value:e.totais.podendo_usar,color:ut}),t.jsx(is,{label:"Sem celular",value:e.totais.com_acesso-e.totais.podendo_usar,color:ot}),t.jsx(is,{label:"Versão limitada",value:e.totais.limitados})]}),s[10]=e,s[11]=z):z=s[11];let v;s[12]!==i?(v=i&&t.jsx("div",{style:{color:"var(--text-muted)"},children:"Carregando…"}),s[12]=i,s[13]=v):v=s[13];let k;s[14]!==o?(k=o&&t.jsxs("div",{style:{color:"var(--danger, #e5484d)"},children:["Erro: ",o]}),s[14]=o,s[15]=k):k=s[15];let A;s[16]!==h||s[17]!==e||s[18]!==f?(A=e&&t.jsxs(t.Fragment,{children:[t.jsx(Sa,{titulo:"Acesso completo",descricao:"Pedem qualquer alteração, com deploy automático.",children:h.length===0?t.jsx(pt,{texto:"Ninguém com acesso completo."}):t.jsx(_a,{usuarios:h,onRag:d})}),t.jsx(Sa,{titulo:"Acesso limitado",descricao:"Versão restrita do Nest.",emBreve:!0,children:f.length===0?t.jsx(pt,{texto:"Ninguém na versão limitada ainda."}):t.jsx(_a,{usuarios:f,onRag:d})})]}),s[16]=h,s[17]=e,s[18]=f,s[19]=A):A=s[19];let C;s[20]===Symbol.for("react.memo_cache_sentinel")?(C=t.jsx(vl,{}),s[20]=C):C=s[20];let N;s[21]!==m?(N=m&&t.jsx(dl,{usuario:m,onClose:()=>d(null)}),s[21]=m,s[22]=N):N=s[22];let W;return s[23]!==A||s[24]!==N||s[25]!==z||s[26]!==v||s[27]!==k?(W=t.jsxs("div",{style:$,children:[S,z,v,k,A,C,N]}),s[23]=A,s[24]=N,s[25]=z,s[26]=v,s[27]=k,s[28]=W):W=s[28],W}function Al(s){return s.nivel==="limitado"}function Rl(s){return s.nivel==="completo"}function Sa(s){const e=re.c(17),{titulo:r,descricao:o,emBreve:l,children:i}=s;let n,m,d;e[0]===Symbol.for("react.memo_cache_sentinel")?(n={display:"flex",flexDirection:"column",gap:12},m={display:"flex",alignItems:"baseline",gap:10,flexWrap:"wrap"},d={margin:0,fontSize:16},e[0]=n,e[1]=m,e[2]=d):(n=e[0],m=e[1],d=e[2]);let u;e[3]!==r?(u=t.jsx("h3",{style:d,children:r}),e[3]=r,e[4]=u):u=e[4];let p;e[5]!==l?(p=l&&t.jsx(Pe,{texto:"Em breve",cor:"var(--text-muted)"}),e[5]=l,e[6]=p):p=e[6];let y;e[7]===Symbol.for("react.memo_cache_sentinel")?(y={fontSize:12,color:"var(--text-muted)"},e[7]=y):y=e[7];let c;e[8]!==o?(c=t.jsx("span",{style:y,children:o}),e[8]=o,e[9]=c):c=e[9];let g;e[10]!==u||e[11]!==p||e[12]!==c?(g=t.jsxs("div",{style:m,children:[u,p,c]}),e[10]=u,e[11]=p,e[12]=c,e[13]=g):g=e[13];let h;return e[14]!==i||e[15]!==g?(h=t.jsxs("section",{style:n,children:[g,i]}),e[14]=i,e[15]=g,e[16]=h):h=e[16],h}function _a(s){const e=re.c(8),{usuarios:r,onRag:o}=s;let l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l={display:"grid",gap:14,gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 260px), 1fr))"},e[0]=l):l=e[0];let i;if(e[1]!==o||e[2]!==r){let m;e[4]!==o?(m=d=>t.jsx(Tl,{u:d,onRag:()=>o(d)},d.user_id),e[4]=o,e[5]=m):m=e[5],i=r.map(m),e[1]=o,e[2]=r,e[3]=i}else i=e[3];let n;return e[6]!==i?(n=t.jsx("div",{style:l,children:i}),e[6]=i,e[7]=n):n=e[7],n}function Tl(s){const e=re.c(65),{u:r,onRag:o}=s,l=`1px solid ${r.pode_usar?"var(--border, rgba(255,255,255,0.08))":ot}`,i=r.pode_usar?1:.8;let n;e[0]!==l||e[1]!==i?(n={background:"var(--surface, #1b1b1f)",border:l,borderRadius:12,padding:16,display:"flex",flexDirection:"column",gap:10,opacity:i},e[0]=l,e[1]=i,e[2]=n):n=e[2];let m,d,u;e[3]===Symbol.for("react.memo_cache_sentinel")?(m={display:"flex",justifyContent:"space-between",gap:8,alignItems:"flex-start"},d={minWidth:0},u={fontSize:15,display:"block"},e[3]=m,e[4]=d,e[5]=u):(m=e[3],d=e[4],u=e[5]);let p;e[6]!==r.nome?(p=t.jsx("strong",{style:u,children:r.nome}),e[6]=r.nome,e[7]=p):p=e[7];let y;e[8]===Symbol.for("react.memo_cache_sentinel")?(y={fontSize:12,color:"var(--text-muted)",wordBreak:"break-all"},e[8]=y):y=e[8];let c;e[9]!==r.email?(c=t.jsx("span",{style:y,children:r.email}),e[9]=r.email,e[10]=c):c=e[10];let g;e[11]!==p||e[12]!==c?(g=t.jsxs("div",{style:d,children:[p,c]}),e[11]=p,e[12]=c,e[13]=g):g=e[13];let h;e[14]!==r.sessao_ativa?(h=r.sessao_ativa&&t.jsx(Pe,{texto:"Conversa aberta",cor:ut}
20),e[14]=r.sessao_ativa,e[15]=h):h=e[15];let f;e[16]!==g||e[17]!==h?(f=t.jsxs("div",{style:m,children:[g,h]}),e[16]=g,e[17]=h,e[18]=f):f=e[18];let $;e[19]===Symbol.for("react.memo_cache_sentinel")?($={display:"flex",gap:6,flexWrap:"wrap"},e[19]=$):$=e[19];const S=r.origem==="admin"?"Admin":"Liberado";let z;e[20]!==S?(z=t.jsx(Pe,{texto:S,cor:tt}),e[20]=S,e[21]=z):z=e[21];let v;e[22]!==r.pode_usar?(v=r.pode_usar?t.jsx(Pe,{texto:"✓ Pode usar",cor:ut}):t.jsx(Pe,{texto:"Sem celular válido",cor:ot}),e[22]=r.pode_usar,e[23]=v):v=e[23];let k;e[24]!==z||e[25]!==v?(k=t.jsxs("div",{style:$,children:[z,v]}),e[24]=z,e[25]=v,e[26]=k):k=e[26];let A;e[27]!==r.motivo?(A=r.motivo&&t.jsxs("div",{style:{fontSize:12,color:"var(--text-muted)"},children:["Motivo: ",r.motivo]}),e[27]=r.motivo,e[28]=A):A=e[28];let C;e[29]===Symbol.for("react.memo_cache_sentinel")?(C={display:"flex",gap:12,fontSize:12,color:"var(--text-muted)",flexWrap:"wrap"},e[29]=C):C=e[29];const N=r.telefone||"—";let W;e[30]!==N?(W=t.jsxs("span",{children:["📱 ",N]}),e[30]=N,e[31]=W):W=e[31];const T=r.pedidos_falha?` (${r.pedidos_falha} com falha)`:"";let B;e[32]!==T||e[33]!==r.pedidos?(B=t.jsxs("span",{children:[r.pedidos," pedidos",T]}),e[32]=T,e[33]=r.pedidos,e[34]=B):B=e[34];let w;e[35]!==r.custo_usd?(w=r.custo_usd>0&&t.jsx("span",{children:Cl(r.custo_usd)}),e[35]=r.custo_usd,e[36]=w):w=e[36];let D;e[37]!==W||e[38]!==B||e[39]!==w?(D=t.jsxs("div",{style:C,children:[W,B,w]}),e[37]=W,e[38]=B,e[39]=w,e[40]=D):D=e[40];let q;e[41]===Symbol.for("react.memo_cache_sentinel")?(q={fontSize:11,color:"var(--text-muted)"},e[41]=q):q=e[41];let P;e[42]!==r.ultimo_pedido?(P=st(r.ultimo_pedido),e[42]=r.ultimo_pedido,e[43]=P):P=e[43];let L;e[44]!==P?(L=t.jsxs("div",{style:q,children:["Último pedido: ",P]}),e[44]=P,e[45]=L):L=e[45];const R=`Abrir a memória (RAG) de ${r.nome}`;let O;e[46]===Symbol.for("react.memo_cache_sentinel")?(O={display:"flex",justifyContent:"space-between",alignItems:"center",gap:8,padding:"6px 10px",fontSize:12},e[46]=O):O=e[46];const G=r.rag.acervo?` · ${r.rag.acervo} do claude.ai`:"";let E;e[47]!==G||e[48]!==r.rag.memorias||e[49]!==r.rag.rotas||e[50]!==r.rag.trechos?(E=t.jsxs("span",{children:["🧠 ",r.rag.memorias," memórias · ",r.rag.rotas," rotas · ",r.rag.trechos," trechos",G]}),e[47]=G,e[48]=r.rag.memorias,e[49]=r.rag.rotas,e[50]=r.rag.trechos,e[51]=E):E=e[51];let M;e[52]===Symbol.for("react.memo_cache_sentinel")?(M=t.jsx("span",{"aria-hidden":!0,children:"›"}),e[52]=M):M=e[52];let H;e[53]!==o||e[54]!==R||e[55]!==E?(H=t.jsxs("button",{type:"button",className:"btn",onClick:o,"aria-label":R,style:O,children:[E,M]}),e[53]=o,e[54]=R,e[55]=E,e[56]=H):H=e[56];let X;return e[57]!==f||e[58]!==k||e[59]!==A||e[60]!==D||e[61]!==L||e[62]!==n||e[63]!==H?(X=t.jsxs("div",{style:n,children:[f,k,A,D,L,H]}),e[57]=f,e[58]=k,e[59]=A,e[60]=D,e[61]=L,e[62]=n,e[63]=H,e[64]=X):X=e[64],X}function is(s){const e=re.c(12),{label:r,value:o,color:l}=s;let i,n;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={background:"var(--surface, #1b1b1f)",border:"1px solid var(--border, rgba(255,255,255,0.08))",borderRadius:10,padding:"10px 16px",minWidth:120},n={fontSize:11,color:"var(--text-muted)"},e[0]=i,e[1]=n):(i=e[0],n=e[1]);let m;e[2]!==r?(m=t.jsx("div",{style:n,children:r}),e[2]=r,e[3]=m):m=e[3];const d=l||"inherit";let u;e[4]!==d?(u={fontSize:18,fontWeight:700,color:d},e[4]=d,e[5]=u):u=e[5];let p;e[6]!==u||e[7]!==o?(p=t.jsx("div",{style:u,children:o}),e[6]=u,e[7]=o,e[8]=p):p=e[8];let y;return e[9]!==m||e[10]!==p?(y=t.jsxs("div",{style:i,children:[m,p]}),e[9]=m,e[10]=p,e[11]=y):y=e[11],y}const Nl="https://behonest.com.br";function El({userId:s,userEmail:e,onToast:r}){const[o,l]=x.useState(!1),[i,n]=x.useState(!1),[m,d]=x.useState(null),[u,p]=x.useState(!1),y=async()=>{n(!0);try{const g=await fetch(`${Nl}/api/admin/users/${s}/reset-password`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${le()}`}}),h=await g.json();if(!g.ok){r("error",h.error||"Erro ao redefinir a senha");return}d(h.temporary_password),l(!1),p(!1),r("success","Senha temporária gerada")}catch(g){console.error(g),r("error","Erro de conexão ao redefinir a senha.")}finally{n(!1)}},c=async()=>
20{if(m)try{await navigator.clipboard.writeText(m),p(!0),setTimeout(()=>p(!1),2e3)}catch{r("error","Não foi possível copiar — selecione e copie manualmente.")}};return t.jsxs("div",{style:{marginTop:"1rem",padding:"0.85rem 1rem",border:"1px solid var(--glass-border)",borderRadius:"8px",background:"var(--glass-highlight)"},children:[t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.75rem",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("strong",{style:{fontSize:"0.9rem"},children:"Redefinir senha"}),t.jsxs("div",{style:{fontSize:"0.78rem",opacity:.75,marginTop:"0.15rem"},children:["Gera uma senha temporária para ",t.jsx("span",{style:{wordBreak:"break-all"},children:e})," e exige a troca no próximo login."]})]}),!o&&t.jsx("button",{type:"button",className:"btn-small",onClick:()=>l(!0),disabled:i,children:"Gerar senha temporária"}),o&&t.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexShrink:0},children:[t.jsx("button",{type:"button",className:"btn-small",onClick:()=>l(!1),disabled:i,children:"Cancelar"}),t.jsx("button",{type:"button",className:"btn-small btn-danger",onClick:y,disabled:i,children:i?"Gerando…":"Confirmar reset"})]})]}),o&&t.jsx("div",{style:{fontSize:"0.78rem",marginTop:"0.6rem",opacity:.85},children:"A senha atual do usuário será invalidada imediatamente, junto com qualquer link de recuperação pendente."}),m&&t.jsxs("div",{style:{marginTop:"0.75rem"},children:[t.jsx("div",{style:{fontSize:"0.78rem",opacity:.75,marginBottom:"0.35rem"},children:"Senha temporária — copie agora, ela não será exibida novamente:"}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",alignItems:"center"},children:[t.jsx("code",{style:{flex:"1 1 180px",padding:"0.5rem 0.65rem",borderRadius:"6px",border:"1px solid var(--glass-border)",background:"var(--glass-bg)",fontSize:"1rem",letterSpacing:"0.06em",userSelect:"all",wordBreak:"break-all"},children:m}),t.jsx("button",{type:"button",className:"btn-small",onClick:c,children:u?"✓ Copiado":"Copiar"})]})]})]})}const he="https://behonest.com.br",Ll=["users","roles","stores","system","contact","redirects","usage","build","repos","nivelpar","claudezap"],ka=s=>Ll.includes(s),Bl=[{id:"orchestrator",label:"Orchestrator"},{id:"access",label:"Access Harvest"},{id:"transactions",label:"Transactions Harvest"},{id:"correlation",label:"Correlation"},{id:"metrics_update",label:"Metrics Update"},{id:"cluster_stats",label:"Cluster Stats"},{id:"inventory_harvest",label:"Inventory Harvest"},{id:"products_harvest",label:"Products Harvest"},{id:"selection",label:"Selection Score"},{id:"market_items",label:"Market Items"},{id:"store_name_sync",label:"Store Name Sync"},{id:"soft_link",label:"Soft Link"},{id:"cleanup_exports",label:"Cleanup Exports"}],Il=[{label:"1s",value:"1"},{label:"30s",value:"30"},{label:"1min",value:"60"},{label:"5min",value:"300"},{label:"15min",value:"900"},{label:"1h",value:"3600"},{label:"6h",value:"21600"},{label:"12h",value:"43200"},{label:"1d",value:"86400"}],Wl=s=>{const e=typeof s=="string"?parseInt(s,10):s;return isNaN(e)||e<=0?String(s):e<60?`${e}s`:e<3600?e%60===0?`${e/60}min`:`${Math.floor(e/60)}min ${e%60}s`:e<86400?e%3600===0?`${e/3600}h`:`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}min`:e%86400===0?`${e/86400}d`:`${Math.floor(e/86400)}d ${Math.floor(e%86400/3600)}h`};function ei(){const{user:s}=sn(),{startImpersonation:e}=rn(),r=an(),[o,l]=nn(),i=o.get("tab")||"",n=ka(i)?i:"users",m=a=>{const b=ka(a)?a:"users",_=new URLSearchParams(o);_.set("tab",b),l(_,{replace:!0})},d=x.useRef(null);x.useEffect(()=>{const a=b=>{(b.metaKey||b.ctrlKey)&&b.key.toLowerCase()==="k"&&(b.preventDefault(),d.current?.focus(),d.current?.select())};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[]);const[u,p]=x.useState(null),[y,c]=x.useState(!1),g=a=>p(a),h=async()=>{if(u)try{c(!0),await u.onConfirm()}finally{c(!1),p(null)}},f=s?.role==="admin",$=async a=>{try{const b=localStorage.getItem("auth_token"),_=await fetch(`${he}/api/admin/impersonate/${a.id}`,{method:"POST",headers:{Authorization:`Bearer ${b}`}});if(!_.ok)throw new Error("Falha ao iniciar visualização");const I=await _.json();e({id:I.user.id,email:I.user.email,name:I.user.name,role:I.user.role,store_access:I.user.store_access}),r("/main")}catch(b){console.error("Impersonate error:",b)}}
20,[S,z]=x.useState([]),[v,k]=x.useState([]),[A,C]=x.useState([]),[N,W]=x.useState([]),[T,B]=x.useState(null),[w,D]=x.useState({status:"healthy"}),[q,P]=x.useState(!0),{getFromCache:L,saveToCache:R}=Rn("admin_v2"),[O,G]=x.useState("orchestrator"),[E,M]=x.useState(""),[H,X]=x.useState(100),[J,U]=x.useState("workers"),[K,Y]=x.useState(Bl),[Q,me]=x.useState(""),[ue,de]=x.useState(""),[je,fe]=x.useState("all"),[_e,ke]=x.useState(""),[Be,te]=x.useState(!1),[ge,Re]=x.useState("dados"),[xe,ye]=x.useState(!1),[pe,Ce]=x.useState(null),[De,Me]=x.useState(null),[rt,Ve]=x.useState(""),[Je,Ke]=x.useState(!1),[Ge,Fe]=x.useState(!1),[be,$e]=x.useState(null),[at,qe]=x.useState(null),[Qe,us]=x.useState(null),[It,ze]=x.useState(""),[Ze,Ye]=x.useState(""),[ht,lt]=x.useState(""),[ve,j]=x.useState("user"),[F,Z]=x.useState([]),[ie,Se]=x.useState([]),[Ee,Wt]=x.useState([]),[Ht,Ta]=x.useState([]),[cr,dr]=x.useState(!1),[Na,ps]=x.useState(!1),[gt,xs]=x.useState([]),[Vt,Ea]=x.useState([]),[mr,ur]=x.useState(!1),[La,hs]=x.useState(!1),[pr,Ba]=x.useState(""),[jt,gs]=x.useState(""),[xr,Jt]=x.use
20State([]),[Ia,hr]=x.useState(!1),[fs,ys]=x.useState(!1),[gr,bs]=x.useState(!1),[Kt,vs]=x.useState(""),[fr,js]=x.useState(50),[yr,Ss]=x.useState(""),[br,_s]=x.useState(!1),[vr,ks]=x.useState(!0),[jr,ws]=x.useState(!1),[Sr,Cs]=x.useState(!1),[_r,$s]=x.useState(!1),[kr,zs]=x.useState(!1),[wr,As]=x.useState(!1),[Cr,Rs]=x.useState(!1),[$r,Ts]=x.useState(!1),[zr,Ns]=x.useState(!1),[Es,Ls]=x.useState(!1),[Ar,Bs]=x.useState(!1),[Rr,Is]=x.useState(!1),[Tr,Ws]=x.useState(!1),[Nr,Ps]=x.useState(!1),[Ds,Ms]=x.useState(!1),[St,Er]=x.useState(!1),[Lr,Br]=x.useState(!1),[Ir,Wr]=x.useState(!1),[Pr,Dr]=x.useState(!1),[Yt,Fs]=x.useState(!1),[qs,Os]=x.useState(!1),[Pl,Us]=x.useState(!1),[Wa,Mr]=x.useState([]),ne=(a,b)=>{const _=Math.random().toString(36).substring(7);Mr(I=>[...I,{id:_,type:a,message:b}])},Pa=a=>{Mr(b=>b.filter(_=>_.id!==a))},ft=a=>{if(!a)return"";const b=new Date(a).getTime(),_=Math.floor((Date.now()-b)/1e3);return _<60?`${_}s`:_<3600?`${Math.floor(_/60)}m ${_%60}s`:`${Math.floor(_/3600)}h ${Math.floor(_%3600/60)}m`},Fr=a=>{if(!a)return"—";const b=new Date(a).getTime(),_=Math.floor((b-Date.now())/1e3);return _<=0?"agora":_<60?`em ${_}s`:_<3600?`em ${Math.floor(_/60)}m`:_<86400?`em ${Math.floor(_/3600)}h`:`em ${Math.floor(_/86400)}d`},qr=a=>{const b=a.schedule_type||"",_=a.schedule_value||"";if(!b&&!_)return"Manual";if(b==="interval"){const I=Number(_);return Number.isFinite(I)&&I>0?I<60?`A cada ${I}s`:I<3600?`A cada ${Math.round(I/60)}min`:I<86400?`A cada ${Math.round(I/3600)}h`:`A cada ${Math.round(I/86400)}d`:`Intervalo: ${_}`}return b==="cron"?`Cron: ${_}`:b==="daily"?`Diário ${_||"00:00"}`:b==="queue"||b==="sequential"?"Sequencial":`${b}: ${_}`};x.useEffect(()=>{_t();const b=setInterval(()=>{et(),n==="system"&&J==="logs"&&Gs()},n==="system"?1e4:3e4);return()=>clearInterval(b)},[n,J]);const et=async a=>{try{const b=le(),_=await fetch(`${he}/api/admin/workers`,{headers:{Authorization:`Bearer ${b}`}});if(_.ok){const I=await _.json();I.workers?(W(I.workers),I.health&&D(I.health),B(I.chain_pipeline||null)):W(I)}}catch(b){console.error(b)}},Da=async()=>{try{const a=le();(await fetch(`${he}/api/admin/workers/chain/start`,{method:"POST",headers:{Authorization:`Bearer ${a}`}})).ok&&(ne("success","Pipeline de dados iniciado"),et())}catch(a){console.error(a)}},Ma=async()=>{try{const a=le();(await fetch(`${he}/api/admin/workers/chain/stop`,{method:"POST",headers:{Authorization:`Bearer ${a}`}})).ok&&(ne("info","Pipeline de dados parado"),et())}catch(a){console.error(a)}},Gs=async()=>{try{const a=le(),b=await fetch(`${he}/api/admin/workers/logs?worker=${O}&lines=${H}`,{headers:{Authorization:`Bearer ${a}`}});if(b.ok){const _=await b.json();M(_.content||"No logs found")}}catch(a){console.error(a),M("Error fetching logs")}},Or=async(a,b=80)=>{Ke(!0);try{const _=le(),V=await(await fetch(`${he}/api/admin/workers/logs?worker=${encodeURIComponent(a)}&lines=${b}`,{headers:{Authorization:`Bearer ${_}`}})).json();Ve(V.content||"Sem logs para este worker.")}catch{Ve("Erro ao carregar os logs.")}finally{Ke(!1)}},Ur=a=>{Me(a),Ve(""),Or(a)},Fa=async()=>{try{const a=le(),b=await fetch(`${he}/api/admin/workers/logs/available`,{headers:{Authorization:`Bearer ${a}`}});if(b.ok){const _=await b.json();Array.isArray(_)&&_.length>0&&Y(_)}}catch(a){console.error("Error fetching available logs:",a)}},_t=async a=>{if(!s)return;const _={Authorization:`Bearer ${le()}`};let I=!1;{const se=L("users"),Te=L("roles"),Ae=L("stores");se&&z(se),Te&&k(Te),Ae&&C(Ae),(n==="users"&&se&&Te||n==="roles"&&Te||n==="stores"&&Ae)&&(I=!0)}I||P(!0);const V=async se=>{try{const Te=await fetch(se,{headers:_});return Te.ok?await Te.json():null}catch(Te){return console.error("fetch failed",se,Te),null}};et();const ee=[];n==="users"?(ee.push(V(`${he}/api/admin/users`).then(se=>{se&&Array.isArray(se)&&(z(se),R("users",se))})),ee.push(V(`${he}/api/admin/roles`).then(se=>{se&&Array.isArray(se)&&(k(se),R("roles",se))}))):n==="roles"?ee.push(V(`${he}/api/admin/roles`).then(se=>{se&&Array.isArray(se)&&(k(se),R("roles",se))})):n==="stores"?ee.push(V(`${he}/api/admin/stores`).then(se=>{se&&Array.isArray(se)&&(C(se),R("stores",se))})):n==="system"&&J==="logs"&&ee.push(Gs()),await Promise.allSettled(ee),P(!1)},Gr=async()=>{const a=le();try{const b=await fetch(`${he}/api/admin/stores`,{headers:{Authorization:`Bearer ${a}`}});if(b.ok){const _=await b.json();Array.isArray(_)&&(C(_),R("stores",_))}}catch(b){console.error("stores load failed",b)}},qa=async a=>{if(a.preventDefault(),!f){ne("error","Modo leitura. Sem permissão para salvar.");return}if(!It.includes("@")){ne("error","Email inválido format.");return}if(!be&&!Ze){ne("error","Senha é obrigatória para novos usuários.");return}try{const b=le(),_=be?`${he}/api/admin/users/${be.id}`:`${he}/api/admin/users`,I=be?"PUT":"POST";console.log("[ADMIN_SAVE_V2]",I,_,{has_promotions_access:fs,evolution_api_token:Kt});
20let V=F;ve==="admin"?V=[]:ve==="fornecedor"?V=[]:V=F;const ee={name:ht,role:ve,store_access:V,product_access:ve==="fornecedor"?ie:[],fornecedor_mix:ve==="fornecedor"?Ee:[],fornecedor_marketplace:ve==="fornecedor"?gt:[],has_promotions_access:fs,mailing:gr,evolution_api_token:Kt,tokens:fr,phone:yr,gestor_de_estoque:br,can_access_hrm:vr,can_access_growth:jr,can_access_bi_opr:Sr,can_access_comercial:_r,can_access_marketing:kr,can_access_logistica:wr,can_access_painel:Cr,can_access_content_generator:$r,can_access_extrabom:zr,can_access_marketplace:Es,can_access_marketplace_mg:Ar,can_access_marketplace_go:Rr,can_access_marketplace_es:Tr,can_access_financeiro:Nr,can_access_fundo_mkt:Ds,can_access_expansao:St,can_access_expansao_mg:St?Lr:!1,can_access_expansao_go:St?Ir:!1,can_access_expansao_df:St?Pr:!1,can_access_classificado:Yt,can_access_classificado_admin:Yt?qs:!1};be?Ze&&(ee.password=Ze):(ee.email=It,ee.password=Ze);const se=await fetch(_,{method:I,headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify(ee)});if(se.ok)te(!1),$e(null),ne("success",be?"Usuário atualizado!":"Usuário criado com sucesso!"),_t();else{const Te=await se.json();ne("error",Te.error||"Erro ao salvar usuário")}}catch(b){console.error(b),ne("error","Erro de conexão ao salvar usuário.")}},Oa=a=>{$e(a),ze(a.email),lt(a.name),j(a.role),Z(a.store_access||[]),Se(a.product_access||[]),Wt(a.fornecedores_mix||[]),xs(a.fornecedores_marketplace||[]),Ye(""),de(""),fe("all"),gs(""),Jt([]),ys(a.has_promotions_access||!1),bs(a.mailing||!1),vs(a.evolution_api_token||""),js(a.tokens??50),Ss(a.phone||""),_s(a.gestor_de_estoque||!1),ks(a.can_access_hrm!==!1),ws(a.can_access_growth||!1),Cs(a.can_access_bi_opr||!1),$s(a.can_access_comercial||!1),zs(a.can_access_marketing||!1),As(a.can_access_logistica||!1),Rs(a.can_access_painel||!1),Ts(a.can_access_content_generator||!1),Ns(a.can_access_extrabom||!1),Ls(a.can_access_marketplace||!1),Bs(a.can_access_marketplace_mg||!1),Is(a.can_access_marketplace_go||!1),Ws(a.can_access_marketplace_es||!1),Ps(a.can_access_financeiro||!1),Ms(a.can_access_fundo_mkt||!1),Er(a.can_access_expansao||!1),Br(a.can_access_expansao_mg||!1),Wr(a.can_access_expansao_go||!1),Dr(a.can_access_expansao_df||!1),Fs(a.can_access_classificado||!1),Os(a.can_access_classificado_admin||!1),Us(!1),Re("dados"),te(!0),Gr()},Ua=()=>{$e(null),ze(""),lt(""),j("user"),Z([]),Se([]),Wt([]),xs([]),Ye(""),de(""),fe("all"),gs(""),Jt([]),ys(!1),bs(!1),vs(""),js(50),Ss(""),_s(!1),ks(!0),ws(!1),Cs(!1),$s(!1),zs(!1),As(!1),Rs(!1),Ts(!1),Ns(!1),Ls(!1),Bs(!1),Is(!1),Ws(!1),Ps(!1),Ms(!1),Fs(!1),Os(!1),Us(!1),Re("dados"),te(!0),Gr()},Hr=a=>{Z(b=>b.includes(a)?b.filter(_=>_!==a):[...b,a])},Vr=a=>{Se(b=>b.includes(a)?b.filter(_=>_!==a):[...b,a])},Jr=a=>{Wt(b=>b.includes(a)?b.filter(_=>_!==a):[...b,a])},Kr=a=>{xs(b=>b.includes(a)?b.filter(_=>_!==a):[...b,a])},Ga=async()=>{if(hs(!0),!(Vt.length||mr)){ur(!0);try{const a=le(),b=await fetch(`${he}/api/marketplace/portal/contexto`,{headers:{Authorization:`Bearer ${a}`}});if(b.ok){const _=await b.json();Ea(_.fornecedores||[])}}catch{}finally{ur(!1)}}},Ha=async()=>{if(ps(!0),!(Ht.length||cr)){dr(!0);try{const a=le(),b=await fetch(`${he}/api/fornecedores`,{headers:{Authorization:`Bearer ${a}`}});if(b.ok){const _=await b.json(),I=Array.isArray(_)?_:_.fornecedores||[];Ta(I.map(V=>({slug:V.slug,nome:V.nome||V.slug,cor:V.cor})))}else ne("error","Falha ao carregar páginas de fornecedor.")}catch(a){console.error("fornecedores load error",a),ne("error","Erro de conexão ao carregar páginas de fornecedor.")}finally{dr(!1)}}};x.useEffect(()=>{if(ve!=="fornecedor"||!jt||jt.length<2){Jt([]);return}const a=setTimeout(async()=>{hr(!0);try{const b=le(),_=await fetch(`${he}/api/products/search?q=${encodeURIComponent(jt)}&limit=20`,{headers:{Authorization:`Bearer ${b}`}});if(_.ok){const I=await _.json(),V=Array.isArray(I)?I:I.products||[];Jt(V.map(ee=>({code:String(ee.code||ee.product_code||ee.id),description:ee.description||ee.name||ee.code,category:ee.category_name||ee.category||""})))}}catch(b){console.error("Product search error:",b)}finally{hr(!1)}},400);return()=>clearTimeout(a)},[jt,ve]);const Va=async a=>{if(!f){ne("error","Sem permissão.");return}try{const b=le(),_=!!a.id,I=_?`${he}/api/admin/roles/${a.id}`:`${he}/api/admin/roles`,ee=await fetch(I,{method:_?"PUT":"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify(a)});if(ee.ok)ye(!1),qe(null),ne("success","Cargo salvo com sucesso!"),_t();else{const se=await ee.json();ne("error",se.error||"Erro ao salvar cargo")}}catch(b){console.error(b),ne("error","Erro de conexão.")}},Ja=a=>{if(s?.role!=="admin"){ne("error","Apenas administradores podem deletar usuários.");return}if(a.id===s?.id){ne("error","Você não pode deletar a própria conta.");return}g({title:"Deletar usuário",message:`Deletar permanentemente ${a.email}? Esta ação não pode ser desfeita.`,confirmLabel:"Deletar",variant:"danger",onConfirm:async()=>{try{const b=le(),_=await fetch(`${he}/api/admin/users/${a.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${b}`}});if(_.ok)ne("success","Usuário deletado."),_t();else{const I=await _.json().catch(()=>({}));ne("error",I.error||`Erro ao deletar (${_.status}).`)}}catch(b){console.error(b),ne("error","Erro de conexão ao deletar usuário.")}}})},Ka=a=>
20{if(!f){ne("error","Sem permissão.");return}g({title:"Deletar cargo",message:"Tem certeza? Isso pode quebrar usuários associados a este cargo.",confirmLabel:"Deletar",variant:"danger",onConfirm:async()=>{try{const b=le(),_=await fetch(`${he}/api/admin/roles/${a}`,{method:"DELETE",headers:{Authorization:`Bearer ${b}`}});if(_.ok)ne("success","Cargo deletado."),_t();else{const I=await _.json();ne("error",I.error||"Erro ao deletar")}}catch(b){console.error(b),ne("error","Erro de conexão.")}}})},Ya=a=>{qe(a),ye(!0)},Xa=()=>{qe(null),ye(!0)},Qa=async a=>{if(!f){ne("error","Sem permissão.");return}try{const b=le(),_=a.unique_id?"PUT":"POST",I=a.unique_id?`${he}/api/admin/stores/${encodeURIComponent(a.unique_id)}`:`${he}/api/admin/stores`,V=await fetch(I,{method:_,headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify(a)});if(V.ok)ne("success","Loja salva!"),Fe(!1),_t();else{const ee=await V.json();ne("error",ee.error||"Erro ao salvar loja")}}catch(b){console.error(b),ne("error","Erro de conexão")}},Za=async a=>{if(a.preventDefault(),!!pe)try{const b=le(),_=a.target,I=_.elements.namedItem("schedule_type").value,V=_.elements.namedItem("schedule_value").value,ee=await fetch(`${he}/api/admin/workers/${pe.name}/config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify({schedule_type:I,schedule_value:V})});if(ee.ok)ne("success","Agendamento atualizado!"),Ce(null),et(!1);else{const se=await ee.json();ne("error",se.error||"Erro ao salvar agendamento")}}catch(b){console.error(b),ne("error","Erro de conexão")}},en=async a=>{if(a.preventDefault(),!!pe)try{const b=le(),_=a.target.closest("form");if(!_)return;const I=_.elements.namedItem("schedule_type").value,V=_.elements.namedItem("schedule_value").value,ee=await fetch(`${he}/api/admin/workers/${pe.name}/apply-restart`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify({schedule_type:I,schedule_value:V})});if(ee.ok)ne("success",`${pe.name}: config atualizada e worker reiniciado!`),Ce(null),et(!1);else{const se=await ee.json();ne("error",se.error||"Erro ao aplicar e reiniciar")}}catch(b){console.error(b),ne("error","Erro de conexão")}},Hs=async a=>{try{const b=le();(await fetch(`${he}/api/admin/workers/${a}/run`,{method:"POST",headers:{Authorization:`Bearer ${b}`}})).ok&&(et(!1),ne("success",`${a} iniciado`))}catch(b){console.error(b)}},Yr=async a=>{try{const b=le();(await fetch(`${he}/api/admin/workers/${a}/stop`,{method:"POST",headers:{Authorization:`Bearer ${b}`}})).ok&&(et(!1),ne("info",`${a} parado`))}catch(b){console.error(b)}},Xr=async a=>{try{const b=le();await fetch(`${he}/api/admin/workers/${a}/toggle`,{method:"POST",headers:{Authorization:`Bearer ${b}`}}),et(!1)}catch(b){console.error(b)}},Pt=a=>a?a.toString().normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim():"",Dt=A.filter(a=>{const b=Q.toLowerCase().trim();return b?a.unique_id&&a.unique_id.toLowerCase().includes(b)||a.name&&a.name.toLowerCase().includes(b):!0}),Xt=S.filter(a=>{const b=_e.toLowerCase().trim();return b?a.name.toLowerCase().includes(b)||a.email.toLowerCase().includes(b):!0}),Mt=x.useMemo(()=>{let a=[...A];if(ue&&ue.trim()!==""){const b=Pt(ue);a=a.filter(_=>{const I=Pt(_.unique_id),V=Pt(_.name),ee=Pt(_.city),se=Pt(_.brand);return I.includes(b)||V.includes(b)||ee.includes(b)||se.includes(b)})}return je!=="all"&&(a=a.filter(b=>Qt(b)===je)),a.sort((b,_)=>(b.unique_id||"").localeCompare(_.unique_id||""))},[A,ue,je]),Vs=x.useMemo(()=>{const a={behonest:[],extrabom:[],franqueados:[]};return A.forEach(b=>{b.unique_id&&a[Qt(b)].push(b.unique_id)}),a},[A]),Js=a=>F.includes(Zr[a]),Qr=a=>{const b=Zr[a],_=Ys[a];if(Js(a))Z(I=>I.filter(V=>V!==b)),ne("info",`${_}: vínculo removido.`);else{const I=new Set(Vs[a]);Z(V=>[...new Set([...V.filter(ee=>!I.has(ee)),b])]),ne("success",`${_}: vinculado — inclui lojas futuras.`)}};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"bg-grid"}),t.jsx("div",{className:"glow-orb glow-orb-1"}),t.jsx("div",{className:"glow-orb glow-orb-2"}),t.jsx(on,{}),t.jsx(zn,{toasts:Wa,onRemove:Pa}),t.jsxs("div",{className:"container",style:{paddingTop:"2rem"}
20,children:[t.jsx(ln,{className:"admin-hero",title:"🛡️ Painel Administrativo",subtitle:"Gerencie usuários, cargos, lojas e configurações do sistema.",action:t.jsx("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:s?.role==="admin"?t.jsx("span",{className:"badge-role badge-role-admin",children:"Admin Total"}):s?.role==="manager"?t.jsx("span",{className:"badge-role badge-role-manager",children:"Manager · Leitura"}):t.jsx("span",{className:"badge-role badge-role-warning",children:"Acesso Limitado"})})}),t.jsxs("div",{className:"glass-card admin-page-glass-card fade-in",children:[t.jsx(ra,{tabs:[{id:"users",icon:"👥",label:"Usuários",count:S.length||void 0},{id:"roles",icon:"🔑",label:"Cargos",count:v.length||void 0},{id:"system",icon:"⚙️",label:"Sistema"},{id:"contact",icon:"📋",label:"Contact Info"},{id:"redirects",icon:"🔗",label:"Redirect Links"},{id:"usage",icon:"📊",label:"Usage"},{id:"build",icon:"🛠",label:"Build"},{id:"repos",icon:"📦",label:"Repositórios"},{id:"nivelpar",icon:"📐",label:"Nível Par"},{id:"claudezap",icon:"🤖",label:"Nest"}],activeTab:n,onTabChange:m}),n==="users"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"admin-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",flexWrap:"wrap",gap:"1rem"},children:[t.jsxs("h3",{children:["Gerenciamento de Usuários",t.jsx("span",{className:"text-muted",style:{fontSize:"0.85rem",fontWeight:400,marginLeft:"0.75rem"},children:Xt.length===S.length?`${S.length} no total`:`${Xt.length} de ${S.length}`})]}),t.jsxs("div",{style:{display:"flex",gap:"1rem"},children:[t.jsxs("div",{className:"search-input-wrap",children:[t.jsx("input",{ref:n==="users"?d:void 0,type:"text",placeholder:"Buscar por nome ou email…",value:_e,onChange:a=>ke(a.target.value),className:"search-input",style:{padding:"0.6rem 1rem",borderRadius:"var(--radius-md)",border:"1px solid var(--glass-border)",background:"var(--glass-bg)",color:"var(--text-primary)",minWidth:"260px"}}),_e?t.jsx("button",{type:"button",className:"search-clear","aria-label":"Limpar busca",onClick:()=>ke(""),children:"✕"}):t.jsx("span",{className:"search-kbd",children:"⌘K"})]}),f&&t.jsx("button",{className:"btn btn-primary",onClick:Ua,children:"+ Novo Usuário"})]})]}),q?t.jsx("div",{style:{padding:"0.5rem"},children:[1,2,3,4,5,6,7,8].map(a=>t.jsx("div",{className:"skeleton",style:{height:"44px",borderRadius:"8px",marginBottom:"0.5rem"}},a))}):Xt.length===0?t.jsx(Et,{icon:_e?"🔍":"👥",title:_e?"Nenhum usuário encontrado":"Nenhum usuário cadastrado",subtitle:_e?`Nada corresponde a "${_e}". Limpe a busca ou tente outro termo.`:"Crie o primeiro usuário no botão acima."}):t.jsx("div",{className:"table-scroll",children:t.jsxs("table",{className:"admin-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{width:"50px"},children:"ID"}),t.jsx("th",{children:"Email"}),t.jsx("th",{children:"Nome"}),t.jsx("th",{children:"Cargo"}),t.jsx("th",{children:"Lojas"}),t.jsx("th",{children:"Promoções"}),t.jsx("th",{children:"Mailing"}),t.jsx("th",{children:"Tokens"}),t.jsx("th",{children:"Status"}),t.jsx("th",{style:{textAlign:"right"},children:"Ações"})]})}),t.jsx("tbody",{children:Xt.map(a=>t.jsxs("tr",{className:a.is_active?"":"inactive",children:[t.jsx("td",{children:a.id}),t.jsx("td",{children:t.jsx("strong",{children:a.email})}),t.jsx("td",{children:a.name}),t.jsx("td",{children:t.jsx("span",{className:`badge-role ${a.role==="admin"?"badge-role-admin":a.role==="manager"?"badge-role-manager":"badge-role-user"}`,children:a.role})}),t.jsx("td",{children:a.role==="admin"?t.jsx("span",{className:"text-muted",children:"Todas"}):(()=>{const b=a.store_access||[],_=[];Ks.forEach(V=>{if(!b.includes(V.sentinel))return;const ee=V.key==="behonest"?{background:"rgba(237,177,37,0.2)",color:"var(--secondary)",border:"1px solid rgba(237,177,37,0.4)"}:V.key==="extrabom"?{background:"rgba(34,197,94,0.18)",color:"#86efac",border:"1px solid rgba(34,197,94,0.4)"}:{background:"rgba(96,165,250,0.18)",color:"#93c5fd",border:"1px solid rgba(96,165,250,0.4)"};_.push(t.jsx("span",{style:{fontSize:"10px",padding:"2px 6px",borderRadius:"10px",...ee},children:V.label},V.key))});const I=b.filter(V=>!dn.includes(V)).length;return I>0&&_.push(t.jsxs("span",{style:{fontSize:"11px",color:"var(--text-muted)"},children:["+",I]},"n")),_.length?t.jsx("span",{style:{display:"inline-flex",gap:"4px",alignItems:"center",flexWrap:"wrap"},children:_}):t.jsx("span",{className:"text-muted",children:"0"})})()}),t.jsx("td",{children:a.has_promotions_access?t.jsx("span",{style:{color:"var(--success)"},children:"✅"}):t.jsx("span",{style:{color:"var(--text-muted)"},children:"—"})}),t.jsx("td",{children:a.mailing?t.jsx("span",{style:{color:"var(--success)"},children:"✅"}):t.jsx("span",{style:{color:"var(--text-muted)"},children:"—"})}),t.jsx("td",{children:t.jsx("span",{style:{fontWeight:600,color:(a.tokens??50)>0?"var(--secondary)":"var(--danger)"},children:a.tokens??50})}),t.jsx("td",{children:t.jsx("span",{className:`status-pill ${a.is_active?"status-pill-active":"status-pill-inactive"}`,children:a.is_active?"Ativo":"Inativo"})}),t.jsx("td",{style:{textAlign:"right",whiteSpace:"nowrap"},children:t.jsxs("div",{style:{display:"inline-flex",gap:"6px",alignItems:"center"},children:[a.is_active&&a.id!==s?.id&&t.jsx("button",{className:"btn-small btn-impersonate",title:`Visualizar como ${a.name||a.email}`,onClick:()=>$(a),children:"👁️"}),t.jsx("button",{className:"btn-small",onClick:()=>Oa(a),children:f?"Editar":"Ver"}),f&&a.id!==s?.id&&t.jsx("button",{className:"btn-small btn-danger",title:`Deletar ${a.email}`,onClick:()=>Ja(a),children:"Excluir"})]})})]},a.id))})]})})]}),n==="roles"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"admin-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[t.jsxs("h3",{children:["Cargos e Níveis de Acesso",t.jsxs("span",{className:"text-muted",style:{fontSize:"0.85rem",fontWeight:400,marginLeft:"0.75rem"},children:[v.length," ",v.length===1?"cargo":"cargos"]})]}),f&&t.jsx("button",{className:"btn btn-primary",onClick:Xa,children:"+ Novo Cargo"})]}),v.length===0?t.jsx(Et,{icon:"🔑",title:"Nenhum cargo definido",subtitle:"Crie um cargo para começar a atribuir permissões aos usuários."}):t.jsx("div",{className:"table-scroll",children:t.jsxs("table",{className:"admin-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{width:"80px"},children:"Nível"}),t.jsx("th",{style:{width:"150px"},children:"Nome"}),t.jsx("th",{children:"Permissões"}),t.jsx("th",{style:{textAlign:"right"},children:"Ações"})]})}),t.jsx("tbody",{children:v.map(a=>t.jsxs("tr",{children:[t.jsx("td",{children:t.jsx("span",{className:"badge",children:a.level})}),t.jsx("td",{children:t.jsx("strong",{children:a.name})}),t.jsx("td",{children:t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Object.entries(a.permissions).filter(([,b])=>b).map(([b])=>t.jsx("span",{className:"badge",style:{fontSize:"0.7em",background:"var(--glass-bg)",border:"1px solid rgba(255,255,255,0.1)"},children:b.replace("_"," ")},b))})}),t.jsxs("td",{style:{textAlign:"right",whiteSpace:"nowrap"},children:[t.jsx("button",{className:"btn-small",onClick:()=>Ya(a),children:f?"Editar":"Ver"}),f&&t.jsx("button",{className:"btn-small btn-danger",onClick:()=>a.id&&Ka(a.id),children:"Excluir"})]})]},a.id))})]})}),t.jsx("p",{className:"text-muted",style:{marginTop:"1rem",fontSize:"0.85rem"},children:"ℹ️ Níveis hierárquicos mais altos têm prioridade sobre os mais baixos."})]}),n==="stores"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"admin-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",flexWrap:"wrap",gap:"1rem"},children:[t.jsxs("h3",{children:["Editor de Lojas",t.jsxs("span",{className:"text-muted",style:{fontSize:"0.85rem",fontWeight:400,marginLeft:"0.75rem"},children:[Dt.length===A.length?`${A.length} no total`:`${Dt.length} de ${A.length}`,Dt.length>50?" · mostrando 50":""]})]}),t.jsxs("div",{className:"search-input-wrap",children:[t.jsx("input",{ref:n==="stores"?d:void 0,type:"text",placeholder:"Buscar loja (ID ou Nome)…",value:Q,onChange:a=>me(a.target.value),className:"search-input",style:{padding:"0.6rem 1rem",borderRadius:"var(--radius-md)",border:"1px solid var(--glass-border)",background:"var(--glass-bg)",color:"var(--text-primary)",minWidth:"300px"}}),Q?t.jsx("button",{type:"button",className:"search-clear","aria-label":"Limpar busca",onClick:()=>me(""),children:"✕"}):t.jsx("span",{className:"search-kbd",children:"⌘K"})]})]}),Dt.length===0?t.jsx(Et,{icon:Q?"🔍":"🏪",title:Q?"Nenhuma loja encontrada":"Nenhuma loja cadastrada",subtitle:Q?`Nada corresponde a "${Q}".`:void 0}):t.jsx("div",{className:"table-scroll",children:t.jsxs("table",{className:"admin-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{style:{width:"60px"},children:"ID"}),t.jsx("th",{children:"Nome da Loja"}),t.jsx("th",{children:"Localização"}),t.jsx("th",{children:"Coordenadas"}),t.jsx("th",{style:{width:"150px",textAlign:"right"},children:"Receita (60d)"}),t.jsx("th",{style:{textAlign:"right"},children:"Ações"})]})}),t.jsx("tbody",{children:Dt.slice(0,50).map(a=>t.jsxs("tr",{children:[t.jsx("td",{children:a.unique_id}),t.jsxs("td",{children:[a.brand?t.jsx("span",{style:{fontSize:"0.75em",background:"var(--glass-highlight)",padding:"2px 6px",borderRadius:"4px",marginRight:"8px",color:"var(--text-secondary)"},children:a.brand.toUpperCase()}):"",t.jsx("strong",{children:a.name})]}),t.jsxs("td",{children:[a.city," ",t.jsx("span",{className:"text-muted",children:"/"})," ",a.state]}),t.jsxs("td",{className:"text-muted",style:{fontSize:"0.85em"},children:[a.lat?.toFixed(4),", ",a.lng?.toFixed(4)]}),t.jsx("td",{style:{textAlign:"right",fontWeight:"bold",color:"var(--text-accent)"},children:cn(a.revenue||0)}),t.jsx("td",{style:{textAlign:"right"},children:t.jsx("button",{className:"btn-small",onClick:()=>{us(a),Fe(!0)},children:f?"Editar":"Ver"})})]},a.unique_id))})]})})]}),n==="system"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"admin-header",style:{marginBottom:"1.5rem"},children:[t.jsx("h3",{style:{marginBottom:"1rem"},children:"Status do Sistema"}),t.jsx(ra,{tabs:[{id:"workers",icon:"⚙️",label:"Processos (Workers)"},{id:"logs",icon:"📄",label:"Logs do Servidor"},{id:"userlogs",icon:"👤",label:"Logs por Usuário"}],activeTab:J,onTabChange:a=>{U(a),a==="logs"&&Fa()}})]}),J==="workers"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"}
20,children:[t.jsx("div",{style:{display:"flex",gap:"15px",alignItems:"center"},children:w.is_low_memory&&t.jsx("span",{style:{fontSize:"0.75rem",color:"#ff4444",background:"rgba(255,68,68,0.1)",padding:"4px 10px",borderRadius:"8px",fontWeight:"bold",border:"1px solid rgba(255,68,68,0.3)",animation:"pulse 1s infinite alternate"},children:"⚠️ MEMÓRIA BAIXA: Orchestrator pausado"})}),t.jsx("button",{className:"btn btn-secondary btn-small",onClick:()=>et(),children:"🔄 Atualizar"})]}),t.jsxs("div",{style:{marginBottom:"2rem"},children:[t.jsxs("h4",{style:{margin:"0 0 1rem",display:"flex",alignItems:"center",gap:"10px"},children:["🔄 Pipeline de Dados",t.jsxs("span",{className:"live-badge",style:{fontSize:"0.6rem",background:T?.status==="running"?"rgba(255, 68, 68, 0.1)":"rgba(255,255,255,0.05)",color:T?.status==="running"?"#ff4444":"var(--text-muted)",padding:"2px 8px",borderRadius:"12px",border:`1px solid ${T?.status==="running"?"rgba(255, 68, 68, 0.2)":"rgba(255,255,255,0.08)"}`,display:"flex",alignItems:"center",gap:"5px",letterSpacing:"0.5px",fontWeight:"bold"},children:[T?.status==="running"&&t.jsx("span",{style:{width:"5px",height:"5px",background:"#ff4444",borderRadius:"50%",boxShadow:"0 0 5px #ff4444"},className:"pulse-text"}),T?.status==="running"?"LIVE":T?.status==="cooldown"?"COOLDOWN":"PARADO"]})]}),t.jsxs("div",{style:{padding:"24px",borderRadius:"16px",background:T?.status==="running"?"rgba(14, 32, 80, 0.4)":"rgba(255,255,255,0.03)",border:`2px solid ${T?.status==="running"?"var(--secondary)":"rgba(255,255,255,0.08)"}`,transition:"all 0.3s ease",boxShadow:T?.status==="running"?"0 0 25px rgba(237, 177, 37, 0.12)":"none"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsxs("div",{children:[t.jsx("strong",{style:{fontSize:"1.1rem"},children:"Coleta & Correlação"}),t.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-muted)",marginTop:"2px"},children:"Access → Transactions → Correlation"})]}),t.jsx("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:T?.status!=="running"?t.jsx("button",{className:"btn-small btn-primary",onClick:Da,title:"Iniciar pipeline",children:"▶ Iniciar"}):t.jsx("button",{className:"btn-small btn-danger",onClick:Ma,title:"Parar pipeline",children:"■ Parar"})})]}),t.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0",padding:"12px 16px",background:"rgba(0,0,0,0.2)",borderRadius:"12px",border:"1px solid var(--glass-border)"},children:(T?.steps||[]).map((a,b,_)=>{const I=a.status==="running",V=a.status==="chain_done"||a.status==="completed",ee=a.status==="error",se=V?"✅":I?"⏳":ee?"❌":"⬜",Te=I?"var(--secondary)":V?"var(--success)":ee?"var(--danger)":"rgba(255,255,255,0.08)",Ae=I?"rgba(14, 32, 80, 0.5)":V?"rgba(0, 180, 90, 0.08)":"transparent";return t.jsxs("div",{style:{display:"flex",alignItems:"center",flex:1},children:[t.jsxs("div",{style:{flex:1,padding:"10px 14px",borderRadius:"10px",background:Ae,border:`1.5px solid ${Te}`,textAlign:"center",transition:"all 0.3s ease",boxShadow:I?"0 0 15px rgba(237, 177, 37, 0.15)":"none",opacity:V?.6:1},children:[t.jsx("div",{style:{fontSize:"1rem",marginBottom:"2px"},children:se}),t.jsx("strong",{style:{fontSize:"0.75rem",textTransform:"capitalize",display:"block"},children:a.name}),t.jsx("div",{style:{fontSize:"0.6rem",marginTop:"2px",color:I?"var(--secondary)":V?"var(--success)":"var(--text-muted)",fontWeight:I?"bold":"normal"},children:I?`Rodando · ${ft(a.last_run)}`:V?"Concluído":ee?"Erro":"Aguardando"})]}),b<_.length-1&&t.jsx("span",{style:{color:"var(--text-muted)",opacity:.55,fontSize:"1.2rem",margin:"0 6px",flexShrink:0},children:"→"})]},a.name)})}),t.jsxs("div",{style:{marginTop:"12px",fontSize:"0.75rem",color:"var(--text-muted)",display:"flex",justifyContent:"space-between"},children:[t.jsx("span",{children:T?.status==="running"?`Etapa ${T.current_step}/${T.total_steps} — ${T.running_step_name}`:T?.status==="cooldown"?"Ciclo completo — aguardando cooldown":T?.status==="error"?"Erro no pipeline":"Pipeline parado"}),T?.last_run&&t.jsxs("span",{children:["Última atividade: ",ft(T.last_run)]})]})]})]}),t.jsxs("div",{style:{marginBottom:"2rem"},children:[t.jsxs("h4",{style:{margin:"0 0 1rem",display:"flex",alignItems:"center",gap:"10px"},children:["🌙 Fila Noturna",t.jsx("span",{style:{fontSize:"0.7em",color:"var(--text-muted)",fontWeight:"normal"},children:"Execução sequencial a partir das 00:00"})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"20px 24px",background:"rgba(0,0,0,0.2)",borderRadius:"16px",border:"1px solid var(--glass-border)",overflowX:"auto",position:"relative",minHeight:"90px"},children:[N.filter(a=>a.worker_category==="daily_queue").sort((a,b)=>(a.queue_position??99)-(b.queue_position??99)).map((a,b,_)=>{const I=a.status==="running",V=a.status==="completed",ee=a.status==="error",se=V?"✅":I?"⏳":ee?"❌":"🕐",Te=I?"var(--secondary)":V?"var(--success)":ee?"var(--danger)":"rgba(255,255,255,0.08)",Ae=I?"rgba(14, 32, 80, 0.4)":V?"rgba(0, 180, 90, 0.08)":"rgba(255,255,255,0.03)";return t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsxs("div",{style:{padding:"12px 16px",borderRadius:"10px",background:Ae,border:`1.5px solid ${Te}`,minWidth:"110px",textAlign:"center",transition:"all 0.3s ease",boxShadow:I?"0 0 15px rgba(237, 177, 37, 0.15)":"none",opacity:V?.6:1},children:[t.jsx("div",{style:{fontSize:"0.65rem",marginBottom:"4px"},children:se}),t.jsx("strong",{style:{fontSize:"0.75rem",whiteSpace:"nowrap",display:"block"},children:a.name}),t.jsx("div",{style:{fontSize:"0.6rem",marginTop:"3px",color:I?"var(--secondary)":V?"var(--success)":"var(--text-muted)",fontWeight:
20I?"bold":"normal"},children:I?`Rodando · ${ft(a.last_run)}`:V?"Concluído":ee?"Erro":`#${a.queue_position}`})]}),b<_.length-1&&t.jsx("span",{style:{color:"var(--text-muted)",opacity:.45,fontSize:"1.2rem",flexShrink:0},children:"→"})]},a.name)}),t.jsx("div",{className:"moving-line-gradient"})]})]}),t.jsxs("div",{style:{marginBottom:"2rem"},children:[t.jsxs("h4",{style:{margin:"0 0 1rem",display:"flex",alignItems:"center",gap:"10px"},children:["⏰ Worker de 6 em 6 horas",t.jsx("span",{style:{fontSize:"0.7em",color:"var(--text-muted)",fontWeight:"normal"},children:"Execução sequencial a cada 6 horas · máx. 1h por módulo"})]}),t.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap",padding:"20px 24px",background:"rgba(0,0,0,0.2)",borderRadius:"16px",border:"1px solid var(--glass-border)",minHeight:"90px"},children:N.filter(a=>a.worker_category==="6h").sort((a,b)=>a.name.localeCompare(b.name)).map(a=>{const b=a.status==="running",_=a.status==="completed",I=a.status==="error",V=_?"✅":b?"⏳":I?"❌":"🕐",ee=b?"var(--secondary)":_?"var(--success)":I?"var(--danger)":"rgba(255,255,255,0.08)",se=b?"rgba(14, 32, 80, 0.4)":I?"rgba(239,68,68,0.08)":"rgba(255,255,255,0.03)";return t.jsxs("div",{onClick:()=>Ur(a.name),title:"Ver estatísticas e logs",style:{padding:"12px 16px",borderRadius:"10px",cursor:"pointer",background:se,border:`1.5px solid ${ee}`,minWidth:"110px",textAlign:"center",transition:"all 0.3s ease",boxShadow:b?"0 0 15px rgba(237, 177, 37, 0.15)":"none",opacity:a.is_active?1:.45},children:[t.jsx("div",{style:{fontSize:"0.65rem",marginBottom:"4px"},children:V}),t.jsx("strong",{style:{fontSize:"0.75rem",whiteSpace:"nowrap",display:"block"},children:a.name}),t.jsx("div",{style:{fontSize:"0.6rem",marginTop:"3px",color:b?"var(--secondary)":I?"var(--danger)":"var(--text-muted)",fontWeight:b?"bold":"normal"},children:b?`Rodando · ${ft(a.last_run)}`:I?"Erro":a.last_run?`há ${ft(a.last_run)}`:"Aguardando"})]},a.name)})})]}),t.jsxs("table",{className:"admin-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{children:"Processo"}),t.jsx("th",{children:"Tipo"}),t.jsx("th",{children:"Estado"}),t.jsx("th",{children:"Agendamento"}),t.jsx("th",{children:"Última"}),t.jsx("th",{children:"Próxima"}),t.jsx("th",{children:"Controle"}),t.jsx("th",{children:"Mensagem"})]})}),t.jsx("tbody",{children:N.map((a,b)=>{const _=a.worker_category||"daily_queue",I=_==="continuous"?{bg:"rgba(34,197,94,0.18)",fg:"#86efac",label:"♾ Contínuo"}:_==="sequential_chain"?{bg:"rgba(237,177,37,0.18)",fg:"#edb125",label:`⛓ Chain #${a.queue_position||"-"}`}:_==="6h"?{bg:"rgba(56,189,248,0.18)",fg:"#7dd3fc",label:"⏰ 6h"}:{bg:"rgba(120,120,255,0.15)",fg:"#8888ff",label:`🌙 Fila #${a.queue_position||"-"}`},V=a.status==="running"&&a.last_run&&a.schedule_type==="interval"&&Number(a.schedule_value)>0&&Date.now()-new Date(a.last_run).getTime()>Number(a.schedule_value)*2*1e3;return t.jsxs("tr",{children:[t.jsx("td",{children:t.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[t.jsx("strong",{onClick:()=>Ur(a.name),title:"Ver estatísticas e logs",style:{cursor:"pointer",color:"var(--secondary)",textDecoration:"underline",textUnderlineOffset:"2px"},children:a.name}),!a.is_active&&t.jsx("span",{style:{fontSize:"0.65rem",color:"var(--text-muted)"},children:"desativado"})]})}),t.jsx("td",{children:t.jsx("span",{className:"badge",style:{fontSize:"0.65rem",background:I.bg,color:I.fg,padding:"2px 8px"},children:I.label})}),t.jsxs("td",{children:[t.jsx("span",{style:{display:"inline-block",width:"8px",height:"8px",borderRadius:"50%",marginRight:"6px",background:a.status==="running"?"var(--success)":a.status==="completed"?"#00b45a":a.status==="error"?"var(--danger)":"var(--warning)"}}),a.status==="completed"?"CONCLUÍDO":a.status==="waiting"?"AGUARDANDO":a.status.toUpperCase(),a.pid&&t.jsxs("span",{style:{fontSize:"0.7em",marginLeft:"5px",opacity:.7},children:["(PID: ",a.pid,")"]}),V&&t.jsx("span",{title:"Rodando há mais que 2× o intervalo configurado",style:{marginLeft:6,fontSize:"0.65rem",padding:"1px 6px",borderRadius:4,background:"rgba(239,68,68,0.18)",color:"#fca5a5",border:"1px solid rgba(239,68,68,0.45)"},children:"⚠ travado"})]}),t.jsx("td",{style:{fontSize:"0.85em"},children:qr(a)}),t.jsx("td",{style:{fontSize:"0.8em",color:"var(--text-muted)"},title:a.last_run||"",children:a.last_run?`há ${ft(a.last_run)}`:"—"}),t.jsx("td",{style:{fontSize:"0.8em"},title:a.next_run||"",children:a.next_run?Fr(a.next_run):"—"}),t.jsx("td",{children:t.jsxs("div",{style:{display:"flex",gap:"5px"},children:[a.status!=="running"&&t.jsx("button",{className:"btn-small btn-primary",onClick:()=>Hs(a.name),title:"Executar agora",children:"▶"}),a.status==="running"&&t.jsx("button",{className:"btn-small btn-danger",onClick:()=>Yr(a.name),title:"Parar",children:"■"}),t.jsx("button",{className:"btn-small btn-secondary",onClick:()=>Ce(a),title:"Configurar",children:"⚙"}),t.jsx("button",{className:`btn-small ${a.is_active?"btn-danger":"btn-success"}`,onClick:()=>Xr(a.name),style:{opacity:.7,fontSize:"0.7rem"},children:a.is_active?"Off":"On"})]})}),t.jsx("td",{style:{maxWidth:"200px",fontSize:"0.85em",color:"var(--text-muted)"},children:a.message})]},b)})})]}),t.jsx("style",{children:`
21                                        @keyframes pulse {
22                                            0% { opacity: 0.6; }
23                                            50% { opacity: 1; }
24                                            100% { opacity: 0.6; }
25                                        }
26                                        .pulse-text {
27                                            animation: pulse 2s infinite ease-in-out;
28                                        }
29                                        .moving-line-gradient {
30                                            position: absolute;
31                                            bottom: 0; left: 0;
32                                            height: 2px; width: 100%;
33                                            background: linear-gradient(90deg, transparent, var(--secondary), transparent);
34                                            background-size: 200% 100%;
35                                            animation: moveLine 4s linear infinite;
36                                            opacity: 0.3;
37                                        }
38                                        @keyframes moveLine {
39                                            0% { background-position: 200% 0; }
40                                            100% { background-position: -200% 0; }
41                                        }
42                                    `})]}),J==="logs"&&t.jsxs("div",{className:"logs-viewer",children:[t.jsxs("div",{className:"logs-controls",style:{display:"flex",gap:"1rem",marginBottom:"1rem",alignItems:"center"},children:[t.jsx("select",{value:O,onChange:a=>G(a.target.value),children:K.map(a=>t.jsx("option",{value:a.id,children:a.label},a.id))}),t.jsxs("select",{value:H,onChange:a=>X(Number(a.target.value)),children:[t.jsx("option",{value:50,children:"50 linhas"}),t.jsx("option",{value:100,children:"100 linhas"}),t.jsx("option",{value:200,children:"200 linhas"}),t.jsx("option",{value:500,children:"500 linhas"})]}),t.jsx("button",{className:"btn btn-primary",onClick:Gs,children:"🔄 Carregar"})]}),t.jsx("pre",{className:"log-output",style:{background:"var(--dark)",color:"var(--text-secondary)",padding:"1rem",borderRadius:"8px",maxHeight:"500px",overflow:"auto",fontSize:"0.85em",fontFamily:"monospace",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:E||'Clique em "Carregar" para visualizar os logs.'})]}),J==="userlogs"&&t.jsx(Io,{})]}),n==="contact"&&t.jsx(Nn,{stores:A}),n==="redirects"&&t.jsx(Ln,{}),n==="usage"&&t.jsx(yo,{}),n==="build"&&t.jsx(ko,{}),n==="repos"&&t.jsx($o,{}),n==="claudezap"&&t.jsx(zl,{}),n==="nivelpar"&&t.jsx(Do,{})]})]}),t.jsxs(mt,{size:"xl",isOpen:Be,onClose:()=>te(!1),title:be?f?"Editar Usuário":"Visualizar Usuário":"Novo Usuário",children:[f&&be&&t.jsx("div",{style:{display:"flex",gap:"4px",marginBottom:"1rem",borderBottom:"1px solid var(--glass-border)"},children:[{id:"dados",label:"Dados & Apps"},{id:"permissoes",label:"🔐 Permissões"}].map(a=>t.jsx("button",{type:"button",onClick:()=>
42Re(a.id),style:{background:"transparent",cursor:"pointer",fontSize:"13px",padding:"8px 14px",border:"none",borderBottom:`2px solid ${ge===a.id?"var(--secondary)":"transparent"}`,color:ge===a.id?"var(--secondary)":"var(--text-muted)",fontWeight:ge===a.id?600:400},children:a.label},a.id))}),f&&be&&ge==="permissoes"?t.jsx(wn,{userId:be.id,onToast:ne}):t.jsxs("form",{onSubmit:qa,style:{maxHeight:"75vh",overflowY:"auto"},children:[t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) minmax(0,1fr)",gap:"1.75rem"},children:[t.jsxs("div",{children:[t.jsx("h4",{className:"admin-section-title",children:"Identidade"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Email"}),t.jsx("input",{type:"email",value:It,onChange:a=>ze(a.target.value),disabled:!!be||!f,required:!0,autoFocus:!be&&f})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Nome"}),t.jsx("input",{type:"text",value:ht,onChange:a=>lt(a.target.value),disabled:!f,autoFocus:!!be&&f})]}),f&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Senha"}),t.jsx("input",{type:"password",value:Ze,onChange:a=>Ye(a.target.value),placeholder:be?"Deixar em branco para manter":""})]}),f&&be&&t.jsx(El,{userId:be.id,userEmail:be.email,onToast:ne},be.id),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Cargo"}),t.jsxs("select",{value:ve,onChange:a=>j(a.target.value),disabled:!f,children:[t.jsx("option",{value:"user",children:"User"}),t.jsx("option",{value:"fornecedor",children:"Fornecedor"}),t.jsx("option",{value:"manager",children:"Manager"}),t.jsx("option",{value:"admin",children:"Admin"})]})]}),t.jsx("h4",{className:"admin-section-title",style:{marginTop:"1.5rem"},children:"Permissões adicionais"}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.75rem"},children:[t.jsxs("div",{className:"form-group",style:{marginBottom:0},children:[t.jsx("label",{children:"Promoções"}),t.jsxs("select",{value:fs?"true":"false",onChange:a=>{const b=a.target.value==="true";ys(b),b&&!Kt&&Us(!0)},disabled:!f,children:[t.jsx("option",{value:"false",children:"Não"}),t.jsx("option",{value:"true",children:"Sim"})]})]}),t.jsxs("div",{className:"form-group",style:{marginBottom:0},children:[t.jsx("label",{children:"📧 Mailing"}),t.jsxs("select",{value:gr?"true":"false",onChange:a=>bs(a.target.value==="true"),disabled:!f,children:[t.jsx("option",{value:"false",children:"Não"}),t.jsx("option",{value:"true",children:"Sim"})]})]}),t.jsxs("div",{className:"form-group",style:{marginBottom:0},children:[t.jsx("label",{children:"📦 Gestor de Estoque"}),t.jsxs("select",{value:br?"true":"false",onChange:a=>_s(a.target.value==="true"),disabled:!f,children:[t.jsx("option",{value:"false",children:"Não"}),t.jsx("option",{value:"true",children:"Sim"})]})]}),t.jsxs("div",{className:"form-group",style:{marginBottom:0},children:[t.jsx("label",{children:"🪙 Tokens"}),t.jsx("input",{type:"number",min:0,value:fr,onChange:a=>js(parseInt(a.target.value)||0),disabled:!f})]})]})]}),t.jsxs("div",{children:[t.jsx("h4",{className:"admin-section-title",children:"🧭 Acesso aos apps"}),t.jsxs("p",{style:{fontSize:"0.78rem",color:"var(--text-muted)",margin:"0 0 0.75rem"},children:["Controla quais módulos aparecem no Honesty System e quais o usuário pode abrir.",ve==="admin"?t.jsxs(t.Fragment,{children:[" ",t.jsx("strong",{style:{color:"var(--secondary)"},children:"Admins têm acesso total."})]}):null]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"},children:[{key:"hrm",label:"HRM",sub:"Sistema de gestão geral",icon:"🏢",value:vr,set:ks},{key:"biopr",label:"BI-OPR",sub:"Business Intelligence",icon:"📊",value:Sr,set:Cs},{key:"crm",label:"CRM",sub:"Expansão de Lojas",icon:"🏬",value:_r,set:$s},{key:"grm",label:"GRM",sub:"Growth · Meta/Google Ads",icon:"🚀",value:jr,set:ws},{key:"mkt",label:"MKT",sub:"Marketing",icon:"🎯",value:kr,set:zs},{key:"log",label:"LOG",sub:"Logística · descontinuada",icon:"🚚",value:wr,set:As},{key:"pai",label:"PAI",sub:"Painel Administrativo",icon:"🧮",value:Cr,set:Rs},{key:"cgn",label:"CGN",sub:"Content Generator",icon:"✍️",value:$r,set:Ts},{key:"ext",label:"EXT",sub:"Extrabom",icon:"🏪",value:zr,set:Ns},{key:"mkp",label:"MKP",sub:"Marketplace",icon:"🛒",value:Es,set:Ls},{key:"fin",label:"FIN",sub:"Financeiro",icon:"💰",value:Nr,set:Ps},{key:"fmk",label:"FUNDO",sub:"Fundo de Marketing",icon:"📣",value:Ds,set:Ms,gestorRoles:["manager"]},{key:"meta",label:"META",sub:"Acompanhamento da Meta (Expansão)",icon:"🎯",value:St,set:Er},{key:"cls",label:"CLS",sub:"Classificado · vender minha loja",icon:"🏷️",value:Yt,set:Fs}].map(a=>{const b=a.gestorRoles,_=ve==="admin"||!!b?.includes(ve),I=_?!0:a.value,V=!f||_;return t.jsxs("button",{type:"button",disabled:V,onClick:()=>
42a.set(!a.value),className:"access-card",style:{display:"flex",alignItems:"center",gap:"10px",padding:"10px 12px",border:`1px solid ${I?"var(--secondary)":"var(--glass-border)"}`,background:I?"rgba(237,177,37,0.10)":"rgba(255,255,255,0.03)",borderRadius:"var(--radius-md)",cursor:V?"not-allowed":"pointer",opacity:V&&!I?.55:1,textAlign:"left",transition:"all 0.15s ease"},title:_?ve==="admin"?"Sempre concedido a admin":"Concedido pelo papel de gestor":I?"Clique para revogar":"Clique para conceder",children:[t.jsx("span",{style:{fontSize:"1.4rem"},children:a.icon}),t.jsxs("span",{style:{flex:1,minWidth:0},children:[t.jsx("span",{style:{display:"block",fontWeight:600,fontSize:"0.85rem",color:I?"var(--secondary)":"var(--text-primary)"},children:a.label}),t.jsx("span",{style:{display:"block",fontSize:"0.7rem",color:"var(--text-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.sub})]}),t.jsx("span",{style:{width:32,height:18,borderRadius:9,background:I?"var(--secondary)":"rgba(255,255,255,0.15)",position:"relative",flexShrink:0,transition:"background 0.2s ease"},children:t.jsx("span",{style:{position:"absolute",top:2,left:I?16:2,width:14,height:14,borderRadius:"50%",background:"#fff",transition:"left 0.2s ease"}})})]},a.key)})}),(ve==="admin"||Es||Ds)&&t.jsxs("div",{style:{marginTop:"12px",padding:"10px 12px",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)",background:"rgba(255,255,255,0.02)"},children:[t.jsxs("p",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 8px"},children:["🛒 Região da operação",t.jsx("span",{style:{fontWeight:400,color:"var(--text-muted)"},children:" — vale para o Marketplace e o Fundo de Marketing"})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 140px), 1fr))",gap:"8px"},children:[{key:"mg",label:"MG",sub:"Minas Gerais",value:Ar,set:Bs},{key:"go",label:"GO",sub:"Goiás",value:Rr,set:Is},{key:"es",label:"ES",sub:"Espírito Santo",value:Tr,set:Ws}].map(a=>{const b=ve==="admin",_=b?!0:a.value,I=!f||b;return t.jsxs("button",{type:"button",disabled:I,onClick:()=>a.set(!a.value),className:"access-card",style:{display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px",border:`1px solid ${_?"var(--secondary)":"var(--glass-border)"}`,background:_?"rgba(237,177,37,0.10)":"rgba(255,255,255,0.03)",borderRadius:"var(--radius-md)",cursor:I?"not-allowed":"pointer",opacity:I&&!_?.55:1,textAlign:"left",transition:"all 0.15s ease"},title:b?"Sempre concedido a admin":_?"Clique para revogar":"Clique para conceder",children:[t.jsxs("span",{style:{flex:1,minWidth:0},children:[t.jsx("span",{style:{display:"block",fontWeight:600,fontSize:"0.85rem",color:_?"var(--secondary)":"var(--text-primary)"},children:a.label}),t.jsx("span",{style:{display:"block",fontSize:"0.7rem",color:"var(--text-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.sub})]}),t.jsx("span",{style:{width:32,height:18,borderRadius:9,background:_?"var(--secondary)":"rgba(255,255,255,0.15)",position:"relative",flexShrink:0,transition:"background 0.2s ease"},children:t.jsx("span",{style:{position:"absolute",top:2,left:_?16:2,width:14,height:14,borderRadius:"50%",background:"#fff",transition:"left 0.2s ease"}})})]},a.key)})})]}),(ve==="admin"||St)&&t.jsxs("div",{style:{marginTop:"12px",padding:"10px 12px",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)",background:"rgba(255,255,255,0.02)"},children:[t.jsxs("p",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 8px"},children:["🎯 Regiões da Expansão",t.jsx("span",{style:{fontWeight:400,color:"var(--text-muted)"},children:" — quais regiões o usuário acompanha (gestor/admin vê todas)"})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"8px"},children:[{key:"mg",label:"MG",sub:"Minas Gerais",value:Lr,set:Br},{key:"go",label:"GO",sub:"Goiânia",value:Ir,set:Wr},{key:"df",label:"DF",sub:"Brasília",value:Pr,set:Dr}].map(a=>{const b=ve==="admin",_=b?!0:a.value,I=!f||b;return t.jsxs("button",{type:"button",disabled:I,onClick:()=>
42a.set(!a.value),className:"access-card",style:{display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px",border:`1px solid ${_?"var(--secondary)":"var(--glass-border)"}`,background:_?"rgba(237,177,37,0.10)":"rgba(255,255,255,0.03)",borderRadius:"var(--radius-md)",cursor:I?"not-allowed":"pointer",opacity:I&&!_?.55:1,textAlign:"left",transition:"all 0.15s ease"},title:b?"Sempre concedido a admin":_?"Clique para revogar":"Clique para conceder",children:[t.jsxs("span",{style:{flex:1,minWidth:0},children:[t.jsx("span",{style:{display:"block",fontWeight:600,fontSize:"0.85rem",color:_?"var(--secondary)":"var(--text-primary)"},children:a.label}),t.jsx("span",{style:{display:"block",fontSize:"0.7rem",color:"var(--text-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:a.sub})]}),t.jsx("span",{style:{width:32,height:18,borderRadius:9,background:_?"var(--secondary)":"rgba(255,255,255,0.15)",position:"relative",flexShrink:0,transition:"background 0.2s ease"},children:t.jsx("span",{style:{position:"absolute",top:2,left:_?16:2,width:14,height:14,borderRadius:"50%",background:"#fff",transition:"left 0.2s ease"}})})]},a.key)})})]}),(ve==="admin"||Yt)&&t.jsxs("div",{style:{marginTop:"12px",padding:"10px 12px",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)",background:"rgba(255,255,255,0.02)"},children:[t.jsxs("p",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 8px"},children:["🏷️ Classificado — equipe Be Honest",t.jsx("span",{style:{fontWeight:400,color:"var(--text-muted)"},children:" — vitrine, aprovação, filas e export do HTML (o vendedor só vê os próprios anúncios)"})]}),(()=>{const a=ve==="admin",b=a?!0:qs,_=!f||a;return t.jsxs("button",{type:"button",disabled:_,onClick:()=>Os(!qs),className:"access-card",style:{display:"flex",alignItems:"center",gap:"10px",width:"100%",padding:"8px 12px",border:`1px solid ${b?"var(--secondary)":"var(--glass-border)"}`,background:b?"rgba(237,177,37,0.10)":"rgba(255,255,255,0.03)",borderRadius:"var(--radius-md)",cursor:_?"not-allowed":"pointer",opacity:_&&!b?.55:1,textAlign:"left",transition:"all 0.15s ease"},title:a?"Sempre concedido a admin":b?"Clique para revogar":"Clique para conceder",children:[t.jsxs("span",{style:{flex:1,minWidth:0},children:[t.jsx("span",{style:{display:"block",fontWeight:600,fontSize:"0.85rem",color:b?"var(--secondary)":"var(--text-primary)"},children:"EQUIPE"}),t.jsx("span",{style:{display:"block",fontSize:"0.7rem",color:"var(--text-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:"Vitrine completa, aprovar/reprovar, pendências e export"})]}),t.jsx("span",{style:{width:32,height:18,borderRadius:9,background:b?"var(--secondary)":"rgba(255,255,255,0.15)",position:"relative",flexShrink:0,transition:"background 0.2s ease"},children:t.jsx("span",{style:{position:"absolute",top:2,left:b?16:2,width:14,height:14,borderRadius:"50%",background:"#fff",transition:"left 0.2s ease"}})})]})})()]})]})]}),t.jsxs("div",{style:{marginTop:"1.5rem",display:"grid",gridTemplateColumns:"1fr 2fr",gap:"0.75rem"},children:[t.jsxs("div",{className:"form-group",style:{marginBottom:0},children:[t.jsx("label",{children:"📱 Telefone (WhatsApp)"}),t.jsx("input",{type:"tel",value:yr,onChange:a=>Ss(a.target.value.replace(/[^0-9+() -]/g,"")),placeholder:"(31) 99999-9999",disabled:!f,maxLength:20,id:"admin-phone-input"}),t.jsx("p",{style:{fontSize:"0.7rem",color:"var(--text-muted)",margin:"4px 0 0"},children:"Recebe relatório semanal em PDF."})]}),t.jsxs("div",{className:"form-group",style:{marginBottom:0,background:"rgba(237,177,37,0.05)",border:"1px solid rgba(237,177,37,0.2)",borderRadius:"var(--radius-md)",padding:"12px"},children:[t.jsx("label",{style:{display:"flex",alignItems:"center",gap:"6px"},children:"🔑 Evolution API Token"}),t.jsx("input",{type:"text",value:Kt,onChange:a=>vs(a.target.value),placeholder:"Cole o token da Evolution API aqui...",disabled:!f,style:{fontFamily:"monospace",fontSize:"0.85rem"}}),t.jsx("p",{style:{fontSize:"0.7rem",color:"var(--text-muted)",margin:"4px 0 0"},children:"Token para WhatsApp (Promoções + Relatório PDF)."})]})]}),t.jsxs("div",{style:{marginTop:"1.5rem"},children:[ve==="fornecedor"&&t.jsxs("div",{className:"form-group",style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-end"},children:[t.jsxs("label",{style:{margin:0},children:["Página de Fornecedor (",Ee.length," selecionada",Ee.length===1?"":"s",")"]}),f&&t.jsx("button",{type:"button",className:"btn-small",style:{padding:"4px 10px",fontSize:"12px"},onClick:Ha,children:"Selecionar página de fornecedor"})]}),t.jsx("p",{style:{fontSize:"0.75rem",color:"var(--text-muted)",margin:0},children:"Ao entrar no HRM, este usuário vê apenas a(s) página(s) de fornecedor vinculada(s) aqui (ex.: Red Bull) — cai direto nela no login."}),Ee.length>0?t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",padding:"10px",background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)"},children:Ee.map(a=>{const b=Ht.find(_=>_.slug===a);return t.jsxs("span",{style:{fontSize:"0.75rem",background:"rgba(237,177,37,0.2)",color:"var(--secondary)",border:"1px solid rgba(237,177,37,0.3)",padding:"3px 8px",borderRadius:"12px",display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx("span",{style:{fontWeight:"bold"},children:b?.nome||a}),f&&t.jsx("button",{type:"button",onClick:()=>Jr(a),style:{background:"none",border:"none",color:"inherit",curs
42or:"pointer",padding:"0 2px",fontSize:"14px"},children:"×"})]},a)})}):t.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-muted)",padding:"8px 0"},children:"Nenhuma página vinculada."})]}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem",borderTop:"1px solid var(--glass-border)",paddingTop:"1rem"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-end"},children:[t.jsxs("label",{style:{margin:0},children:["Fornecedor do Marketplace (",gt.length," vinculado",gt.length===1?"":"s",")"]}),f&&t.jsx("button",{type:"button",className:"btn-small",style:{padding:"4px 10px",fontSize:"12px"},onClick:Ga,children:"Vincular fornecedor"})]}),t.jsxs("p",{style:{fontSize:"0.75rem",color:"var(--text-muted)",margin:0},children:["Abre o ",t.jsx("strong",{children:"portal do marketplace"})," (/system/marketplace/portal): os pedidos pendurados nele, as etapas e as estatísticas. Cria também a página de ",t.jsx("strong",{children:"Vendas"})," desse fornecedor."]}),gt.length>0?t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",padding:"10px",background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)"},children:gt.map(a=>{const b=Vt.find(_=>_.id===a);return t.jsxs("span",{style:{fontSize:"0.75rem",background:"rgba(237,177,37,0.2)",color:"var(--secondary)",border:"1px solid rgba(237,177,37,0.3)",padding:"3px 8px",borderRadius:"12px",display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx("span",{style:{fontWeight:"bold"},children:b?b.nome_fantasia||b.nome:`Fornecedor #${a}`}),b&&t.jsx("span",{style:{opacity:.7},children:b.region}),f&&t.jsx("button",{type:"button",onClick:()=>Kr(a),style:{background:"none",border:"none",color:"inherit",cursor:"pointer",padding:"0 2px",fontSize:"14px"},children:"×"})]},a)})}):t.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-muted)",padding:"8px 0"},children:"Nenhum fornecedor vinculado."})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-end",borderTop:"1px solid var(--glass-border)",paddingTop:"1rem"},children:[t.jsxs("label",{style:{margin:0},children:["Acesso a Produtos — legado (",ie.length," selecionados)"]}),ie.length>0&&t.jsx("button",{type:"button",className:"btn-small btn-danger",style:{padding:"2px 8px",fontSize:"10px"},onClick:()=>{Se([]),ne("info","Seleção de produtos limpa.")},children:"Limpar Tudo"})]}),ie.length>0&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",padding:"12px",background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)",maxHeight:"120px",overflowY:"auto"},children:ie.map(a=>t.jsxs("span",{style:{fontSize:"0.75rem",background:"rgba(237,177,37,0.2)",color:"var(--secondary)",border:"1px solid rgba(237,177,37,0.3)",padding:"3px 8px",borderRadius:"12px",display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx("span",{style:{fontWeight:"bold"},children:a}),f&&t.jsx("button",{type:"button",onClick:()=>Vr(a),style:{background:"none",border:"none",color:"inherit",cursor:"pointer",padding:"0 2px",fontSize:"14px"},children:"×"})]},a))}),f&&t.jsxs("div",{className:"glass-card",style:{padding:"12px",background:"rgba(0,0,0,0.2)",marginBottom:0},children:[t.jsx("div",{style:{position:"relative",marginBottom:"8px"},children:t.jsx("input",{type:"text",placeholder:"🔍 Buscar produto por nome ou código...",style:{marginBottom:0,fontSize:"13px"},value:jt,onChange:a=>gs(a.target.value)})}),jt.length>=2&&t.jsx("div",{style:{maxHeight:"220px",overflowY:"auto",background:"rgba(0,0,0,0.3)",borderRadius:"var(--radius-md)",padding:"4px",border:"1px solid rgba(255,255,255,0.05)"},children:Ia?t.jsx("div",{style:{padding:"20px",textAlign:"center",color:"var(--text-muted)",fontSize:"13px"},children:"Buscando..."}):xr.length===0?t.jsx("div",{style:{padding:"20px",textAlign:"center",color:"var(--text-muted)",fontSize:"13px"},children:"Nenhum produto encontrado"}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:xr.map(a=>{const b=ie.includes(a.code);return t.jsxs("div",{onClick:()=>Vr(a.code),style:{padding:"8px 10px",cursor:"pointer",borderRadius:"var(--radius-sm)",background:b?"rgba(237,177,37,0.15)":"transparent",border:`1px solid ${b?"var(--secondary)":"rgba(255,255,255,0.05)"}`,display:"flex",alignItems:"center",gap:"10px",transition:"all 0.15s ease"},onMouseEnter:_=>!b&&(_.currentTarget.style.background="rgba(255,255,255,0.05)"),onMouseLeave:_=>!b&&(_.currentTarget.style.background="transparent"),children:[t.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"4px",border:`1px solid ${b?"var(--secondary)":"rgba(255,255,255,0.3)"}`,background:b?"var(--secondary)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",color:"var(--primary)",flexShrink:0},children:b&&"✓"}),t.jsxs("div",{style:{overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"12px",fontWeight:"bold"},children:[a.code," — ",a.description]}
42),a.category&&t.jsx("div",{style:{fontSize:"10px",opacity:.5},children:a.category})]})]},a.code)})})}),t.jsx("div",{style:{marginTop:"8px",fontSize:"11px",color:"var(--text-muted)",textAlign:"center"},children:"Digite pelo menos 2 caracteres para buscar"})]})]}),ve!=="admin"&&ve!=="fornecedor"&&t.jsxs("div",{className:"form-group",style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-end"},children:[t.jsxs("label",{style:{margin:0},children:["Acesso a Lojas (",F.length," selecionadas)"]}),F.length>0&&t.jsx("button",{type:"button",className:"btn-small btn-danger",style:{padding:"2px 8px",fontSize:"10px"},onClick:()=>{Z([]),ne("info","Seleção limpa.")},children:"Limpar Tudo"})]}),F.length>0&&t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",padding:"12px",background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-md)",maxHeight:"120px",overflowY:"auto"},children:[...F].sort().map(a=>{const b=mn(a);if(b){const V=b,ee=Ys[V];return t.jsxs("span",{style:{fontSize:"0.75rem",background:"rgba(34, 197, 94, 0.18)",color:"#86efac",border:"1px solid rgba(34, 197, 94, 0.4)",padding:"3px 8px",borderRadius:"12px",display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx("span",{style:{fontSize:"11px"},children:"🌐"}),t.jsxs("span",{style:{fontWeight:"bold"},children:["Todas ",ee]}),t.jsxs("span",{style:{opacity:.7},children:["(",Vs[V].length,"+ futuras)"]}),f&&t.jsx("button",{type:"button",onClick:()=>Qr(V),style:{background:"none",border:"none",color:"inherit",cursor:"pointer",padding:"0 2px",fontSize:"14px",display:"flex",alignItems:"center",opacity:.6},onMouseOver:se=>se.currentTarget.style.opacity="1",onMouseOut:se=>se.currentTarget.style.opacity="0.6",children:"×"})]},a)}const _=A.find(V=>V.unique_id===a),I=Qt(_??{unique_id:a})==="behonest";return t.jsxs("span",{style:{fontSize:"0.75rem",background:I?"rgba(237, 177, 37, 0.2)":"rgba(14, 32, 80, 0.4)",color:I?"var(--secondary)":"var(--text-primary)",border:`1px solid ${I?"rgba(237, 177, 37, 0.3)":"rgba(255,255,255,0.1)"}`,padding:"3px 8px",borderRadius:"12px",display:"flex",alignItems:"center",gap:"6px",transition:"all 0.2s"},children:[t.jsx("span",{style:{fontWeight:"bold",opacity:.7},children:a}),t.jsx("span",{style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_?.name||a}),f&&t.jsx("button",{type:"button",onClick:()=>Hr(a),style:{background:"none",border:"none",color:"inherit",cursor:"pointer",padding:"0 2px",fontSize:"14px",display:"flex",alignItems:"center",opacity:.6},onMouseOver:V=>V.currentTarget.style.opacity="1",onMouseOut:V=>V.currentTarget.style.opacity="0.6",children:"×"})]},a)})}),f&&t.jsxs("div",{className:"glass-card",style:{padding:"12px",background:"rgba(0,0,0,0.2)",marginBottom:0},children:[t.jsx("div",{style:{display:"flex",gap:"8px",marginBottom:"12px",alignItems:"center"},children:t.jsxs("div",{style:{position:"relative",flex:1},children:[t.jsx("input",{type:"text",placeholder:"🔍 Buscar por nome, ID ou cidade...",style:{marginBottom:0,paddingRight:"30px",fontSize:"13px"},value:ue,onChange:a=>de(a.target.value)}),ue&&t.jsx("button",{type:"button",onClick:()=>de(""),style:{position:"absolute",right:"10px",top:"50%",transform:"translateY(-50%)",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer"},children:"×"})]})}),t.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"12px",flexWrap:"wrap"},children:[t.jsx("button",{type:"button",className:`btn-small ${je==="all"?"btn-primary":""}`,onClick:()=>fe("all"),style:{padding:"4px 10px",fontSize:"11px"},children:"Todos"}),Ks.map(a=>t.jsx("button",{type:"button",className:`btn-small ${je===a.key?"btn-primary":""}`,onClick:()=>fe(a.key),style:{padding:"4px 10px",fontSize:"11px"},children:a.label},a.key)),t.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:"6px"},children:t.jsx("button",{type:"button",className:"btn-small",style:{background:"var(--glass-bg)",border:"1px solid rgba(255,255,255,0.1)",padding:"4px 10px",fontSize:"11px"},onClick:()=>{const a=Mt.map(b=>b.unique_id);Z(b=>[...new Set([...b,...a])]),ne("info",`Selecionadas ${a.length} lojas.`)},children:"Marcar Visíveis"})})]}),(()=>{const a=_=>({padding:"6px 12px",fontSize:"11px",borderRadius:"999px",cursor:"pointer",border:`1px solid ${_?"var(--secondary)":"rgba(255,255,255,0.15)"}`,background:_?"rgba(237, 177, 37, 0.18)":"rgba(255,255,255,0.03)",color:_?"var(--secondary)":"var(--text-muted)",display:"flex",alignItems:"center",gap:"8px",transition:"all 0.15s"}),b=_=>({width:"14px",height:"14px",borderRadius:"999px",background:_?"var(--secondary)":"transparent",border:`1px solid ${_?"var(--secondary)":"rgba(255,255,255,0.3)"}`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",color:"var(--primary)"});return t.jsxs("div",{style:{display:"flex",gap:"8px",marginBottom:"12px",flexWrap:"wrap",alignItems:"center"},children:[t.jsx("span",{style:{fontSize:"10px",color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Acesso por conta:"}),Ks.map(_=>
42{const I=Js(_.key);return t.jsxs("button",{type:"button",onClick:()=>Qr(_.key),style:a(I),children:[t.jsx("span",{style:b(I),children:I&&"✓"}),_.label," ",t.jsxs("span",{style:{opacity:.6},children:["(",Vs[_.key].length,")"]})]},_.key)})]})})(),t.jsx("div",{style:{maxHeight:"220px",overflowY:"auto",background:"rgba(0,0,0,0.3)",borderRadius:"var(--radius-md)",padding:"4px",border:"1px solid rgba(255,255,255,0.05)"},children:Mt.length===0?t.jsx("div",{style:{padding:"20px",textAlign:"center",color:"var(--text-muted)",fontSize:"13px"},children:"Nenhuma loja encontrada"}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 200px), 1fr))",gap:"4px"},children:Mt.map(a=>{const b=Qt(a),_=Js(b),I=_||F.includes(a.unique_id);return t.jsxs("div",{onClick:()=>_?ne("info","Vínculo de marca ativo — remova-o para escolher lojas individuais."):Hr(a.unique_id),title:_?"Coberta pelo vínculo da marca":"",style:{padding:"8px 10px",cursor:_?"not-allowed":"pointer",borderRadius:"var(--radius-sm)",background:I?"rgba(var(--secondary-rgb), 0.15)":"transparent",border:`1px solid ${I?"var(--secondary)":"rgba(255,255,255,0.05)"}`,display:"flex",alignItems:"center",gap:"10px",transition:"all 0.15s ease",opacity:_?.85:1},onMouseEnter:V=>!I&&!_&&(V.currentTarget.style.background="rgba(255,255,255,0.05)"),onMouseLeave:V=>!I&&!_&&(V.currentTarget.style.background="transparent"),children:[t.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"4px",border:`1px solid ${I?"var(--secondary)":"rgba(255,255,255,0.3)"}`,background:I?"var(--secondary)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",color:"var(--primary)",flexShrink:0},children:I&&"✓"}),t.jsxs("div",{style:{overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"12px",fontWeight:"bold",display:"flex",alignItems:"center",gap:"4px"},children:[t.jsx("span",{children:a.unique_id}),t.jsxs("span",{style:{fontSize:"10px",opacity:.5,fontWeight:"normal"},title:Ys[b],children:["[",un[b],"]"]})]}),t.jsx("div",{style:{fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",opacity:.8},children:a.name||`Loja ${a.unique_id}`}),a.city&&t.jsx("div",{style:{fontSize:"9px",opacity:.5},children:a.city})]})]},a.unique_id)})})}),t.jsxs("div",{style:{marginTop:"8px",fontSize:"11px",color:"var(--text-muted)",textAlign:"center"},children:[Mt.length," lojas mostradas ",Mt.length!==A.length&&`(filtrado de ${A.length})`]})]})]}),ve==="admin"&&t.jsxs("div",{style:{padding:"2rem",textAlign:"center",color:"var(--text-muted)",background:"rgba(255,255,255,0.03)",borderRadius:"var(--radius-md)",border:"1px solid var(--glass-border)"},children:[t.jsx("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"},children:"👑"}),t.jsx("div",{style:{fontSize:"14px",fontWeight:"bold",color:"var(--secondary)"},children:"Admin"}),t.jsx("div",{style:{fontSize:"12px",marginTop:"4px"},children:"Acesso total a todas as lojas"})]}),f&&t.jsxs("div",{className:"modal-sticky-footer",style:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",marginTop:"1.5rem",position:"sticky",bottom:0,background:"linear-gradient(to top, rgba(10,14,25,0.96) 60%, rgba(10,14,25,0))",padding:"1rem 0 0.25rem",zIndex:5},children:[t.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>te(!1),style:{minWidth:"120px"},children:"Cancelar"}),t.jsx("button",{type:"submit",className:"btn btn-primary",style:{minWidth:"120px"},children:"Salvar"})]})]})]})]}),t.jsxs(mt,{isOpen:Na,onClose:()=>ps(!1),title:"Selecionar página de fornecedor",size:"md",footer:t.jsxs("button",{type:"button",className:"btn-primary",onClick:()=>ps(!1),children:["Concluir (",Ee.length,")"]}),children:[t.jsx("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",marginTop:0},children:"Marque as páginas que este fornecedor pode acessar. Ele verá somente a(s) selecionada(s)."}),cr?t.jsx("div",{style:{padding:"24px",textAlign:"center",color:"var(--text-muted)"},children:"Carregando…"}):Ht.length===0?t.jsx("div",{style:{padding:"24px",textAlign:"center",color:"var(--text-muted)"},children:"Nenhuma página de fornecedor cadastrada."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:Ht.filter(a=>!a.marketplace_fornecedor_id).map(a=>{const b=Ee.includes(a.slug);return t.jsxs("div",{onClick:()=>f&&Jr(a.slug),style:{padding:"10px 12px",cursor:f?"pointer":"default",borderRadius:"var(--radius-md)",background:b?"rgba(237,177,37,0.15)":"rgba(255,255,255,0.03)",border:`1px solid ${b?"var(--secondary)":"var(--glass-border)"}`,display:"flex",alignItems:"center",gap:"10px"},children:[t.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"4px",border:`1px solid ${b?"var(--secondary)":"rgba(255,255,255,0.3)"}`,background:b?"var(--secondary)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",color:"var(--primary)",flexShrink:0},children:b&&"✓"}),a.cor&&t.jsx("span",{style:{width:"12px",height:"12px",borderRadius:"50%",background:a.cor,flexShrink:0}}),t.jsxs("div",{style:{overflow:"hidden"},children:[t.jsx("div",{style:{fontSize:"13px",fontWeight:"bold"},children:a.nome}
42),t.jsxs("div",{style:{fontSize:"10px",opacity:.5},children:["/mix/fornecedor/",a.slug]})]})]},a.slug)})})]}),t.jsxs(mt,{isOpen:La,onClose:()=>hs(!1),title:"Vincular fornecedor do marketplace",size:"md",footer:t.jsxs("button",{type:"button",className:"btn-primary",onClick:()=>hs(!1),children:["Concluir (",gt.length,")"]}),children:[t.jsxs("p",{style:{fontSize:"0.8rem",color:"var(--text-muted)",marginTop:0},children:["Esta conta passa a ver o portal desses fornecedores. O selo ",t.jsx("em",{children:"já tem conta"})," marca fornecedor que já está vinculado a alguém."]}),t.jsx("input",{value:pr,onChange:a=>Ba(a.target.value),placeholder:"Buscar por nome ou CNPJ…",style:{width:"100%",padding:"8px 10px",marginBottom:"10px",borderRadius:"var(--radius-md)",border:"1px solid var(--glass-border)",background:"rgba(255,255,255,0.03)",color:"inherit",fontSize:"13px"}}),mr?t.jsx("div",{style:{padding:"24px",textAlign:"center",color:"var(--text-muted)"},children:"Carregando…"}):Vt.length===0?t.jsx("div",{style:{padding:"24px",textAlign:"center",color:"var(--text-muted)"},children:"Nenhum fornecedor no marketplace."}):t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px",maxHeight:"48vh",overflowY:"auto"},children:Vt.filter(a=>{const b=pr.trim().toLowerCase();return b?[a.nome,a.nome_fantasia,a.cnpj].some(_=>(_||"").toLowerCase().includes(b)):!0}).map(a=>{const b=gt.includes(a.id);return t.jsxs("div",{onClick:()=>f&&Kr(a.id),style:{padding:"10px 12px",cursor:f?"pointer":"default",borderRadius:"var(--radius-md)",background:b?"rgba(237,177,37,0.15)":"rgba(255,255,255,0.03)",border:`1px solid ${b?"var(--secondary)":"var(--glass-border)"}`,display:"flex",alignItems:"center",gap:"10px"},children:[t.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"4px",border:`1px solid ${b?"var(--secondary)":"rgba(255,255,255,0.3)"}`,background:b?"var(--secondary)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",color:"var(--primary)",flexShrink:0},children:b&&"✓"}),t.jsxs("div",{style:{overflow:"hidden",flex:1},children:[t.jsx("div",{style:{fontSize:"13px",fontWeight:"bold"},children:a.nome_fantasia||a.nome}),t.jsxs("div",{style:{fontSize:"10px",opacity:.5},children:[a.region," · ",a.cnpj||"sem CNPJ"]})]}),a.tem_acesso&&t.jsx("span",{style:{fontSize:"9px",opacity:.6,whiteSpace:"nowrap"},children:"já tem conta"})]},a.id)})})]}),t.jsx(mt,{isOpen:xe,onClose:()=>{ye(!1),qe(null)},title:f?at?"Editar Cargo":"Novo Cargo":"Visualizar Cargo",children:t.jsx(Cn,{initialRole:at,onSave:Va,onCancel:()=>{ye(!1),qe(null)},readOnly:!f})}),t.jsx(mt,{isOpen:Ge,onClose:()=>Fe(!1),title:f?"Editar Loja":"Detalhes da Loja",children:Qe&&t.jsx($n,{store:Qe,onSave:Qa,onCancel:()=>Fe(!1),readOnly:!f})}),t.jsx(mt,{isOpen:!!De,onClose:()=>Me(null),title:"Detalhes do Worker",size:"lg",children:(()=>{const a=De&&N.find(Ae=>Ae.name===De)||null;if(!a)return null;const b=a.worker_category||"daily_queue",_=b==="continuous"?"♾ Contínuo":b==="sequential_chain"?`⛓ Chain #${a.queue_position??"-"}`:b==="6h"?"⏰ 6h":`🌙 Fila #${a.queue_position??"-"}`,I=a.status==="running"?"var(--success)":a.status==="completed"?"#00b45a":a.status==="error"?"var(--danger)":"var(--warning)",V=a.status==="completed"?"CONCLUÍDO":a.status==="waiting"?"AGUARDANDO":(a.status||"idle").toUpperCase(),ee=a.status==="running"&&a.last_run&&a.schedule_type==="interval"&&Number(a.schedule_value)>0&&Date.now()-new Date(a.last_run).getTime()>Number(a.schedule_value)*2*1e3,se=Ae=>Ae?new Date(Ae).toLocaleString("pt-BR"):"",Te=[{label:"Status",value:V},{label:"Agendamento",value:qr(a)},{label:"Ativo",value:a.is_active?"Sim":"Não"},{label:"Categoria",value:_},{label:"Última execução",value:a.last_run?`há ${ft(a.last_run)}`:"—",sub:se(a.last_run)},{label:"Próxima execução",value:a.next_run?Fr(a.next_run):"—",sub:se(a.next_run)},{label:"PID",value:a.pid?String(a.pid):"—"},{label:"Posição na fila",value:a.queue_position!=null?`#${a.queue_position}`:"—"}];return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",marginBottom:16},children:[t.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:"50%",background:I}}),t.jsx("strong",{style:{fontSize:"1.05rem"},children:a.name}),t.jsx("span",{className:"badge",style:{fontSize:"0.65rem",background:"rgba(120,120,255,0.15)",color:"#8888ff",padding:"2px 8px"},children:_}),!a.is_active&&t.jsx("span",{className:"badge",style:{fontSize:"0.65rem",background:"rgba(255,255,255,0.06)",color:"var(--text-muted)",padding:"2px 8px"},children:"desativado"}),ee&&t.jsx("span",{className:"badge",style:{fontSize:"0.65rem",background:"rgba(239,68,68,0.18)",color:"#fca5a5",padding:"2px 8px",border:"1px solid rgba(239,68,68,0.45)"},children:"⚠ travado"})]}),t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(100%, 150px), 1fr))",gap:10,marginBottom:16},children:Te.map(Ae=>
42t.jsxs("div",{style:{background:"var(--glass-highlight)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-sm)",padding:"10px 12px"},children:[t.jsx("div",{style:{fontSize:"0.68rem",textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--text-muted)",marginBottom:4},children:Ae.label}),t.jsx("div",{style:{fontSize:"0.95rem",fontWeight:700},children:Ae.value}),Ae.sub&&t.jsx("div",{style:{fontSize:"0.7rem",color:"var(--text-muted)",marginTop:2},children:Ae.sub})]},Ae.label))}),a.message&&t.jsxs("div",{style:{background:"rgba(255,255,255,0.03)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-sm)",padding:"10px 12px",marginBottom:16,fontSize:"0.85rem",color:"var(--text-secondary)"},children:[t.jsx("span",{style:{color:"var(--text-muted)"},children:"Mensagem: "}),a.message]}),t.jsxs("div",{style:{display:"flex",gap:8,marginBottom:18,flexWrap:"wrap"},children:[a.status!=="running"?t.jsx("button",{className:"btn-small btn-primary",onClick:()=>Hs(a.name),children:"▶ Executar agora"}):t.jsx("button",{className:"btn-small btn-danger",onClick:()=>Yr(a.name),children:"■ Parar"}),t.jsx("button",{className:"btn-small btn-secondary",onClick:()=>{Ce(a),Me(null)},children:"⚙ Configurar"}),t.jsx("button",{className:`btn-small ${a.is_active?"btn-danger":"btn-success"}`,onClick:()=>Xr(a.name),children:a.is_active?"Desativar":"Ativar"})]}),t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6},children:[t.jsx("strong",{style:{fontSize:"0.9rem"},children:"Logs recentes"}),t.jsx("button",{className:"btn btn-secondary btn-small",onClick:()=>Or(a.name),children:"🔄 Atualizar"})]}),t.jsx("pre",{style:{background:"#0b1020",color:"#cdd6f4",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-sm)",padding:12,maxHeight:300,overflow:"auto",fontSize:"0.75rem",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:Je?"Carregando logs…":rt})]})})()}),t.jsx(mt,{isOpen:!!pe,onClose:()=>Ce(null),title:"Configurar Agendamento",children:pe&&t.jsxs("form",{onSubmit:Za,children:[t.jsxs("div",{style:{background:"var(--glass-highlight)",border:"1px solid var(--glass-border)",borderRadius:"var(--radius-sm)",padding:"12px 16px",marginBottom:"1.2rem",textAlign:"center"},children:[t.jsx("span",{style:{fontSize:"0.85em",color:"var(--text-muted)"},children:"Frequência atual:"}),t.jsx("div",{style:{fontSize:"1.3em",fontWeight:"bold",color:"var(--secondary)",marginTop:"4px"},children:pe.schedule_type==="interval"?`A cada ${Wl(pe.schedule_value||"3600")}`:`Diário às ${pe.schedule_value}`}),t.jsxs("span",{style:{fontSize:"0.75em",color:"var(--text-muted)"},children:["Status: ",pe.status?.toUpperCase()||"IDLE",pe.is_active?" · Ativo":" · Inativo"]})]}),t.jsxs("div",{style:{marginBottom:"1rem"},children:[t.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Worker"}),t.jsx("input",{type:"text",value:pe.name,disabled:!0,className:"admin-input",style:{opacity:.7}})]}),t.jsxs("div",{style:{marginBottom:"1rem"},children:[t.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Tipo de Agendamento"}),t.jsxs("div",{style:{display:"flex",gap:"1rem"},children:[t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer"},children:[t.jsx("input",{type:"radio",name:"schedule_type",value:"interval",defaultChecked:pe.schedule_type==="interval"||!pe.schedule_type}),"Intervalo"]}),t.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"5px",cursor:"pointer"},children:[t.jsx("input",{type:"radio",name:"schedule_type",value:"daily",defaultChecked:pe.schedule_type==="daily"}),"Diário (Horário)"]})]})]}),t.jsxs("div",{style:{marginBottom:"1rem"},children:[t.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Presets Rápidos"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Il.map(a=>t.jsx("button",{type:"button",className:"btn-small",style:{background:pe.schedule_value===a.value?"var(--secondary)":"var(--glass-highlight)",color:pe.schedule_value===a.value?"var(--primary)":"var(--text-primary)",border:pe.schedule_value===a.value?"1px solid var(--secondary)":"1px solid var(--glass-border)",padding:"6px 14px",borderRadius:"var(--radius-sm)",fontWeight:"bold",cursor:"pointer",transition:"all 0.15s"},onClick:()=>{const b=document.querySelector('input[name="schedule_value"]');b&&(b.value=a.value);const _=document.querySelector('input[name="schedule_type"][value="interval"]');_&&(_.checked=!0),Ce({...pe,schedule_value:a.value,schedule_type:"interval"})},children:a.label},a.value))})]}),t.jsxs("div",{style:{marginBottom:"1rem"},children:[t.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Valor Personalizado"}),t.jsx("input",{type:"text",name:"schedule_value",defaultValue:pe.schedule_value||"3600",className:"admin-input",placeholder:"Ex: 3600 (segundos) ou 03:00 (H:M)"}),t.jsx("p",{style:{fontSize:"0.8em",color:"var(--text-muted)",marginTop:"5px"}
42,children:"Intervalo: segundos (3600 = 1h). Diário: HH:MM (03:00)."})]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:"10px",marginTop:"1.5rem"},children:[t.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>Ce(null),children:"Cancelar"}),pe.status!=="running"&&t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>{Hs(pe.name),Ce(null)},children:"▶ Iniciar Agora"}),t.jsx("button",{type:"submit",className:"btn",style:{background:"var(--glass-highlight)",border:"1px solid var(--glass-border)"},children:"💾 Salvar"}),t.jsx("button",{type:"button",className:"btn",style:{background:"var(--success)",color:"#fff",fontWeight:"bold"},onClick:a=>en(a),children:"🔄 Aplicar e Reiniciar"})]})]})}),t.jsx(Ca,{isOpen:!!u,title:u?.title||"",message:u?.message||"",confirmLabel:u?.confirmLabel,variant:u?.variant,busy:y,onCancel:()=>!y&&p(null),onConfirm:h})]})}export{ei as default};

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