1import{ab as Ts,a8 as xa,j as e,b4 as Ls,B as E,l as V,v as qe,w as Ue,x as Ve,H as ha,aN as Q,aO as Z,aP as J,aQ as K,aR as L,a as me,by as zs,L as oe,P as ze,ez as fa,bf as ga,F as va,u as ls,t as _a,a5 as ja,T as Be,_ as Fs,A as Is,c as qs,d as Us,e as Vs,f as Bs,g as Gs,h as Hs,i as Qs,I as G,a$ as cs,aw as Ge,aE as $e,bO as Zs,bg as Xe,as as ba,at as Na,au as wa,av as ya,ax as Ca,a6 as ds,b5 as Js,mM as Ks,mN as ne,dX as Ws,aX as Ys,mL as Xs}from"./index-BnIFACY4.js";import{u as et}from"./useVibeAppAccess-CBclI4Bq.js";import{r as b}from"./recharts-DVWcRXdZ.js";import{L as at}from"./link-2-bwLHVpRQ.js";import{E as st}from"./external-link-CnWsfGh5.js";import{D as tt}from"./download-5BKLQMzF.js";import{L as rt}from"./list-checks-CLulHt5k.js";import{C as nt}from"./calendar-range-Doauv9dF.js";import{S as ot}from"./settings-2-hTwlv-rf.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const it=Ts("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),ms=["cliente","prospect","ambos"],us={cliente:"Clientes",prospect:"Prospects",ambos:"Clientes e prospects"},Sa=["presencial","hibrido","online","nao_se_aplica"],Aa={presencial:"Presencial",hibrido:"HÃbrido",online:"Online",nao_se_aplica:"Não se aplica"},lt=["nacional","regional"],ct={nacional:"Nacional",regional:"Regional"},He=["ideia","planejada","confirmada","realizada","cancelada"],De={ideia:"Ideia",planejada:"Planejada",confirmada:"Confirmada",realizada:"Realizada",cancelada:"Cancelada"},we=["G","E","M","P"],Ne={G:"Grandes Contas",E:"Enterprise",M:"Middle Market",P:"Reativo"},ps=["AC","AL","AP","AM","BA","CE","DF","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RJ","RN","RS","RO","RR","SC","SP","SE","TO"];function Me(a,s){return s==null||s===""?"â":Object.prototype.hasOwnProperty.call(a,s)?a[s]:s}const ka=a=>Me(us,a),Qe=a=>Me(Aa,a),dt=a=>Me(ct,a),fe=a=>Me(De,a),xs=a=>Me(Ne,a),hs=a=>typeof a=="string"&&ms.includes(a),Oe=a=>typeof a=="string"&&Sa.includes(a),Fe=a=>typeof a=="string"&<.includes(a),Ea=a=>typeof a=="string"&&He.includes(a),$a=a=>typeof a=="string"&&we.includes(a),Da=a=>typeof a=="string"&&ps.includes(a),Ze=a=>a==="cliente"||a==="ambos",fs=a=>a==="prospect"||a==="ambos";function Oa(a){const s=new Set(a??[]);return we.filter(t=>s.has(t))}function gs(a){const s=Oa(a);return s.length===0?"â":s.length===we.length?"Toda a base":s.map(t=>Ne[t]).join(", ")}function Ra(a){var r;if(!a.reach)return"â";if(a.reach==="nacional")return"Nacional";const s=(a.states??[]).join(", "),t=(r=a.city)==null?void 0:r.trim();return t&&s?`${t}/${s}`:t||s||"Regional"}const mt="Sem alavanca",ut="Alavanca removida";function vs(a,s,t){const r=new Map(t.map(m=>[m.id,m])),n=a?r.get(a):void 0,o=n?{id:n.id,slug:n.slug,nome:n.name,removida:!1}:{id:null,slug:null,nome:mt,removida:!1},u=new Set(n?[n.id]:[]),c=[];for(const m of s??[]){if(!m||u.has(m))continue;u.add(m);const g=r.get(m);c.push(g?{id:g.id,slug:g.slug,nome:g.name,removida:!1}:{id:m,slug:null,nome:ut,removida:!0})}return{primaria:o,secundarias:c}}function _s(a){return a.secundarias.length===0?a.primaria.nome:`${a.primaria.nome} · também ${a.secundarias.map(s=>s.nome).join(", ")}`}const pt={guests:!1,format:!0,reach:!0,client_visible_allowed:!1};function Pa(a){const s=a&&typeof a=="object"&&!Array.isArray(a)?a:{},t=(r,n)=>typeof r=="boolean"?r:n;return{guests:s.guests===!0,format:t(s.format,!0),reach:t(s.reach,!0),client_visible_allowed:s.client_visible_allowed===!0}}const js=[{token:"--primary",label:"Cobalt"},{token:"--track-blue",label:"Azul"},{token:"--track-indigo",label:"Ãndigo"},{token:"--track-ink",label:"Tinta"},{token:"--vibe-lilac",label:"Lilás"},{token:"--vibe-lilac-light",label:"Lilás claro"},{token:"--chart-green",label:"Verde"},{token:"--vibe-green-light",label:"Verde claro"},{token:"--chart-amber",label:"Ãmbar"},{token:"--vibe-orange",label:"Laranja"},{token:"--track-tan",label:"Areia"},{token:"--track-cloud",label:"Nuvem"},{token:"--track-slate",label:"Cinza"}],xt="--track-slate",Ma="Sem frente",ht=new Set(js.map(a=>a.token));
6function Je(a){return a&&ht.has(a)?a:xt}const ft=/^[A-Z][A-Z0-9]*-\d+$/,bs=/\/?cards\/([a-z0-9-]+)\/c\/([A-Z][A-Z0-9]*-\d+)/;function gt(a){const s=(a??"").trim();if(s==="")return null;const t=s.match(bs);if(t)return`${t[1]}/c/${t[2]}`;const r=s.toUpperCase();return ft.test(r)?r:s}function vt(a){const s=(a??"").trim();if(s==="")return null;const t=s.match(/^([a-z0-9-]+)\/c\/([A-Z][A-Z0-9]*-\d+)$/);if(t)return{chave:t[2],caminho:`/cards/${t[1]}/c/${t[2]}`};const r=s.match(bs);return r?{chave:r[2],caminho:`/cards/${r[1]}/c/${r[2]}`}:{chave:s,caminho:null}}function ca(a){return a.normalize("NFD").replace(/[Ì-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}const z=()=>xa.schema("vibe_apps"),I=a=>`calendario_marketing_${a}`;function F(a,s){throw new Error(`${a}: ${(s==null?void 0:s.message)??"erro desconhecido"}`)}const _t="id, slug, name, description, default_owner_user_id, default_owner_name, color_token, applies, sort_order, is_active, updated_at",jt="id, slug, name, description, sort_order, is_active",Ka="id, title, description, url, front_id, primary_lever_id, secondary_lever_ids, audience, segments, format, reach, states, city, starts_on, ends_on, starts_at, status, owner_user_id, owner_name, client_visible, external_system, external_ref, origin, created_by, created_at, updated_at, deleted_at",bt="id, action_id, name, email, phone, company, company_size, role_title, blindagem_risk, csm, cs_leader, ae, ae_leader, is_client, products, invite_status, risk_checked_by, risk_checked_at, notes, source, import_batch_id, salesforce_account_id, created_at, updated_at";class Ie extends Error{constructor(){super("Esta ação mudou desde que você abriu a tela (ou você não pode mais editá-la). Recarregue para ver a versão atual â nada foi salvo.")}}class ${static async frentes(){const{data:s,error:t}=await z().from(I("fronts")).select(_t).order("sort_order").order("name");return t&&F("Não foi possÃvel carregar as frentes",t),s??[]}static async alavancas(){const{data:s,error:t}=await z().from(I("levers")).select(jt).order("sort_order").order("name");return t&&F("Não foi possÃvel carregar as alavancas",t),s??[]}static async config(){const{data:s,error:t}=await z().from(I("config")).select("*").eq("id",!0).maybeSingle();return t&&F("Não foi possÃvel carregar a configuração",t),s??null}static async nomes(){const{data:s,error:t}=await z().rpc(I("nomes"));return t&&F("Não foi possÃvel carregar os nomes",t),s??[]}static async pessoas(){const{data:s,error:t}=await z().rpc(I("pessoas"));return t&&F("Não foi possÃvel carregar as pessoas",t),s??[]}static async frescor(){const{data:s,error:t}=await z().from("calendario_marketing_frescor").select("*").order("sort_order");return t&&F("Não foi possÃvel carregar o frescor das frentes",t),s??[]}static async acoesDoPeriodo(s,t){const{data:r,error:n}=await z().from(I("actions")).select(Ka).is("deleted_at",null).lte("starts_on",t).or(`ends_on.gte.${s},starts_on.gte.${s}`).order("starts_on").limit(2e3);return n&&F("Não foi possÃvel carregar as ações",n),r??[]}static async acao(s){const{data:t,error:r}=await z().from(I("actions")).select(Ka).eq("id",s).maybeSingle();return r&&F("Não foi possÃvel carregar a ação",r),t??null}static async eventos(s){const{data:t,error:r}=await z().from(I("events")).select("id, entity, entity_id, action_id, kind, from_status, to_status, changes, actor_user_id, actor_kind, created_at").eq("action_id",s).order("created_at",{ascending:!1}).limit(200);return r&&F("Não foi possÃvel carregar o histórico",r),t??[]}static async criarAcao(s,t){const{data:r,error:n}=await z().from(I("actions")).insert({...s,origin:"manual",created_by:t}).select("id").single();return n&&F("Não foi possÃvel criar a ação",n),r.id}static async atualizarAcao(s,t,r){const{data:n,error:o}=await z().from(I("actions")).update(t).eq("id",s).eq("updated_at",r).select("id");if(o&&F("Não foi possÃvel salvar a ação",o),!n||n.length===0)throw new Ie}static async apagarAcao(s){const{data:t,error:r}=await z().from(I("actions")).update({deleted_at:new Date().toISOString()}).eq("id",s).is("deleted_at",null).select("id");if(r&&F("Não foi possÃvel apagar a ação",r),!t||t.length===0)throw new Error("A ação não foi apagada (já estava apagada, ou você não pode editá-la).")}static async restaurarAcao(s){const{data:t,error:r}=await z().from(I("actions")).update({deleted_at:null}).eq("id",s).select("id");if(r&&F("Não foi possÃvel restaurar a ação",r),!t||t.length===0)throw new Error("A ação não foi restaurada (você pode não ter acesso de edição).")}static async criarFrente(s){const{error:t}=await z().from(I("fronts")).insert(s).select("id");t&&F("Não foi possÃvel criar a frente",t)}static async atualizarFrente(s,t){const{data:r,error:n}=await z().from(I("fronts")).update(t).eq("id",s).select("id");if(n&&F("Não foi possÃvel salvar a frente",n),!r||r.length===0)throw new Error("A frente não foi salva (você pode não ter acesso de edição).")}static async apagarFrente(s){const{data:t,error:r}=await z().from(I("fronts")).delete().eq("id",s).select("id");if(r&&F("Não foi possÃvel apagar a frente",r),!t||t.length===0)throw new Error("A frente não foi apagada (você pode não ter acesso de edição).")}static async criarAlavanca(s){const{error:t}=await z().from(I("levers")).insert(s).select("id");t&&F("Não foi possÃvel criar a alavanca",t)}static async atualizarAlavanca(s,t){const{data:r,error:n}=await z().from(I("levers")).update(t).eq("id",s).select("id");if(n&&F("Não foi possÃvel salvar a alavanca",n),!r||r.length===0)throw new Error("A alavanca não foi salva (você pode não ter acesso de edição).")}static async apagarAlavanca(s){const{data:t,error:r}=await z().from(I("levers")).delete().eq("id",s).select("id");if(r&&F("Não foi possÃvel apagar a alavanca",r),!t||t.length===0)throw new Error("A alavanca não foi apagada (você pode não ter acesso de edição).")}static async contarAcoesDaFrente(s){const{count:t,error:r}=await z().from(I("actions")).select("id",{count:"exact",head:!0}).eq("front_id",s).is("deleted_at",null);return r&&F("Não foi possÃvel contar as ações da frente",r),t??0}static async contarAcoesDaAlavanca(s){const{count:t,error:r}=await z().from(I("actions")).select("id",{count:"exact",head:!0}).or(`primary_lever_id.eq.${s},secondary_lever_ids.cs.{${s}}`).is("deleted_at",null);return r&&F("Não foi possÃvel contar as ações da alavanca",r),t??0}static async convidados(s){const{data:t,error:r}=await z().from(I("guests")).select(bt).eq("action_id",s).is("deleted_at",null).order("name").limit(5e3);return r&&F("Não foi possÃvel carregar os convidados",r),t??[]}static async importarConvidados(s,t,r){const n=crypto.randomUUID(),o=t.map(m=>({...m,action_id:s,source:"import",import_batch_id:n,created_by:r})),{data:u,error:c}=await z().from(I("guests")).insert(o).select("id");return c&&F(/uq_cm_guests_email|duplicate/i.test(c.message??"")?"Um dos e-mails já entrou na lista enquanto você conferia â nada foi gravado. Releia a planilha":"O lote não foi gravado (nada entrou)",c),{batchId:n,gravados:(u??[]).length}}static async criarConvidado(s,t,r){const{error:n}=await z().from(I("guests")).insert({...t,action_id:s,source:"manual",created_by:r}).select("id");n&&F(/uq_cm_guests_email|duplicate/i.test(n.message??"")?"Este e-mail já está na lista":"Não foi possÃvel acrescentar o convidado",n)}static async atualizarConvidado(s,t){const{data:r,error:n}=await z().from(I("guests")).update(t).eq("id",s).is("deleted_at",null).select("id");if(n&&F(/uq_cm_guests_email|duplicate/i.test(n.message??"")?"Este e-mail já está na lista":"Não foi possÃvel salvar o convidado",n),!r||r.length===0)throw new Error("O convidado não foi salvo (foi removido, ou você não pode editar).")}static async conferirRisco(s){await $.atualizarConvidado(s,{risk_checked_at:new Date().toISOString()})}static async removerConvidado(s){const{data:t,error:r}=await z().from(I("guests")).update({deleted_at:new Date().toISOString()}).eq("id",s).is("deleted_at",null).select("id");if(r&&F("Não foi possÃvel remover o convidado",r),!t||t.length===0)throw new Error("O convidado não foi removido.")}static async desfazerLote(s){const{data:t,error:r}=await z().from(I("guests")).update({deleted_at:new Date().toISOString()}).eq("import_batch_id",s).is("deleted_at",null).select("id");return r&&F("Não foi possÃvel desfazer o lote",r),(t??[]).length}static async cobertura(s,t){const{data:r,error:n}=await z().rpc(I("cobertura"),{p_mes_ini:s,p_mes_fim:t});return n&&F("Não foi possÃvel carregar a cobertura",n),(r??[]).map(o=>({...o,mes:String(o.mes).slice(0,10)}))}static async salvarConfig(s,t){const{data:r,error:n}=await z().from(I("config")).update({...s,updated_by:t}).eq("id",!0).select("id");if(n&&F("Não foi possÃvel salvar a configuração",n),!r||r.length===0)throw new Error("A configuração não foi salva (você pode não ter acesso de edição).")}static async pipeline(s,t={}){const{data:r,error:n}=await xa.functions.invoke("calendario-marketing-pipeline",{body:{mode:s,...t}});if(n){const u=n.context,c=u!=null&&u.json?await u.json().catch(()=>null):null;throw new Error((c==null?void 0:c.error)??n.message)}const o=r??{};if(typeof o.error=="string")throw new Error(o.error);return o}static async ultimasRodadas(s){const t="id, kind, status, triggered_by, stats, posted_at, error, started_at, finished_at",[r,n]=await Promise.all([z().from(I("pipeline_runs")).select(t).eq("kind",s).order("started_at",{ascending:!1}).limit(1).maybeSingle(),z().from(I("pipeline_runs")).select(t).eq("kind",s).eq("triggered_by","cron").order("started_at",{ascending:!1}).limit(1).maybeSingle()]);return r.error&&F("Não foi possÃvel ler as rodadas",r.error),n.error&&F("Não foi possÃvel ler as rodadas",n.error),{ultima:r.data??null,doCron:n.data??null}}}const Ns=b.createContext(null);function Y(){const a=b.useContext(Ns);if(!a)throw new Error("useCatalogoCm precisa do CatalogoCmProvider");return a}function Nt({canEdit:a,children:s,carregando:t,erro:r}){const[n,o]=b.useState(null),[u,c]=b.useState(null),m=b.useCallback(async()=>{var l;c(null);try{const[{data:h},i,d,v,N]=await Promise.all([xa.auth.getUser(),$.frentes(),$.alavancas(),$.config(),$.nomes()]);o({uid:((l=h.user)==null?void 0:l.id)??null,frentes:i,alavancas:d,config:v,nomes:N})}catch(h){c(h instanceof Error?h.message:String(h))}},[]);b.useEffect(()=>{m()},[m]);const g=b.useMemo(()=>
6{if(!n)return null;const l=new Map(n.frentes.map(d=>[d.id,d])),h=new Map(n.alavancas.map(d=>[d.id,d])),i=new Map(n.nomes.map(d=>[d.id,d.nome]));return{uid:n.uid,canEdit:a,frentes:n.frentes,alavancas:n.alavancas,config:n.config,nomes:i,frente:d=>d?l.get(d):void 0,frentePorSlug:d=>n.frentes.find(v=>v.slug===d),alavanca:d=>d?h.get(d):void 0,alavancaPorSlug:d=>n.alavancas.find(v=>v.slug===d),aplica:d=>{const v=d?l.get(d):void 0;return v?Pa(v.applies):pt},nome:d=>d?i.get(d)??null:null,catDoFiltro:{frenteSlugPorId:new Map(n.frentes.map(d=>[d.id,d.slug])),alavancaSlugPorId:new Map(n.alavancas.map(d=>[d.id,d.slug]))},recarregar:m}},[n,a,m]);return u?e.jsx(e.Fragment,{children:r(u,()=>void m())}):g?e.jsx(Ns.Provider,{value:g,children:s}):e.jsx(e.Fragment,{children:t})}const wt=/^\d{4}-\d{2}-\d{2}$/;function de(a){const[s,t,r]=a.split("-").map(Number);return new Date(Date.UTC(s,t-1,r))}function ye(a){const s=a.getUTCFullYear(),t=String(a.getUTCMonth()+1).padStart(2,"0"),r=String(a.getUTCDate()).padStart(2,"0");return`${s}-${t}-${r}`}function Ee(a){return typeof a!="string"||!wt.test(a)?!1:ye(de(a))===a}function Ce(a,s){return ye(new Date(de(a).getTime()+s*864e5))}function yt(a,s){return Math.round((de(s).getTime()-de(a).getTime())/864e5)}function te(a){return`${a.slice(0,7)}-01`}function Ke(a){const[s,t]=a.slice(0,7).split("-").map(Number);return ye(new Date(Date.UTC(s,t,0)))}function ge(a,s){const t=de(te(a));return ye(new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+s,1)))}const ws=["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"],Ct=["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"];function ys(a){const[s,t]=a.split("-").map(Number);return`${ws[t-1]} de ${s}`}function _e(a){return ws[Number(a.slice(5,7))-1]}function St(a){return`${Number(a.slice(8,10))} ${Ct[Number(a.slice(5,7))-1]}`}function ie(a){return`${a.slice(8,10)}/${a.slice(5,7)}`}function Se(a){return a.ends_on&&a.ends_on>=a.starts_on?a.ends_on:a.starts_on}function Ta(a){return Se(a)>a.starts_on}function La(a,s,t){return a.starts_on<=t&&Se(a)>=s}function Re(a){return Ta(a)?`${ie(a.starts_on)} a ${ie(Se(a))}`:ie(a.starts_on)}function At(a){return Ta(a)?`até ${ie(Se(a))}`:null}function kt(a,s){const t=te(s),r=Ke(s);return a.filter(n=>La(n,t,r))}function Et(a,s){const t=te(s);return a.starts_on<t?{dia:t,desde:a.starts_on}:{dia:a.starts_on,desde:null}}const $t=["Seg","Ter","Qua","Qui","Sex","Sáb","Dom"];function Dt(a){const s=de(te(a)),t=de(Ke(a)),r=s.getUTCDay();let n=new Date(s.getTime()-(r===0?6:r-1)*864e5);const o=[];for(;n.getTime()<=t.getTime();){const u=[];for(let c=0;c<7;c++){const m=new Date(n.getTime()+c*864e5);u.push({data:ye(m),diaDaSemana:c+1,noMes:m.getUTCMonth()===s.getUTCMonth(),fimDeSemana:c>=5})}o.push(u),n=new Date(n.getTime()+7*864e5)}return o}function Ot(a,s){const t=new Map;for(const r of kt(a,s)){const{dia:n,desde:o}=Et(r,s),u=t.get(n);u?u.push({acao:r,desde:o}):t.set(n,[{acao:r,desde:o}])}for(const r of t.values())r.sort((n,o)=>(n.acao.starts_at??"99").localeCompare(o.acao.starts_at??"99")||n.acao.title.localeCompare(o.acao.title,"pt-BR")||n.acao.id.localeCompare(o.acao.id));return t}function Wa(a,s,t=15){const r=Ce(s,t-1);return a.filter(n=>n.status!=="cancelada"&&La(n,s,r)).map(n=>({acao:n,emCurso:n.starts_on<s})).sort((n,o)=>n.acao.starts_on.localeCompare(o.acao.starts_on)||n.acao.title.localeCompare(o.acao.title,"pt-BR")||n.acao.id.localeCompare(o.acao.id))}function Cs(a){const[s,t]=a.split("-").map(Number),r=Math.floor((t-1)/3)*3+1,n=`${s}
6-${String(r).padStart(2,"0")}-01`,o=[0,1,2].map(u=>ge(n,u));return{ini:n,fim:Ke(o[2]),meses:o,rotulo:`${_e(o[0])} a ${_e(o[2])} de ${s}`}}function Rt(a){const s=de(a.ini),t=s.getUTCDay();let r=ye(new Date(s.getTime()-(t===0?6:t-1)*864e5));const n=[];for(;r<=a.fim;)n.push(r),r=Ce(r,7);return n}function Pt(a,s){if(s.length===0)return null;const t=s[0],r=Ce(s[s.length-1],6);if(!La(a,t,r))return null;const n=u=>{let c=0;for(let m=0;m<s.length;m++)s[m]<=u&&(c=m);return c},o=Se(a);return{de:a.starts_on<t?0:n(a.starts_on),ate:o>r?s.length-1:n(o),cortadaAntes:a.starts_on<t,cortadaDepois:o>r,marco:!Ta(a)}}function Mt(a,s){if(s.length===0||a<s[0]||a>Ce(s[s.length-1],6))return null;let t=0;for(let r=0;r<s.length;r++)s[r]<=a&&(t=r);return t}function za(a=new Date){return new Intl.DateTimeFormat("en-CA",{timeZone:"America/Sao_Paulo",year:"numeric",month:"2-digit",day:"2-digit"}).format(a)}function Ya(a,s){if(!a)return null;const t=new Date(a);return Number.isNaN(t.getTime())?null:Math.max(0,yt(za(t),s))}const Fa=["cliente","prospect","todos"],da={cliente:"Toca clientes",prospect:"Toca prospects",todos:"Todos os públicos"},Xa="cliente",se="sem",ae={mes:"mes",publico:"publico",frente:"frente",alavanca:"alavanca",formato:"formato",praca:"praca",segmento:"segmento",status:"status",responsavel:"resp"},Ss="cm-ultimo-filtro",Tt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ia(a){if(typeof a!="string")return null;const s=a.trim();return s===""?null:s}function ea(a){return Ee(a)?te(a):null}function es(a){return typeof a=="string"&&Fa.includes(a)?a:null}function as(a,s){const t=Ia(a);return t===null?null:t===se?se:s===null||s.includes(t)?t:null}function Lt(a){const s=Ia(a);return s==="nacional"||s==="regional"||s&&s.startsWith("uf:")&&Da(s.slice(3))?s:null}function zt(a){const s=Ia(a);return s===null?null:s===se?se:Tt.test(s)?s.toLowerCase():null}function pe(a,s,t){var n;const r=a.url(ae[s]);return t(r!==null?r:(n=a.lembrado)==null?void 0:n[s])}function Ft(a){var o,u;const s=a.url(ae.mes),t=ea(s)??ea((o=a.lembrado)==null?void 0:o.mes)??te(ea(a.hoje)??"2026-01-01"),r=a.url(ae.publico),n=r!==null?es(r)??Xa:es((u=a.lembrado)==null?void 0:u.publico)??Xa;return{mes:t,publico:n,frente:pe(a,"frente",c=>as(c,a.frentesValidas)),alavanca:pe(a,"alavanca",c=>as(c,a.alavancasValidas)),formato:pe(a,"formato",c=>Oe(c)?c:null),praca:pe(a,"praca",Lt),segmento:pe(a,"segmento",c=>$a(c)?c:null),status:pe(a,"status",c=>Ea(c)?c:null),responsavel:pe(a,"responsavel",zt)}}function ma(a){const s=new URLSearchParams;return s.set(ae.mes,a.mes),s.set(ae.publico,a.publico),s.set(ae.frente,a.frente??""),s.set(ae.alavanca,a.alavanca??""),s.set(ae.formato,a.formato??""),s.set(ae.praca,a.praca??""),s.set(ae.segmento,a.segmento??""),s.set(ae.status,a.status??""),s.set(ae.responsavel,a.responsavel??""),s.toString()}function It(a){return{mes:a.mes,publico:"todos",frente:null,alavanca:null,formato:null,praca:null,segmento:null,status:null,responsavel:null}}function qt(a,s,t){if(s.publico==="cliente"&&!Ze(a.audience)||s.publico==="prospect"&&!fs(a.audience))return!1;if(s.frente!==null){const r=a.front_id?t.frenteSlugPorId.get(a.front_id)??null:null;if(s.frente===se?r!==null:r!==s.frente)return!1}if(s.alavanca!==null){const r=a.primary_lever_id?t.alavancaSlugPorId.get(a.primary_lever_id)??null:null;if(s.alavanca===se){if(r!==null)return!1}else{const n=(a.secondary_lever_ids??[]).map(o=>t.alavancaSlugPorId.get(o));if(r!==s.alavanca&&!n.includes(s.alavanca))return!1}}if(s.formato!==null&&a.format!==s.formato)return!1;if(s.praca!==null){if(s.praca==="nacional"&&a.reach!=="nacional"||s.praca==="regional"&&a.reach!=="regional")return!1;if(s.praca.startsWith("uf:")){const r=s.praca.slice(3);if(a.reach!=="regional"||!(a.states??[]).includes(r))return!1}}return!(s.segmento!==null&&!(a.segments??[]).includes(s.segmento)||s.status!==null&&a.status!==s.status||s.responsavel!==null&&(s.responsavel===se?a.owner_user_id!==null:a.owner_user_id!==s.responsavel))}function Ut(a,s,t){const r=[],n=[];for(const o of a)(qt(o,s,t)?r:n).push(o);return{visiveis:r,escondidas:n}}function Vt(a,s){const t=[];return t.push(a.publico==="cliente"?"o que toca clientes":a.publico==="prospect"?"o que toca prospects":"todos os públicos"),a.frente&&t.push(a.frente===se?"sem frente":s.frente(a.frente)),a.alavanca&&t.push(a.alavanca===se?"sem alavanca":s.alavanca(a.alavanca)),a.formato&&t.push(Qe(a.formato).toLowerCase()),a.praca&&t.push(a.praca==="nacional"?"nacional":a.praca==="regional"?"regional":a.praca.slice(3)),a.segmento&&t.push(xs(a.segmento)),a.status&&t.push(fe(a.status).toLowerCase()),a.responsavel&&t.push(a.responsavel===se?"sem responsável":s.responsavel(a.responsavel)),t.join(", ")}function Bt(a){if(!a)return null;try{const s=a.getItem(Ss);if(!s)return null;const t=JSON.parse(s);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Gt(a,s){if(a)try{a.setItem(Ss,JSON.stringify(s))}catch{}}const As="calendario-marketing",W=`/apps/${As}`;function ua(a,s){return`${W}${a?`/${a}
6`:""}?${ma(s)}`}function Ht(a){const s=Je(a);return{backgroundColor:`hsl(var(${s}) / 0.14)`,borderLeftColor:`hsl(var(${s}))`}}function Te(a){return{backgroundColor:`hsl(var(${Je(a)}))`}}function Qt(a){const s=Je(a);return{backgroundColor:`hsl(var(${s}) / 0.30)`,borderColor:`hsl(var(${s}))`}}const Zt={ideia:"border border-dashed border-border bg-background text-muted-foreground",planejada:"bg-muted text-foreground",confirmada:"bg-primary/10 text-primary",realizada:"bg-[hsl(var(--chart-green)/0.18)] text-foreground",cancelada:"bg-muted text-muted-foreground line-through"};function ss(a){return a===null?"nunca":a===0?"hoje":a===1?"há 1 dia":`há ${a} dias`}const aa=30;function ks(a,s){var t;return s(a.owner_user_id)??(((t=a.owner_name)==null?void 0:t.trim())||"sem responsável")}function le({rotulo:a="Carregandoâ¦"}){return e.jsxs("div",{className:"flex items-center justify-center gap-2 py-16 text-sm text-muted-foreground",children:[e.jsx(Ls,{className:"h-4 w-4 animate-spin"}),a]})}function ve({titulo:a,children:s,acao:t}){return e.jsxs("div",{className:"mx-auto max-w-xl px-4 py-16 text-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:a}),s&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground",children:s}),t&&e.jsx("div",{className:"mt-5 flex justify-center",children:t})]})}function ue({mensagem:a,onTentar:s}){return e.jsx(ve,{titulo:"Não deu para carregar",acao:s&&e.jsx(E,{variant:"outline",onClick:s,children:"Tentar de novo"}),children:a})}function Es({status:a,className:s}){return e.jsx("span",{className:V("inline-flex items-center whitespace-nowrap rounded-full px-2 py-0.5 text-[11px] font-medium",Zt[a]??"bg-muted text-muted-foreground",s),children:fe(a)})}function We({frente:a,className:s}){return e.jsxs("span",{className:V("inline-flex min-w-0 items-center gap-1.5",s),children:[e.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:Te(a==null?void 0:a.color_token)}),e.jsx("span",{className:"truncate",children:(a==null?void 0:a.name)??Ma})]})}function Le({children:a,tom:s="neutro",dica:t}){const r={neutro:"bg-muted text-muted-foreground",alerta:"bg-[hsl(var(--tier-warn-bg))] text-[hsl(var(--tier-warn-text))]",info:"bg-primary/10 text-primary"}[s],n=e.jsx("span",{tabIndex:t?0:void 0,className:V("inline-flex items-center gap-1 whitespace-nowrap rounded-md px-1.5 py-0.5 text-[11px] font-medium",r),children:a});return t?e.jsxs(qe,{children:[e.jsx(Ue,{asChild:!0,children:n}),e.jsx(Ve,{className:"max-w-xs",children:t})]}):n}function R({rotulo:a,children:s,dica:t,erro:r,obrigatorio:n,htmlFor:o}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{htmlFor:o,className:"block text-sm font-medium",children:[a,n&&e.jsx("span",{className:"ml-0.5 text-destructive",children:"*"})]}),s,t&&!r&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t}),r&&e.jsx("div",{className:"text-xs font-medium text-destructive",children:r})]})}function ce({opcoes:a,valor:s,onChange:t,multipla:r=!1,rotuloDoGrupo:n}){return e.jsx("div",{className:"flex flex-wrap gap-1.5",role:"group","aria-label":n,children:a.map(o=>{const u=s.includes(o.id);return e.jsx("button",{type:"button","aria-pressed":u,onClick:()=>{t(r?u?s.filter(c=>c!==o.id):[...s,o.id]:[o.id])},className:V("rounded-full border px-3 py-1 text-xs transition-colors",u?"border-primary bg-primary text-primary-foreground":"border-border bg-background hover:bg-muted"),children:o.nome},o.id)})})}const ts=()=>{try{return typeof window>"u"?null:window.localStorage}catch{return null}};function Ae(){const[a,s]=ha(),{frentes:t,alavancas:r}=Y(),n=za(),o=b.useMemo(()=>t.map(l=>l.slug),[t]),u=b.useMemo(()=>r.map(l=>l.slug),[r]),c=Ft({url:l=>a.get(l),lembrado:Bt(ts()),hoje:n,frentesValidas:o,alavancasValidas:u}),m=ma(c);b.useEffect(()=>{Gt(ts(),c)},[m]);const g=l=>{const h=new URLSearchParams(a),i=new URLSearchParams(ma(l));for(const d of Object.values(ae))h.set(d,i.get(d)??"");s(h,{replace:!0})};return{filtro:c,hoje:n,mudar:l=>g({...c,...l}),limpar:()=>g(It(c))}}const Jt=/^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;function Kt(a){try{const s=new URL(a);return s.protocol==="https:"||s.protocol==="http:"}catch{return!1}}function Wt(a,s){const t={};return a.title.trim()||(t.title="Dê um tÃtulo à ação."),a.front_id||(t.front_id="Escolha a frente da ação."),!a.owner_user_id&&!a.owner_name.trim()&&(t.owner="Escolha quem responde pela ação."),hs(a.audience)||(t.audie
6nce="Escolha o público."),Ze(a.audience)&&Oa(a.segments).length===0&&(t.segments="Se toca clientes, marque ao menos um segmento."),s.format&&!Oe(a.format)&&(t.format="Escolha o formato."),s.reach&&(Fe(a.reach)?a.reach==="regional"&&a.states.filter(Da).length===0&&(t.states="Praça regional pede ao menos um estado."):t.reach="Escolha a praça."),a.starts_on?Ee(a.starts_on)||(t.starts_on="Data inválida."):t.starts_on="Informe quando começa.",a.ends_on&&(Ee(a.ends_on)?Ee(a.starts_on)&&a.ends_on<a.starts_on&&(t.ends_on="O fim não pode ser antes do começo."):t.ends_on="Data inválida."),a.starts_at&&!Jt.test(a.starts_at)&&(t.starts_at="Hora inválida (use HH:MM)."),a.url.trim()&&!Kt(a.url.trim())&&(t.url="O link precisa começar com https://"),Ea(a.status)||(t.status="Escolha o estado."),t}function Yt(a,s,t,r=null){const n=l=>l.trim()===""?null:l.trim(),o=r!==null&&r.front_id===a.front_id,u=o&&Fe(r.reach)?r.reach:null,c=s.reach?Fe(a.reach)?a.reach:null:u,m=s.reach?c==="regional"?Array.from(new Set(a.states.filter(Da))):[]:c==="regional"?[...(r==null?void 0:r.states)??[]]:[],g=n(a.ends_on);return{title:a.title.trim(),description:n(a.description),url:n(a.url),front_id:a.front_id,primary_lever_id:a.primary_lever_id,secondary_lever_ids:Array.from(new Set(a.secondary_lever_ids)).filter(l=>l!==a.primary_lever_id),audience:a.audience,segments:a.audience==="prospect"?[]:Oa(a.segments.filter($a)),format:s.format?Oe(a.format)?a.format:null:o&&Oe(r.format)?r.format:null,reach:c,states:m,city:c!=="regional"?null:s.reach?n(a.city):(r==null?void 0:r.city)??null,starts_on:a.starts_on,ends_on:g&&g!==a.starts_on?g:null,starts_at:n(a.starts_at),status:a.status,owner_user_id:a.owner_user_id,owner_name:n(a.owner_name),external_system:t?"cards":null,external_ref:t}}function Xt(a){return{title:"",description:"",url:"",front_id:a.front_id??null,primary_lever_id:null,secondary_lever_ids:[],audience:"cliente",segments:["G","E","M","P"],format:a.aplica.format?"online":null,reach:a.aplica.reach?"nacional":null,states:[],city:"",starts_on:a.hoje,ends_on:"",starts_at:"",status:"planejada",owner_user_id:a.default_owner_user_id??null,owner_name:a.default_owner_user_id?"":a.default_owner_name??"",card_ref:""}}function er(a,s,t,r){const n=!a.owner_user_id&&!a.owner_name.trim()||s!==null&&a.owner_user_id===s.default_owner_user_id&&(a.owner_user_id!==null||a.owner_name.trim()===(s.default_owner_name??"").trim());return{...a,front_id:t.id,owner_user_id:n?t.default_owner_user_id:a.owner_user_id,owner_name:n?t.default_owner_user_id?"":t.default_owner_name??"":a.owner_name,format:r.format?a.format??"online":a.format,reach:r.reach?a.reach??"nacional":a.reach}}function ar(a){return{title:a.title,description:a.description??"",url:a.url??"",front_id:a.front_id,primary_lever_id:a.primary_lever_id,secondary_lever_ids:a.secondary_lever_ids??[],audience:hs(a.audience)?a.audience:"cliente",segments:a.segments??[],format:Oe(a.format)?a.format:null,reach:Fe(a.reach)?a.reach:null,states:a.states??[],city:a.city??"",starts_on:a.starts_on,ends_on:a.ends_on??"",starts_at:a.starts_at?a.starts_at.slice(0,5):"",status:Ea(a.status)?a.status:"ideia",owner_user_id:a.owner_user_id,owner_name:a.owner_name??"",card_ref:a.external_system==="cards"?a.external_ref??"":""}}function qa(a){return/\b(A CONFIRMAR|A DEFINIR)\b/.test(a.description??"")}function sr(a,s){return a&&a.external_system&&a.external_system!=="cards"?{external_system:a.external_system,external_ref:a.external_ref}:s?{external_system:"cards",external_ref:s}:{external_system:null,external_ref:null}}const sa="__todos__";function xe({valor:a,onChange:s,rotulo:t,todos:r,itens:n,largura:o="w-[160px]"}){return e.jsxs(Q,{value:a??sa,onValueChange:u=>s(u===sa?null:u),children:[e.jsx(Z,{className:`h-8 ${o} text-xs`,"aria-label":t,children:e.jsx(J,{placeholder:t})}),e.jsxs(K,{children:[e.jsx(L,{value:sa,children:r}),n.map(u=>e.jsx(L,{value:u.id,children:u.nome},u.id))]})]})}function Ua({f:a,ufsEmUso:s,responsaveisEmUso:t}){const{frentes:r,alavancas:n}=Y(),{filtro:o,mudar:u}=a,[c,m]=b.useState(!1),g=[o.alavanca,o.formato,o.praca,o.segmento,o.status,o.responsavel].filter(l=>l!==null).length;return e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Q,{value:o.publico,onValueChange:l=>u({publico:l}),children:[e.jsx(Z,{className:"h-8 w-[150px] text-xs","aria-label":"Público",children:e.jsx(J,{})}),e.jsx(K,{children:Fa.map(l=>e.jsx(L,{value:l,children:da[l]},l))})]}),e.jsx(xe,{rotulo:"Frente",todos:"Todas as frentes",valor:o.frente,onChange:l=>u({frente:l}),itens:[...r.filter(l=>l.is_active).map(l=>({id:l.slug,nome:l.name})),{id:se,nome:"Sem frente"}],largura:"w-[190px]"}),e.jsx(E,{variant:"outline",size:"sm",className:"h-8 text-xs md:hidden","aria-expanded":c,onClick:()=>m(l=>!l),children:c?"Menos filtros":`Mais filtros${g?` (${g})`:""}`}),e.jsxs("div",{className:V(c?"flex":"hidden","w-full flex-wrap items-center gap-2 md:contents"),children:[e.jsx(xe,{rotulo:"Alavanca",todos:"Todas as alavancas",valor:o.alavanca,onChange:l=>u({alavanca:l}),itens:[...n.filter(l=>l.is_active).map(l=>({id:l.slug,nome:l.name})),{id:se,nome:"Sem alavanca"}],largura:"w-[190px]"}),e.jsx(xe,{rotulo:"Formato",todos:"Todos os formatos",valor:o.formato,onChange:l=>u({formato:l}
6),itens:Sa.map(l=>({id:l,nome:Aa[l]})),largura:"w-[150px]"}),e.jsx(xe,{rotulo:"Praça",todos:"Todas as praças",valor:o.praca,onChange:l=>u({praca:l}),itens:[{id:"nacional",nome:"Nacional"},{id:"regional",nome:"Regional (todas)"},...s.map(l=>({id:`uf:${l}`,nome:`Regional · ${l}`}))],largura:"w-[150px]"}),e.jsx(xe,{rotulo:"Segmento",todos:"Todos os segmentos",valor:o.segmento,onChange:l=>u({segmento:l}),itens:we.map(l=>({id:l,nome:Ne[l]})),largura:"w-[160px]"}),e.jsx(xe,{rotulo:"Estado",todos:"Todos os estados",valor:o.status,onChange:l=>u({status:l}),itens:He.map(l=>({id:l,nome:De[l]})),largura:"w-[160px]"}),e.jsx(xe,{rotulo:"Responsável",todos:"Todos os responsáveis",valor:o.responsavel,onChange:l=>u({responsavel:l}),itens:[...t,{id:se,nome:"Sem responsável com conta"}],largura:"w-[180px]"})]}),e.jsx($s,{})]})}function $s(){const{toast:a}=me(),[s,t]=b.useState(!1);return e.jsxs(E,{variant:"outline",size:"sm",className:"h-8 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(window.location.href),t(!0),setTimeout(()=>t(!1),2e3),a({title:"Link copiado",description:"Quem abrir verá exatamente esta vista, com este filtro."})}catch{a({title:"Não deu para copiar",description:"Copie o endereço da barra do navegador.",variant:"destructive"})}},children:[s?e.jsx(zs,{className:"mr-1 h-3.5 w-3.5"}):e.jsx(at,{className:"mr-1 h-3.5 w-3.5"}),"Copiar link desta vista"]})}function Va({n:a,filtro:s,onLimpar:t}){const{frentePorSlug:r,alavancaPorSlug:n,nome:o}=Y();if(a===0)return null;const u=Vt(s,{frente:c=>{var m;return((m=r(c))==null?void 0:m.name)??c},alavanca:c=>{var m;return((m=n(c))==null?void 0:m.name)??c},responsavel:c=>o(c)??"responsável"});return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-lg border border-dashed border-border bg-muted/40 px-3 py-2 text-sm",children:[e.jsxs("span",{children:[e.jsx("b",{children:a})," ",a===1?"ação escondida":"ações escondidas"," pelo filtro (",u,")."]}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:t,children:"Mostrar todas"})]})}function tr({hoje:a}){const{frente:s,nome:t}=Y(),[r,n]=b.useState(null),[o,u]=b.useState(null),[c,m]=b.useState(!1);if(b.useEffect(()=>{$.frescor().then(n).catch(i=>u(i instanceof Error?i.message:String(i)))},[]),o)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Frescor indisponÃvel: ",o]});if(!r)return null;const g=r.filter(i=>i.is_active),l=g.filter(i=>{const d=Ya(i.last_update_at,a);return d!==null&&d>aa}).length,h=g.filter(i=>i.last_update_at===null).length;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("button",{type:"button",className:"text-left text-xs text-muted-foreground underline-offset-2 hover:underline md:hidden","aria-expanded":c,onClick:()=>m(i=>!i),children:["Frescor das frentes: ",g.length-l-h," em dia",l?` · ${l} há mais de ${aa} dias`:"",h?` · ${h} sem ação`:""," ",c?"â´":"â¾"]}),e.jsxs("div",{className:V(c?"flex":"hidden","flex-wrap items-center gap-1.5 text-xs md:flex"),"aria-label":"Quando cada frente foi atualizada",children:[e.jsx("span",{className:"mr-1 hidden text-muted-foreground md:inline",children:"Atualizada:"}),g.map(i=>{var C;const d=Ya(i.last_update_at,a),v=d===null,N=d!==null&&d>aa,j=i.last_actor_user_id?t(i.last_actor_user_id)??"alguém":"a carga inicial",w=d===null?`${i.name}: nenhuma ação registrada ainda.`:`${i.name}: última mudança ${ss(d)}, por ${j}. ${i.acoes_mes_seguinte} ${i.acoes_mes_seguinte===1?"ação":"ações"} no mês seguinte.`;return e.jsxs(qe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs("span",{tabIndex:0,className:V("inline-flex items-center gap-1 rounded-full border px-2 py-0.5",N?"border-[hsl(var(--tier-warn-text)/0.4)] bg-[hsl(var(--tier-warn-bg))] text-[hsl(var(--tier-warn-text))]":v?"border-dashed border-border bg-background text-muted-foreground":"border-border bg-background"),children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:Te((C=s(i.front_id))==null?void 0:C.color_token)}),i.name," · ",ss(d)]})}),e.jsx(Ve,{className:"max-w-xs",children:w})]},i.front_id)})]})]})}function Ba(a,s){const[t,r]=b.useState(null),[n,o]=b.useState(null),u=b.useRef(""),c=b.useCallback(async()=>{const m=`${a}|${s}`;u.current=m,o(null);try{const g=await $.acoesDoPeriodo(a,s);u.current===m&&r(g)}catch(g){u.current===m&&o(g instanceof Error?g.message:String(g))}},[a,s]);return b.useEffect(()=>{r(null),c()},[c]),{acoes:t,erro:n,recarregar:c}}function Ga(a,s){const{catDoFiltro:t,nome:r}=Y();return b.useMemo(()=>{var h;const n=a??[],{visiveis:o,escondidas:u}=Ut(n,s,t),c=new Set(n.flatMap(i=>i.reach==="regional"?i.states:[]));(h=s.praca)!=null&&h.startsWith("uf:")&&c.add(s.praca.slice(3));const m=Array.from(c).sort(),g=new Map;for(const i of n)i.owner_user_id&&g.set(i.owner_user_id,r(i.owner_user_id
6)??i.owner_name??"sem nome");s.responsavel&&s.responsavel!=="sem"&&!g.has(s.responsavel)&&g.set(s.responsavel,r(s.responsavel)??"responsável");const l=Array.from(g,([i,d])=>({id:i,nome:d})).sort((i,d)=>i.nome.localeCompare(d.nome,"pt-BR"));return{visiveis:o,escondidas:u,ufs:m,responsaveis:l}},[a,s,t,r])}function rr({mes:a,onChange:s,hoje:t}){const r=ys(a);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center rounded-lg border border-border",children:[e.jsx(E,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Mês anterior",onClick:()=>s(ge(a,-1)),children:e.jsx(fa,{className:"h-4 w-4"})}),e.jsx("span",{className:"min-w-[10rem] px-1 text-center text-sm font-medium",children:r.charAt(0).toUpperCase()+r.slice(1)}),e.jsx(E,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Próximo mês",onClick:()=>s(ge(a,1)),children:e.jsx(ga,{className:"h-4 w-4"})})]}),te(t)!==a&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>s(te(t)),children:"Hoje"})]})}function nr({acao:a,desde:s}){const{frente:t}=Y(),r=t(a.front_id),n=At(a),o=qa(a),u=[a.title,(r==null?void 0:r.name)??Ma,fe(a.status),o?"data a confirmar":null].filter(Boolean).join(" · ");return e.jsxs(qe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs(oe,{to:`${W}/acoes/${a.id}`,"aria-label":u,className:V("block rounded-md border-l-[3px] px-1.5 py-1 text-[11px] leading-tight text-foreground transition-opacity hover:opacity-80",a.status==="ideia"&&"border border-dashed border-l-[3px]",a.status==="cancelada"&&"line-through opacity-60"),style:Ht(r==null?void 0:r.color_token),children:[e.jsxs("span",{className:"line-clamp-2 font-medium",children:[o&&e.jsx("span",{className:"mr-0.5 text-[hsl(var(--tier-warn-text))]",children:"?"}),a.title]}),(s||n)&&e.jsxs("span",{className:"mt-0.5 block text-[10px] text-muted-foreground",children:[s?`desde ${ie(s)}`:null,s&&n?" · ":null,n]})]})}),e.jsx(Ve,{className:"max-w-xs",children:u})]})}function or(){const a=Ae(),{filtro:s,hoje:t,mudar:r,limpar:n}=a,{canEdit:o,frentes:u}=Y(),c=s.mes,{acoes:m,erro:g,recarregar:l}=Ba(te(c),Ke(c)),{visiveis:h,escondidas:i,ufs:d,responsaveis:v}=Ga(m,s),N=Ot(h,c),j=Dt(c);return e.jsxs("div",{className:"mx-auto max-w-7xl space-y-4 px-4 py-5 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Calendário de Marketing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Os touches de Marketing com a base, por mês."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(rr,{mes:c,onChange:w=>r({mes:w}),hoje:t}),o&&e.jsx(E,{asChild:!0,size:"sm",className:"h-8",children:e.jsxs(oe,{to:`${W}/acoes/nova?inicio=${c===te(t)?t:c}`,children:[e.jsx(ze,{className:"mr-1 h-4 w-4"})," Nova ação"]})})]})]}),e.jsx(tr,{hoje:t}
6),e.jsx(Ua,{f:a,ufsEmUso:d,responsaveisEmUso:v}),g?e.jsx(ue,{mensagem:g,onTentar:()=>void l()}):m?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:e.jsxs("div",{className:"grid min-w-[760px] grid-cols-7",children:[$t.map((w,C)=>e.jsx("div",{className:V("border-b border-border bg-muted/40 px-2 py-1.5 text-xs font-medium text-muted-foreground",C>=5&&"bg-muted/70"),children:w},w)),j.flat().map(w=>{const C=w.noMes?N.get(w.data)??[]:[],P=w.data===t;return e.jsxs("div",{className:V("min-h-[6.5rem] space-y-1 border-b border-r border-border p-1.5 [&:nth-child(7n)]:border-r-0",!w.noMes&&"bg-muted/30",w.noMes&&w.fimDeSemana&&"bg-muted/20"),children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px]",children:[e.jsx("span",{className:V("font-semibold",!w.noMes&&"text-muted-foreground/50",P&&"rounded bg-primary px-1 text-primary-foreground"),children:Number(w.data.slice(8,10))}),P&&e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"hoje"})]}),C.map(({acao:_,desde:A})=>e.jsx(nr,{acao:_,desde:A},_.id))]},w.data)})]})}),h.length===0&&i.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Nenhuma ação em ",ys(c),"."]}),e.jsx(Va,{n:i.length,filtro:s,onLimpar:n}),e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground","aria-label":"Legenda das frentes",children:[u.filter(w=>w.is_active).map(w=>e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:Te(w.color_token)}),w.name]},w.id)),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"inline-block h-2.5 w-4 rounded-sm border border-dashed border-muted-foreground"})," ideia"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"font-semibold text-[hsl(var(--tier-warn-text))]",children:"?"})," data a confirmar"]})]})]}):e.jsx(le,{})]})}const ta=15;function ir(){const a=Ae(),{filtro:s,hoje:t,limpar:r}=a,{frentes:n,frente:o,alavancas:u,nome:c}=Y(),m=Ce(t,ta-1),{acoes:g,erro:l,recarregar:h}=Ba(t,m),{visiveis:i,escondidas:d,ufs:v,responsaveis:N}=Ga(g,s),j=Wa(i,t,ta),w=Wa(d,t,ta).length,C=[];for(const _ of[...n,void 0]){const A=j.filter(S=>_?S.acao.front_id===_.id:!o(S.acao.front_id));A.length&&C.push({frente:_,itens:A})}const P=_=>[ka(_.audience),_.format?Qe(_.format):null,_.reach?Ra(_):null,_s(vs(_.primary_lever_id,_.secondary_lever_ids,u)),ks(_,c)].filter(Boolean).join(" · ");return e.jsxs("div",{className:"mx-auto max-w-5xl space-y-4 px-4 py-5 sm:px-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Próximos 15 dias"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ie(t)," a ",ie(m)," · a lista do cascateamento do CS"]})]}
6),e.jsx(Ua,{f:a,ufsEmUso:v,responsaveisEmUso:N}),l?e.jsx(ue,{mensagem:l,onTentar:()=>void h()}):g?e.jsxs(e.Fragment,{children:[C.length===0&&e.jsx("p",{className:"rounded-lg border border-dashed border-border px-3 py-6 text-center text-sm text-muted-foreground",children:"Nada nos próximos 15 dias com este filtro."}),e.jsx("div",{className:"space-y-4",children:C.map(_=>{var A;return e.jsxs("section",{className:"rounded-lg border border-border",children:[e.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border bg-muted/40 px-3 py-2",children:[e.jsx(We,{frente:_.frente,className:"text-sm font-medium"}),_.frente&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Dono: ",c(_.frente.default_owner_user_id)??_.frente.default_owner_name??"definido em cada ação"]})]}),e.jsx("ul",{className:"divide-y divide-border",children:_.itens.map(({acao:S,emCurso:O})=>e.jsx("li",{children:e.jsxs(oe,{to:`${W}/acoes/${S.id}`,className:"flex items-start gap-3 px-3 py-2.5 transition-colors hover:bg-muted/40",children:[e.jsx("span",{className:"w-24 flex-shrink-0 text-xs font-medium text-muted-foreground",children:O?e.jsxs(e.Fragment,{children:["em curso",e.jsx("br",{}),"até ",ie(Se(S))]}):Re(S)}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium",children:S.title}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:P(S)})]}),e.jsxs("span",{className:"flex flex-shrink-0 flex-col items-end gap-1",children:[e.jsx(Es,{status:S.status}),qa(S)&&e.jsx(Le,{tom:"alerta",dica:"A descrição diz que a data ainda não está fechada.",children:"data a confirmar"})]})]})},S.id))})]},((A=_.frente)==null?void 0:A.id)??"sem")})}),e.jsx(Va,{n:w,filtro:s,onLimpar:r})]}):e.jsx(le,{})]})}const lr="min(14rem, 38vw)",cr="4.25rem";function dr(){const a=Ae(),{filtro:s,hoje:t,mudar:r,limpar:n}=a,{frentes:o,frente:u}=Y(),c=Cs(s.mes),m=Rt(c),g=m[0],l=Ce(m[m.length-1],6),{acoes:h,erro:i,recarregar:d}=Ba(g,l),{visiveis:v,escondidas:N,ufs:j,responsaveis:w}=Ga(h,s),C=Mt(t,m),P=[];for(const S of[...o,void 0]){const O=v.filter(D=>S?D.front_id===S.id:!u(D.front_id)).sort((D,M)=>D.starts_on.localeCompare(M.starts_on)||D.title.localeCompare(M.title,"pt-BR"));O.length&&P.push({frente:S,acoes:O})}const _=`${lr} repeat(${m.length}, ${cr})`,A=c.rotulo.charAt(0).toUpperCase()+c.rotulo.slice(1);return e.jsxs("div",{className:"mx-auto max-w-7xl space-y-4 px-4 py-5 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Trimestre"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Linha do tempo por frente, semana a semana"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center rounded-lg border border-border",children:[e.jsx(E,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Trimestre anterior",onClick:()=>r({mes:ge(c.ini,-3)}),children:e.jsx(fa,{className:"h-4 w-4"})}),e.jsx("span",{className:"min-w-[13rem] px-1 text-center text-sm font-medium",children:A}),e.jsx(E,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Próximo trimestre",onClick:()=>r({mes:ge(c.ini,3)}),children:e.jsx(ga,{className:"h-4 w-4"})})]}),C===null&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>r({mes:te(t)}),children:"Hoje"})]})]}
6),e.jsx(Ua,{f:a,ufsEmUso:j,responsaveisEmUso:w}),i?e.jsx(ue,{mensagem:i,onTentar:()=>void d()}):h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:e.jsxs("div",{className:"min-w-max",children:[e.jsxs("div",{className:"grid border-b border-border bg-muted/40 text-[11px] text-muted-foreground",style:{gridTemplateColumns:_},children:[e.jsx("div",{className:"sticky left-0 z-10 bg-muted px-2 py-1.5 font-medium",children:"Semana de"}),m.map((S,O)=>e.jsx("div",{className:V("px-1 py-1.5 text-center",O===C&&"font-semibold text-primary"),children:St(S)},S))]}),P.length===0&&e.jsx("p",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:"Nada neste trimestre com este filtro."}),P.map(S=>{var O;return e.jsxs("div",{children:[e.jsxs("div",{className:"grid border-b border-border bg-muted/20",style:{gridTemplateColumns:_},children:[e.jsx("div",{className:"sticky left-0 z-10 bg-muted/90 px-2 py-1.5 text-xs font-semibold",children:e.jsx(We,{frente:S.frente})}),e.jsx("div",{style:{gridColumn:`2 / span ${m.length}`}})]}),S.acoes.map(D=>{var B;const M=Pt(D,m);if(!M)return null;const f=`${D.title} · ${Re(D)} · ${fe(D.status)}`,U=Qt((B=S.frente)==null?void 0:B.color_token);return e.jsxs("div",{className:"relative grid items-center border-b border-border/60",style:{gridTemplateColumns:_},children:[e.jsx("div",{className:"sticky left-0 z-10 truncate bg-background px-2 py-1.5 text-xs",title:D.title,children:D.title}),C!==null&&e.jsx("div",{className:"h-full w-px justify-self-center bg-primary/40",style:{gridColumn:C+2,gridRow:1},"aria-hidden":"true"}),e.jsxs(qe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(oe,{to:`${W}/acoes/${D.id}`,"aria-label":f,style:{gridColumn:`${M.de+2} / ${M.ate+3}`,gridRow:1,...U},className:V("mx-0.5 my-1 flex h-5 items-center overflow-hidden border text-[10px] text-foreground",M.marco?"mx-auto w-3 rounded-full":"rounded-md px-1.5",M.cortadaAntes&&"rounded-l-none border-l-0",M.cortadaDepois&&"rounded-r-none border-r-0",D.status==="ideia"&&"border-dashed",D.status==="cancelada"&&"line-through opacity-50"),children:!M.marco&&e.jsx("span",{className:"truncate",children:Re(D)})})}),e.jsx(Ve,{className:"max-w-xs",children:f})]})]},D.id)})]},((O=S.frente)==null?void 0:O.id)??"sem")})]})}),e.jsx(Va,{n:N.length,filtro:s,onLimpar:n}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Barra = ação com começo e fim; ponto = ação de um dia; tracejado = ideia; linha azul = hoje. ",Ma," fica por último."]})]}):e.jsx(le,{})]})}const mr=new Set(["id","created_by","created_at","updated_at","origin","external_system"]),ur={title:"TÃtulo",description:"Descrição",url:"Link",front_id:"Frente",primary_lever_id:"Alavanca principal",secondary_lever_ids:"Também serve a",audience:"Público",segments:"Segmentos",format:"Formato",reach:"Praça",states:"Estados",city:"Cidade",starts_on:"InÃcio",ends_on:"Fim",starts_at:"Hora",status:"Estado",owner_user_id:"Responsável",owner_name:"Responsável (nome)",client_visible:"VisÃvel para clientes",public_title:"TÃtulo público",public_description:"Descrição pública",public_url:"Link público",external_ref:"Card no Cards",deleted_at:"Apagada"},pr=new Set(["description","public_description"]);function rs(a,s,t){if(s==null||s===""||Array.isArray(s)&&s.length===0)return"â";switch(a){case"starts_on":case"ends_on":return typeof s=="string"?ie(s):String(s);case"starts_at":return typeof s=="string"?s.slice(0,5):String(s);case"status":return fe(String(s));case"audience":return ka(String(s));case"format":return Qe(String(s));case"reach":return dt(String(s));case"segments":return Array.isArray(s)?gs(s):String(s);case"states":return Array.isArray(s)?s.join(", "):String(s);case"front_id":return t.frente(String(s))??"frente removida";case"primary_lever_id":return t.alavanca(String(s))??"alavanca removida";case"secondary_lever_ids":return Array.isArray(s)?s.map(r=>t.alavanca(r)??"alavanca removida").join(", "):String(s);case"owner_user_id":return t.pessoa(String(s))??"alguém sem acesso ao app";case"client_visible":return s===!0?"sim":"não";default:return typeof s=="object"?JSON.stringify(s):String(s)}}function xr(a,s){const t=a.changes??{};if(a.kind==="criado")return{titulo:a.actor_kind==="sistema"?"Criada pela carga inicial (reunião de 02/09)":"Criada",detalhes:[]};if(a.kind==="apagado")return{titulo:"Apagada",detalhes:[]};if(a.kind==="restaurado")return{titulo:"Restaurada",detalhes:[]};const r=[];for(const[o,u]of Object.entries(t)){if(mr.has(o)||o==="deleted_at")continue;const c=ur[o]??o;if(pr.has(o)){r.push(`${c}: alterada`);continue}const m=u&&typeof u=="object"?u:{};r.push(`${c}: ${rs(o,m.de,s)} â ${rs(o,m.para,s)}`)}return{titulo:a.kind==="status"?`Estado: ${fe(a.from_status)} â ${fe(a.to_status)}`:a.kind==="remarcado"?"Remarcada":"Editada",detalhes:a.kind==="status"?r.filter(o=>!o.startsWith("Estado:")):r}}const Pe=["saudavel","medio","alto","altissimo"],Ha={saudavel:"Saudável",medio:"Médio",alto:"Alto",altissimo:"AltÃssimo"},Qa=["alto","altissimo"],he=["sugerido","convidado","confirmado","participou","recusou","vetado"],je={sugerido:"Sugerido",convidado:"Convidado",confirmado:"Confirmado",participou:"Participou",recusou:"Recusou",vetado:"Vetado"},pa=["rs","admissao","treinamento","clima_engajamento","performance"],Ye={rs:"R&S",admissao:"Admissão",treinamento:"Treinamento",clima_engajamento:"Clima e Engajamento",performance:"Performance"};function ke(a){return a.normalize("NFD").replace(/[Ì-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9&]+/g," ").trim()}function Ds(a){return a?Ha[a]??a:"Não informado"}function hr(a){return a?je[a]??a:"â"}const fr=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function Os(a){const s=(a??"").trim().toLowerCase();return s===""?{valor:null}:fr.test(s)?{valor:s}:{valor:null,erro:`e-mail inválido ("${a==null?void 0:a.trim()}")`}}function Rs(a){const s=(a??"").trim();if(s==="")return{valor:null};const t=s.replace(/\D/g,"");return t.length<10?{valor:null,erro:`telefone curto demais ("${s}")`}:t.length===10||t.length===11?{valor:`+55${t}`}:{valor:`+${t}`}}const gr={saudavel:"saudavel",baixo:"saudavel",ok:"saudavel",medio:"medio",moderado:"medio",alto:"alto",altissimo:"altissimo","muito alto":"altissimo",critico:"altissimo"};function vr(a){const s=(a??"").trim();if(s==="")return{valor:null};const t=gr[ke(s)];return t?{valor:t}:{valor:s,aviso:`risco "${s}" fora da escala conhecida (saudável, médio, alto, altÃssimo) â gravado como veio`}}
6const _r={rs:"rs","r&s":"rs","r s":"rs",ats:"rs",recrutamento:"rs","recrutamento e selecao":"rs","recrutamento & selecao":"rs",admissao:"admissao",treinamento:"treinamento",edc:"treinamento","educacao corporativa":"treinamento",lms:"treinamento",clima:"clima_engajamento",engajamento:"clima_engajamento","clima e engajamento":"clima_engajamento","clima & engajamento":"clima_engajamento","c&e":"clima_engajamento",performance:"performance",desempenho:"performance","p&d":"performance"};function jr(a){const s=(a??"").split(/[,;/|+]/).map(o=>o.trim()).filter(Boolean),t=[],r=[];for(const o of s){const u=_r[ke(o)];u?t.includes(u)||t.push(u):r.push(o)}const n=pa.filter(o=>t.includes(o));return r.length?{valor:n,erro:`produto desconhecido: ${r.map(o=>`"${o}"`).join(", ")} (os produtos são ${pa.map(o=>Ye[o]).join(", ")})`}:{valor:n}}const br={sugerido:"sugerido",sugestao:"sugerido",wishlist:"sugerido",convidado:"convidado","convite enviado":"convidado",enviado:"convidado",confirmado:"confirmado",confirmou:"confirmado",participou:"participou",presente:"participou",compareceu:"participou",recusou:"recusou",recusado:"recusou",vetado:"vetado",veto:"vetado"};function Nr(a){const s=(a??"").trim();if(s==="")return{valor:"sugerido"};const t=br[ke(s)];return t?{valor:t}:{valor:"sugerido",erro:`status do convite desconhecido ("${s}"; use ${he.map(r=>je[r]).join(", ")})`}}
6function wr(a){const s=ke(a??"");return s===""?null:["sim","s","yes","y","x","1","true","cliente","verdadeiro"].includes(s)?!0:["nao","n","no","0","false","falso","prospect","nao cliente"].includes(s)?!1:null}const yr={g:"G","grandes contas":"G","grande conta":"G",gc:"G",e:"E",enterprise:"E",m:"M","middle market":"M",mid:"M","mid market":"M",p:"P",reativo:"P",reativos:"P"};function Cr(a){const s=(a??"").trim();return s===""?null:yr[ke(s)]??s}const Sr={nome:"name",name:"name","nome completo":"name",convidado:"name",email:"email","e mail":"email","endereco de email":"email",telefone:"phone",celular:"phone",whatsapp:"phone",phone:"phone",fone:"phone",empresa:"company",company:"company",conta:"company",cliente:"company",porte:"company_size",carteira:"company_size",segmento:"company_size",cargo:"role_title",funcao:"role_title",role:"role_title",risco:"blindagem_risk","risco de blindagem":"blindagem_risk","risco da blindagem":"blindagem_risk",blindagem:"blindagem_risk",csm:"csm","lider de cs":"cs_leader","lider cs":"cs_leader","lider do cs":"cs_leader",ae:"ae","executivo de contas":"ae","account executive":"ae","lider de ae":"ae_leader","lider ae":"ae_leader","lider do ae":"ae_leader","e cliente":"is_client","eh cliente":"is_client","cliente sim nao":"is_client",produtos:"products",produto:"products","cliente de":"products","de qual produto":"products","cliente de qual produto":"products",status:"invite_status",convite:"invite_status","status do convite":"invite_status",observacoes:"notes",observacao:"notes",obs:"notes",notas:"notes","id da conta":"salesforce_account_id","salesforce id":"salesforce_account_id","id salesforce":"salesforce_account_id","account id":"salesforce_account_id"};function Ar(a){return Sr[ke(a)]??null}function kr(a){const s=a.split(/\r?\n/,1)[0]??"",t=u=>s.split(u).length-1,r=t(" "),n=t(";"),o=t(",");return r>0&&r>=n&&r>=o?" ":n>0&&n>=o?";":","}function Er(a,s=kr(a)){const t=[];let r=[],n="",o=!1;const u=a.replace(/^\uFEFF/,"");for(let c=0;c<u.length;c++){const m=u[c];if(o){m==='"'?u[c+1]==='"'?(n+='"',c++):o=!1:n+=m;continue}m==='"'&&n===""?o=!0:m===s?(r.push(n),n=""):m===` 7`||m==="\r"?(m==="\r"&&u[c+1]===` 8`&&c++,r.push(n),t.push(r),r=[],n=""):n+=m}return(n!==""||r.length>0)&&(r.push(n),t.push(r)),t.filter(c=>c.some(m=>m.trim()!==""))}function $r(a,s){const t={convidados:[],erros:[],avisos:[],colunas:[],repetidosNaPlanilha:0,jaNaLista:0},r=Er(a);if(r.length===0)return{...t,erros:[{linha:1,mensagem:"A planilha está vazia."}]};const o=r[0].map(d=>({cabecalho:d.trim(),campo:Ar(d)}));if(!o.some(d=>d.campo==="name"))return{...t,colunas:o,erros:[{linha:1,mensagem:'O cabeçalho precisa ter uma coluna "Nome" (a primeira linha da planilha é o cabeçalho).'}]};const c=o.filter((d,v)=>d.campo&&o.findIndex(N=>N.campo===d.campo)!==v).map(d=>({linha:1,mensagem:`A coluna "${d.cabecalho}" repete um campo que outra coluna já preenche.`})),m=[],g=[],l=new Map;let h=0,i=0;for(let d=1;d<r.length;d++){const v=d+1,N=D=>{const M=o.findIndex(f=>f.campo===D);return M>=0?(r[d][M]??"").trim():""},j=N("name");if(!j){c.push({linha:v,mensagem:"sem nome"});continue}const w=[],C=Os(N("email"));C.erro&&w.push(C.erro);const P=Rs(N("phone"));P.erro&&w.push(P.erro);const _=jr(N("products"));_.erro&&w.push(_.erro);const A=Nr(N("invite_status"));A.erro&&w.push(A.erro);const S=vr(N("blindagem_risk"));if(S.aviso&&m.push({linha:v,mensagem:S.aviso}),w.length){c.push({linha:v,mensagem:`${j}: ${w.join("; ")}`});continue}if(C.valor){const D=l.get(C.valor);if(D!==void 0){h++,m.push({linha:v,mensagem:`${C.valor} repete a linha ${D} â fica a primeira`});continue}if(l.set(C.valor,v),s.has(C.valor)){i++,m.push({linha:v,mensagem:`${C.valor} já está na lista â não foi reimportado`});continue}}const O=wr(N("is_client"));g.push({name:j,email:C.valor,phone:P.valor,company:N("company")||null,company_size:Cr(N("company_size")),role_title:N("role_title")||null,blindagem_risk:S.valor,csm:N("csm")||null,cs_leader:N("cs_leader")||null,ae:N("ae")||null,ae_leader:N("ae_leader")||null,is_client:O??(_.valor.length>0?!0:null),products:_.valor,invite_status:A.valor,notes:N("notes")||null,salesforce_account_id:N("salesforce_account_id")||null})}return{convidados:g,erros:c,avisos:m,colunas:o,repetidosNaPlanilha:h,jaNaLista:i}}const Za=a=>{var s;return a.is_client===!0||(((s=a.products)==null?void 0:s.length)??0)>0};function Ps(a){const s={saudavel:0,medio:0,alto:0,altissimo:0,outro:0,sem:0},t=Object.fromEntries(he.map(u=>[u,0]));let r=0,n=0,o=0;for(const u of a){if(he.includes(u.invite_status)&&t[u.invite_status]++,Za(u)&&o++,u.invite_status==="vetado")continue;const c=u.blindagem_risk;c?Pe.includes(c)?s[c]++:s.outro++:s.sem++,c&&Qa.includes(c)&&r++,u.risk_checked_at||n++}return{total:a.length,porRisco:s,porStatus:t,emRisco:r,naoConferidos:n,clientes:o}}function Dr(a,s){return a.filter(t=>!(s.soClientes&&!Za(t)||s.soRiscoAlto&&!(t.blindagem_risk&&Qa.includes(t.blindagem_risk))||s.soNaoConferidos&&t.risk_checked_at||s.status&&t.invite_status!==s.status))}function Or(a){const t=/^[=+\-@]/.test(a)&&!/^[+-]?\d[\d\s().-]*$/.test(a)?`'${a}`:a;return/[;"\n\r]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Rr(a,s){const t=["Nome","E-mail","Telefone","Empresa","Porte","Cargo","Risco de blindagem","Conferido por","CSM","LÃder de CS","AE","LÃder de AE","à cliente","Produtos","Status do convite","Observações"],r=a.map(n=>
8[n.name,n.email??"",n.phone??"",n.company??"",n.company_size??"",n.role_title??"",n.blindagem_risk?Ds(n.blindagem_risk):"",n.risk_checked_at?s(n):"",n.csm??"",n.cs_leader??"",n.ae??"",n.ae_leader??"",n.is_client===null?"":n.is_client?"Sim":"Não",n.products.map(o=>Ye[o]??o).join(", "),hr(n.invite_status),n.notes??""]);return[t,...r].map(n=>n.map(Or).join(";")).join(`\r 9`)}const Pr=["name","email","phone","company","company_size","role_title","blindagem_risk","csm","cs_leader","ae","ae_leader","is_client","products","invite_status","notes","salesforce_account_id"];function Mr(a,s){const t={};for(const r of Pr){const n=a[r]??null,o=s[r]??null;JSON.stringify(n)!==JSON.stringify(o)&&(t[r]=s[r])}return t}function Tr({acaoId:a}){const[s,t]=b.useState(null),[r,n]=b.useState(null);return b.useEffect(()=>{$.convidados(a).then(o=>t(Ps(o))).catch(o=>n(o instanceof Error?o.message:String(o)))},[a]),r?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Lista indisponÃvel: ",r]}):s?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-sm",children:[e.jsxs("span",{children:[s.total===0?"Nenhum convidado ainda.":e.jsxs(e.Fragment,{children:[s.total," na lista",s.emRisco>0&&e.jsxs("span",{className:"text-[hsl(var(--tier-risk-text))]",children:[" · ",s.emRisco," com risco alto ou altÃssimo"]}),s.naoConferidos>0&&` · ${s.naoConferidos} sem conferência`]})," ",e.jsx("span",{className:"text-xs text-muted-foreground",children:"Só quem edita vê."})]}),e.jsx(E,{size:"sm",variant:"outline",asChild:!0,children:e.jsx(oe,{to:`${W}/acoes/${a}/convidados`,children:"Abrir a lista"})})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Carregandoâ¦"})}function Lr(a){return new Intl.DateTimeFormat("pt-BR",{timeZone:"America/Sao_Paulo",day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(a))}function zr(){const{id:a}=va(),s=ls(),{toast:t}=me(),{filtro:r}=Ae(),n=Y(),{canEdit:o,frente:u,alavancas:c,aplica:m}=n,[g,l]=b.useState(new Map),h=p=>p?g.get(p)??n.nome(p):null,[i,d]=b.useState(void 0),[v,N]=b.useState([]),[j,w]=b.useState(null),[C,P]=b.useState(!1),[_,A]=b.useState(!1),S=b.useCallback(async()=>{if(a){w(null);try{const[p,y,k]=await Promise.all([$.acao(a),$.eventos(a),$.nomes().catch(()=>[])]);d(p),N(y),l(new Map(k.map(x=>[x.id,x.nome])))}catch(p){w(p instanceof Error?p.message:String(p))}}},[a]);if(b.useEffect(()=>{S()},[S]),j)return e.jsx(ue,{mensagem:j,onTentar:()=>void S()});if(i===void 0)return e.jsx(le,{});if(i===null||i.deleted_at!==null&&!o)return e.jsx(ve,{titulo:"Ação não encontrada",acao:e.jsx(E,{variant:"outline",onClick:()=>s(ua("",r)),children:"Voltar ao calendário"}),children:"O link pode estar errado, ou a ação foi apagada."});const O=u(i.front_id),D=m(i.front_id),M=i.external_system==="cards"?vt(i.external_ref):null,f=i.deleted_at!==null,U=async p=>{if(p!==i.status){P(!0);try{await $.atualizarAcao(i.id,{status:p},i.updated_at),t({title:`Estado: ${De[p]}`}),await S()}catch(y){t({title:y instanceof Ie?"Outra pessoa mexeu nesta ação":"Não deu para mudar o estado",description:y instanceof Error?y.message:String(y),variant:"destructive"}),y instanceof Ie&&await S()}finally{P(!1)}}},B=async()=>{P(!0);try{await $.apagarAcao(i.id),t({title:"Ação apagada",description:"Fica no histórico; dá para restaurar por esta página."}),await S()}catch(p){t({title:"Não deu para apagar",description:p instanceof Error?p.message:String(p),variant:"destructive"})}finally{P(!1),A(!1)}},q=async()=>{P(!0);try{await $.restaurarAcao(i.id),t({title:"Ação restaurada"}),await S()}catch(p){t({title:"Não deu para restaurar",description:p instanceof Error?p.message:String(p),variant:"destructive"})}finally{P(!1)}},X=[["Quando",`${Re(i)}${i.starts_at?` · ${i.starts_at.slice(0,5)}`:""}`],["Público",ka(i.audience)]];return i.segments.length&&X.push(["Segmentos",gs(i.segments)]),X.push(["Alavancas",_s(vs(i.primary_lever_id,i.secondary_lever_ids,c))]),(D.format||i.format)&&X.push(["Formato",Qe(i.format)]),(D.reach||i.reach)&&X.push(["Praça",Ra(i)]),X.push(["Responsável",ks(i,h)]),i.url&&/^https?:\/\//i.test(i.url)&&X.push(["Link",e.jsxs("a",{href:i.url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-primary underline-offset-2 hover:underline",children:[i.url," ",e.jsx(st,{className:"h-3 w-3"})]},"u")]),M&&X.push(["Execução (Cards)",M.caminho?e.jsx(oe,{to:M.caminho,className:"text-primary underline-offset-2 hover:underline",children:M.chave},"c"):e.jsxs("span",{children:[M.chave," ",e.jsx("span",{className:"text-xs text-muted-foreground",children:"(cole o link do card na edição para virar link)"})]},"c")]),e.jsxs("div",{className:"mx-auto max-w-3xl space-y-5 px-4 py-5 sm:px-6",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"-ml-2 h-8 text-xs",asChild:!0,children:e.jsxs(oe,{to:ua("",{...r,mes:`${i.starts_on.slice(0,7)}-01`}),children:[e.jsx(_a,{className:"mr-1 h-3.5 w-3.5"})," Calendário"]})}),e.jsxs("header",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsx(We,{frente:O,className:"text-sm"}),e.jsx(Es,{status:i.status}
9),i.origin==="carga_inicial"&&e.jsx(Le,{tom:"info",dica:"Veio da reunião de lideranças MKT/CS de 02/09 como rascunho, para o dono da frente validar.",children:"Rascunho da reunião"}),qa(i)&&e.jsx(Le,{tom:"alerta",dica:"A descrição diz que a data ainda não está fechada â não trate como compromisso.",children:"data a confirmar"}),f&&e.jsx(Le,{tom:"alerta",children:"Apagada"})]}),e.jsx("h1",{className:"text-xl font-semibold",children:i.title}),i.description&&e.jsx("p",{className:"whitespace-pre-line text-sm text-muted-foreground",children:i.description})]}),e.jsx("dl",{className:"grid grid-cols-[8.5rem_1fr] gap-x-3 gap-y-2 rounded-lg border border-border p-4 text-sm",children:X.map(([p,y])=>e.jsxs("div",{className:"contents",children:[e.jsx("dt",{className:"text-muted-foreground",children:p}),e.jsx("dd",{className:"min-w-0 break-words",children:y})]},p))}),o&&!f&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Q,{value:i.status,onValueChange:p=>void U(p),disabled:C,children:[e.jsx(Z,{className:"h-8 w-[170px] text-xs","aria-label":"Estado da ação",children:e.jsx(J,{})}),e.jsx(K,{children:He.map(p=>e.jsx(L,{value:p,children:De[p]},p))})]}),e.jsx(E,{variant:"outline",size:"sm",className:"h-8",asChild:!0,children:e.jsxs(oe,{to:`${W}/acoes/${i.id}/editar`,children:[e.jsx(ja,{className:"mr-1 h-3.5 w-3.5"})," Editar"]})}),e.jsxs(E,{variant:"ghost",size:"sm",className:"h-8 text-destructive",onClick:()=>A(!0),disabled:C,children:[e.jsx(Be,{className:"mr-1 h-3.5 w-3.5"})," Apagar"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Mudar o estado é decisão de gente â o app não muda sozinho quando a data passa."})]}),o&&f&&e.jsx(E,{variant:"outline",size:"sm",onClick:()=>void q(),disabled:C,children:"Restaurar ação"}),D.guests&&o&&e.jsxs("section",{className:"space-y-2 rounded-lg border border-border p-4",children:[e.jsxs("h2",{className:"flex items-center gap-1.5 text-sm font-semibold",children:[e.jsx(Fs,{className:"h-4 w-4"})," Convidados"]}),e.jsx(Tr,{acaoId:i.id})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Histórico"}),v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sem registro."}):e.jsx("ol",{className:"space-y-2 border-l border-border pl-4",children:v.map(p=>{const y=xr(p,{frente:x=>{var T;return((T=u(x))==null?void 0:T.name)??null},alavanca:x=>{var T;return((T=c.find(ee=>ee.id===x))==null?void 0:T.name)??null},pessoa:x=>h(x)}),k=p.actor_kind==="sistema"?"sistema":h(p.actor_user_id)??"alguém";return e.jsxs("li",{className:"text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2",children:[e.jsx("span",{className:"font-medium",children:y.titulo}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Lr(p.created_at)," · ",k]})]}),y.detalhes.length>0&&e.jsx("ul",{className:"mt-0.5 text-xs text-muted-foreground",children:y.detalhes.map(x=>e.jsx("li",{children:x},x))})]},p.id)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Quando o cliente cobra um compromisso, aqui está a versão que valia naquele dia."})]}),e.jsx(Is,{open:_,onOpenChange:A,children:e.jsxs(qs,{children:[e.jsxs(Us,{children:[e.jsx(Vs,{children:"Apagar esta ação?"}),e.jsxs(Bs,{children:["Ela sai do calendário, mas fica no histórico â e dá para restaurar por esta mesma página. Se ela só não vai mais acontecer, prefira mudar o estado para ",e.jsx("b",{children:"Cancelada"}),": assim o CS vê que foi cancelada."]})]}),e.jsxs(Gs,{children:[e.jsx(Hs,{children:"Voltar"}),e.jsx(Qs,{onClick:()=>void B(),children:"Apagar"})]})]})})]})}const ra="__sem__",na="__sem_conta__";function ns(){const{id:a}=va(),s=!!a,[t]=ha(),r=ls(),{toast:n}=me(),{canEdit:o,uid:u,frentes:c,alavancas:m,frente:g,aplica:l}=Y(),[h,i]=b.useState(null),[d,v]=b.useState(null),[N,j]=b.useState({}),[w,C]=b.useState(null),[P,_]=b.useState(!1),[A,S]=b.useState(null),[O,D]=b.useState(!1);b.useEffect(()=>{let x=!0;return(async()=>{try{if(a){const T=await $.acao(a);if(!x)return;if(!T){C("Ação não encontrada.");return}i(T),v(ar(T)),D(!T.owner_user_id&&!!T.owner_name)}else{const T=za(),ee=t.get("inicio"),H=c.find(Ja=>Ja.slug===t.get("frente")&&Ja.is_active)??null,re=Xt({hoje:Ee(ee)?ee:T,front_id:(H==null?void 0:H.id)??null,default_owner_user_id:(H==null?void 0:H.default_owner_user_id
9)??null,default_owner_name:(H==null?void 0:H.default_owner_name)??null,aplica:l((H==null?void 0:H.id)??null)});v(re),D(!re.owner_user_id&&!!re.owner_name)}}catch(T){x&&C(T instanceof Error?T.message:String(T))}})(),()=>{x=!1}},[a]),b.useEffect(()=>{o&&$.pessoas().then(S).catch(()=>S([]))},[o]);const M=b.useMemo(()=>l((d==null?void 0:d.front_id)??null),[l,d==null?void 0:d.front_id]);if(!o)return e.jsx(ve,{titulo:"Só quem edita o calendário cria e muda ações",children:"Peça acesso de edição a um administrador."});if(w)return e.jsx(ue,{mensagem:w});if(!d)return e.jsx(le,{});const f=x=>v(T=>T&&{...T,...x}),U=!!(h&&h.external_system&&h.external_system!=="cards"),B=c.filter(x=>x.is_active||x.id===d.front_id),q=g(d.front_id),X=x=>{const T=c.find(re=>re.id===x);if(!T)return;const ee=g(d.front_id),H=er(d,ee?{default_owner_user_id:ee.default_owner_user_id,default_owner_name:ee.default_owner_name}:null,{id:T.id,default_owner_user_id:T.default_owner_user_id,default_owner_name:T.default_owner_name},l(T.id));v(H),D(!H.owner_user_id&&!!H.owner_name)},p=async()=>{const x=Wt(d,M);if(j(x),Object.keys(x).length>0){n({title:"Faltam alguns campos",description:"Veja os avisos em vermelho.",variant:"destructive"});return}const T=U?null:gt(d.card_ref),ee=Yt(d,M,T,h),H=sr(h,T);_(!0);try{if(h)await $.atualizarAcao(h.id,{...ee,...H},h.updated_at),n({title:"Ação salva"}),r(`${W}/acoes/${h.id}`);else{const re=await $.criarAcao({...ee,...H},u);n({title:"Ação criada",description:"Ela já aparece para toda a Gupy."}),r(`${W}/acoes/${re}`)}}catch(re){n({title:re instanceof Ie?"Outra pessoa salvou esta ação antes":"Não deu para salvar",description:re instanceof Error?re.message:String(re),variant:"destructive"})}finally{_(!1)}},y=A??[],k=O?na:d.owner_user_id??"";return e.jsxs("div",{className:"mx-auto max-w-6xl space-y-4 px-4 py-5 sm:px-6",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"-ml-2 h-8 text-xs",asChild:!0,children:e.jsxs(oe,{to:h?`${W}/acoes/${h.id}`:W,children:[e.jsx(_a,{className:"mr-1 h-3.5 w-3.5"})," ",h?"Voltar para a ação":"Calendário"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold",children:s?"Editar ação":"Nova ação"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Um touch com a base: evento, Open Call, comunicado, campanha, piloto, matéria."})]}),e.jsxs("form",{className:"grid gap-6 lg:grid-cols-[1fr_18rem]",noValidate:!0,onSubmit:x=>{x.preventDefault(),p()},children:[e.jsxs("div",{className:"space-y-5",children:[e.jsx(R,{rotulo:"TÃtulo",obrigatorio:!0,erro:N.title,htmlFor:"cm-titulo",children:e.jsx(G,{id:"cm-titulo",value:d.title,onChange:x=>f({title:x.target.value}),placeholder:"Ex.: Open Call de novembro â Admissão"})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx(R,{rotulo:"Frente",obrigatorio:!0,erro:N.front_id,children:e.jsxs(Q,{value:d.front_id??"",onValueChange:X,children:[e.jsx(Z,{"aria-label":"Frente",children:e.jsx(J,{placeholder:"Escolha a frente"})}),e.jsx(K,{children:B.map(x=>e.jsxs(L,{value:x.id,children:[x.name,x.is_active?"":" (inativa)"]},x.id))})]})}),e.jsxs(R,{rotulo:"Responsável",obrigatorio:!0,erro:N.owner,dica:q!=null&&q.default_owner_user_id||q!=null&&q.default_owner_name?"Sugerido pela frente.":"Esta frente define o dono em cada ação.",children:[e.jsxs(Q,{value:k,onValueChange:x=>{x===na?(D(!0),f({owner_user_id:null})):(D(!1),f({owner_user_id:x,owner_name:""}))},children:[e.jsx(Z,{"aria-label":"Responsável",children:e.jsx(J,{placeholder:A===null?"Carregando pessoasâ¦":"Escolhaâ¦"})}),e.jsxs(K,{children:[y.map(x=>e.jsx(L,{value:x.id,children:x.nome},x.id)),d.owner_user_id&&!y.some(x=>x.id===d.owner_user_id)&&e.jsx(L,{value:d.owner_user_id,children:"Responsável atual"}),e.jsx(L,{value:na,children:"Outra pessoa (sem conta no VMOS)â¦"})]})]}),O&&e.jsx(G,{className:"mt-2",value:d.owner_name,onChange:x=>f({owner_name:x.target.value}),placeholder:"Nome de quem responde (ex.: Bruna Castilhos, CS)","aria-label":"Nome do responsável sem conta"})]})]}),e.jsx(R,{rotulo:"Público",obrigatorio:!0,erro:N.audience,children:e.jsx(ce,{rotuloDoGrupo:"Público",opcoes:ms.map(x=>({id:x,nome:us[x]})),valor:[d.audience],onChange:([x])=>
9f({audience:x})})}),Ze(d.audience)&&e.jsx(R,{rotulo:"Segmentos da base que a ação alcança",obrigatorio:!0,erro:N.segments,children:e.jsx(ce,{multipla:!0,rotuloDoGrupo:"Segmentos",opcoes:we.map(x=>({id:x,nome:Ne[x]})),valor:d.segments,onChange:x=>f({segments:x})})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx(R,{rotulo:"Alavanca principal",dica:"à ela que a Cobertura conta por padrão.",children:e.jsxs(Q,{value:d.primary_lever_id??ra,onValueChange:x=>{const T=x===ra?null:x;f({primary_lever_id:T,secondary_lever_ids:d.secondary_lever_ids.filter(ee=>ee!==T)})},children:[e.jsx(Z,{"aria-label":"Alavanca principal",children:e.jsx(J,{})}),e.jsxs(K,{children:[e.jsx(L,{value:ra,children:"Sem alavanca"}),m.filter(x=>x.is_active||x.id===d.primary_lever_id).map(x=>e.jsx(L,{value:x.id,children:x.name},x.id))]})]})}),e.jsx(R,{rotulo:"Também serve a",children:e.jsx(ce,{multipla:!0,rotuloDoGrupo:"Alavancas secundárias",opcoes:m.filter(x=>(x.is_active||d.secondary_lever_ids.includes(x.id))&&x.id!==d.primary_lever_id).map(x=>({id:x.id,nome:x.name})),valor:d.secondary_lever_ids,onChange:x=>f({secondary_lever_ids:x})})})]}),M.format&&e.jsx(R,{rotulo:"Formato",obrigatorio:!0,erro:N.format,children:e.jsx(ce,{rotuloDoGrupo:"Formato",opcoes:Sa.map(x=>({id:x,nome:Aa[x]})),valor:d.format?[d.format]:[],onChange:([x])=>f({format:x})})}),M.reach&&e.jsxs(R,{rotulo:"Praça",obrigatorio:!0,erro:N.reach??N.states,children:[e.jsx(ce,{rotuloDoGrupo:"Praça",opcoes:[{id:"nacional",nome:"Nacional"},{id:"regional",nome:"Regional"}],valor:d.reach?[d.reach]:[],onChange:([x])=>f({reach:x})}),d.reach==="regional"&&e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx(ce,{multipla:!0,rotuloDoGrupo:"Estados",opcoes:ps.map(x=>({id:x,nome:x})),valor:d.states,onChange:x=>f({states:x})}),e.jsx(G,{value:d.city,onChange:x=>f({city:x.target.value}),placeholder:"Cidade (opcional)","aria-label":"Cidade"})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(R,{rotulo:"Começa em",obrigatorio:!0,erro:N.starts_on,htmlFor:"cm-ini",children:e.jsx(G,{id:"cm-ini",type:"date",value:d.starts_on,onChange:x=>f({starts_on:x.target.value})})}),e.jsx(R,{rotulo:"Termina em",erro:N.ends_on,dica:"Se durar mais de um dia.",htmlFor:"cm-fim",children:e.jsx(G,{id:"cm-fim",type:"date",value:d.ends_on,onChange:x=>f({ends_on:x.target.value})})}),e.jsx(R,{rotulo:"Hora",erro:N.starts_at,htmlFor:"cm-hora",children:e.jsx(G,{id:"cm-hora",type:"time",value:d.starts_at,onChange:x=>f({starts_at:x.target.value})})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx(R,{rotulo:"Estado",obrigatorio:!0,erro:N.status,children:e.jsxs(Q,{value:d.status,onValueChange:x=>f({status:x}),children:[e.jsx(Z,{"aria-label":"Estado",children:e.jsx(J,{})}),e.jsx(K,{children:He.map(x=>e.jsx(L,{value:x,children:De[x]},x))})]})}),e.jsx(R,{rotulo:"Onde a execução acontece (opcional)",htmlFor:"cm-card",dica:U?void 0:"Cole o link do card no Cards.",children:U?e.jsxs("div",{className:"flex items-start gap-1.5 rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(cs,{className:"mt-0.5 h-3 w-3 flex-shrink-0"}),e.jsxs("span",{children:["Esta ação veio da carga inicial, e a referência dela (",h==null?void 0:h.external_ref,") é o que impede a carga de duplicá-la. O link do card fica para as ações novas."]})]}):e.jsx(G,{id:"cm-card",value:d.card_ref,onChange:x=>f({card_ref:x.target.value}),placeholder:"https://â¦/cards/martech/c/MTCH-123"})})]}),e.jsx(R,{rotulo:"Descrição",htmlFor:"cm-desc",children:e.jsx(Ge,{id:"cm-desc",rows:4,value:d.description,onChange:x=>f({description:x.target.value})})}),e.jsx(R,{rotulo:"Link do material ou da inscrição",erro:N.url,htmlFor:"cm-url",children:e.jsx(G,{id:"cm-url",value:d.url,onChange:x=>f({url:x.target.value}),placeholder:"https://"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{type:"submit",disabled:P,children:P?"Salvandoâ¦":s?"Salvar alterações":"Salvar ação"}),e.jsx(E,{type:"button",variant:"ghost",onClick:()=>r(h?`${W}/acoes/${h.id}`:W),children:"Cancelar"})]})]}),e.jsxs("aside",{className:"h-fit space-y-3 rounded-lg border border-border bg-muted/30 p-4 text-sm lg:sticky lg:top-4",children:[e.jsx("h2",{className:"font-semibold",children:"O que esta frente pede"}),e.jsxs("ul",{className:"space-y-1.5 text-xs",children:[e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{children:"Lista de convidados"}),e.jsx("b",{children:M.guests?"Sim":"Não"})]}),e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{children:"Formato"}),e.jsx("b",{children:M.format?"Sim":"Não se aplica"})]}),e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{children:"Praça"}
9),e.jsx("b",{children:M.reach?"Sim":"Não se aplica"})]}),e.jsxs("li",{className:"flex justify-between gap-2",children:[e.jsx("span",{children:"Pode ir para clientes"}),e.jsx("b",{children:M.client_visible_allowed?"Se marcado (versão para clientes)":"Nunca"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Estas regras são da ",e.jsx("b",{children:"frente"})," e se mudam na Configuração, sem programar. O histórico guarda quem criou e quem mudou."]})]})]})]})}const Fr=["","segunda","terça","quarta","quinta","sexta"],oa="__ninguem__";function Ms(a){return a?new Intl.DateTimeFormat("pt-BR",{timeZone:"America/Sao_Paulo",day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(a)):"â"}function Ir(a){if(!a)return"nenhuma ainda";const s=a.stats??{},t=a.posted_at?"postou":s.skipped??s.motivo??(a.error?`falhou: ${a.error}`:a.status);return`${Ms(a.started_at)} · ${a.triggered_by==="cron"?"cron":"manual"} · ${t}`}function qr(){var O,D,M;const{config:a,uid:s,recarregar:t}=Y(),{toast:r}=me(),[n,o]=b.useState(a),[u,c]=b.useState([]),[m,g]=b.useState(!1),[l,h]=b.useState(null),[i,d]=b.useState(null),[v,N]=b.useState(null),[j,w]=b.useState(null);if(b.useEffect(()=>o(a),[a]),b.useEffect(()=>{$.pessoas().then(c).catch(()=>c([])),Promise.all(["digest","lembrete","resumo"].map(async f=>[f,await $.ultimasRodadas(f)])).then(f=>N(Object.fromEntries(f))).catch(f=>w(f instanceof Error?f.message:String(f)))},[]),!n)return e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configuração indisponÃvel."});const C=f=>o(U=>U&&{...U,...f}),P=async()=>{g(!0);try{await $.salvarConfig({digest_active:n.digest_active,digest_cadence:n.digest_cadence,digest_weekday:n.digest_weekday,digest_horizon_days:n.digest_horizon_days,sla_day:n.sla_day,sla_reminder_days_before:n.sla_reminder_days_before,cs_focal_user_id:n.cs_focal_user_id,mkt_tactical_user_id:n.mkt_tactical_user_id,slack_channel_label:n.slack_channel_label,...n.sla_active===void 0?{}:{sla_active:n.sla_active}},s),r({title:"Configuração salva"}),await t()}catch(f){r({title:"Não deu para salvar",description:f instanceof Error?f.message:String(f),variant:"destructive"})}finally{g(!1)}},_=async()=>{d("previa");try{const f=await $.pipeline("preview");h({digest:String(f.digest??""),lembrete:String(f.lembrete??""),resumo:String(f.resumo??""),agenda:f.agenda}),r({title:"Prévia gerada â nada foi enviado."})}catch(f){r({title:"Não deu para gerar a prévia",description:f instanceof Error?f.message:String(f),variant:"destructive"})}finally{d(null)}},A=async f=>{var U;if(window.confirm(`Enviar o ${f==="digest"?"resumo quinzenal":f==="lembrete"?"lembrete do corte":"resumo do mês"} para o canal AGORA?`)){d(f);try{const B=f==="digest"?await $.pipeline("digest"):await $.pipeline("sla",{tipo:f}),q=(f==="digest"?B:(U=B.resultados)==null?void 0:U[0])??{};q.postado===!0?r({title:"Enviado para o canal"}):r({title:"Nada foi enviado",description:String(q.motivo??q.erro??"sem detalhe")})}catch(B){r({title:"Não deu para enviar",description:B instanceof Error?B.message:String(B),variant:"destructive"})}finally{d(null)}}},S=(f,U,B)=>e.jsxs(Q,{value:f??oa,onValueChange:q=>U(q===oa?null:q),children:[e.jsx(Z,{"aria-label":B,children:e.jsx(J,{})}),e.jsxs(K,{children:[e.jsx(L,{value:oa,children:"Ninguém definido"}),u.map(q=>e.jsx(L,{value:q.id,children:q.nome},q.id))]})]});return e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold",children:"Resumo no Slack"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["O resumo quinzenal dos touches, o lembrete antes do corte e o resumo do mês, no canal"," ",n.slack_channel_label?e.jsx("b",{children:n.slack_channel_label}):"das lideranças",". Texto simples, sem marcar pessoas, e só quando há o que dizer."]})]}),e.jsxs("div",{className:"grid gap-4 rounded-lg border border-border p-4 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center justify-between gap-3 text-sm sm:col-span-2",children:[e.jsxs("span",{children:[e.jsx("b",{children:"Resumo quinzenal automático"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"O que toca clientes n
9os próximos dias, por frente."})]}),e.jsx($e,{checked:n.digest_active,onCheckedChange:f=>C({digest_active:f}),"aria-label":"Resumo automático"})]}),e.jsx(R,{rotulo:"Cadência",children:e.jsxs(Q,{value:n.digest_cadence,onValueChange:f=>C({digest_cadence:f}),children:[e.jsx(Z,{"aria-label":"Cadência",children:e.jsx(J,{})}),e.jsxs(K,{children:[e.jsx(L,{value:"quinzenal",children:"Quinzenal"}),e.jsx(L,{value:"semanal",children:"Semanal"})]})]})}),e.jsx(R,{rotulo:"Dia da semana",children:e.jsxs(Q,{value:String(n.digest_weekday),onValueChange:f=>C({digest_weekday:Number(f)}),children:[e.jsx(Z,{"aria-label":"Dia da semana",children:e.jsx(J,{})}),e.jsx(K,{children:[1,2,3,4,5].map(f=>e.jsx(L,{value:String(f),children:Fr[f]},f))})]})}),e.jsx(R,{rotulo:"Horizonte (dias)",htmlFor:"cm-horizonte",children:e.jsx(G,{id:"cm-horizonte",type:"number",min:1,max:60,value:n.digest_horizon_days,onChange:f=>C({digest_horizon_days:Math.min(60,Math.max(1,Number(f.target.value)||15))})})}),e.jsx(R,{rotulo:"Nome do canal (só para a tela)",htmlFor:"cm-canal",children:e.jsx(G,{id:"cm-canal",value:n.slack_channel_label??"",onChange:f=>C({slack_channel_label:f.target.value||null}),placeholder:"Lideranças de Marketing e CS"})}),e.jsxs("label",{className:"flex items-center justify-between gap-3 border-t border-border pt-4 text-sm sm:col-span-2",children:[e.jsxs("span",{children:[e.jsx("b",{children:"Lembrete do corte e resumo do mês"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Antes do corte, as frentes sem nada no mês seguinte; no 1º dia útil, o mês."})]}),n.sla_active===void 0?e.jsx("span",{className:"text-xs text-muted-foreground",children:"disponÃvel depois da migration da F3"}):e.jsx($e,{checked:n.sla_active,onCheckedChange:f=>C({sla_active:f}),"aria-label":"Lembrete automático"})]}),e.jsx(R,{rotulo:"Dia do corte",htmlFor:"cm-corte",dica:"Fevereiro usa o último dia do mês.",children:e.jsx(G,{id:"cm-corte",type:"number",min:1,max:31,value:n.sla_day,onChange:f=>C({sla_day:Math.min(31,Math.max(1,Number(f.target.value)||30))})})}),e.jsx(R,{rotulo:"Lembrar quantos dias antes",htmlFor:"cm-antes",dica:"Fim de semana recua para a sexta.",children:e.jsx(G,{id:"cm-antes",type:"number",min:0,max:20,value:n.sla_reminder_days_before,onChange:f=>C({sla_reminder_days_before:Math.max(0,Number(f.target.value)||0)})})}),e.jsx(R,{rotulo:"Ponto focal do CS",children:S(n.cs_focal_user_id,f=>C({cs_focal_user_id:f}),"Ponto focal do CS")}),e.jsx(R,{rotulo:"Tático do Marketing",dica:"Quem recebe os pedidos de ajuste na ferramenta.",children:S(n.mkt_tactical_user_id,f=>C({mkt_tactical_user_id:f}),"Tático do Marketing")}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(E,{onClick:()=>void P(),disabled:m,children:m?"Salvandoâ¦":"Salvar"})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>void _(),disabled:i!==null,children:[e.jsx(Zs,{className:"mr-1 h-4 w-4"})," ",i==="previa"?"Gerandoâ¦":"Ver prévia"]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>void A("digest"),disabled:i!==null,children:[e.jsx(Xe,{className:"mr-1 h-4 w-4"})," Enviar o resumo agora"]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>void A("lembrete"),disabled:i!==null,children:[e.jsx(Xe,{className:"mr-1 h-4 w-4"})," Enviar o lembrete agora"]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>void A("resumo"),disabled:i!==null,children:[e.jsx(Xe,{className:"mr-1 h-4 w-4"})," Enviar o resumo do mês agora"]})]}),l&&e.jsx("div",{className:"grid gap-3 lg:grid-cols-3",children:[["Resumo quinzenal",l.digest,(O=l.agenda)==null?void 0:O.digest_hoje],["Lembrete do corte",l.lembrete,(D=l.agenda)==null?void 0:D.lembrete],["Resumo do mês",l.resumo,(M=l.agenda)==null?void 0:M.resumo]].map(([f,U,B])=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs font-medium",children:[e.jsx("span",{children:f}),e.jsx("span",{className:"text-muted-foreground",children:B?"o cron manda hoje":"o cron não manda hoje"})]}),e.jsx("pre",{className:"max-h-80 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted/40 p-3 text-xs",children:U||"Nada a dizer â e o texto não é enviado."})]},f))}),e.jsxs("div",{className:"rounded-lg border border-border p-3 text-xs",children:[e.jsx("p",{className:"mb-1 font-medium",children:"Ãltima execução"}),j?e.jsxs("p",{className:"text-muted-foreground",children:["IndisponÃvel: ",j]}):v?e.jsx("ul",{className:"space-y-0.5 text-muted-foreground",children:["digest","lembrete","resumo"].map(f=>{const U=f==="digest"?v.digest.doCron:[v.lembrete.doCron,v.resumo.doCron].filter(
9Boolean).sort((B,q)=>q.started_at.localeCompare(B.started_at))[0]??null;return e.jsxs("li",{children:[e.jsxs("b",{className:"text-foreground",children:[f==="digest"?"Resumo":f==="lembrete"?"Lembrete":"Resumo do mês",":"]})," ",Ir(v[f].ultima),U?` · cron vivo (${Ms(U.started_at)})`:" · o cron ainda não rodou"]},f)})}):e.jsx("p",{className:"text-muted-foreground",children:"Carregandoâ¦"})]})]})}const ia="__sem__";function Ur(a,s){return a?{id:a.id,name:a.name,description:a.description??"",default_owner_user_id:a.default_owner_user_id,default_owner_name:a.default_owner_name??"",color_token:Je(a.color_token),applies:Pa(a.applies),sort_order:a.sort_order,is_active:a.is_active}:{id:null,name:"",description:"",default_owner_user_id:null,default_owner_name:"",color_token:"--track-slate",applies:{guests:!1,format:!0,reach:!0,client_visible_allowed:!1},sort_order:s,is_active:!0}}function os({titulo:a,descricao:s,acao:t,children:r}){return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold",children:a}),s&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]}),t]}),r]})}function Vr({rascunho:a,pessoas:s,onFechar:t}){const{toast:r}=me(),[n,o]=b.useState(a),[u,c]=b.useState(!1),[m,g]=b.useState(null),l=j=>o(w=>({...w,...j})),h=j=>o(w=>({...w,applies:{...w.applies,...j}})),i=async()=>{if(!n.name.trim()){r({title:"Dê um nome à frente",variant:"destructive"});return}c(!0);try{const j={name:n.name.trim(),description:n.description.trim()||null,default_owner_user_id:n.default_owner_user_id,default_owner_name:n.default_owner_name.trim()||null,color_token:n.color_token,applies:n.applies,sort_order:n.sort_order,is_active:n.is_active};if(n.id)await $.atualizarFrente(n.id,j);else{const w=ca(n.name);if(!w)throw new Error("O nome precisa ter ao menos uma letra ou número.");await $.criarFrente({...j,slug:w})}r({title:"Frente salva"}),t(!0)}catch(j){const w=j instanceof Error?j.message:String(j);r({title:"Não deu para salvar a frente",description:/duplicate|uq_cm_fronts_slug/i.test(w)?"Já existe uma frente com esse nome.":w,variant:"destructive"})}finally{c(!1)}},d=async()=>{if(n.id)try{g(await $.contarAcoesDaFrente(n.id))}catch(j){r({title:"Não deu para contar as ações",description:j instanceof Error?j.message:String(j),variant:"destructive"})}},v=async()=>{if(n.id){c(!0);try{await $.apagarFrente(n.id),r({title:"Frente apagada",description:'As ações dela ficaram "sem frente".'}),t(!0)}catch(j){r({title:"Não deu para apagar",description:j instanceof Error?j.message:String(j),variant:"destructive"})}finally{c(!1)}}},N=n.default_owner_user_id??ia;return e.jsx(ba,{open:!0,onOpenChange:j=>!j&&t(!1),children:e.jsxs(Na,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg",children:[e.jsx(wa,{children:e.jsx(ya,{children:n.id?"Editar frente":"Nova frente"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(R,{rotulo:"Nome",obrigatorio:!0,htmlFor:"cm-fr-nome",children:e.jsx(G,{id:"cm-fr-nome",value:n.name,onChange:j=>l({name:j.target.value})})}),e.jsx(R,{rotulo:"Descrição",htmlFor:"cm-fr-desc",children:e.jsx(Ge,{id:"cm-fr-desc",rows:2,value:n.description,onChange:j=>l({description:j.target.value})})}),e.jsxs(R,{rotulo:"Dono padrão",dica:"Quem a ação nova da frente sugere como responsável.",children:[e.jsxs(Q,{value:N,onValueChange:j=>l({default_owner_user_id:j===ia?null:j}),children:[e.jsx(Z,{"aria-label":"Dono padrão",children:e.jsx(J,{})}),e.jsxs(K,{children:[e.jsx(L,{value:ia,children:"Sem conta (só o nome abaixo)"}),s.map(j=>e.jsx(L,{value:j.id,children:j.nome},j.id)),n.default_owner_user_id&&!s.some(j=>j.id===n.default_owner_user_id)&&e.jsx(L,{value:n.default_owner_user_id,children:"Dono atual"})]})]}),e.jsx(G,{className:"mt-2",value:n.default_owner_name,onChange:j=>l({default_owner_name:j.target.value}),placeholder:"Nome do dono (aparece mesmo sem conta)","aria-label":"Nome do dono"})]}),e.jsx(R,{rotulo:"Cor",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",role:"radiogroup","aria-label":"Cor da frente",children:js.map(j=>e.jsx("button",{type:"button",role:"radio","aria-checked":n.color_token===j.token,"aria-label":j.label,title:j.label,onClick:()=>l({color_token:j.token}),className:V("h-7 w-7 rounded-full border-2 transition-transform",n.color_token===j.token?"scale-110 border-foreground":"border-transparent"),style:Te(j.token)},j.token))})}),e.jsx(R,{rotulo:"O que esta frente usa",dica:"O formulário da ação esconde o que a frente não usa.",children:e.jsx("div",{className:"space-y-2 text-sm",children:[["guests","Lista de convidados"],["format","Formato (presencial, hÃbrido, online)"],["reach","Praça (nacional ou regional)"],["client_visible_allowed","Pode ir para a versão dos clientes"]].map(([j,w])=>e.jsxs("label",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{children:w}),e.jsx($e,{checked:n.applies[j],onCheckedChange:C=>h({[j]:C})})]},j))})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(R,{rotulo:"Ordem",htmlFor:"cm-fr-ordem",children:e.jsx(G,{id:"cm-fr-ordem",type:"number",value:n.sort_order,onChange:j=>l({sort_order:Number(j.target.value)||0})})}),e.jsx(R,{rotulo:"Ativa",dica:"Inativa some dos filtros e do formulário; as ações dela continuam.",children:e.jsx($e,{checked:n.is_active,onCheckedChange:j=>l({is_active:j}),"aria-label":"Frente ativa"})})]}),m!==null&&e.jsxs("div",{className:"space-y-2 rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[e.jsxs("p",{children:[m===0?"Nenhuma ação usa esta frente.":`${m} ${m===1?"ação fica":"ações ficam"} "sem frente" (continuam no calendário, com cor neutra).`," ",'A exclusão não se desfaz â para só esconder, desligue "Ativa".']}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{size:"sm",variant:"destructive",onClick:()=>void v(),disabled:u,children:"Apagar de vez"}),e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>g(null),children:"Voltar"})]})]})]}),e.jsxs(Ca,{className:"gap-2 sm:justify-between",children:[n.id?e.jsxs(E,{variant:"ghost",className:"text-destructive",onClick:()=>void d(),disabled:u,children:[e.jsx(Be,{className:"mr-1 h-4 w-4"})," Apagar frente"]}):e.jsx("span",{}),e.jsx(E,{onClick:()=>void i(),disabled:u,children:u?"Salvandoâ¦":"Salvar"})]})]})})}function Br({l:a,onMudou:s}){const{toast:t}=me(),[r,n]=b.useState(a.name),[o,u]=b.useState(a.sort_order),c=r.trim()!==a.name||o!==a.sort_order,m=async l=>{try{await $.atualizarAlavanca(a.id,l),s()}catch(h){t({title:"Não deu para salvar a alavanca",description:h instanceof Error?h.message:String(h),variant:"destructive"})}},g=async()=>{try{const l=await $.contarAcoesDaAlavanca(a.id);if(!window.confirm(l===0?`Apagar a alavanca "${a.name}"? Nenhuma ação a usa.`:`Apagar a alavanca "${a.name}"? ${l} ${l===1?"ação a usa":"ações a usam"}: como principal, ficam "sem alavanca"; como secundária, aparecem como "Alavanca removida". Não se desfaz â para só esconder, desligue "Ativa".`))return;await $.apagarAlavanca(a.id),s()}catch(l){t({title:"Não deu para apagar",description:l instanceof Error?l.message:String(l),variant:"destructive"})}};return e.jsxs("li",{className:"flex flex-wrap items-center gap-2 px-3 py-2",children:[e.jsx(G,{className:"h-8 min-w-[12rem] flex-1",value:r,onChange:l=>n(l.target.value),"aria-label":"Nome da alavanca"}),e.jsx(G,{className:"h-8 w-20",type:"number",value:o,onChange:l=>u(Number(l.target.value)||0),"aria-label":"Ordem"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx($e,{checked:a.is_active,onCheckedChange:l=>void m({is_active:l}),"aria-label":"Alavanca ativa"})," ativa"]}),e.jsx(E,{size:"sm",variant:"outline",className:"h-8",disabled:!c||!r.trim(),onClick:()=>void m({name:r.trim(),sort_order:o}),children:"Salvar"}),e.jsx(E,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive","aria-label":`Apagar ${a.name}`,onClick:()=>void g(),children:e.jsx(Be,{className:"h-4 w-4"})})]})}function Gr(){const{canEdit:a,frentes:s,alavancas:t,nome:r,recarregar:n}=Y(),{toast:o}=me(),[u,c]=b.useState(null),[m,g]=b.useState(null),[l,h]=b.useState("");
9if(!a)return e.jsx(ve,{titulo:"Só quem edita o calendário vê a configuração"});const i=async v=>{var N;if(m===null)try{g(await $.pessoas())}catch{g([])}c(Ur(v,(((N=s.at(-1))==null?void 0:N.sort_order)??0)+1))},d=async()=>{var j;const v=l.trim(),N=ca(v);if(N)try{await $.criarAlavanca({slug:N,name:v,sort_order:(((j=t.at(-1))==null?void 0:j.sort_order)??0)+1}),h(""),await n()}catch(w){const C=w instanceof Error?w.message:String(w);o({title:"Não deu para criar",description:/duplicate|uq_cm_levers_slug/i.test(C)?"Já existe uma alavanca com esse nome.":C,variant:"destructive"})}};return e.jsxs("div",{className:"mx-auto max-w-4xl space-y-8 px-4 py-5 sm:px-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Configuração"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Frentes, alavancas e o resumo no Slack. Mudam aqui, sem programar."})]}),e.jsx(os,{titulo:"Frentes",descricao:"Cada frente tem um dono e diz quais campos fazem sentido para as ações dela.",acao:e.jsxs(E,{size:"sm",onClick:()=>void i(null),children:[e.jsx(ze,{className:"mr-1 h-4 w-4"})," Nova frente"]}),children:e.jsx("ul",{className:"divide-y divide-border rounded-lg border border-border",children:s.map(v=>{const N=Pa(v.applies),j=[N.guests&&"convidados",N.format&&"formato",N.reach&&"praça",N.client_visible_allowed&&"vai para clientes"].filter(Boolean).join(" · ");return e.jsxs("li",{className:V("flex items-center gap-3 px-3 py-2.5",!v.is_active&&"opacity-60"),children:[e.jsx("span",{className:"h-3 w-3 flex-shrink-0 rounded-full",style:Te(v.color_token)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm font-medium",children:[v.name,!v.is_active&&e.jsx("span",{className:"ml-2 text-xs font-normal text-muted-foreground",children:"(inativa)"})]}),e.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:["Dono: ",r(v.default_owner_user_id)??v.default_owner_name??"â"," · ",j||"só data e público"]})]}),e.jsx(E,{size:"sm",variant:"ghost",className:"h-8",onClick:()=>void i(v),"aria-label":`Editar ${v.name}`,children:e.jsx(ja,{className:"h-4 w-4"})})]},v.id)})})}),e.jsx(os,{titulo:"Alavancas",descricao:"O objetivo da ação com a base. A ação tem uma principal e, se fizer sentido, secundárias.",children:e.jsxs("ul",{className:"divide-y divide-border rounded-lg border border-border",children:[t.map(v=>e.jsx(Br,{l:v,onMudou:()=>void n()},`${v.id}-${v.name}-${v.sort_order}`)),e.jsxs("li",{className:"flex flex-wrap items-center gap-2 px-3 py-2",children:[e.jsx(G,{className:"h-8 min-w-[12rem] flex-1",value:l,onChange:v=>h(v.target.value),placeholder:"Nova alavanca","aria-label":"Nova alavanca"}),e.jsxs(E,{size:"sm",className:"h-8",disabled:!ca(l),onClick:()=>void d(),children:[e.jsx(ze,{className:"mr-1 h-4 w-4"})," Acrescentar"]})]})]})}),e.jsx(qr,{}),u&&e.jsx(Vr,{rascunho:u,pessoas:m??[],onFechar:v=>{c(null),v&&n()}})]})}const be="__sem__";function is(a){return new Intl.DateTimeFormat("pt-BR",{timeZone:"America/Sao_Paulo",day:"2-digit",month:"2-digit"}).format(new Date(a))}function Hr(){return{name:"",email:null,phone:null,company:null,company_size:null,role_title:null,blindagem_risk:null,csm:null,cs_leader:null,ae:null,ae_leader:null,is_client:null,products:[],invite_status:"sugerido",notes:null,salesforce_account_id:null}}function Qr({inicial:a,onSalvar:s,onFechar:t}){const[r,n]=b.useState(a),[o,u]=b.useState(null),[c,m]=b.useState(!1),g=i=>n(d=>({...d,...i})),l=(i,d)=>e.jsx(R,{rotulo:d,htmlFor:`cm-g-${i}`,children:e.jsx(G,{id:`cm-g-${i}`,value:r[i]??"",onChange:v=>g({[i]:v.target.value||null})})}),h=async()=>{if(!r.name.trim())return u("Dê o nome do convidado.");const i=Os(r.email);if(i.erro)return u(i.erro);const d=Rs(r.phone);if(d.erro)return u(d.erro);m(!0),u(null);try{await s({...r,name:r.name.trim(),email:i.valor,phone:d.valor})}catch(v){u(v instanceof Error?v.message:String(v))}finally{m(!1)}};return e.jsx(ba,{open:!0,onOpenChange:i=>!i&&t(),children:e.jsxs(Na,{className:"max-h-[90vh] overflow-y-auto sm:max-w-2xl",children:[e.jsx(wa,{children:e.jsx(ya,{children:a.id?"Editar convidado":"Novo convidado"})}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(R,{rotulo:"Nome",obrigatorio:!0,htmlFor:"cm-g-name",children:e.jsx(G,{id:"cm-g-name",value:r.name,onChange:i=>
9g({name:i.target.value})})}),l("role_title","Cargo"),l("email","E-mail"),l("phone","Telefone"),l("company","Empresa"),l("company_size","Porte (G, E, M, P ou texto)"),e.jsx(R,{rotulo:"Risco de blindagem",dica:"Mudar o risco registra você como quem conferiu.",children:e.jsxs(Q,{value:r.blindagem_risk??be,onValueChange:i=>g({blindagem_risk:i===be?null:i}),children:[e.jsx(Z,{"aria-label":"Risco de blindagem",children:e.jsx(J,{})}),e.jsxs(K,{children:[e.jsx(L,{value:be,children:"Não informado"}),Pe.map(i=>e.jsx(L,{value:i,children:Ha[i]},i)),r.blindagem_risk&&!Pe.includes(r.blindagem_risk)&&e.jsxs(L,{value:r.blindagem_risk,children:[r.blindagem_risk," (fora da escala)"]})]})]})}),e.jsx(R,{rotulo:"Status do convite",children:e.jsxs(Q,{value:r.invite_status,onValueChange:i=>g({invite_status:i}),children:[e.jsx(Z,{"aria-label":"Status do convite",children:e.jsx(J,{})}),e.jsx(K,{children:he.map(i=>e.jsx(L,{value:i,children:je[i]},i))})]})}),l("csm","CSM"),l("cs_leader","LÃder de CS"),l("ae","AE"),l("ae_leader","LÃder de AE"),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(R,{rotulo:"à cliente de",children:e.jsx(ce,{multipla:!0,rotuloDoGrupo:"Produtos",opcoes:pa.map(i=>({id:i,nome:Ye[i]})),valor:r.products,onChange:i=>g({products:i,is_client:i.length>0?!0:r.is_client})})})}),e.jsx(R,{rotulo:"à cliente?",children:e.jsx(ce,{rotuloDoGrupo:"à cliente",opcoes:[{id:"sim",nome:"Sim"},{id:"nao",nome:"Não"},{id:"nao_sei",nome:"Não sei"}],valor:[r.is_client===!0?"sim":r.is_client===!1?"nao":"nao_sei"],onChange:([i])=>g({is_client:i==="sim"?!0:i==="nao"?!1:null})})}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(R,{rotulo:"Observações",htmlFor:"cm-g-notes",children:e.jsx(Ge,{id:"cm-g-notes",rows:2,value:r.notes??"",onChange:i=>g({notes:i.target.value||null})})})})]}),o&&e.jsx("p",{className:"text-sm font-medium text-destructive",children:o}),e.jsxs(Ca,{children:[e.jsx(E,{variant:"ghost",onClick:t,children:"Cancelar"}),e.jsx(E,{onClick:()=>void h(),disabled:c,children:c?"Salvandoâ¦":"Salvar"})]})]})})}function Zr({emailsNaLista:a,onImportar:s,onFechar:t}){const[r,n]=b.useState(""),[o,u]=b.useState(!1),c=b.useRef(null),m=b.useMemo(()=>r.trim()?$r(r,a):null,[r,a]),g=!!(m&&m.erros.length===0&&m.convidados.length>0);return e.jsx(ba,{open:!0,onOpenChange:l=>!l&&t(),children:e.jsxs(Na,{className:"max-h-[90vh] overflow-y-auto sm:max-w-3xl",children:[e.jsx(wa,{children:e.jsx(ya,{children:"Colar ou subir a planilha de convidados"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Cole as linhas copiadas da planilha (com o cabeçalho na primeira linha) ou escolha um arquivo .csv. Colunas reconhecidas: Nome, E-mail, Telefone, Empresa, Porte, Cargo, Risco de blindagem, CSM, LÃder de CS, AE, LÃder de AE, à cliente, Produtos, Status do convite, Observações. O lote entra inteiro ou não entra."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{ref:c,type:"file",accept:".csv,.tsv,.txt,text/csv,text/plain",className:"hidden",onChange:async l=>{var i;const h=(i=l.target.files)==null?void 0:i[0];h&&n(await h.text()),l.target.value=""}}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=c.current)==null?void 0:l.click()},children:[e.jsx(ds,{className:"mr-1 h-4 w-4"})," Escolher arquivo"]}),r&&e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>n(""),children:"Limpar"})]}),e.jsx(Ge,{rows:8,value:r,onChange:l=>n(l.target.value),placeholder:`Nome E-mail Empresa Risco de blindagem 10Ana Silva [email protected] Empresa A Alto`,className:"font-mono text-xs","aria-label":"Planilha colada"}),m&&e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("p",{children:[e.jsx("b",{children:m.convidados.length})," ",m.convidados.length===1?"convidado pronto":"convidados prontos"," para entrar",m.jaNaLista>0&&` · ${m.jaNaLista} já na lista`,m.repetidosNaPlanilha>0&&` · ${m.repetidosNaPlanilha} repetidos na planilha`,m.erros.length>0&&e.jsxs("span",{className:"text-destructive",children:[" ","· ",m.erros.length," ",m.erros.length===1?"linha com erro":"linhas com erro"," â corrija e cole de novo"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Colunas:"," ",m.colunas.map(l=>e.jsx("span",{className:V("mr-1.5",!l.campo&&"line-through"),children:l.cabecalho},l.cabecalho)),m.colunas.some(l=>!l.campo)&&"(riscadas = ignoradas)"]}),m.erros.length>0&&e.jsx("ul",{className:"max-h-40 overflow-y-auto rounded-md border border-destructive/40 bg-destructive/5 p-2 text-xs",children:m.erros.map((l,h)=>e.jsxs("li",{children:["Linha ",l.linha,": ",l.mensagem]},h))}),m.avisos.length>0&&e.jsx("ul",{className:"max-h-32 overflow-y-auto rounded-md border border-border bg-muted/40 p-2 text-xs text-muted-foreground",children:m.avisos.map((l,h)=>e.jsxs("li",{children:["Linha ",l.linha,": ",l.mensagem]},h))})]}),e.jsxs(Ca,{children:[e.jsx(E,{variant:"ghost",onClick:t,children:"Cancelar"}),e.jsx(E,{disabled:!g||o,onClick:async()=>
10{if(m){u(!0);try{await s(m.convidados)}finally{u(!1)}}},children:o?"Importandoâ¦":`Importar ${(m==null?void 0:m.convidados.length)??0}`})]})]})})}function Jr(){const{id:a}=va(),{toast:s}=me(),{canEdit:t,uid:r,frente:n,aplica:o}=Y(),[u,c]=b.useState(void 0),[m,g]=b.useState(null),[l,h]=b.useState(new Map),[i,d]=b.useState(null),[v,N]=b.useState({soClientes:!1,soRiscoAlto:!1,soNaoConferidos:!1,status:null}),[j,w]=b.useState(null),[C,P]=b.useState(!1),_=b.useCallback(async()=>{if(a){d(null);try{const[p,y]=await Promise.all([$.acao(a),$.convidados(a)]);c(p),g(y)}catch(p){d(p instanceof Error?p.message:String(p))}}},[a]);b.useEffect(()=>{t&&_()},[t,_]),b.useEffect(()=>{t&&$.pessoas().then(p=>h(new Map(p.map(y=>[y.id,y.nome])))).catch(()=>{})},[t]);const A=b.useMemo(()=>new Set((m??[]).map(p=>p.email).filter(p=>!!p)),[m]);if(!t)return e.jsx(ve,{titulo:"Só quem edita o calendário vê os convidados",children:"A lista tem e-mail, telefone e o risco de cada conta. Peça acesso de edição a um administrador."});if(i)return e.jsx(ue,{mensagem:i,onTentar:()=>void _()});if(u===void 0||m===null)return e.jsx(le,{});if(u===null)return e.jsx(ve,{titulo:"Ação não encontrada"});const S=o(u.front_id),O=Ps(m),D=Dr(m,v),M=Array.from(m.reduce((p,y)=>{if(y.import_batch_id){const k=p.get(y.import_batch_id)??{n:0,em:y.created_at};p.set(y.import_batch_id,{n:k.n+1,em:k.em<y.created_at?k.em:y.created_at})}return p},new Map)).sort((p,y)=>y[1].em.localeCompare(p[1].em)),f=p=>p.risk_checked_at?`${l.get(p.risk_checked_by??"")??"alguém"} em ${is(p.risk_checked_at)}`:"",U=async(p,y)=>{try{await $.atualizarConvidado(p.id,y),await _()}catch(k){s({title:"Não deu para salvar",description:k instanceof Error?k.message:String(k),variant:"destructive"})}},B=()=>{const p=Rr(D,f),y=new Blob(["\uFEFF",p],{type:"text/csv;charset=utf-8"}),k=URL.createObjectURL(y),x=document.createElement("a");x.href=k,x.download=`convidados-${u.starts_on}-${u.title.replace(/[^\w-]+/g,"-").slice(0,40)}.csv`,x.click(),URL.revokeObjectURL(k)},q=(p,y,k=!1)=>e.jsxs("div",{className:V("rounded-lg border p-3",k&&y>0?"border-[hsl(var(--tier-risk-text)/0.4)] bg-[hsl(var(--tier-risk-bg))]":"border-border"),children:[e.jsx("div",{className:V("text-xs",k&&y>0?"text-[hsl(var(--tier-risk-text))]":"text-muted-foreground"),children:p}),e.jsx("div",{className:"text-xl font-semibold",children:y})]}),X=(p,y)=>e.jsx("button",{type:"button","aria-pressed":v[p],onClick:()=>N(k=>({...k,[p]:!k[p]})),className:V("rounded-full border px-3 py-1 text-xs",v[p]?"border-primary bg-primary text-primary-foreground":"border-border bg-background hover:bg-muted"),children:y});return e.jsxs("div",{className:"mx-auto max-w-7xl space-y-4 px-4 py-5 sm:px-6",children:[e.jsx(E,{variant:"ghost",size:"sm",className:"-ml-2 h-8 text-xs",asChild:!0,children:e.jsxs(oe,{to:`${W}/acoes/${u.id}`,children:[e.jsx(_a,{className:"mr-1 h-3.5 w-3.5"})," Voltar para a ação"]})}),e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-xl font-semibold",children:["Convidados · ",u.title]}),e.jsxs("p",{className:"flex flex-wrap items-center gap-x-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Re(u)}),u.reach&&e.jsxs("span",{children:["· ",Ra(u)]}),e.jsx("span",{children:"·"}),e.jsx(We,{frente:n(u.front_id)})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>P(!0),children:[e.jsx(ds,{className:"mr-1 h-4 w-4"})," Colar ou subir planilha"]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>w(Hr()),children:[e.jsx(ze,{className:"mr-1 h-4 w-4"})," Convidado"]}),e.jsxs(E,{size:"sm",onClick:B,disabled:D.length===0,children:[e.jsx(tt,{className:"mr-1 h-4 w-4"})," Baixar lista conferida"]})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(cs,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{children:"Só quem edita o calendário vê esta lista: ela tem e-mail, telefone e o risco de cada conta. A MAIA não a lê."})]}),!S.guests&&e.jsx("p",{className:"rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground",children:"A frente desta ação não usa lista de convidados. A lista que existe continua aqui, mas a aba some da ação."}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-6",children:[q("Saudável",O.porRisco.saudavel),q("Médio",O.porRisco.medio),q("Alto",O.porRisco.alto,!0),q("AltÃssimo",O.porRisco.altissimo,!0),q("Não informado",O.porRisco.sem+O.porRisco.outro),q("Risco não conferido",O.naoConferidos)]}),O.emRisco>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-[hsl(var(--tier-risk-bg))] px-3 py-2 text-sm text-[hsl(var(--tier-risk-text))]",children:[e.jsx(Js,{className:"h-4 w-4 flex-shrink-0"}),O.emRisco," ",O.emRisco===1?"convidado com risco alto ou altÃssimo":"convidados com risco alto ou altÃssimo"," ainda n
10a lista. Confira antes de o convite sair."]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[O.total," na lista · ",O.clientes," ",O.clientes===1?"cliente":"clientes"," ·"," ",he.filter(p=>O.porStatus[p]>0).map(p=>`${O.porStatus[p]} ${je[p].toLowerCase()}`).join(" · ")]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[X("soClientes","Só clientes"),X("soRiscoAlto","Risco alto ou altÃssimo"),X("soNaoConferidos","Risco ainda não conferido"),e.jsxs(Q,{value:v.status??"__todos__",onValueChange:p=>N(y=>({...y,status:p==="__todos__"?null:p})),children:[e.jsx(Z,{className:"h-8 w-[200px] text-xs","aria-label":"Status do convite (filtro)",children:e.jsx(J,{})}),e.jsxs(K,{children:[e.jsx(L,{value:"__todos__",children:"Todo status do convite"}),he.map(p=>e.jsx(L,{value:p,children:je[p]},p))]})]})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:e.jsxs("table",{className:"w-full min-w-[960px] text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-left text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 font-medium",children:"Convidado"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Empresa"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Cliente de"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Risco"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"CSM"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Convite"}),e.jsx("th",{className:"px-3 py-2 font-medium",children:"Conferido"}),e.jsx("th",{className:"px-3 py-2"})]})}),e.jsxs("tbody",{className:"divide-y divide-border",children:[D.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-6 text-center text-muted-foreground",children:m.length===0?"Ninguém na lista ainda. Cole a planilha do time de eventos.":"Ninguém com este filtro."})}),D.map(p=>{const y=p.blindagem_risk!==null&&Qa.includes(p.blindagem_risk)&&p.invite_status!=="vetado";return e.jsxs("tr",{className:V(y&&"bg-[hsl(var(--tier-risk-bg)/0.5)]",p.invite_status==="vetado"&&"text-muted-foreground"),children:[e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:p.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:[p.role_title,p.email].filter(Boolean).join(" · ")})]}),e.jsxs("td",{className:"px-3 py-2",children:[p.company??"â",p.company_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[" · ",xs(p.company_size)]})]}),e.jsx("td",{className:"px-3 py-2",children:p.products.length?e.jsx("span",{className:"flex flex-wrap gap-1",children:p.products.map(k=>e.jsx("span",{className:"rounded bg-primary/10 px-1.5 py-0.5 text-[11px] text-primary",children:Ye[k]??k},k))}):Za(p)?e.jsx("span",{className:"text-xs",children:"Cliente"}):p.is_client===!1?e.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground",children:"Não é cliente"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"})}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs(Q,{value:p.blindagem_risk??be,onValueChange:k=>void U(p,{blindagem_risk:k===be?null:k}),children:[e.jsx(Z,{className:"h-7 w-[130px] text-xs","aria-label":`Risco de ${p.name}`,children:e.jsx(J,{children:Ds(p.blindagem_risk)})}),e.jsxs(K,{children:[e.jsx(L,{value:be,children:"Não informado"}),Pe.map(k=>e.jsx(L,{value:k,children:Ha[k]},k)),p.blindagem_risk&&!Pe.includes(p.blindagem_risk)&&e.jsx(L,{value:p.blindagem_risk,children:p.blindagem_risk})]})]})}),e.jsx("td",{className:"px-3 py-2 text-xs",children:p.csm??"â"}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs(Q,{value:p.invite_status,onValueChange:k=>void U(p,{invite_status:k}),children:[e.jsx(Z,{className:"h-7 w-[125px] text-xs","aria-label":`Convite de ${p.name}`,children:e.jsx(J,{})}),e.jsx(K,{children:he.map(k=>e.jsx(L,{value:k,children:je[k]},k))})]})}),e.jsx("td",{className:"px-3 py-2 text-xs",children:p.risk_checked_at?e.jsx("span",{className:"text-muted-foreground",children:f(p)}):p.blindagem_risk?e.jsx(E,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>void $.conferirRisco(p.id).then(_).catch(k=>s({title:"Não deu para marcar",description:String(k),variant:"destructive"})),children:"Marcar conferido"}):e.jsx("span",{className:"text-muted-foreground",children:"sem risco"})}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(E,{size:"icon",variant:"ghost",className:"h-7 w-7","aria-label":`Editar ${p.name}`,onClick:()=>w({...p}),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(E,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive","aria-label":`Remover ${p.name}`,onClick:async()=>
10{if(window.confirm(`Remover ${p.name} da lista?`))try{await $.removerConvidado(p.id),await _()}catch(k){s({title:"Não deu para remover",description:k instanceof Error?k.message:String(k),variant:"destructive"})}},children:e.jsx(Be,{className:"h-3.5 w-3.5"})})]})})]},p.id)})]})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Quem vira "vetado" é decisão do CS; o app mostra o risco e guarda quem conferiu. A exportação leva o recorte do filtro atual.'}),M.length>0&&e.jsxs("section",{className:"space-y-2",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Lotes importados"}),e.jsx("ul",{className:"divide-y divide-border rounded-lg border border-border text-sm",children:M.map(([p,y])=>e.jsxs("li",{className:"flex items-center justify-between gap-2 px-3 py-2",children:[e.jsxs("span",{children:[y.n," ",y.n===1?"convidado":"convidados"," · importado em ",is(y.em)]}),e.jsx(E,{size:"sm",variant:"ghost",className:"h-7 text-xs text-destructive",onClick:async()=>{if(window.confirm(`Desfazer este lote? Os ${y.n} convidados dele saem da lista (o histórico guarda).`))try{const k=await $.desfazerLote(p);s({title:`Lote desfeito: ${k} saÃram da lista`}),await _()}catch(k){s({title:"Não deu para desfazer",description:k instanceof Error?k.message:String(k),variant:"destructive"})}},children:"Desfazer lote"})]},p))})]}),j&&e.jsx(Qr,{inicial:j,onFechar:()=>w(null),onSalvar:async p=>{if(j.id){const y=Mr(j,p);Object.keys(y).length&&await $.atualizarConvidado(j.id,y)}else await $.criarConvidado(u.id,p,r);w(null),s({title:"Convidado salvo"}),await _()}}),C&&e.jsx(Zr,{emailsNaLista:A,onFechar:()=>P(!1),onImportar:async p=>{try{const y=await $.importarConvidados(u.id,p,r);s({title:`${y.gravados} convidados importados`,description:"Se algo saiu errado, desfaça o lote no fim da página."}),P(!1),await _()}catch(y){s({title:"Nada foi importado",description:y instanceof Error?y.message:String(y),variant:"destructive"})}}})]})}const Kr="Sem alavanca";function Wr(a,s){return s==="cliente"?Ze(a):s==="prospect"?fs(a):!0}function Yr(a,s){const t=s.segmento??"todos",r=new Set(s.meses),n=new Map,o={};for(const h of s.meses)o[h]={cliente:0,ambos:0,prospect:0};for(const h of a){const i=h.mes.slice(0,10);if(!r.has(i)||h.recorte!==t||(h.audience in o[i]&&(o[i][h.audience]+=h.n_primaria),!Wr(h.audience,s.publico)))continue;const d=h.lever_id===null||!s.incluirSecundarias?h.n_primaria:h.n_com_secundarias;if(d===0)continue;const v=`${h.lever_id??""}|${i}`;n.set(v,(n.get(v)??0)+d)}const u=()=>Object.fromEntries(s.meses.map(h=>[h,0])),c=[];for(const h of s.alavancas){const i=u();let d=!1;for(const v of s.meses)i[v]=n.get(`${h.id}|${v}`)??0,i[v]>0&&(d=!0);(h.is_active||d)&&c.push({id:h.id,nome:h.name,porMes:i,semAlavanca:!1})}const m=u();for(const h of s.meses)m[h]=n.get(`|${h}`)??0;c.push({id:null,nome:Kr,porMes:m,semAlavanca:!0});const g=new Set(s.alavancas.filter(h=>h.is_active).map(h=>h.id)),l=[];for(const h of c)if(!(h.semAlavanca||!h.id||!g.has(h.id)))for(const i of s.meses)h.porMes[i]===0&&l.push({alavanca:h.nome,mes:i});return{linhas:c,lacunas:l,porPublico:o}}function Xr(a){return a<=0?0:a===1?1:a<=3?2:3}const la="__todos__",en=["bg-muted/40 text-muted-foreground","bg-primary/15","bg-primary/35","bg-primary/60 text-primary-foreground"];function an(){const{filtro:a,mudar:s,hoje:t}=Ae(),{alavancas:r}=Y(),[n,o]=ha(),u=n.get("seg"),c=$a(u)?u:null,m=n.get("sec")==="1",g=Cs(a.mes),[l,h]=b.useState(null),[i,d]=b.useState(null),v=(_,A)=>{const S=new URLSearchParams(n);A===null?S.delete(_):S.set(_,A),o(S,{replace:!0})},N=b.useRef(""),j=()=>{const _=`${g.ini}|${g.fim}`;N.current=_,d(null),h(null),$.cobertura(g.ini,g.fim).then(A=>N.current===_&&h(A)).catch(A=>N.current===_&&d(A instanceof Error?A.message:String(A)))};b.useEffect(j,[g.ini,g.fim]);const w=g.rotulo.charAt(0).toUpperCase()+g.rotulo.slice(1),C=a.publico,P=l?Yr(l,{meses:g.meses,alavancas:r,segmento:c,incluirSecundarias:m,publico:C}):null;return e.jsxs("div",{className:"mx-auto max-w-5xl space-y-4 px-4 py-5 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-semibold",children:"Cobertura da base"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Ações por alavanca e mês · o "esse mês não fizemos nada deâ¦"'})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center rounded-lg border border-border",children:[e.jsx(E,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Trimestre anterior",onClick:()=>s({mes:ge(g.ini,-3)}),children:e.jsx(fa,{className:"h-4 w-4"})}),e.jsx("span",{className:"min-w-[13rem] px-1 text-center text-sm font-medium",children:w}),e.jsx(E,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Próximo trimestre",onClick:()=>s({mes:ge(g.ini,3)}),children:e.jsx(ga,{className:"h-4 w-4"})})]}),!g.meses.includes(te(t))&&e.jsx(E,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>s({mes:te(t)}),children:"Hoje"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Q,{value:C,onValueChange:_=>s({publico:_}),children:[e.jsx(Z,{className:"h-8 w-[160px] text-xs","aria-label":"Público",children:e.jsx(J,{})}),e.jsx(K,{children:Fa.map(_=>e.jsx(L,{value:_,children:da[_]},_))})]}),e.jsxs(Q,{value:c??la,onValueChange:_=>
10v("seg",_===la?null:_),children:[e.jsx(Z,{className:"h-8 w-[180px] text-xs","aria-label":"Segmento",children:e.jsx(J,{})}),e.jsxs(K,{children:[e.jsx(L,{value:la,children:"Todos os segmentos"}),we.map(_=>e.jsx(L,{value:_,children:Ne[_]},_))]})]}),e.jsx("button",{type:"button","aria-pressed":m,onClick:()=>v("sec",m?null:"1"),className:V("rounded-full border px-3 py-1 text-xs",m?"border-primary bg-primary text-primary-foreground":"border-border bg-background hover:bg-muted"),children:"Contar também as alavancas secundárias"}),e.jsx($s,{})]}),(a.frente||a.alavanca||a.formato||a.praca||a.segmento||a.status||a.responsavel)&&e.jsx("p",{className:"rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground",children:"A cobertura recorta só por público e segmento: as outras dimensões do filtro (frente, alavanca, formato, praça, estado e responsável) não se aplicam aqui â a matriz conta todas as ações do trimestre."}),i?e.jsx(ue,{mensagem:i,onTentar:j}):P?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:e.jsxs("table",{className:"w-full min-w-[520px] text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Alavanca"}),g.meses.map(_=>e.jsx("th",{className:"px-3 py-2 text-center font-medium capitalize",children:_e(_)},_))]})}),e.jsx("tbody",{className:"divide-y divide-border",children:P.linhas.map(_=>e.jsxs("tr",{className:V(_.semAlavanca&&"text-muted-foreground"),children:[e.jsx("td",{className:"px-3 py-2",children:_.nome}),g.meses.map(A=>{const S=_.porMes[A];return e.jsx("td",{className:"p-1 text-center",children:e.jsx("span",{className:V("block rounded-md py-2 font-semibold",en[Xr(S)]),"aria-label":`${_.nome} em ${_e(A)}: ${S}`,children:S})},A)})]},_.id??"sem"))})]})}),P.lacunas.length>0?e.jsxs("div",{className:"rounded-lg border border-[hsl(var(--tier-warn-text)/0.3)] bg-[hsl(var(--tier-warn-bg))] p-3 text-sm text-[hsl(var(--tier-warn-text))]",children:[e.jsxs("p",{className:"font-medium",children:["Sem nenhuma ação",c?` para ${Ne[c]}`:""," (",da[C].toLowerCase(),"):"]}),e.jsx("ul",{className:"mt-1 list-disc pl-5",children:P.lacunas.map(_=>e.jsxs("li",{children:[_.alavanca," em ",_e(_.mes)]},`${_.alavanca}-${_.mes}`))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Todas as alavancas têm pelo menos uma ação em cada mês."}),e.jsxs("section",{className:"space-y-2 rounded-lg border border-border p-4",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Para quem falamos, mês a mês"}),g.meses.map(_=>{const A=P.porPublico[_],S=A.cliente+A.ambos+A.prospect,O=D=>S?`${Math.round(D*100/S)}%`:"0%";return e.jsxs("div",{className:"grid grid-cols-[6rem_1fr_auto] items-center gap-2 text-xs",children:[e.jsx("span",{className:"capitalize",children:_e(_)}),e.jsxs("span",{className:"flex h-3 overflow-hidden rounded-full bg-muted","aria-label":`${A.cliente} só clientes, ${A.ambos} clientes e prospects, ${A.prospect} só prospects`,children:[e.jsx("i",{className:"bg-[hsl(var(--chart-green))]",style:{width:O(A.cliente)}}),e.jsx("i",{className:"bg-[hsl(var(--track-blue))]",style:{width:O(A.ambos)}}),e.jsx("i",{className:"bg-[hsl(var(--track-indigo))]",style:{width:O(A.prospect)}})]}),e.jsxs("span",{className:"text-muted-foreground",children:[A.cliente," · ",A.ambos," · ",A.prospect]})]},_)}),e.jsxs("p",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("i",{className:"h-2 w-2 rounded-full bg-[hsl(var(--chart-green))]"})," só clientes (Farmer)"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("i",{className:"h-2 w-2 rounded-full bg-[hsl(var(--track-blue))]"})," clientes e prospects"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("i",{className:"h-2 w-2 rounded-full bg-[hsl(var(--track-indigo))]"})," só prospects (Hunter)"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Uma ação conta em todo mês que a janela dela toca. Cancelada não conta. "Sem alavanca" é a ação sem alavanca principal.'})]}):e.jsx(le,{})]})}const sn=[{vista:"",rotulo:"Mês",icone:Ys,fim:!0},{vista:"proximos",rotulo:"Próximos 15 dias",icone:rt},{vista:"trimestre",rotulo:"Trimestre",icone:nt},{vista:"cobertura",rotulo:"Cobertura",icone:it},{vista:"config",rotulo:"Configuração",icone:ot,soEdit:!0}];function tn(){const{canEdit:a}=Y(),{filtro:s}=Ae();return e.jsx("nav",{className:"flex-shrink-0 border-b border-border bg-background",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl items-center gap-1 overflow-x-auto px-4 sm:px-6",children:[e.jsx("div",{className:"mr-3 hidden items-center gap-2 py-3 text-sm font-semibold md:flex",children:"Calendário de Marketing"}),sn.filter(t=>!t.soEdit||a).map(t=>e.jsxs(Xs,{to:t.vista==="config"?`${W}/config`:ua(t.vista,s),end:t.fim,className:({isActive:r})=>V("flex items-center gap-1.5 whitespace-nowrap border-b-2 px-3 py-3 text-sm transition-colors",r?"border-primary font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:[e.jsx(t.icone,{className:"h-4 w-4"}),t.rotulo]},t.rotulo))]})})}const xn=()=>{const{canView:a,canEdit:s,loading:t}=et(As);return t?e.jsx(le,{}):a?e.jsx(Nt,{canEdit:s,carregando:e.jsx(le,{}),erro:(r,n)=>e.jsx(ue,{mensagem:r,onTentar:n}),children:e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx(tn,{}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsxs(Ks,{children:[e.jsx(ne,{index:!0,element:e.jsx(or,{})}),e.jsx(ne,{path:"proximos",element:e.jsx(ir,{})}),e.jsx(ne,{path:"trimestre",element:e.jsx(dr,{})}),e.jsx(ne,{path:"cobertura",element:e.jsx(an,{})}),e.jsx(ne,{path:"acoes/nova",element:e.jsx(ns,{})}),e.jsx(ne,{path:"acoes/:id",element:e.jsx(zr,{})}),e.jsx(ne,{path:"acoes/:id/editar",element:e.jsx(ns,{})}),e.jsx(ne,{path:"acoes/:id/convidados",element:e.jsx(Jr,{})}),e.jsx(ne,{path:"config",element:e.jsx(Gr,{})}),e.jsx(ne,{path:"*",element:e.jsx(Ws,{to:W,replace:!0})})]})})]})}):e.jsx(ve,{titulo:"Sem acesso",children:"Você não tem acesso ao Calendário de Marketing. Fale com um administrador."})};export{xn 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.