1import{a8 as T,j as e,aK as me,ak as Ue,al as De,am as M,bh as Fe,aX as Le,n as ze,_ as Oe,an as R,aT as U,aU as D,aV as Y,aW as $,a as B,aH as He,aI as Ke,aJ as We,aM as Ye,bi as $e,bj as Be,aL as V,aE as Z,B as C,bb as v,I as f,aw as fe,aN as F,aO as L,aP as z,aQ as O,aR as H,P as se,T as Qe,m as ee,a5 as Ge,l as ye,as as Je,at as Xe,au as Ze,av as es,ax as ss,bk as as,$ as Ne,a0 as we,a1 as _e,v as xe,w as he,x as pe,aS as ve,a_ as ts}from"./index-BnIFACY4.js";import{r}from"./recharts-DVWcRXdZ.js";import{S as K}from"./skeleton-CCPBiZD9.js";const w=()=>T.schema("workforce_v2");class x{static async updateConfig(a,t){const{data:{user:l}}=await T.auth.getUser(),{error:o}=await w().from("gamification_config").upsert({key:a,value:t,updated_by:l==null?void 0:l.id,updated_at:new Date().toISOString()},{onConflict:"key"});if(o)throw o}static async updateWeights(a,t){await Promise.all([x.updateConfig("weights_volume",a),x.updateConfig("weights_consistency",t)])}static async listWeightVersions(){const{data:a,error:t}=await w().from("gamification_weight_versions").select("id, effective_from_period, weights, notes, created_at").order("effective_from_period",{ascending:!1});if(t)throw t;return a??[]}static async createWeightVersion(a){const{error:t}=await w().from("gamification_weight_versions").upsert({effective_from_period:a.effective_from_period,weights:a.weights,notes:a.notes??null},{onConflict:"effective_from_period"});if(t)throw t}static async deleteWeightVersion(a){const{error:t}=await w().from("gamification_weight_versions").delete().eq("id",a);if(t)throw t}static async setEnabled(a){await x.updateConfig("is_enabled",a)}static async setMinParticipants(a){await x.updateConfig("min_participants",a)}static async setHeaderMessage(a){await x.updateConfig("header_message",a)}static async getHolidays(a){let t=w().from("holidays").select("id, date, name, created_at").order("date",{ascending:!0});a&&(t=t.gte("date",`${a}-01-01`).lte("date",`${a}-12-31`));const{data:l,error:o}=await t;if(o)throw o;return l??[]}static async addHoliday(a,t){const{data:{user:l}}=await T.auth.getUser(),{data:o,error:g}=await w().from("holidays").insert({date:a,name:t,created_by:l==null?void 0:l.id}).select().single();if(g)throw g;return o}static async removeHoliday(a){const{error:t}=await w().from("holidays").delete().eq("id",a);if(t)throw t}static async getAchievements(){const{data:a,error:t}=await w().from("achievements").select("*").order("sort_order",{ascending:!0});if(t)throw t;return a??[]}static async createAchievement(a){const{data:t,error:l}=await w().from("achievements").insert({...a,updated_at:new Date().toISOString()}).select().single();if(l)throw l;return t}static async updateAchievement(a,t){const{data:l,error:o}=await w().from("achievements").update({...t,updated_at:new Date().toISOString()}).eq("id",a).select().single();if(o)throw o;return l}static async toggleAchievement(a,t){const{error:l}=await w().from("achievements").update({is_active:t,updated_at:new Date().toISOString()}).eq("id",a);if(l)throw l}static async getAllUserAchievements(){const t=[];for(let l=0;;l+=1e3){const{data:o,error:g}=await w().from("user_achievements").select("user_id, achievement_id, unlocked_at, context").order("unlocked_at",{ascending:!0}).range(l,l+1e3-1);if(g)throw g;const j=o??[];if(t.push(...j),j.length<1e3)break}return t}static async addExcludedUser(a,t){const{data:{user:l}}=await T.auth.getUser(),{error:o}=await w().from("airats_excluded_users").insert({user_id:a,excluded_by:l==null?void 0:l.id,reason:t??null});if(o)throw o}static async removeExcludedUser(a){const{error:t}=await w().from("airats_excluded_users").delete().eq("user_id",a);if(t)throw t}static async recalculateLeaderboard(a,t){var j,m;const{data:{session:l}}=await T.auth.getSession(),o=await T.functions.invoke("analytics-aggregate",{body:{scope:"gamification",period_type:a,period_key:t,backfill:!0,force:!0},headers:l!=null&&l.access_token?{Authorization:`Bearer ${l.access_token}`}:void 0});if(o.error)throw o.error;return(((j=o.data)==null?void 0:j.gamification_requested)||((m=o.data)==null?void 0:m.gamification_monthly)||o.data)??{updated:0}}}function be(u){const a=u.trim().split(/\s+/);return a.length>=2?`${a[0][0]}${a[a.length-1][0]}`.toUpperCase():u.slice(0,2).toUpperCase()}const is=[{value:"messages_total",label:"Total de mensagens (all-time)"},{value:"agents_used",label:"Agentes distintos usados"},{value:"agents_used_all",label:"Todos os agentes usados"},{value:"streak_days",label:"Dias úteis consecutivos"},{value:"feedback_count",label:"Feedbacks dados"},{value:"leaderboard_top3",label:"Top 3 em qualquer categoria (mês)"},{value:"leaderboard_first",label:"1º lugar geral (mês)"},{value:"leaderboard_wins",label:"Meses como 1º lugar (total)"},{value:"leaderboard_dual_top3",label:"Top 3 em Volume E Consistência no mesmo mês"}],ge=[{value:"volume",label:"Volume"},{value:"exploration",label:"Exploração"},{value:"consistency",label:"Consistência"},{value:"engagement",label:"Engajamento"},{value:"leaderboard",label:"Leaderboard"}];function rs(){const{toast:u}=B(),[a,t]=r.useState(!0),[l,o]=r.useState("1.0"),[g,j]=r.useState("1.0"),[m,_]=r.useState("5"),[d,h]=r.useState(""),[b,N]=r.useState(!0),[S,A]=r.useState(!1),[k,c]=r.useState(He()),[s,i]=r.useState(Ke()),[p,E]=r.useState(We()),[P,q]=r.useState(null),[ae,te]=r.useState([]),[W,ie]=r.useState(""),[re,Se]=r.useState("1"),[ne,Ce]=r.useState("1"),[le,Ae]=r.useState("0"),[ce,oe]=r.useState(""),[de,ue]=r.useState(!1),ke=Ye(12),Ee=$e(8),Ie=Be(5),Q=()=>x.listWeightVersions().then(te).catch(()=>te([]));r.useEffect(()=>{Promise.all([V.getConfig(),Q()]).then(([n])=>{t(n.is_enabled),o(String(n.weights_volume)),j(String(n.weights_consistency)),_(String(n.min_participants)),h(n.header_message),N(!1)})},[]);const Te=async()=>
1{if(!/^\d{4}-\d{2}$/.test(W)){u({title:"Informe o mês de vigência no formato AAAA-MM",variant:"destructive"});return}const n={volume:parseFloat(re.replace(",",".")),consistency:parseFloat(ne.replace(",",".")),roi_hours:parseFloat(le.replace(",","."))};if(Object.values(n).some(y=>!Number.isFinite(y)||y<0)){u({title:"Pesos inválidos",description:"Use números >= 0.",variant:"destructive"});return}ue(!0);try{await x.createWeightVersion({effective_from_period:W,weights:n,notes:ce||void 0}),u({title:"Versão de pesos salva",description:`Vale para perÃodos que abrem a partir de ${W}. PerÃodos já fechados não mudam.`}),ie(""),oe(""),await Q()}catch(y){u({title:"Erro ao salvar versão",description:String(y),variant:"destructive"})}finally{ue(!1)}},Ve=async n=>{try{await x.deleteWeightVersion(n),await Q(),u({title:"Versão removida"})}catch(y){u({title:"Erro ao remover versão",description:String(y),variant:"destructive"})}},Pe=async()=>{A(!0);try{await Promise.all([x.setEnabled(a),x.updateWeights(parseFloat(l),parseFloat(g)),x.setMinParticipants(parseInt(m,10)),x.setHeaderMessage(d)]),u({title:"Configurações salvas com sucesso."})}catch(n){u({title:"Erro ao salvar",description:String(n),variant:"destructive"})}finally{A(!1)}},qe=async(n,y)=>{q(n);try{const I=await x.recalculateLeaderboard(n,y);u({title:`Leaderboard recalculado â ${ve(n,y)}`,description:`${I.updated} entradas atualizadas.`})}catch(I){u({title:"Erro ao recalcular",description:String(I),variant:"destructive"})}finally{q(null)}};if(b)return e.jsx("div",{className:"space-y-3",children:[...Array(4)].map((n,y)=>e.jsx(K,{className:"h-10"},y))});const G=({label:n,periodType:y,value:I,onChange:Me,options:Re})=>{const J=P===y;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(v,{className:"w-24 text-sm text-muted-foreground",children:n}),e.jsxs(F,{value:I,onValueChange:Me,disabled:J,children:[e.jsx(L,{className:"w-[220px]",children:e.jsx(z,{})}),e.jsx(O,{children:Re.map(X=>e.jsx(H,{value:X,children:ve(y,X)},X))})]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>qe(y,I),disabled:J||P!==null,children:[e.jsx(ts,{className:ye("h-4 w-4 mr-2",J&&"animate-spin")}),"Recalcular"]})]})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sistema ativo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Quando desativado, a seção AIrats fica oculta para todos os usuários."})]}),e.jsx(Z,{checked:a,onCheckedChange:t})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Pesos do ranking â versões por perÃodo"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Cada versão vale para perÃodos que ",e.jsx("b",{children:"abrem"})," a partir do mês informado â mudar pesos nunca reescreve rankings passados. A dimensão ",e.jsx("b",{children:"Horas economizadas"})," (ROI) fica em observação (shadow) enquanto o peso for 0."]})]}),ae.length>0&&e.jsx("div",{className:"divide-y divide-border rounded-md border border-border",children:ae.map(n=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[e.jsx("span",{className:"font-mono text-xs w-20",children:n.effective_from_period}),e.jsxs("span",{className:"flex-1 text-xs text-muted-foreground tabular-nums",children:["volume ",n.weights.volume??1," · consistência ",n.weights.consistency??1," · horas econ. ",n.weights.roi_hours??0,n.notes&&e.jsx("span",{className:"block truncate",children:n.notes})]}),e.jsx(C,{size:"sm",variant:"ghost",className:"h-7 text-xs text-destructive",onClick:()=>Ve(n.id),children:"Remover"})]},n.id))}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{className:"text-xs",children:"Vale a partir de (AAAA-MM)"}),e.jsx(f,{className:"w-32",placeholder:"2026-08",value:W,onChange:n=>ie(n.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{className:"text-xs",children:"Volume"}),e.jsx(f,{className:"w-20",value:re,onChange:n=>Se(n.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{className:"text-xs",children:"Consistência"}),e.jsx(f,{className:"w-20",value:ne,onChange:n=>Ce(n.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(v,{className:"text-xs",children:"Horas econ."}),e.jsx(f,{className:"w-20",value:le,onChange:n=>Ae(n.target.value)})]}),e.jsxs("div",{className:"space-y-1 flex-1 min-w-[160px]",children:[e.jsx(v,{className:"text-xs",children:"Notas (opcional)"}),e.jsx(f,{value:ce,onChange:n=>oe(n.target.value),placeholder:"ex.: ativa horas econ. com peso 0,5"})]}),e.jsx(C,{size:"sm",onClick:Te,disabled:de,children:de?"Salvandoâ¦":"Criar versão"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Pesos legados (fallback sem versões)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{htmlFor:"wv",children:"Peso de Volume"}),e.jsx(f,{id:"wv",type:"number",step:"0.1",min:"0",value:l,onCh
1ange:n=>o(n.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{htmlFor:"wc",children:"Peso de Consistência"}),e.jsx(f,{id:"wc",type:"number",step:"0.1",min:"0",value:g,onChange:n=>j(n.target.value)})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Usados apenas se nenhuma versão acima cobrir o perÃodo. Fórmula: pontuação = (pts_volume à ",l||"1",") + (pts_consistência à ",g||"1",")"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{htmlFor:"mp",children:"MÃnimo de participantes para exibir ranking"}),e.jsx(f,{id:"mp",type:"number",min:"1",value:m,onChange:n=>_(n.target.value),className:"max-w-[120px]"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Se houver menos participantes ativos no mês, exibe mensagem de encorajamento em vez do ranking."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{htmlFor:"hm",children:"Mensagem de boas-vindas"}),e.jsx(fe,{id:"hm",value:d,onChange:n=>h(n.target.value),rows:3,placeholder:"Texto que aparece no topo da página AIrats..."})]}),e.jsx("div",{children:e.jsx(C,{onClick:Pe,disabled:S,children:S?"Salvando...":"Salvar configurações"})}),e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Recalcular leaderboards"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Reprocessa as snapshots para o perÃodo selecionado. Ãtil para atualizar dados após o virar do mês/trimestre/ano ou ver parciais."})]}),e.jsx(G,{label:"Mensal",periodType:"monthly",value:k,onChange:c,options:ke}),e.jsx(G,{label:"Trimestral",periodType:"quarterly",value:s,onChange:i,options:Ee}),e.jsx(G,{label:"Anual",periodType:"yearly",value:p,onChange:E,options:Ie})]})]})}function ns(){const{toast:u}=B(),[a,t]=r.useState([]),[l,o]=r.useState(!0),[g,j]=r.useState(""),[m,_]=r.useState(""),[d,h]=r.useState(!1),[b,N]=r.useState(String(new Date().getFullYear())),S=async()=>{o(!0);try{t(await x.getHolidays(parseInt(b,10)))}finally{o(!1)}};r.useEffect(()=>{S()},[b]);const A=async()=>{if(!(!g||!m.trim())){h(!0);try{const s=await x.addHoliday(g,m.trim());t(i=>[...i,s].sort((p,E)=>p.date.localeCompare(E.date))),j(""),_(""),u({title:"Feriado adicionado."})}catch(s){u({title:"Erro ao adicionar feriado",description:String(s),variant:"destructive"})}finally{h(!1)}}},k=async s=>{try{await x.removeHoliday(s),t(i=>i.filter(p=>p.id!==s)),u({title:"Feriado removido."})}catch(i){u({title:"Erro ao remover",description:String(i),variant:"destructive"})}},c=new Date().getFullYear();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(F,{value:b,onValueChange:N,children:[e.jsx(L,{className:"w-[120px]",children:e.jsx(z,{})}),e.jsx(O,{children:[c-1,c,c+1].map(s=>e.jsx(H,{value:String(s),children:s},s))})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[a.length," feriados"]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"space-y-1 flex-shrink-0",children:[e.jsx(v,{children:"Data"}),e.jsx(f,{type:"date",value:g,onChange:s=>j(s.target.value),className:"w-[160px]"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx(v,{children:"Nome"}),e.jsx(f,{value:m,onChange:s=>_(s.target.value),placeholder:"Ex: Feriado da empresa"})]}),e.jsxs(C,{onClick:A,disabled:d||!g||!m.trim(),children:[e.jsx(se,{className:"h-4 w-4 mr-1"}),"Adicionar"]})]}),l?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((s,i)=>e.jsx(K,{className:"h-10"},i))}):a.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["Nenhum feriado cadastrado para ",b,"."]}):e.jsx("div",{className:"border rounded-lg divide-y",children:a.map(s=>e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:s.name}),e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:new Date(s.date+"T12:00:00").toLocaleDateString("pt-BR",{weekday:"short",day:"2-digit",month:"2-digit"})})]}),e.jsx(C,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>k(s.id),children:e.jsx(Qe,{className:"h-3.5 w-3.5"})})]},s.id))})]})}const je={slug:"",name:"",description:"",icon:"ð",category:"volume",criteria_type:"messages_total",criteria_value:0,criteria_config:null,sort_order:100,is_active:!0};function ls(){const{toast:u}=B(),[a,t]=r.useState([]),[l,o]=r.useState(!0),[g,j]=r.useState(!1),[m,_]=r.useState(null),[d,h]=r.useState(je),[b,N]=r.useState(!1);r.useEffect(()=>{x.getAchievements().then(s=>{t(s),o(!1)})},[]);const S=()=>{_(null),h(je),j(!0)},A=s=>{_(s),h({slug:s.slug,name:s.name,description:s.description,icon:s.icon,category:s.category,criteria_type:s.criteria_type,criteria_value:s.criteria_value,criteria_config:s.criteria_config,sort_order:s.sort_order,is_active:s.is_active}),j(!0)},k=async()=>{N(!0);try{if(m){const s=await x.updateAchievement(m.id,d);t(i=>i.map(p=>p.id===s.id?s:p))}else{const s=await x.createAchievement(d);t(i=>[...i,s].sort((p,E)=>p.sort_order-E.sort_order))}u({title:m?"Conquista atualizada.":"Conquista criada."}),j(!1)}catch(s){u({title:"Erro ao salvar",description:String(s),variant:"destructive"})}finally{N(!1)}},c=async s=>{try{await x.toggleAchievement(s.id,!s.is_active),t(i=>i.map(p=>p.id===s.id?{...p,is_active:!s.is_active}:p))}catch(i){u({title:"Erro",description:String(i),variant:"destructive"})}};return l?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((s,i)=>e.jsx(K,{className:"h-12"},i))}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(C,{size:"sm",onClick:S,children:[e.jsx(se,{className:"h-4 w-4 mr-1"}),"Nova conquista"]})}),e.jsx("div",{className:"border rounded-lg divide-y",children:a.map(s=>{var i;return e.jsxs("div",{className:ye("flex items-center gap-3 px-4 py-3",!s.is_active&&"opacity-50"),children:[e.jsx("span",{className:"text-xl w-8",children:s.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.name}),e.jsx(ee,{variant:"outline",className:"text-[9px] px-1.5 py-0 shrink-0",children:(i=ge.find(p=>p.value===s.category))==null?void 0:i.label}),!s.is_active&&e.jsx(ee,{variant:"secondary",className:"text-[9px] px-1.5 py-0",children:"Inativo"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.description})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(C,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>A(s),children:e.jsx(Ge,{className:"h-3.5 w-3.5"})}),e.jsx(Z,{checked:s.is_active,onCheckedChange:()=>c(s),className:"scale-75"})]})]},s.id)})}),e.jsx(Je,{open:g,onOpenChange:j,children:e.jsxs(Xe,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Ze,{children:e.jsx(es,{children:m?"Editar conquista":"Nova conquista"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Ãcone (emoji)"}),e.jsx(f,{value:d.icon,onChange:s=>h({...d,icon:s.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Slug (único)"}),e.jsx(f,{value:d.slug,onChange:s=>h({...d,slug:s.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Nome"}),e.jsx(f,{value:d.name,onChange:s=>h({...d,name:s.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Descrição"}),e.jsx(fe,{rows:2,value:d.description,onChange:s=>h({...d,description:s.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Categoria"}),e.jsxs(F,{value:d.category,onValueChange:s=>h({...d,category:s}),children:[e.jsx(L,{children:e.jsx(z,{})}),e.jsx(O,{children:ge.map(s=>e.jsx(H,{value:s.value,children:s.label},s.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Ordem de exibição"}),e.jsx(f,{type:"number",value:d.sort_order,onChange:s=>h({...d,sort_order:parseInt(s.target.value,10)})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Tipo de critério"}),e.jsxs(F,{value:d.criteria_type,onValueChange:s=>h({...d,criteria_type:s}),children:[e.jsx(L,{children:e.jsx(z,{})}),e.jsx(O,{children:is.map(s=>e.jsx(H,{value:s.value,children:s.label},s.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(v,{children:"Valor do critério"}),e.jsx(f,{type:"number",min:"0",value:d.criteria_value,onChange:s=>h({...d,criteria_value:parseInt(s.target.value,10)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Z,{id:"active",checked:d.is_active,onCheckedChange:s=>h({...d,is_active:s})}),e.jsx(v,{htmlFor:"active",children:"Conquista ativa"})]})]}),e.jsxs(ss,{children:[e.jsx(C,{variant:"outline",onClick:()=>j(!1),children:"Cancelar"}),e.jsx(C,{onClick:k,disabled:b||!d.name||!d.slug,children:b?"Salvando...":"Salvar"})]})]})})]})}function cs(){const[u,a]=r.useState([]),[t,l]=r.useState([]),[o,g]=r.useState([]),[j,m]=r.useState(new Set),[_,d]=r.useState(!0),[h,b]=r.useState("");
1if(r.useEffect(()=>{Promise.all([V.getAllProfiles(),V.getAchievements(),x.getAllUserAchievements(),V.getExcludedUsers()]).then(([c,s,i,p])=>{a(c),l(s),g(i),m(new Set(p.map(E=>E.user_id))),d(!1)})},[]),_)return e.jsx("div",{className:"space-y-2",children:[...Array(6)].map((c,s)=>e.jsx(K,{className:"h-12"},s))});const N=new Map;for(const c of o)N.has(c.user_id)||N.set(c.user_id,new Map),N.get(c.user_id).set(c.achievement_id,c.unlocked_at);const S=h.trim().toLowerCase(),A=u.filter(c=>{var s,i;return!S||((s=c.display_name)==null?void 0:s.toLowerCase().includes(S))||((i=c.email)==null?void 0:i.toLowerCase().includes(S))}).map(c=>({profile:c,userUnlocks:N.get(c.id)??new Map})).sort((c,s)=>s.userUnlocks.size-c.userUnlocks.size),k=t.length;return e.jsx(as,{delayDuration:150,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(f,{value:h,onChange:c=>b(c.target.value),placeholder:"Buscar usuário por nome ou email...",className:"max-w-xs"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.length," desbloqueios · ",k," conquistas ativas"]})]}),e.jsxs("div",{className:"border rounded-lg divide-y",children:[A.map(({profile:c,userUnlocks:s})=>e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsxs(Ne,{className:"h-8 w-8 flex-shrink-0",children:[e.jsx(we,{src:c.avatar_url??void 0}),e.jsx(_e,{className:"text-xs",children:be(c.display_name??c.email??"?")})]}),e.jsxs("div",{className:"w-44 flex-shrink-0 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx("p",{className:"text-sm font-medium truncate",children:c.display_name||c.email})}),e.jsx(pe,{side:"top",children:c.email})]}),j.has(c.id)&&e.jsx(ee,{variant:"secondary",className:"text-[9px] px-1.5 py-0 flex-shrink-0",children:"ExcluÃdo"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.size,"/",k," conquistas"]})]}),e.jsxs("div",{className:"flex-1 flex flex-wrap gap-1",children:[t.filter(i=>s.has(i.id)).map(i=>e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx("span",{className:"text-lg leading-none cursor-default",children:i.icon})}),e.jsxs(pe,{side:"top",className:"text-xs",children:[e.jsx("p",{className:"font-medium",children:i.name}),e.jsx("p",{className:"text-muted-foreground",children:new Date(s.get(i.id)).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]},i.id)),s.size===0&&e.jsx("span",{className:"text-xs text-muted-foreground/60",children:"Nenhuma conquista ainda"})]})]},c.id)),A.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhum usuário encontrado."})]})]})})}function os(){const{toast:u}=B(),[a,t]=r.useState([]),[l,o]=r.useState([]),[g,j]=r.useState(!0),[m,_]=r.useState(""),[d,h]=r.useState(""),[b,N]=r.useState(!1);r.useEffect(()=>{Promise.all([V.getExcludedUsers(),V.getAllProfiles()]).then(([s,i])=>{t(s),o(i),j(!1)})},[]);const S=new Set(a.map(s=>s.user_id)),A=l.filter(s=>!S.has(s.id)),k=async()=>{if(m){N(!0);try{await x.addExcludedUser(m,d.trim()||void 0);const s=l.find(i=>i.id===m);t(i=>[...i,{user_id:m,reason:d.trim()||null,excluded_at:new Date().toISOString(),profile:s}]),_(""),h(""),u({title:"Usuário excluÃdo da competição."})}catch(s){u({title:"Erro",description:String(s),variant:"destructive"})}finally{N(!1)}}},c=async s=>{try{await x.removeExcludedUser(s),t(i=>i.filter(p=>p.user_id!==s)),u({title:"Usuário reincluÃdo na competição."})}catch(i){u({title:"Erro",description:String(i),variant:"destructive"})}};return g?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((s,i)=>e.jsx(K,{className:"h-12"},i))}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Usuários excluÃdos não aparecem nos rankings nem são considerados nos cálculos de pontuação. Use para remover contas de teste, admins ou usuários que por alguma razão não devem competir."}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx(v,{children:"Usuário"}),e.jsxs(F,{value:m,onValueChange:_,children:[e.jsx(L,{children:e.jsx(z,{placeholder:"Selecione um usuário..."})}),e.jsx(O,{children:A.map(s=>e.jsxs(H,{value:s.id,children:[s.display_name," (",s.email,")"]},s.id))})]})]}),e.jsxs("div",{className:"space-y-1 w-48",children:[e.jsx(v,{children:"Motivo (opcional)"}),e.jsx(f,{value:d,onChange:s=>h(s.target.value),placeholder:"Conta de teste..."})]}),e.jsxs(C,{onClick:k,disabled:b||!m,children:[e.jsx(se,{className:"h-4 w-4 mr-1"}),"Excluir"]})]}),a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhum usuário excluÃdo."}):e.jsx("div",{className:"border rounded-lg divide-y",children:a.map(s=>{var i,p,E,P,q;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsxs(Ne,{className:"h-8 w-8",children:[e.jsx(we,{src:((i=s.profile)==null?void 0:i.avatar_url)??void 0}),e.jsx(_e,{className:"text-xs",children:be(((p=s.profile)==null?void 0:p.display_name)??((E=s.profile)==null?void 0:E.email)??"?")})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:((P=s.profile)==null?void 0:P.display_name)??((q=s.profile)==null?void 0:q.email)??s.user_id}),s.reason&&e.jsx("p",{className:"text-xs text-muted-foreground",children:s.reason})]}),e.jsx(C,{variant:"ghost",size:"sm",className:"text-muted-foreground hover:text-foreground",onClick:()=>
1c(s.user_id),children:"Reincluir"})]},s.user_id)})})]})}const xs=()=>e.jsxs("div",{className:"max-w-3xl mx-auto px-4 sm:px-6 py-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(me,{className:"h-5 w-5 text-yellow-500"}),e.jsx("h1",{className:"text-xl font-bold",children:"Admin â AIrats"})]}),e.jsxs(Ue,{defaultValue:"config",children:[e.jsxs(De,{className:"mb-6",children:[e.jsxs(M,{value:"config",children:[e.jsx(Fe,{className:"h-3.5 w-3.5 mr-1.5"}),"Config"]}),e.jsxs(M,{value:"holidays",children:[e.jsx(Le,{className:"h-3.5 w-3.5 mr-1.5"}),"Feriados"]}),e.jsxs(M,{value:"achievements",children:[e.jsx(ze,{className:"h-3.5 w-3.5 mr-1.5"}),"Conquistas"]}),e.jsxs(M,{value:"user-achievements",children:[e.jsx(me,{className:"h-3.5 w-3.5 mr-1.5"}),"Por usuário"]}),e.jsxs(M,{value:"excluded",children:[e.jsx(Oe,{className:"h-3.5 w-3.5 mr-1.5"}),"ExcluÃdos"]})]}),e.jsx(R,{value:"config",children:e.jsx(U,{children:e.jsx(D,{className:"pt-6",children:e.jsx(rs,{})})})}),e.jsx(R,{value:"holidays",children:e.jsxs(U,{children:[e.jsx(Y,{className:"pb-3",children:e.jsx($,{className:"text-base",children:"Feriados e dias não úteis"})}),e.jsx(D,{children:e.jsx(ns,{})})]})}),e.jsx(R,{value:"achievements",children:e.jsxs(U,{children:[e.jsx(Y,{className:"pb-3",children:e.jsx($,{className:"text-base",children:"Conquistas disponÃveis"})}),e.jsx(D,{children:e.jsx(ls,{})})]})}),e.jsx(R,{value:"user-achievements",children:e.jsxs(U,{children:[e.jsx(Y,{className:"pb-3",children:e.jsx($,{className:"text-base",children:"Conquistas por usuário"})}),e.jsx(D,{children:e.jsx(cs,{})})]})}),e.jsx(R,{value:"excluded",children:e.jsxs(U,{children:[e.jsx(Y,{className:"pb-3",children:e.jsx($,{className:"text-base",children:"Usuários excluÃdos da competição"})}),e.jsx(D,{children:e.jsx(os,{})})]})})]})]});export{xs 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.