1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-react-BPk9u-w4.js","assets/index-J-3D7Fc9.css"])))=>i.map(i=>d[i]); 2import{j as e}from"./vendor-editor-BX0sR0z-.js";import{r as t,R as Vs,h as qs}from"./vendor-react-BPk9u-w4.js";import{toast as d}from"./vendor-sonner-DPZ7yCFm.js";import{l as k,N as J,u as ne,h as Ns,d as is,am as Gs}from"./index-FZUSOwo2.js";import{m as Fe,g as we,f as G,d as q,s as Te,D as de,u as ns,t as zs,v as _e,b as je,w as Ce,x as ys,y as Ks,z as Ys,M as Qs,r as Ye,B as us,F as ps,G as hs,H as Ws,J as Xs,K as ws,L as Hs,O as ls,Q as Js,T as Zs,U as et,V as Se,W as st,h as Ue,k as tt,i as _s,I as Me,N as Qe,R as Cs,X as at,Y as Ss,Z as ks,_ as Es,n as Ie,E as We,o as rt,$ as it,a0 as nt,A as Ve,q as lt,a1 as Ps,a2 as ot,a3 as ct,a4 as Xe,a5 as dt,a6 as xt,a7 as qe,a8 as mt,a9 as ut,aa as pt,ab as ht,ac as He,ad as ft,ae as Je,C as Ze,af as bt,ag as jt,ah as vt,e as gt,ai as Nt,aj as zt,ak as yt,P as wt,S as _t,a as Ct}from"./partnershipService-DRYyEwVe.js";import{ap as Ls,cp as As,a5 as Be,ep as os,cR as cs,av as ds,bo as T,aT as St,t as es,v as $e,ah as ss,X,a as kt,aq as ke,w as Et,a$ as Rs,x as Oe,a_ as Pt,s as ts,h as fs,eQ as Lt,ei as Ds,gz as Ms,y as oe,cm as At,d8 as Ee,eb as Ts,l as ve,aZ as Rt,gE as Dt,ed as Mt,dO as Tt,an as xs,cP as ms,aD as It,ae as as,n as $t,a7 as Ot,U as Ft,aX as Bt,K as Ut,bp as Vt,u as qt,aE as Gt,bm as Kt,fC as Yt,o as Qt,z as Wt,Y as Xt,i as Ht}from"./vendor-icons-D7M_7Je-.js";import{u as ge}from"./ConfirmProvider-DHQTVUCD.js";import{_ as Is}from"./vendor-graph-Df3mHyA7.js";import"./vendor-charts-Cf-ruFca.js";import"./vendor-ui-utils-Bbg69IUi.js";import"./vendor-supabase-UBwEW4nm.js";import"./vendor-helmet-C74EPpLp.js";import"./SocialLogos-BgxGK6Ep.js";import"./useEscapeKey-BwRSuhVP.js";import"./index-P8wGLujW.js";const Jt=["planned","in_production","awaiting_approval","approved"];function bs(s,r,i){return s!=null?Math.round(s):i?Math.round(r/i*100):0}const Zt=({partnership:s,balance:r,refresh:i})=>{const[f,o]=t.useState([]),[N,y]=t.useState(!0),[w,v]=t.useState(!1);t.useEffect(()=>{let a=!1;return(async()=>{try{const h=await Fe(s.portal_id,{partnershipId:s.id});a||o(h.filter(m=>Jt.includes(m.status)).slice(0,5))}catch(h){k.error("[Partnerships] overview deliveries error:",h),a||d.error("Erro ao carregar próximas entregas")}finally{a||y(!1)}})(),()=>{a=!0}},[s.id,s.portal_id]);const u=we(s.end_date),p=u!==null&&u<=60,j=r?bs(r.pct_executed_portal,r.executed_portal,r.contracted_portal):0,x=r?bs(r.pct_executed_partner,r.executed_partner,r.contracted_partner):0,_=(r==null?void 0:r.balance)??0,g=_>0?"text-emerald-600":_<0?"text-rose-600":"text-zinc-900",n=!!(s.coupon_code||s.commission_pct!=null||s.affiliate_url),l=n||s.partnership_type==="mista"||s.partnership_type==="comercial";return e.jsxs("div",{className:"space-y-6",children:[(p||s.is_regulated_content)&&e.jsxs("div",{className:"space-y-2",children:[p&&e.jsxs("div",{className:"flex items-start gap-2.5 p-3 bg-amber-50 border border-amber-200 rounded-lg text-[12px] text-amber-800",children:[e.jsx(Ls,{size:15,className:"shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("strong",{children:"Renovação próxima"})," â a vigência"," ",u!==null&&u<0?`terminou há ${Math.abs(u)} dias`:`termina em ${u} dias (${G(s.end_date)})`,". Avalie renovação ou encerramento formal."]})]}),s.is_regulated_content&&e.jsxs("div",{className:"flex items-start gap-2.5 p-3 bg-violet-50 border border-violet-200 rounded-lg text-[12px] text-violet-800",children:[e.jsx(As,{size:15,className:"shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("strong",{children:"Conteúdo regulado"})," â checklist de compliance obrigatório antes de cada publicação (saúde, financeiro, infância, bebidas etc)."]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Executado · Portal"}),e.jsxs("div",{className:"text-[18px] font-bold text-zinc-900 mb-1.5",children:[j,"%"]}),e.jsx("div",{className:"h-1.5 bg-zinc-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-500 rounded-full",style:{width:`${Math.min(100,j)}%`}})}),e.jsxs("div",{className:"text-[10px] text-zinc-400 mt-1.5",children:[q(r==null?void 0:r.executed_portal)," de"," ",q(r==null?void 0:r.contracted_portal)]})]}),e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f
20f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Executado · Parceiro"}),e.jsxs("div",{className:"text-[18px] font-bold text-zinc-900 mb-1.5",children:[x,"%"]}),e.jsx("div",{className:"h-1.5 bg-zinc-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-violet-500 rounded-full",style:{width:`${Math.min(100,x)}%`}})}),e.jsxs("div",{className:"text-[10px] text-zinc-400 mt-1.5",children:[q(r==null?void 0:r.executed_partner)," de"," ",q(r==null?void 0:r.contracted_partner)]})]}),e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Saldo"}),e.jsx("div",{className:`text-[18px] font-bold ${g}`,children:q(r==null?void 0:r.balance)}),e.jsx("div",{className:"text-[10px] text-zinc-400 mt-1.5",children:"executado portal â parceiro (referencial)"})]}),e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Pendências"}),e.jsxs("div",{className:"text-[12px] text-zinc-700 space-y-0.5 mt-1",children:[e.jsxs("div",{children:["Portal: ",e.jsx("strong",{children:q(r==null?void 0:r.pending_portal)})]}),e.jsxs("div",{children:["Parceiro: ",e.jsx("strong",{children:q(r==null?void 0:r.pending_partner)})]})]})]})]}),l&&e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 gap-2",children:[e.jsxs("h2",{className:"text-[14px] font-semibold text-zinc-800 flex items-center gap-2",children:[e.jsx(Be,{size:14})," Cupom e comissão"]}),e.jsxs("button",{onClick:()=>v(!0),className:"px-2.5 py-1 border border-zinc-200 text-zinc-600 rounded-md text-[11px] font-semibold hover:bg-zinc-50 flex items-center gap-1.5",children:[e.jsx(os,{size:12})," ",n?"Editar":"Cadastrar cupom"]})]}),n?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Cupom"}),s.coupon_code?e.jsx(js,{value:s.coupon_code,label:"Cupom copiado",className:"text-[15px] font-bold tracking-wide text-zinc-900 font-mono"}):e.jsx("div",{className:"text-[13px] text-zinc-400",children:"â"})]}),e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Desconto ao leitor"}),e.jsx("div",{className:"text-[18px] font-bold text-zinc-900",children:Te(s.discount_pct)}),e.jsx("div",{className:"text-[10px] text-zinc-400 mt-1",children:"benefÃcio da audiência, não é receita"})]}),e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Comissão do portal"}),e.jsx("div",{className:"text-[18px] font-bold text-emerald-600",children:Te(s.commission_pct)}),e.jsx("div",{className:"text-[10px] text-zinc-400 mt-1",children:"sobre as vendas com o cupom"})]}),e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Link de afiliado"}),s.affiliate_url?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{value:s.affiliate_url,label:"Link copiado",className:"text-[12px] text-zinc-700 truncate"}),e.jsx("a",{href:s.affiliate_url,target:"_blank",rel:"noopener noreferrer",className:"text-zinc-400 hover:text-zinc-700 shrink-0",title:"Abrir link",children:e.jsx(cs,{size:13})})]}):e.jsx("div",{className:"text-[13px] text-zinc-400",children:"â"})]})]}):e.jsx("p",{className:"text-[12px] text-zinc-400",children:"Sem cupom cadastrado. Use este bloco quando a parceria tiver código de afiliado com comissão sobre as vendas â a apuração fica na aba Financeiro."})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("section",{children:[e.jsxs("h2",{className:"text-[14px] font-semibold text-zinc-800 mb
2-3 flex items-center gap-2",children:[e.jsx(ds,{size:14})," Próximas entregas"]}),N?e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-zinc-400",children:[e.jsx(T,{size:13,className:"animate-spin"})," Carregandoâ¦"]}):f.length===0?e.jsx("p",{className:"text-[12px] text-zinc-400",children:"Nenhuma entrega aberta."}):e.jsx("div",{className:"space-y-1.5",children:f.map(a=>{const h=de[a.status],m=a.due_date&&we(a.due_date)!==null&&we(a.due_date)<0;return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 border border-zinc-100 rounded-md",children:[e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold shrink-0",style:{background:a.side==="portal"?"#eff6ff":"#f5f3ff",color:a.side==="portal"?"#3b82f6":"#8b5cf6"},children:a.side==="portal"?"Portal":"Parceiro"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] text-zinc-800 font-medium truncate",children:a.title}),e.jsxs("div",{className:"text-[11px] text-zinc-400",children:[e.jsx("span",{style:{color:h.color},children:h.label}),a.due_date&&e.jsxs("span",{className:m?"text-rose-600 font-semibold":"",children:[" ⢠",G(a.due_date)]})]})]})]},a.id)})})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-[14px] font-semibold text-zinc-800 mb-3 flex items-center gap-2",children:[e.jsx(St,{size:14})," Objetivo"]}),s.objective||s.description?e.jsxs("div",{className:"space-y-2 text-[13px] text-zinc-700",children:[s.objective&&e.jsx("p",{className:"font-medium",children:s.objective}),s.description&&e.jsx("p",{className:"text-zinc-500 whitespace-pre-line",children:s.description})]}):e.jsx("p",{className:"text-[12px] text-zinc-400",children:"Sem objetivo/descrição cadastrados."})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-[14px] font-semibold text-zinc-800 mb-3 flex items-center gap-2",children:[e.jsx(es,{size:14})," Regras contratuais"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:[{label:"SLA de aprovação",value:`${s.approval_sla_days} dias úteis`},{label:"Aprovação tácita",value:s.tacit_approval_enabled?"Ativada":"Desativada",highlight:s.tacit_approval_enabled},{label:"Aviso prévio",value:`${s.notice_period_days} dias`},{label:"Prazo de cura",value:`${s.cure_period_days} dias`},{label:"Confidencialidade",value:`${s.confidentiality_days} dias`},{label:"Canal formal",value:s.formal_channel||"â"}].map((a,h)=>e.jsxs("div",{style:{padding:"10px 12px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-0.5",children:a.label}),e.jsx("div",{className:`text-[12px] font-semibold ${a.highlight?"text-emerald-600":"text-zinc-800"}`,children:a.value})]},h))})]}),w&&e.jsx(ea,{partnership:s,onClose:()=>v(!1),onSaved:async()=>{v(!1),await i()}})]})},js=({value:s,label:r,className:i})=>{const[f,o]=t.useState(!1),N=async()=>{try{await navigator.clipboard.writeText(s),o(!0),d.success(r),setTimeout(()=>o(!1),1800)}catch(y){k.error("[Partnerships] copy error:",y),d.error("Não foi possÃvel copiar")}};return e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:`min-w-0 ${i??""}`,children:s}),e.jsx("button",{onClick:N,className:"text-zinc-400 hover:text-zinc-700 shrink-0",title:"Copiar",children:f?e.jsx($e,{size:13,className:"text-emerald-600"}):e.jsx(ss,{size:13})})]})},Le="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",Ae="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1",ea=({partnership:s,onClose:r,onSaved:i})=>{const[f,o]=t.useState(s.coupon_code??""),[N,y]=t.useState(s.discount_pct!=null?String(s.discount_pct):""),[w,v]=t.useState(s.commission_pct!=null?String(s.commission_pct):""),[u,p]=t.useState(s.affiliate_url??""),[j,x]=t.useState(!1),_=n=>{const l=n.trim().replace(",",".");if(!l)return null;const a=Number(l);return Number.isNaN(a)?null:a},g=async()=>{for(const[n,l]of[[N,"desconto"],[w,"comissão"]]){const a=n.trim();if(!a)continue;const h=_(a);if(h===null||h<0||h>100){d.error(`Percentual de ${l} inválido (0 a 100)`);return}}x(!0);try{await ns({...s,coupon_code:f.trim().toUpperCase()||null,discount_pct:_(N),commission_pct:_(w),affiliate_url:u.trim()||null}),d.success("Cupom atualizado"),await i()}catch(n){k.error("[Partnerships] save coupon error:",n),d.error("Erro ao salvar cupom")}finally{x(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-lg w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-[15px] font-semibold text-zinc-900 flex items-center gap-2",children:[e.jsx(Be,{size:15})," Cupom e comissão"]}),e.jsx("button",{onClick:r,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsx("p",{className:"text-[12px] text-zinc-500 mb-4",children:"Código que o portal divulga para a audiência. O desconto é o benefÃcio do leitor; a comissão é o que o parceiro repassa ao portal sobre as vendas feitas com o cupom."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:Ae,children:"Código do cupom"}),e.jsx("input",{value:f,onChange:n=>o(n.target.value),className:`${Le} font-mono uppercase`,placeholder:"Ex.: BARUERI10"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ae,children:"Desconto ao leitor (%)"}),e.jsx("input",{type:"number",min:"0",max:"100",step:"0.01",value:N,onChange:n=>y(n.target.value),className:Le,placeholder:"10"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ae,children:"Comissão do portal (%)"}),e.jsx("input",{type:"number",min:"0",max:"100",step:"0.01",value:w,onChange:n=>v(n.target.value),className:Le,placeholder:"5"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:Ae,children:"Link de afiliado (opcional)"}),e.jsx("input",{value:u,onChange:n=>p(n.target.value),className:Le,placeholder:"https://parceiro.com.br/?cupom=BARUERI10"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:r,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:g,disabled:j,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[j&&e.jsx(T,{size:13,className:"animate-spin"}),"Salvar"]})]})]})})})},Ne=["draft","legal_review","pending_signature","signed"],Ge="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1",vs="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",sa=({partnership:s,refresh:r})=>{const{user:i}=ne(),f=ge(),[o,N]=t.useState([]),[y,w]=t.useState(!0),[v,u]=t.useState(null),[p,j]=t.useState(null),[x,_]=t.useState(!1),[g,n]=t.useState(!1),[l,a]=t.useState(!1),h=t.useCallback(async()=>{try{const z=(await zs(s.id)).filter(I=>I.kind==="contract"||I.kind==="amendment");N(z);const R=z.find(I=>I.kind==="contract")??z[0]??null;u(I=>I??R)}catch(C){k.error("[Partnerships] load contract docs error:",C),d.error("Erro ao carregar contrato")}finally{w(!1)}},[s.id]);t.useEffect(()=>{h()}
2,[h]),t.useEffect(()=>{let C=!0;if(!(v!=null&&v.storage_path)){j(null);return}return _(!0),_e(v.storage_path,600).then(z=>{C&&j(z)}).finally(()=>{C&&_(!1)}),()=>{C=!1}},[v]);const m=Ne.indexOf(s.status_legal),c=async C=>{const z=je[C],R=C==="signed"?` 3 4O documento de contrato mais recente também será marcado como assinado hoje.`:"";if(await f({title:"Avançar status jurÃdico",message:`Avançar o status jurÃdico para "${z.label}"?${R}`,confirmLabel:"Avançar",variant:"info"})){a(!0);try{if(await ns({...s,status_legal:C}),C==="signed"){const I=o.find(O=>O.kind==="contract");I&&!I.signed_at&&await Ns.from("partnership_documents").update({signed_at:new Date().toISOString()}).eq("id",I.id)}d.success(`Status jurÃdico: ${z.label}`),await Promise.all([h(),r()])}catch(I){k.error("[Partnerships] legal status error:",I),d.error("Erro ao atualizar status jurÃdico")}finally{a(!1)}}},$=t.useMemo(()=>["Partes, CNPJs e representantes corretos","Vigência e datas batem com o cadastro da parceria","Plano comercial (Anexo I) reflete os itens e valores do plano cadastrado",`Prazo de aprovação (${s.approval_sla_days} dias úteis) e aprovação tácita ${s.tacit_approval_enabled?"prevista":"NÃO prevista"}`,"Cláusulas de comprovação, compensação e rescisão revisadas",s.is_regulated_content?"Conteúdo regulado (saúde/estética): responsabilidade do parceiro pelas alegações (cl. 38ªâ40ª)":null].filter(Boolean),[s]);return y?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"border border-zinc-100 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2 mb-3",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-zinc-800",children:"Fluxo de revisão e assinatura"}),m>=0&&m<Ne.length-1&&e.jsxs("button",{onClick:()=>c(Ne[m+1]),disabled:l,className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 flex items-center gap-1.5 disabled:opacity-50",children:[l?e.jsx(T,{size:12,className:"animate-spin"}):e.jsx(kt,{size:13}),"Avançar p/ ",je[Ne[m+1]].label]})]}),e.jsxs("div",{className:"flex items-center gap-0 flex-wrap",children:[Ne.map((C,z)=>{const R=je[C],I=m>z||s.status_legal==="signed"&&C==="signed",O=m===z;return e.jsxs(Vs.Fragment,{children:[z>0&&e.jsx("div",{className:`h-px w-6 ${m>=z?"bg-emerald-400":"bg-zinc-200"}`}),e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-semibold",style:O||I?{background:R.bg,color:R.color}:{background:"#fafafa",color:"#a1a1aa"},children:[I?e.jsx(ke,{size:12}):e.jsx(R.icon,{size:12}),R.label]})]},C)}),m===-1&&e.jsxs("span",{className:"ml-3 text-[11px] text-zinc-500",children:["Status atual:"," ",e.jsx("b",{style:{color:je[s.status_legal].color},children:je[s.status_legal].label})," ","(fora do fluxo padrão â ajuste pelo chip no topo da página)"]})]}),(s.status_legal==="draft"||s.status_legal==="legal_review")&&e.jsxs("div",{className:"mt-4 bg-amber-50/60 border border-amber-100 rounded-lg p-3",children:[e.jsx("p",{className:"text-[11px] font-semibold text-amber-800 uppercase tracking-wider mb-1.5",children:"Checklist de revisão"}),e.jsx("ul",{className:"space-y-1",children:$.map((C,z)=>e.jsxs("li",{className:"text-[12px] text-amber-900 flex gap-1.5",children:[e.jsx("span",{className:"text-amber-400",children:"â¢"})," ",C]},z))})]})]}),e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("h3",{className:"text-[13px] font-semibold text-zinc-800",children:["Contrato e aditivos (",o.length,")"]}),e.jsxs("button",{onClick:()=>n(!0),className:"px-3 py-1.5 border border-zinc-200 text-zinc-700 rounded-md text-[12px] font-semibold hover:bg-zinc-50 flex items-center gap-1.5",children:[e.jsx(Et,{size:13})," Enviar contrato/aditivo"]})]}),o.length===0?e.jsxs("div",{className:"flex flex-col items-center py-12 text-zinc-400 border border-dashed border-zinc-200 rounded-xl",children:[e.jsx(Rs,{size:32,className:"text-zinc-300"}),e.jsx("p",{className:"mt-2 text-[13px]",children:"Nenhum contrato anexado ainda."}),e.jsx("p",{className:"text-[11px]",children:"Envie o PDF do contrato para revisá-lo aqui dentro."})]}):e.jsxs("div",{className:"grid lg:grid-cols-[280px_1fr] gap-4",children:[e.jsx("div",{className:"space-y-1.5",children:o.map(C=>e.jsxs("button",{onClick:()=>u(C),className:`w-full text-left p-3 rounded-lg border transition-colors ${(v==null?void 0:v.id)===C.id?"border-zinc-900 bg-zinc-50":"border-zinc-100 hover:border-zinc-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{size:14,className:"text-zinc-400 shrink-0"}),e.jsx("span",{className:"text-[12px] font-medium text-zinc-800 truncate",children:C.title})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-[10px] text-zinc-400",children:[e.jsxs("span",{children:[C.kind==="contract"?"Contrato":"Aditivo"," ⢠v",C.version]}),C.signed_at?e.jsxs("span",{className:"text-emerald-600 font-semibold",children:["Assinado ",G(C.signed_at)]}):e.jsxs("span",{children:["enviado ",G(C.created_at)]})]})]},C.id))}),e.jsx("div",{className:"border border-zinc-100 rounded-xl overflow-hidden min-h-[480px] bg-zinc-50 flex flex-col",children:x?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):p?e.jsx("iframe",{title:(v==null?void 0:v.title)||"Contrato",src:p,className:"flex-1 w-full min-h-[480px]"}):e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-zinc-400",children:[e.jsx(Oe,{size:28,className:"text-zinc-300"}),e.jsx("p",{className:"mt-2 text-[12px]",children:v?"Documento sem arquivo anexado.":"Selecione um documento para visualizar."})]})})]}),g&&e.jsx(ta,{partnership:s,uploadedBy:(i==null?void 0:i.id)??null,existingContract:o.some(C=>C.kind==="contract"),onClose:()=>n(!1),onSaved:async()=>{n(!1),u(null),await h(),await r()}})]})},ta=({partnership:s,uploadedBy:r,existingContract:i,onClose:f,onSaved:o})=>{const[N,y]=t.useState(i?"amendment":"contract"),[w,v]=t.useState(""),[u,p]=t.useState(null),[j,x]=t.useState(!1),_=async()=>
4{if(!u){d.error("Selecione o PDF do contrato");return}x(!0);try{const g=await Ce(s.portal_id,s.id,N,u);await ys({partnership_id:s.id,portal_id:s.portal_id,kind:N,title:w.trim()||(N==="contract"?"Contrato de parceria":"Termo aditivo"),storage_path:g,uploaded_by:r}),d.success("Documento enviado â disponÃvel para revisão."),await o()}catch(g){k.error("[Partnerships] upload contract error:",g),d.error("Erro ao enviar contrato")}finally{x(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-md w-full p-6 no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:"Enviar contrato/aditivo"}),e.jsx("button",{onClick:f,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ge,children:"Tipo"}),e.jsxs("select",{value:N,onChange:g=>y(g.target.value),className:vs,children:[e.jsx("option",{value:"contract",children:"Contrato"}),e.jsx("option",{value:"amendment",children:"Termo aditivo"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,children:"TÃtulo"}),e.jsx("input",{value:w,onChange:g=>v(g.target.value),className:vs,placeholder:N==="contract"?"Contrato de parceria":"Termo aditivo"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,children:"Arquivo (PDF) *"}),e.jsx("input",{type:"file",accept:"application/pdf",onChange:g=>{var n;return p(((n=g.target.files)==null?void 0:n[0])??null)},className:"w-full text-[12px] text-zinc-600 file:mr-3 file:px-3 file:py-1.5 file:rounded-md file:border-0 file:bg-zinc-100 file:text-zinc-700 file:text-[12px] file:font-semibold hover:file:bg-zinc-200"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:f,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:_,disabled:j,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[j&&e.jsx(T,{size:13,className:"animate-spin"}),"Enviar"]})]})]})})})},aa=14,ra=864e5;function ia(s,r=new Date){if(!s)return{state:"none",days:null};const i=new Date(s).getTime();if(Number.isNaN(i))return{state:"none",days:null};const f=i-r.getTime(),o=Math.ceil(f/ra);return f<=0?{state:"expired",days:o}:o<=aa?{state:"expiring",days:o}:{state:"valid",days:o}}const me="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",ue="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1",na=({partnership:s,refresh:r})=>{const{user:i}=ne(),{currentPortal:f}=is(),o=ge(),[N,y]=t.useState([]),[w,v]=t.useState(!0),[u,p]=t.useState(!1),[j,x]=t.useState(null),[_,g]=t.useState(null),[n,l]=t.useState(null),[a,h]=t.useState(null),[m,c]=t.useState(null),[$,C]=t.useState(!1),[z,R]=t.useState(!1),[I,O]=t.useState(""),[B,Y]=t.useState(null),[se,L]=t.useState(!1),D=t.useCallback(async()=>{try{const[b,M]=await Promise.all([Ks(s.id),Ys(s.id)]);y(b),h(M.find(K=>!K.revoked_at)??null)}catch(b){k.error("[Partnerships] load materials error:",b),d.error("Erro ao carregar materiais")}finally{v(!1)}},[s.id]);t.useEffect(()=>{D()},[D]);const E=t.useMemo(()=>ia(a==null?void 0:a.expires_at),[a]),F=t.useMemo(()=>({pending:N.filter(b=>b.status==="pending"||b.status==="rejected").length,received:N.filter(b=>b.status==="received").length,approved:N.filter(b=>b.status==="approved").length}),[N]),Q=async()=>{p(!0);try{const b=await ws(s.id),M=b.find(le=>le.status==="active")??b[0];if(!M){d.error("A parceria ainda não tem plano comercial.");return}const K=await Hs(s,M.id);d.success(K>0?`${K} materiais adicionados ao checklist.`:"Nenhum material novo â o checklist já cobre o plano."),await D()}catch(b){k.error("[Partnerships] generate materials error:",b),d.error("Erro ao gerar checklist")}finally{p(!1)}},ae=async b=>{p(!0);try{const M=await Se(s.id),{generateMaterialsBriefPdf:K,fetchLogoDataUrl:le}=await Is(async()=>{const{generateMaterialsBriefPdf:Bs,fetchLogoDataUrl:Us}=await import("./partnershipMaterialsBriefPdf-BffPUrJv.js");return{generateMaterialsBriefPdf:Bs,fetchLogoDataUrl:Us}},__vite__mapDeps([0,1])),Os=(f==null?void 0:f.portalLogoUrl)??(f==null?void 0:f.logoUrl)??null,Fs=await le(Os);await K({partnership:s,requests:N,contacts:M,portalName:f==null?void 0:f.name,portalUrl:b,logoDataUrl:Fs}),d.success("Briefing gerado â pronto para enviar ao cliente.")}catch(M){k.error("[Partnerships] brief pdf error:",M),d.error("Erro ao gerar briefing")}finally{p(!1)}},xe=async()=>
4{if(m){await ae(m);return}if(a){p(!0);try{const K=await us(s.id);if(K){const le=ps(K);c(le),await ae(le);return}}catch(K){k.error("[Partnerships] get active link token error:",K)}finally{p(!1)}R(!0);return}const b=await o({title:"Incluir link do cliente no PDF?",message:`Gerar o link exclusivo do cliente para incluir no PDF (com QR code)? 5 6"Gerar sem link" = criar o PDF sem o link.`,confirmLabel:"Gerar com link",cancelLabel:"Gerar sem link",variant:"info"});let M=null;if(b){p(!0);try{const{url:K}=await hs(s,(i==null?void 0:i.id)??null);M=K,c(K),await D()}catch(K){k.error("[Partnerships] create share link error:",K),d.error("Erro ao gerar link"),p(!1);return}}await ae(M)},A=async()=>{if(!(!a||!I.trim())){L(!0),Y(null);try{const b=await Zs(I,a.token_hash);if(!b){Y("Este não é o link ativo desta parceria. Confira se copiou o link mais recente enviado ao cliente â links antigos (revogados) não conferem.");return}try{await et(a.id,b.token)}catch(M){k.error("[Partnerships] attach link token error:",M)}c(b.url),R(!1),O(""),await ae(b.url)}finally{L(!1)}}},S=async(b,M)=>{try{await ls({...b,status:M,reviewed_by:M==="approved"||M==="rejected"?(i==null?void 0:i.id)??null:b.reviewed_by}),await D()}catch(K){k.error("[Partnerships] material status error:",K),d.error("Erro ao atualizar material")}},V=async b=>{if(await o({title:"Remover material",message:`Remover "${b.title}" do checklist?`,confirmLabel:"Remover"}))try{await Js(b.id),await D()}catch(M){k.error("[Partnerships] delete material error:",M),d.error("Erro ao remover material")}},H=async b=>{if(b.storage_path){l(b.id);try{const M=await _e(b.storage_path);M?window.open(M,"_blank","noopener"):d.error("Não foi possÃvel gerar o link do arquivo")}finally{l(null)}}},re=async()=>{if(a&&await o({title:"Prorrogar validade do link",message:"A validade é recalculada pelo fim da vigência da parceria (+30 dias). O link do cliente NÃO muda â quem já tem a URL continua usando a mesma.",confirmLabel:"Prorrogar",variant:"info"})){C(!0);try{const b=await Ws(a.id);await D(),d.success(`Link válido até ${G(b)}`)}catch(b){k.error("[Partnerships] extend share link error:",b),d.error("Erro ao prorrogar o link")}finally{C(!1)}}},ee=async()=>{if(await o({title:a?"Gerar novo link":"Gerar link do cliente",message:a?"Gerar um NOVO link revoga o link atual do cliente (ele para de funcionar). Continuar?":"Gerar link público do cliente? Quem tiver o link poderá ver o checklist e enviar materiais (sem login). O link tem validade: por padrão, 30 dias após o fim da vigência da parceria.",confirmLabel:"Gerar link",variant:a?"warning":"info"})){C(!0);try{const{url:M}=await hs(s,(i==null?void 0:i.id)??null);c(M),await D(),d.success("Link gerado â copie agora, ele não será exibido novamente.")}catch(M){k.error("[Partnerships] create share link error:",M),d.error("Erro ao gerar link")}finally{C(!1)}}},ce=async()=>{if(a){C(!0);try{const b=await us(s.id);if(!b){d.info("Este link foi criado antes do cofre de links. Cole-o uma vez ao gerar o briefing PDF (será memorizado) ou gere um novo link.");return}const M=ps(b);c(M),await U(M),E.state==="expired"&&d.warning('Atenção: este link está EXPIRADO. Use "Prorrogar" antes de enviar ao cliente.')}catch(b){k.error("[Partnerships] show link error:",b),d.error("Erro ao recuperar o link")}finally{C(!1)}}},P=async()=>{if(a&&await o({title:"Revogar link",message:"Revogar o link do cliente? Ele deixará de funcionar imediatamente.",confirmLabel:"Revogar link"})){C(!0);try{await Xs(a.id),c(null),await D(),d.success("Link revogado")}catch(b){k.error("[Partnerships] revoke share link error:",b),d.error("Erro ao revogar link")}finally{C(!1)}}},U=async b=>{try{await navigator.clipboard.writeText(b),d.success("Link copiado")}catch{d.error("Não foi possÃvel copiar â selecione e copie manualmente")}};return w?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"border border-emerald-100 bg-emerald-50/40 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{size:15,className:"text-emerald-600"}),e.jsx("span",{className:"text-[13px] font-semibold text-zinc-800",children:"Portal do cliente"}),a?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 text-[10px] font-semibold",children:["Link ativo · ",a.access_count," acesso(s)",a.last_accessed_at?` · último ${G(a.last_accessed_at)}`:""]}),e.jsxs("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-semibold flex items-center gap-1 ${E.state==="expired"?"bg-rose-100 text-rose-700":E.state==="expiring"||E.state==="none"?"bg-amber-100 text-amber-700":"bg-zinc-100 text-zinc-600"}`,children:[e.jsx(ts,{size:10}),E.state==="expired"?`Expirado em ${G(a.expires_at)}`:E.state==="expiring"?`Expira em ${E.days} dia(s)`:E.state==="none"?"Sem validade":`Válido até ${G(a.expires_at)}`]})]}):e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-zinc-100 text-zinc-500 text-[10px] font-semibold",children:"Sem link ativo"})]}),e.jsxs("div",{className:"flex gap-2",children:[a&&!m&&e.jsxs("button",{onClick:ce,disabled:$,className:"px-3 py-1.5 border border-zinc-200 text-zinc-700 rounded-md text-[12px] font-semibold hover:bg-zinc-50 flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(ss,{size:13})," Copiar link"]}),e.jsxs("button",{onClick:ee,disabled:$,className:"px-3 py-1.5 bg-emerald-600 text-white rounded-md text-[12px] font-semibold hover:bg-emerald-700 flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(fs,{size:13})," ",a?"Gerar novo link":"Gerar link do cliente"]}),a&&e.jsxs("button",{onClick:re,disabled:$,title:"Estende a validade mantendo a mesma URL do cliente",className:`px-3 py-1.5 rounded-md text-[12px] font-semibold flex items-center gap-1.5 disabled:opacity-50 ${E.state==="valid"?"border border-zinc-200 text-zinc-700 hover:bg-zinc-50":"border border-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100"}`,children:[e.jsx(ts,{size:13})," ",E.state==="none"?"Definir validade":"Prorrogar"]}),a&&e.jsxs("button",{onClick:P,disabled:$,className:"px-3 py-1.5 border border-rose-200 text-rose-600 rounded-md text-[12px] font-semibold hover:bg-rose-50 flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(Lt,{size:13})," Revogar"]})]})]}),e.jsxs("p",{className:"mt-1.5 text-[11px] text-zinc-500",children:["O parceiro acessa o checklist e envia arquivos/respostas pelo link â sem login. A equipe pode copiar o link ativo a qualquer momento (fica guardado criptografado no banco). Como o link é a própria credencial, ele tem validade: por padrão vale até 30 dias após o fim da vigência. ",e.jsx("b",{children:"Prorrogar"})," estende o prazo mantendo a mesma URL; ",e.jsx("b",{children:"gerar novo link"}
6)," ","invalida o atual e exige reenviar ao cliente."]}),m&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 bg-white border border-emerald-200 rounded-lg p-2.5",children:[e.jsx("code",{className:"flex-1 text-[11px] text-zinc-700 break-all",children:m}),e.jsxs("button",{onClick:()=>U(m),className:"shrink-0 px-2.5 py-1.5 bg-zinc-900 text-white rounded-md text-[11px] font-semibold hover:bg-zinc-800 flex items-center gap-1",children:[e.jsx(ss,{size:12})," Copiar"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-3 text-[12px] text-zinc-500",children:[e.jsxs("span",{children:[e.jsx("b",{className:"text-amber-600",children:F.pending})," aguardando"]}),e.jsxs("span",{children:[e.jsx("b",{className:"text-blue-600",children:F.received})," recebidos"]}),e.jsxs("span",{children:[e.jsx("b",{className:"text-emerald-600",children:F.approved})," aprovados"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("button",{onClick:Q,disabled:u,className:"px-3 py-1.5 border border-zinc-200 text-zinc-700 rounded-md text-[12px] font-semibold hover:bg-zinc-50 flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(Ds,{size:13})," Gerar a partir do plano"]}),e.jsxs("button",{onClick:xe,disabled:u||N.length===0,className:"px-3 py-1.5 border border-zinc-200 text-zinc-700 rounded-md text-[12px] font-semibold hover:bg-zinc-50 flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(Ms,{size:13})," Briefing (PDF)"]}),e.jsxs("button",{onClick:()=>x({}),className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 flex items-center gap-1.5",children:[e.jsx(oe,{size:13})," Novo material"]})]})]}),N.length===0?e.jsxs("div",{className:"flex flex-col items-center py-12 text-zinc-400",children:[e.jsx(At,{size:32,className:"text-zinc-300"}),e.jsx("p",{className:"mt-2 text-[13px]",children:"Nenhum material no checklist."}),e.jsx("p",{className:"text-[11px]",children:"Use âGerar a partir do planoâ para criar as peças (artes, logo, fotos, briefingâ¦)."})]}):e.jsx("div",{className:"space-y-1.5",children:N.map(b=>{const M=Qs[b.status],K=M.icon;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border border-zinc-100 rounded-lg flex-wrap",children:[e.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold shrink-0",style:{background:M.bg,color:M.color},children:[e.jsx(K,{size:11})," ",M.label]}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[13px] text-zinc-800 font-medium",children:b.title}),e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-zinc-100 text-zinc-600 text-[10px] font-semibold",children:Ye[b.material_type]})]}),b.specs&&e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5",children:b.specs}),b.client_response&&e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-700 bg-zinc-50 border border-zinc-100 rounded px-2 py-1 break-words",children:[e.jsx("span",{className:"text-zinc-400 font-semibold uppercase tracking-wide text-[9px]",children:"Resposta do parceiro"}),e.jsx("br",{}),b.client_response]}),e.jsxs("p",{className:"text-[10px] text-zinc-400 mt-0.5",children:["Prazo:"," ",G(b.due_date)==="â"?"a combinar":G(b.due_date),b.received_at?` ⢠recebido ${G(b.received_at)}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[b.storage_path&&e.jsxs("button",{onClick:()=>H(b),disabled:n===b.id,className:"text-[11px] text-blue-600 hover:underline flex items-center gap-1 disabled:opacity-50",children:[n===b.id?e.jsx(T,{size:12,className:"animate-spin"}):e.jsx(Ee,{size:12}),"Arquivo"]}),(b.status==="pending"||b.status==="rejected")&&e.jsx("button",{onClick:()=>g(b),className:"px-2 py-1 text-[11px] font-semibold text-blue-700 bg-blue-50 rounded hover:bg-blue-100",children:"Registrar recebimento"}),b.status==="received"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>S(b,"approved"),title:"Aprovar material",className:"p-1.5 text-emerald-600 bg-emerald-50 rounded hover:bg-emerald-100",children:e.jsx($e,{size:13})}),e.jsx("button",{onClick:()=>S(b,"rejected"),title:"Reprovar / pedir nova versão",className:"p-1.5 text-rose-600 bg-rose-50 rounded hover:bg-rose-100",children:e.jsx(Ts,{size:13})})]}),e.jsx("button",{onClick:()=>x(b),className:"text-[11px] text-zinc-500 hover:underline",children:"Editar"}),e.jsx("button",{onClick:()=>V(b),className:"p-1 text-zinc-400 hover:text-rose-600",title:"Remover",children:e.jsx(ve,{size:14})})]})]},b.id)})}),j&&e.jsx(la,{partnership:s,initial:j,onClose:()=>x(null),onSaved:async()=>{x(null),await D(),await r()}}),_&&e.jsx(oa,{partnership:s,request:_,onClose:()=>g(null),onSaved:async()=>{g(null),await D()}}),z&&a&&e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-lg w-full p-6 no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-[15px] font-semibold text-zinc-900 flex items-center gap-2",children:[e.jsx(fs,{size:15,className:"text-emerald-600"})," Incluir o link do cliente no PDF"]}),e.jsx("button",{onClick:()=>{R(!1),Y(null)},className:"p-1 text-zinc-400 hover:text-zinc-700 rounded","aria-label":"Fechar",children:e.jsx(X,{size:16})})]}),e.jsxs("p",{className:"text-[12.5px] text-zinc-600 leading-relaxed",children:["O link ativo desta parceria ",e.jsx("b",{children:"continua válido"})," e não será alterado â mas ele foi criado antes do cofre de links, então cole abaixo o link que você já enviou ao cliente. Depois disso ele fica memorizado e o sistema o recupera sozinho."]}),e.jsx("input",{value:I,onChange:b=>{O(b.target.value),Y(null)},onKeyDown:b=>{b.key==="Enter"&&A()},placeholder:"https://anuncie.seuportal.com.br/parceria/â¦",autoFocus:!0,className:`mt-3 ${me} font-mono ${B?"border-rose-400":""}`}),B&&e.jsx("p",{className:"mt-1.5 text-[11.5px] text-rose-600 font-medium",children:B}),e.jsx("p",{className:"mt-2 text-[11px] text-zinc-400",children:"Perdeu o link? Use âGerar novo linkâ no card acima â isso revoga o atual e mostra o novo uma única vez."}),e.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2 flex-wrap",children:[e.jsx("button",{onClick:()=>{R(!1),Y(null),ae(null)},disabled:se,className:"px-3 py-1.5 border border-zinc-200 text-zinc-600 rounded-md text-[12px] font-semibold hover:bg-zinc-50 disabled:opacity-50",children:"Gerar PDF sem link"}),e.jsxs("button",{onClick:A,disabled:se||!I.trim(),className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-1.5",children:[se?e.jsx(T,{size:12,className:"animate-spin"}):e.jsx($e,{size:13}),"Validar e gerar PDF"]})]})]})})})]})},la=({partnership:s,initial:r,onClose:i,onSaved:f})=>{const[o,N]=t.useState(r.title??""),[y,w]=t.useState(r.material_type??"arte"),[v,u]=t.useState(r.specs??""),[p,j]=t.useState(r.due_date??""),[x,_]=t.useState(r.notes??""),[g,n]=t.useState(!1),l=async()=>
6{if(!o.trim()){d.error("Informe o tÃtulo do material");return}n(!0);try{await ls({...r.id?r:{},partnership_id:s.id,portal_id:s.portal_id,title:o.trim(),material_type:y,specs:v.trim()||null,due_date:p||null,notes:x.trim()||null}),d.success("Material salvo"),await f()}catch(a){k.error("[Partnerships] save material error:",a),d.error("Erro ao salvar material")}finally{n(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-lg w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:r.id?"Editar material":"Novo material"}),e.jsx("button",{onClick:i,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"TÃtulo *"}),e.jsx("input",{value:o,onChange:a=>N(a.target.value),className:me,placeholder:"Ex.: Arte do banner 300Ã250"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Tipo"}),e.jsx("select",{value:y,onChange:a=>w(a.target.value),className:me,children:Object.keys(Ye).map(a=>e.jsx("option",{value:a,children:Ye[a]},a))})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Prazo"}),e.jsx("input",{type:"date",value:p??"",onChange:a=>j(a.target.value),className:me})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Especificações (vai no briefing do cliente)"}),e.jsx("textarea",{value:v,onChange:a=>u(a.target.value),rows:3,className:me,placeholder:"Dimensões, formato, peso máximo, observaçõesâ¦"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Observações internas"}),e.jsx("input",{value:x,onChange:a=>_(a.target.value),className:me})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:l,disabled:g,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[g&&e.jsx(T,{size:13,className:"animate-spin"}),"Salvar"]})]})]})})})},oa=({partnership:s,request:r,onClose:i,onSaved:f})=>{const[o,N]=t.useState(null),[y,w]=t.useState(""),[v,u]=t.useState(!1),p=async()=>{u(!0);try{let j=r.storage_path??null;o&&(j=await Ce(s.portal_id,s.id,"material",o)),await ls({...r,status:"received",storage_path:j,received_at:new Date().toISOString(),notes:y.trim()?`${r.notes?`${r.notes} | `:""}${y.trim()}`:r.notes}),d.success("Recebimento registrado"),await f()}catch(j){k.error("[Partnerships] receive material error:",j),d.error("Erro ao registrar recebimento")}finally{u(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-md w-full p-6 no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:"Registrar recebimento"}),e.jsx("button",{onClick:i,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsx("p",{className:"text-[12px] text-zinc-500 mb-3",children:r.title}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Arquivo recebido (opcional)"}),e.jsx("input",{type:"file",onChange:j=>{var x;return N(((x=j.target.files)==null?void 0:x[0])??null)},className:"w-full text-[12px] text-zinc-600 file:mr-3 file:px-3 file:py-1.5 file:rounded-md file:border-0 file:bg-zinc-100 file:text-zinc-700 file:text-[12px] file:font-semibold hover:file:bg-zinc-200"}),e.jsx("p",{className:"text-[10px] text-zinc-400 mt-1",children:"Se o material veio por e-mail/WhatsApp, anexe aqui para centralizar no bucket da parceria."})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Observação"}),e.jsx("input",{value:y,onChange:j=>w(j.target.value),className:me,placeholder:"Ex.: recebido por WhatsApp em 12/06"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:p,disabled:v,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[v&&e.jsx(T,{size:13,className:"animate-spin"}),"Confirmar"]})]})]})})})}
6,ca={initial:"Inicial",amendment:"Aditivo",renewal:"Renovação"},da={draft:{label:"Rascunho",cls:"bg-zinc-100 text-zinc-600"},active:{label:"Ativo",cls:"bg-emerald-50 text-emerald-600"},superseded:{label:"SubstituÃdo",cls:"bg-amber-50 text-amber-600"}},xa=({partnership:s,planId:r,item:i,onClose:f,onSaved:o})=>{var V,H,re,ee,ce;const[N,y]=t.useState((i==null?void 0:i.side)||"portal"),[w,v]=t.useState((i==null?void 0:i.item_type)||"sponsored_article"),[u,p]=t.useState((i==null?void 0:i.title)||""),[j,x]=t.useState((i==null?void 0:i.description)||""),[_,g]=t.useState((i==null?void 0:i.nature)||"one_shot"),[n,l]=t.useState(((V=i==null?void 0:i.quantity_total)==null?void 0:V.toString())||""),[a,h]=t.useState((i==null?void 0:i.recurrence_freq)||"monthly"),[m,c]=t.useState(((H=i==null?void 0:i.period_start)==null?void 0:H.slice(0,10))||""),[$,C]=t.useState(((re=i==null?void 0:i.period_end)==null?void 0:re.slice(0,10))||""),[z,R]=t.useState(((ee=i==null?void 0:i.unit_value)==null?void 0:ee.toString())||""),[I,O]=t.useState(((ce=i==null?void 0:i.total_value)==null?void 0:ce.toString())||""),[B,Y]=t.useState((i==null?void 0:i.proof_method)||""),[se,L]=t.useState((i==null?void 0:i.limitations)||""),[D,E]=t.useState((i==null?void 0:i.requires_partner_approval)??!1),[F,Q]=t.useState(!1),ae=t.useMemo(()=>{const P=new Map;return Object.keys(Me).forEach(U=>{const b=Me[U].group;P.set(b,[...P.get(b)||[],U])}),Array.from(P.entries())},[]),xe=async()=>{if(!u.trim()){d.error("Informe o tÃtulo do item");return}const P=b=>{const M=b.trim();if(M==="")return null;const K=M.includes(",")?M.replace(/\./g,"").replace(/,/g,"."):M,le=Number(K);return Number.isFinite(le)?le:null};if(z.trim()&&P(z)===null){d.error("Valor unitário inválido â use o formato 1.500,00");return}if(I.trim()&&P(I)===null){d.error("Valor total inválido â use o formato 1.500,00");return}const U=P(n);if(_!=="continuous"&&n.trim()&&(U===null||!Number.isInteger(U)||U<1)){d.error("Quantidade total deve ser um número inteiro maior que zero");return}Q(!0);try{const b={...i?{...i}:{plan_id:r,partnership_id:s.id,portal_id:s.portal_id},side:N,item_type:w,title:u.trim(),description:j.trim()||null,nature:_,quantity_total:P(n),recurrence_freq:_==="recurring"?a:null,period_start:m||null,period_end:$||null,unit_value:P(z),total_value:P(I)??(P(z)!==null&&U!==null?P(z)*U:null),proof_method:B.trim()||null,limitations:se.trim()||null,requires_partner_approval:D};await _s(b),d.success(i?"Item atualizado":"Item adicionado"),o()}catch(b){k.error("[Partnerships] save item error:",b),d.error("Erro ao salvar item")}finally{Q(!1)}},A="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",S="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1";return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:i?"Editar item do plano":"Adicionar item ao plano"}),e.jsx("button",{onClick:f,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:S,children:"Lado *"}),e.jsxs("select",{value:N,onChange:P=>y(P.target.value),className:A,children:[e.jsx("option",{value:"portal",children:"Portal (nós entregamos)"}),e.jsx("option",{value:"partner",children:"Parceiro (contrapartida)"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:S,children:"Tipo *"}),e.jsx("select",{value:w,onChange:P=>v(P.target.value),className:A,children:ae.map(([P,U])=>e.jsx("optgroup",{label:P,children:U.map(b=>e.jsx("option",{value:b,children:Me[b].label},b))},P))})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:S,children:"TÃtulo *"}),e.jsx("input",{value:u,onChange:P=>p(P.target.value),className:A,placeholder:"Ex.: 2 matérias patrocinadas por mês"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:S,children:"Descrição"}),e.jsx("textarea",{value:j,onChange:P=>x(P.target.value),rows:2,className:`${A} resize-none`})]}),e.jsxs("div",{children:[e.jsx("label",{className:S,children:"Natureza *"}
6),e.jsx("select",{value:_,onChange:P=>g(P.target.value),className:A,children:Object.keys(Qe).map(P=>e.jsx("option",{value:P,children:Qe[P]},P))})]}),_==="recurring"&&e.jsxs("div",{children:[e.jsx("label",{className:S,children:"Frequência"}),e.jsx("select",{value:a,onChange:P=>h(P.target.value),className:A,children:Object.entries(Cs).map(([P,U])=>e.jsx("option",{value:P,children:U},P))})]}),e.jsxs("div",{children:[e.jsx("label",{className:S,children:"Quantidade total"}),e.jsx("input",{type:"number",min:"0",value:n,onChange:P=>l(P.target.value),className:A})]}),e.jsxs("div",{children:[e.jsx("label",{className:S,children:"PerÃodo â inÃcio"}),e.jsx("input",{type:"date",value:m,onChange:P=>c(P.target.value),className:A})]}),e.jsxs("div",{children:[e.jsx("label",{className:S,children:"PerÃodo â fim"}),e.jsx("input",{type:"date",value:$,onChange:P=>C(P.target.value),className:A})]}),e.jsxs("div",{children:[e.jsx("label",{className:S,children:"Valor unitário (R$)"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:z,onChange:P=>R(P.target.value),className:A})]}),e.jsxs("div",{children:[e.jsx("label",{className:S,children:"Valor total (R$)"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:I,onChange:P=>O(P.target.value),className:A})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:S,children:"Método de comprovação"}),e.jsx("input",{value:B,onChange:P=>Y(P.target.value),className:A,placeholder:"Ex.: link da publicação + print de métricas"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:S,children:"Limitações"}),e.jsx("input",{value:se,onChange:P=>L(P.target.value),className:A,placeholder:"Ex.: não cumulativo, sujeito a pauta editorial"})]}),e.jsxs("label",{className:"col-span-2 flex items-center gap-2 text-[13px] text-zinc-700",children:[e.jsx("input",{type:"checkbox",checked:D,onChange:P=>E(P.target.checked)}),"Exige aprovação do parceiro antes de publicar"]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:f,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:xe,disabled:F,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[F&&e.jsx(T,{size:13,className:"animate-spin"}),"Salvar item"]})]})]})})})},ma=({partnership:s,refresh:r})=>{const{user:i}=ne(),f=ge(),[o,N]=t.useState([]),[y,w]=t.useState(null),[v,u]=t.useState([]),[p,j]=t.useState(!0),[x,_]=t.useState(!1),[g,n]=t.useState(null),[l,a]=t.useState(!1),[h,m]=t.useState(!1),c=t.useCallback(async L=>{try{const D=await ws(s.id);N(D),w(E=>{var F;return L&&D.some(Q=>Q.id===L)?L:E&&D.some(Q=>Q.id===E)?E:((F=D[0])==null?void 0:F.id)??null})}catch(D){k.error("[Partnerships] load plans error:",D),d.error("Erro ao carregar planos")}finally{j(!1)}},[s.id]);t.useEffect(()=>{c()},[c]);const $=t.useCallback(async()=>{if(!y){u([]);return}_(!0);try{u(await st(y))}catch(L){k.error("[Partnerships] load items error:",L),d.error("Erro ao carregar itens do plano")}finally{_(!1)}},[y]);t.useEffect(()=>{$()},[$]);const C=o.find(L=>L.id===y)??null,z=!!C&&C.status!=="superseded",R=t.useMemo(()=>{const L=v.filter(E=>E.side==="portal").reduce((E,F)=>E+(F.total_value??0),0),D=v.filter(E=>E.side==="partner").reduce((E,F)=>E+(F.total_value??0),0);return{portal:L,partner:D,delta:L-D}},[v]),I=async L=>{if(await f({title:"Remover item",message:`Remover o item "${L.title}" do plano?`,confirmLabel:"Remover"}))try{await at(L.id),d.success("Item removido"),await $()}catch(D){k.error("[Partnerships] delete item error:",D),d.error("Erro ao remover item")}},O=async()=>{if(C){a(!0);try{const L=await tt(C.id);d.success(`${L} entrega(s) gerada(s) a partir do plano`),await r()}catch(L){k.error("[Partnerships] generate deliveries error:",L),d.error("Erro ao gerar entregas")}finally{a(!1)}}},B=async()=>{try{const L=await Ue({partnership_id:s.id,portal_id:s.portal_id,version:1,kind:"initial",status:"active",effective_from:new Date().toISOString().slice(0,10),created_by:(i==null?void 0:i.id)??null});d.success("Plano inicial criado"),await c(L.id)}catch(L){k.error("[Partnerships] create initial plan error:",L),d.error("Erro ao criar plano")}},Y=async()=>
6{if(C&&await f({title:"Criar aditivo",message:"Os itens do plano atual serão COPIADOS para a nova versão (edite o que mudou); o plano atual será marcado como substituÃdo.",confirmLabel:"Criar aditivo",variant:"warning"})){m(!0);try{const L=Math.max(...o.map(F=>F.version)),D=await Ue({partnership_id:s.id,portal_id:s.portal_id,version:L+1,kind:"amendment",status:"active",total_value_portal:C.total_value_portal,total_value_partner:C.total_value_partner,effective_from:new Date().toISOString().slice(0,10),created_by:(i==null?void 0:i.id)??null}),E=v.filter(F=>F.plan_id===C.id);for(const F of E){const{id:Q,created_at:ae,updated_at:xe,...A}=F;await _s({...A,plan_id:D.id})}for(const F of o.filter(Q=>Q.status==="active"&&Q.id!==D.id))await Ue({...F,status:"superseded"});d.success(`Aditivo v${D.version} criado com ${E.length} item${E.length===1?"":"s"} copiado${E.length===1?"":"s"}`),await c(D.id),await r()}catch(L){k.error("[Partnerships] create amendment error:",L),d.error("Erro ao criar aditivo")}finally{m(!1)}}};if(p)return e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})});if(o.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-14 text-zinc-500",children:[e.jsx(Rt,{size:36,className:"text-zinc-300"}),e.jsx("p",{className:"mt-3 text-[13px]",children:"Nenhum plano comercial cadastrado."}),e.jsxs("button",{onClick:B,className:"mt-4 px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 flex items-center gap-1.5",children:[e.jsx(oe,{size:13})," Criar plano inicial"]})]});const se=L=>{const D=v.filter(E=>E.side===L);return e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("h3",{className:"text-[13px] font-semibold text-zinc-800",children:[L==="portal"?"Lado Portal (nós entregamos)":"Lado Parceiro (contrapartida)",e.jsxs("span",{className:"text-[11px] text-zinc-400 font-normal ml-1.5",children:["(",D.length,")"]})]}),e.jsxs("span",{className:"text-[12px] font-bold text-zinc-700",children:["Σ ",q(L==="portal"?R.portal:R.partner)]})]}),D.length===0?e.jsx("p",{className:"text-[12px] text-zinc-400 py-3",children:"Nenhum item deste lado."}):e.jsx("div",{className:"space-y-1.5",children:D.map(E=>{const F=Me[E.item_type],Q=F.icon;return e.jsxs("div",{className:"flex items-start gap-3 p-2.5 border border-zinc-100 rounded-md",children:[e.jsx(Q,{size:15,className:"text-zinc-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] text-zinc-800 font-medium",children:E.title}),e.jsxs("div",{className:"text-[11px] text-zinc-400",children:[F.label," ⢠",Qe[E.nature],E.nature==="recurring"&&E.recurrence_freq&&` (${Cs[E.recurrence_freq]})`,E.quantity_total!=null&&` ⢠${E.quantity_total}Ã`]}),e.jsxs("div",{className:"text-[11px] text-zinc-500 mt-0.5",children:[E.unit_value!=null&&e.jsxs(e.Fragment,{children:["unit. ",q(E.unit_value)," ⢠"]}),"total ",e.jsx("strong",{children:q(E.total_value)})]}),E.proof_method&&e.jsxs("div",{className:"text-[11px] text-zinc-400 mt-0.5 italic",children:["Comprovação: ",E.proof_method]})]}),z&&e.jsxs("div",{className:"flex gap-1 shrink-0",children:[e.jsx("button",{onClick:()=>n({item:E}),title:"Editar",className:"p-1 text-zinc-400 hover:text-zinc-700",children:e.jsx(os,{size:13})}),e.jsx("button",{onClick:()=>I(E),title:"Remover",className:"p-1 text-zinc-400 hover:text-rose-600",children:e.jsx(ve,{size:13})})]})]},E.id)})})]})};return e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:o.map(L=>{const D=da[L.status];return e.jsxs("button",{onClick:()=>w(L.id),className:`flex items-center gap-2 px-3 py-1.5 rounded-md border text-[12px] font-semibold transition-colors ${L.id===y?"border-zinc-900 text-zinc-900 bg-zinc-50":"border-zinc-200 text-zinc-500 hover:bg-zinc-50"}`,children:["v",L.version," · ",ca[L.kind],e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D.cls}`,children:D.label})]},L.id)})}),C&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"text-[11px] text-zinc-500",children:[C.effective_from&&e.jsxs(e.Fragment,{children:["Vigente desde ",G(C.effective_from)," ⢠"]}),"Î equilÃbrio:"," ",e.jsx("strong",{className:R.delta===0?"text-emerald-600":"text-amber-600",children:q(R.delta)}),R.delta!==0&&" (portal â parceiro)"]}),z&&e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("button",{onClick:()=>n({item:null}),className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 flex items-center gap-1.5",children:[e.jsx(oe,{size:13})," Adicionar item"]}),e.jsxs("button",{onClick:O,disabled:l||v.length===0,className:"px-3 py-1.5 bg-white border border-zinc-200 text-zinc-700 rounded-md text-[12px] font-semibold hover:bg-zinc-50 disabled:opacity-50 flex items-center gap-1.5",children:[l?e.jsx(T,{size:13,className:"animate-spin"}):e.jsx(Ds,{size:13}),"Gerar entregas"]}),e.jsxs("button",{onClick:Y,disabled:h,className:"px-3 py-1.5 bg-white border border-zinc-200 text-zinc-700 rounded-md text-[12px] font-semibold hover:bg-zinc-50 disabled:opacity-50 flex items-center gap-1.5",children:[h?e.jsx(T,{size:13,className:"animate-spin"}):e.jsx(Dt,{size:13}),"Criar aditivo"]})]})]}),C.notes&&e.jsx("p",{className:"text-[12px] text-zinc-500 italic",children:C.notes}),x?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{size:16,className:"animate-spin text-zinc-400"})}):e.jsxs("div",{className:"flex flex-col md:flex-row gap-6",children:[se("portal"),e.jsx("div",{className:"hidden md:block w-px bg-zinc-100"}),se("partner")]})]}),g&&C&&e.jsx(xa,{partnership:s,planId:C.id,item:g.item,onClose:()=>n(null),onSaved:async()=>{n(null),await $(),await r()}})]})},ua=["planned","in_production","awaiting_approval","approved"],ze=s=>ua.includes(s),Z="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",W="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1",pa=({side:s})=>e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold whitespace-nowrap",style:{background:s==="portal"?"#eff6ff":"#f5f3ff",color:s==="portal"?"#3b82f6":"#8b5cf6"},children:s==="portal"?"Portal":"Parceiro"}),Pe=({title:s,onClose:r,children:i,footer:f,wide:o})=>e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:`bg-white rounded-xl shadow-xl ${o?"max-w-2xl":"max-w-lg"} w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:s}),e.jsx("button",{onClick:r,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),i,e.jsx("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:f})]})})}),ha=({partnership:s,refresh:r})=>{const{user:i}=ne(),[f,o]=t.useState([]),[N,y]=t.useState({}),[w,v]=t.useState({}),[u,p]=t.useState([]),[j,x]=t.useState({}),[_,g]=t.useState(!0),[n,l]=t.useState("all"),[a,h]=t.useState("all"),[m,c]=t.useState(null),[$,C]=t.useState(!1),[z,R]=t.useState(null),[I,O]=t.useState(null),[B,Y]=t.useState(null),[se,L]=t.useState(null),D=t.useCallback(async()=>{try{const[A,S,V,H,re]=await Promise.all([Fe(s.portal_id,{partnershipId:s.id}),Ss(s.id),ks(s.id),Se(s.id),Es(s.id)]);o(A);const ee={};
6S.forEach(U=>{ee[U.delivery_id]=(ee[U.delivery_id]||0)+1}),y(ee);const ce={};V.forEach(U=>{ce[U.delivery_id]=(ce[U.delivery_id]||0)+1}),v(ce),p(H);const P={};re.forEach(U=>{var b,M;P[U.user_id]=((b=U.profile)==null?void 0:b.full_name)||((M=U.profile)==null?void 0:M.email)||""}),x(P)}catch(A){k.error("[Partnerships] load deliveries error:",A),d.error("Erro ao carregar entregas")}finally{g(!1)}},[s.id,s.portal_id]);t.useEffect(()=>{D()},[D]);const E=t.useCallback(async()=>{await D(),await r()},[D,r]),F=t.useMemo(()=>{const A=f.filter(V=>(n==="all"||V.status===n)&&(a==="all"||V.side===a)),S=new Map;for(const V of A){const H=V.due_date?V.due_date.slice(0,7):"zz-sem-data";S.set(H,[...S.get(H)||[],V])}return Array.from(S.entries()).sort(([V],[H])=>V.localeCompare(H)).map(([V,H])=>{let re="Sem data";if(V!=="zz-sem-data"){const ee=new Date(`${V}-01T12:00:00`).toLocaleDateString("pt-BR",{month:"long",year:"numeric"});re=ee.charAt(0).toUpperCase()+ee.slice(1)}return{key:V,label:re,items:H}})},[f,n,a]),Q=new Date().toISOString().slice(0,10),ae=async A=>{try{await Ie(A.id,"in_production"),d.success("Entrega iniciada"),await E()}catch(S){k.error("[Partnerships] start delivery error:",S),d.error("Erro ao iniciar entrega")}},xe=async A=>{try{await Ie(A.id,A.status,{blocked_by_partner:!A.blocked_by_partner}),d.success(A.blocked_by_partner?"Bloqueio do parceiro removido":"Marcada como aguardando parceiro"),await E()}catch(S){k.error("[Partnerships] toggle blocked error:",S),d.error("Erro ao atualizar bloqueio")}};return _?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("select",{value:n,onChange:A=>l(A.target.value),className:"border border-zinc-200 rounded-md px-2 py-1.5 text-[12px] text-zinc-700 focus:outline-none",children:[e.jsx("option",{value:"all",children:"Todos os status"}),Object.keys(de).map(A=>e.jsx("option",{value:A,children:de[A].label},A))]}),e.jsxs("select",{value:a,onChange:A=>h(A.target.value),className:"border border-zinc-200 rounded-md px-2 py-1.5 text-[12px] text-zinc-700 focus:outline-none",children:[e.jsx("option",{value:"all",children:"Ambos os lados"}),e.jsx("option",{value:"portal",children:"Portal"}),e.jsx("option",{value:"partner",children:"Parceiro"})]})]}),e.jsxs("button",{onClick:()=>C(!0),className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 flex items-center gap-1.5",children:[e.jsx(oe,{size:13})," Nova entrega avulsa"]})]}),F.length===0?e.jsxs("div",{className:"flex flex-col items-center py-12 text-zinc-400",children:[e.jsx(ds,{size:32,className:"text-zinc-300"}),e.jsx("p",{className:"mt-2 text-[13px]",children:"Nenhuma entrega encontrada."}),e.jsx("p",{className:"text-[11px]",children:"Gere entregas a partir do plano ou crie uma avulsa."})]}):F.map(A=>e.jsxs("section",{children:[e.jsxs("h3",{className:"text-[12px] font-semibold text-zinc-500 uppercase tracking-wider mb-2",children:[A.label,e.jsxs("span",{className:"text-zinc-300 font-normal ml-1.5",children:["(",A.items.length,")"]})]}),e.jsx("div",{className:"border border-zinc-100 rounded-lg overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] text-zinc-400 uppercase tracking-wider border-b border-zinc-100",children:[e.jsx("th",{className:"px-3 py-2 font-semibold",children:"TÃtulo"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Lado"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Status"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Prazo"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Responsável"}),e.jsx("th",{className:"px-3 py-2 font-semibold text-right",children:"Valor ref."}),e.jsx("th",{className:"px-3 py-2 font-semibold text-center",children:"Evid."}),e.jsx("th",{className:"px-3 py-2 font-semibold text-right",children:"Ações"})]})}),e.jsx("tbody",{children:A.items.map(S=>{const V=de[S.status],H=V.icon,re=!!S.due_date&&S.due_date<Q&&ze(S.status);return e.jsxs("tr",{className:"border-b border-zinc-50 last:border-0 hover:bg-zinc-50/60",children:[e.jsxs("td",{className:"px-3 py-2.5",children:[e.jsx("div",{className:"text-[13px] text-zinc-800 font-medium",children:S.title}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[S.blocked_by_partner&&e.jsx("span",{className:"text-[10px] font-semibold text-amber-600 bg-amber-50 px-1.5 py-0.5 rounded",children:"Aguardando parceiro"}),S.cancel_reason&&e.jsxs("span",{className:"text-[10px] text-zinc-400 italic",title:S.cancel_reason,children:["motivo: ",S.cancel_reason.slice(0,60),S.cancel_reason.length>60?"â¦":""]})]})]}),e.jsx("td",{className:"px-3 py-2.5",children:e.jsx(pa,{side:S.side})}),e.jsx("td",{className:"px-3 py-2.5",children:e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-semibold whitespace-nowrap",style:{background:V.bg,color:V.color},children:[e.jsx(H,{size:11})," ",V.label]})}),e.jsx("td",{className:`px-3 py-2.5 text-[12px] whitespace-nowrap ${re?"text-rose-600 font-semibold":"text-zinc-600"}`,children:G(S.due_date)}),e.jsx("td",{className:"px-3 py-2.5 text-[12px] text-zinc-600",children:S.assignee_user_id&&j[S.assignee_user_id]||"â"}),e.jsx("td",{className:"px-3 py-2.5 text-[12px] text-zinc-600 text-right whitespace-nowrap",children:q(S.reference_value)}),e.jsx("td",{className:"px-3 py-2.5 text-center",children:e.jsx("span",{className:`text-[12px] ${N[S.id]?"text-zinc-700 font-semibold":"text-zinc-300"}`,children:N[S.id]||0})}),e.jsx("td",{className:"px-3 py-2.5 text-right",children:e.jsxs("div",{className:"relative inline-block",children:[e.jsx("button",{onClick:()=>c(ee=>ee===S.id?null:S.id),className:"p-1.5 text-zinc-400 hover:text-zinc-700 hover:bg-zinc-100 rounded",children:e.jsx(Mt,{size:15})}),m===S.id&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>c(null)}),e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-40 bg-white border border-zinc-200 rounded-lg shadow-lg py-1 min-w-[230px] text-left",children:[S.status==="planned"&&e.jsxs("button",{onClick:()=>{c(null),ae(S)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-zinc-700 hover:bg-zinc-50",children:[e.jsx(Tt,{size:13,className:"text-blue-600"})," Iniciar produção"]}),ze(S.status)&&e.jsxs("button",{onClick:()=>{c(null),R(S)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-zinc-700 hover:bg-zinc-50",children:[e.jsx(ke,{size:13,className:"text-emerald-600"})," ","Concluirâ¦"]}),ze(S.status)&&S.status!=="awaiting_approval"&&e.jsxs("button",{onClick:()=>{c(null),O(S)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-zinc-700 hover:bg-zinc-50",children:[e.jsx(xs,{size:13,className:"text-violet-600"}
6)," Enviar p/ aprovaçãoâ¦"]}),e.jsxs("button",{onClick:()=>{c(null),L(S)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-zinc-700 hover:bg-zinc-50",children:[e.jsx(Ee,{size:13,className:"text-zinc-500"})," Registrar evidênciaâ¦"]}),ze(S.status)&&e.jsxs("button",{onClick:()=>{c(null),xe(S)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-zinc-700 hover:bg-zinc-50",children:[e.jsx(Ts,{size:13,className:"text-amber-600"}),S.blocked_by_partner?"Remover bloqueio do parceiro":"Bloqueio por parceiro"]}),ze(S.status)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-px bg-zinc-100 my-1"}),e.jsxs("button",{onClick:()=>{c(null),Y({delivery:S,action:"cancel"})},className:"w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-rose-600 hover:bg-rose-50",children:[e.jsx(ms,{size:13})," Cancelarâ¦"]}),e.jsxs("button",{onClick:()=>{c(null),Y({delivery:S,action:"refuse"})},className:"w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-rose-600 hover:bg-rose-50",children:[e.jsx(As,{size:13})," Recusa editorialâ¦"]})]})]})]})]})})]},S.id)})})]})})]},A.key)),$&&e.jsx(fa,{partnership:s,onClose:()=>C(!1),onSaved:async()=>{C(!1),await E()}}),z&&e.jsx(ba,{delivery:z,onClose:()=>R(null),onDone:async A=>{const S=z;R(null),await E(),A&&L(S)}}),I&&e.jsx(ja,{partnership:s,delivery:I,contacts:u,nextRound:(w[I.id]||0)+1,onClose:()=>O(null),onSent:async()=>{O(null),await E()}}),B&&e.jsx(va,{delivery:B.delivery,action:B.action,onClose:()=>Y(null),onDone:async()=>{Y(null),await E()}}),se&&e.jsx(ga,{partnership:s,delivery:se,capturedBy:(i==null?void 0:i.id)??null,onClose:()=>L(null),onSaved:async()=>{L(null),await E()}})]})},fa=({partnership:s,onClose:r,onSaved:i})=>{const[f,o]=t.useState(""),[N,y]=t.useState("portal"),[w,v]=t.useState(""),[u,p]=t.useState(""),[j,x]=t.useState(""),[_,g]=t.useState(!1),n=async()=>{if(!f.trim()){d.error("Informe o tÃtulo da entrega");return}g(!0);try{await rt({partnership_id:s.id,portal_id:s.portal_id,organization_id:s.organization_id??null,side:N,title:f.trim(),description:j.trim()||null,status:"planned",due_date:w||null,reference_value:u.trim()===""?null:Number(u),notes:"extra"}),d.success("Entrega avulsa criada"),await i()}catch(l){k.error("[Partnerships] new delivery error:",l),d.error("Erro ao criar entrega")}finally{g(!1)}};return e.jsxs(Pe,{title:"Nova entrega avulsa",onClose:r,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:r,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:n,disabled:_,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[_&&e.jsx(T,{size:13,className:"animate-spin"}),"Criar entrega"]})]}),children:[e.jsxs("p",{className:"text-[12px] text-zinc-500 mb-3",children:["Entrega fora do plano (marcada como ",e.jsx("strong",{children:"extra"})," nas notas). Não altera o equilÃbrio contratado."]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:W,children:"TÃtulo *"}),e.jsx("input",{value:f,onChange:l=>o(l.target.value),className:Z})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Lado"}),e.jsxs("select",{value:N,onChange:l=>y(l.target.value),className:Z,children:[e.jsx("option",{value:"portal",children:"Portal"}),e.jsx("option",{value:"partner",children:"Parceiro"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Prazo"}),e.jsx("input",{type:"date",value:w,onChange:l=>v(l.target.value),className:Z})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Valor ref. (R$)"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:u,onChange:l=>p(l.target.value),className:Z})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Descrição"}),e.jsx("textarea",{value:j,onChange:l=>x(l.target.value),rows:3,className:`${Z} resize-none`})]})]})]})},ba=({delivery:s,onClose:r,onDone:i})=>{const[f,o]=t.useState(s.side==="portal"?"published":"completed"),[N,y]=t.useState(new Date().toISOString().slice(0,10)),[w,v]=t.useState(s.notes||""),[u,p]=t.useState(!0),[j,x]=t.useState(!1),_=async()=>{x(!0);try{await Ie(s.id,f,{executed_at:new Date(`${N}T12:00:00`).toISOString(),notes:w.trim()||null}),d.success(`Entrega marcada como ${de[f].label.toLowerCase()}`),await i(u)}catch(g){k.error("[Partnerships] complete delivery error:",g),d.error("Erro ao concluir entrega")}finally{x(!1)}};
6return e.jsxs(Pe,{title:s.title,onClose:r,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:r,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:_,disabled:j,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[j&&e.jsx(T,{size:13,className:"animate-spin"}),"Salvar mudanças"]})]}),children:[e.jsxs("p",{className:"text-[12px] text-zinc-500 mb-4",children:["Status atual: ",e.jsx("strong",{children:de[s.status].label})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Novo status"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"published",label:"Publicada",desc:"foi ao ar (conteúdo/mÃdia)"},{value:"completed",label:"ConcluÃda",desc:"executada/consumida"}].map(g=>e.jsxs("button",{onClick:()=>o(g.value),className:`p-2.5 border rounded-lg text-left transition-all ${f===g.value?"text-emerald-600 border-emerald-200 bg-zinc-50 ring-1 ring-zinc-200":"text-zinc-500 border-zinc-200 hover:bg-zinc-50"}`,children:[e.jsxs("span",{className:"flex items-center gap-2 text-[13px] font-medium",children:[e.jsx(ke,{size:14})," ",g.label]}),e.jsx("span",{className:"block text-[11px] text-zinc-400 mt-0.5",children:g.desc})]},g.value))})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Executada em"}),e.jsx("input",{type:"date",value:N,onChange:g=>y(g.target.value),className:Z})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Notas (opcional)"}),e.jsx("textarea",{value:w,onChange:g=>v(g.target.value),rows:3,className:`${Z} resize-none`,placeholder:"Observações internasâ¦"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-zinc-700",children:[e.jsx("input",{type:"checkbox",checked:u,onChange:g=>p(g.target.checked)}),"Registrar evidência em seguida"]})]})]})},ja=({partnership:s,delivery:r,contacts:i,nextRound:f,onClose:o,onSent:N})=>{const y=i.find(h=>h.is_default_approver)??i[0],[w,v]=t.useState("external"),[u,p]=t.useState((y==null?void 0:y.id)??""),[j,x]=t.useState("email"),[_,g]=t.useState(""),[n,l]=t.useState(!1),a=async()=>{l(!0);try{await it({delivery:r,scope:w,round:f,material_url:_.trim()||void 0,sent_to_contact_id:w==="external"&&u||void 0,sent_channel:j,sla_days:s.approval_sla_days}),d.success(`Rodada ${f} de aprovação aberta`),await N()}catch(h){k.error("[Partnerships] send approval error:",h),d.error("Erro ao enviar para aprovação")}finally{l(!1)}};return e.jsxs(Pe,{title:"Enviar para aprovação",onClose:o,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:o,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:a,disabled:n,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[n&&e.jsx(T,{size:13,className:"animate-spin"}),e.jsx(xs,{size:13})," Enviar"]})]}),children:[e.jsxs("p",{className:"text-[12px] text-zinc-500 mb-4",children:[e.jsx("strong",{children:r.title})," â rodada ",e.jsx("strong",{children:f})," · SLA de resposta:"," ",e.jsxs("strong",{children:[s.approval_sla_days," dias úteis"]}),s.tacit_approval_enabled&&" (aprovação tácita habilitada no contrato)"]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Escopo"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"internal",label:"Interna",desc:"aprovação do time do portal"},{value:"external",label:"Externa",desc:"aprovação do parceiro"}].map(h=>e.jsxs("button",{onClick:()=>v(h.value),className:`p-2.5 border rounded-lg text-left transition-all ${w===h.value?"text-violet-600 border-violet-200 bg-zinc-50 ring-1 ring-zinc-200":"text-zinc-500 border-zinc-200 hover:bg-zinc-50"}`,children:[e.jsx("span",{className:"text-[13px] font-medium",children:h.label}),e.jsx("span",{className:"block text-[11px] text-zinc-400 mt-0.5",children:h.desc})]},h.value))})]}),w==="external"&&e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Destinatário (contato do parceiro)"}),i.length===0?e.jsx("p",{className:"text-[12px] text-amber-600 bg-amber-50 border border-amber-200 rounded-md p-2",children:"Nenhum contato cadastrado â cadastre na aba Pessoas para registrar o destinatário."}):e.jsx("select",{value:u,onChange:h=>p(h.target.value),className:Z,children:i.map(h=>e.jsxs("option",{value:h.id,children:[h.name,h.is_default_approver?" (aprovador padrão)":""]},h.id))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Canal"}),e.jsxs("select",{value:j,onChange:h=>x(h.target.value),className:Z,children:[e.jsx("option",{value:"email",children:"E-mail"}),e.jsx("option",{value:"whatsapp",children:"WhatsApp"}),e.jsx("option",{value:"meeting",children:"Reunião"}),e.jsx("option",{value:"other",children:"Outro"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"URL do material"}
6),e.jsx("input",{type:"url",value:_,onChange:h=>g(h.target.value),placeholder:"https://â¦",className:Z})]})]})]})]})},va=({delivery:s,action:r,onClose:i,onDone:f})=>{const[o,N]=t.useState(""),[y,w]=t.useState(!1),v=r==="refuse",u=async()=>{if(!o.trim()){d.error("Informe o motivo");return}w(!0);try{await Ie(s.id,v?"editorial_refused":"cancelled",{cancel_reason:o.trim()}),d.success(v?"Recusa editorial registrada":"Entrega cancelada"),await f()}catch(p){k.error("[Partnerships] reason action error:",p),d.error("Erro ao atualizar entrega")}finally{w(!1)}};return e.jsxs(Pe,{title:v?"Recusa editorial":"Cancelar entrega",onClose:i,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Voltar"}),e.jsxs("button",{onClick:u,disabled:y||!o.trim(),className:"px-4 py-2 bg-rose-600 text-white text-[13px] font-semibold rounded-md hover:bg-rose-700 disabled:opacity-50 flex items-center gap-2",children:[y&&e.jsx(T,{size:13,className:"animate-spin"}),"Confirmar"]})]}),children:[e.jsxs("p",{className:"text-[12px] text-zinc-500 mb-3",children:[v?"A redação recusou a pauta/material por critério editorial. O motivo fica registrado e visÃvel na entrega.":"A entrega será cancelada e deixa de contar nas pendências. O motivo fica registrado."," ","Entrega: ",e.jsx("strong",{children:s.title})]}),e.jsx("textarea",{value:o,onChange:p=>N(p.target.value),rows:4,placeholder:"Motivo *",className:`${Z} resize-none`})]})},ga=({partnership:s,delivery:r,capturedBy:i,onClose:f,onSaved:o})=>{const[N,y]=t.useState("link"),[w,v]=t.useState(""),[u,p]=t.useState(null),[j,x]=t.useState(""),[_,g]=t.useState(!1),n=async()=>{if(!w.trim()&&!u){d.error("Informe uma URL ou anexe um arquivo");return}g(!0);try{let l=null;u&&(l=await Ce(s.portal_id,s.id,"evidence",u)),await nt({delivery_id:r.id,partnership_id:s.id,portal_id:s.portal_id,kind:N,url:w.trim()||null,storage_path:l,captured_by:i,notes:j.trim()||null}),d.success("Evidência registrada"),await o()}catch(l){k.error("[Partnerships] add evidence error:",l),d.error("Erro ao registrar evidência")}finally{g(!1)}};return e.jsxs(Pe,{title:"Registrar evidência",onClose:f,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:f,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:n,disabled:_,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[_&&e.jsx(T,{size:13,className:"animate-spin"}),"Salvar evidência"]})]}),children:[e.jsxs("p",{className:"text-[12px] text-zinc-500 mb-3",children:["Comprovação da entrega ",e.jsx("strong",{children:r.title}),". Informe uma URL pública e/ou anexe um arquivo (print, PDF, voucher) â o arquivo vai para o bucket privado da parceria."]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Tipo"}),e.jsx("select",{value:N,onChange:l=>y(l.target.value),className:Z,children:Object.keys(We).map(l=>e.jsx("option",{value:l,children:We[l]},l))})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"URL"}),e.jsx("input",{type:"url",value:w,onChange:l=>v(l.target.value),placeholder:"https://â¦",className:Z})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Arquivo"}),e.jsx("input",{type:"file",onChange:l=>{var a;return p(((a=l.target.files)==null?void 0:a[0])??null)},className:"w-full text-[12px] text-zinc-600 file:mr-3 file:px-3 file:py-1.5 file:rounded-md file:border-0 file:bg-zinc-100 file:text-zinc-700 file:text-[12px] file:font-semibold hover:file:bg-zinc-200"})]}),e.jsxs("div",{children:[e.jsx("label",{className:W,children:"Notas (opcional)"}),e.jsx("textarea",{value:j,onChange:l=>x(l.target.value),rows:2,className:`${Z} resize-none`})]})]})]})},Na={approved:"bg-emerald-50 text-emerald-600",changes_requested:"bg-amber-50 text-amber-600",rejected:"bg-rose-50 text-rose-600",tacit:"bg-blue-50 text-blue-600"};
6function gs(s){return s?new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}):"â"}const za=({partnership:s,refresh:r})=>{var m;const{user:i}=ne(),[f,o]=t.useState([]),[N,y]=t.useState([]),[w,v]=t.useState(!0),[u,p]=t.useState(null),[j,x]=t.useState(""),[_,g]=t.useState(!1),n=t.useCallback(async()=>{try{const[c,$]=await Promise.all([ks(s.id),Se(s.id)]);o(c),y($)}catch(c){k.error("[Partnerships] load approvals error:",c),d.error("Erro ao carregar aprovações")}finally{v(!1)}},[s.id]);t.useEffect(()=>{n()},[n]);const l=c=>{var $;return c&&(($=N.find(C=>C.id===c))==null?void 0:$.name)||null},a=c=>!c.decision&&!!c.due_at&&new Date(c.due_at).getTime()<Date.now()&&s.tacit_approval_enabled,h=async()=>{if(u){g(!0);try{await lt(u.approval.id,u.decision,{comments:j.trim()||void 0,decidedBy:i==null?void 0:i.id,deliveryId:u.approval.delivery_id}),d.success(`Decisão registrada: ${Ve[u.decision]}`),p(null),x(""),await n(),await r()}catch(c){k.error("[Partnerships] decide approval error:",c),d.error("Erro ao registrar decisão")}finally{g(!1)}}};return w?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):f.length===0?e.jsxs("div",{className:"flex flex-col items-center py-12 text-zinc-400",children:[e.jsx(xs,{size:32,className:"text-zinc-300"}),e.jsx("p",{className:"mt-2 text-[13px]",children:"Nenhuma rodada de aprovação registrada."}),e.jsx("p",{className:"text-[11px]",children:"Envie uma entrega para aprovação na aba Entregas."})]}):e.jsxs("div",{className:"space-y-2",children:[f.map(c=>{var R;const $=!c.decision,C=a(c),z=c.due_at?we(c.due_at):null;return e.jsx("div",{className:"p-3.5 border border-zinc-100 rounded-lg",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-zinc-100 text-zinc-600 text-[10px] font-semibold",children:["Rodada ",c.round]}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold ${c.scope==="external"?"bg-violet-50 text-violet-600":"bg-blue-50 text-blue-600"}`,children:c.scope==="external"?"Externa (parceiro)":"Interna"}),c.decision?e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold ${Na[c.decision]}`,children:Ve[c.decision]}):e.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-amber-50 text-amber-600 text-[10px] font-semibold flex items-center gap-1",children:[e.jsx(ts,{size:10})," Pendente"]}),C&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-600 text-white text-[10px] font-bold tracking-wide",children:"TÃCITA ELEGÃVEL"})]}),e.jsx("div",{className:"text-[13px] text-zinc-800 font-medium",children:((R=c.delivery)==null?void 0:R.title)||"Entrega"}),e.jsxs("div",{className:"text-[11px] text-zinc-400 mt-0.5",children:["Enviado ",gs(c.sent_at),l(c.sent_to_contact_id)&&e.jsxs(e.Fragment,{children:[" ","para ",e.jsx("strong",{children:l(c.sent_to_contact_id)})]}),c.sent_channel&&e.jsxs(e.Fragment,{children:[" via ",c.sent_channel]}),c.material_url&&e.jsxs(e.Fragment,{children:[" ⢠",e.jsxs("a",{href:c.material_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline inline-flex items-center gap-0.5",children:["material ",e.jsx(cs,{size:10})]})]})]}),e.jsxs("div",{className:"text-[11px] mt-0.5",children:[c.due_at&&$&&z!==null&&e.jsxs("span",{className:z<0?"text-rose-600 font-semibold":z<=1?"text-amber-600 font-semibold":"text-zinc-500",children:["Prazo ",G(c.due_at)," â"," ",z<0?`vencido há ${Math.abs(z)} dia(s)`:z===0?"vence hoje":`${z} dia(s) restantes`]}),c.decision&&c.decided_at&&e.jsxs("span",{className:"text-zinc-400",children:["Decidido em ",gs(c.decided_at)]})]}),c.comments&&e.jsxs("p",{className:"text-[11px] text-zinc-500 italic mt-1",children:["â",c.comments,"â"]}
6)]}),$&&e.jsxs("div",{className:"flex gap-1.5 flex-wrap shrink-0",children:[e.jsxs("button",{onClick:()=>{x(""),p({approval:c,decision:"approved"})},className:"px-2.5 py-1.5 bg-emerald-600 text-white rounded-md text-[11px] font-semibold hover:bg-emerald-700 flex items-center gap-1",children:[e.jsx(ke,{size:12})," Aprovar"]}),e.jsxs("button",{onClick:()=>{x(""),p({approval:c,decision:"changes_requested"})},className:"px-2.5 py-1.5 bg-white border border-amber-200 text-amber-600 rounded-md text-[11px] font-semibold hover:bg-amber-50 flex items-center gap-1",children:[e.jsx(It,{size:12})," Ajustes"]}),e.jsxs("button",{onClick:()=>{x(""),p({approval:c,decision:"rejected"})},className:"px-2.5 py-1.5 bg-white border border-rose-200 text-rose-600 rounded-md text-[11px] font-semibold hover:bg-rose-50 flex items-center gap-1",children:[e.jsx(ms,{size:12})," Reprovar"]}),C&&e.jsxs("button",{onClick:()=>{x(""),p({approval:c,decision:"tacit"})},className:"px-2.5 py-1.5 bg-blue-600 text-white rounded-md text-[11px] font-semibold hover:bg-blue-700 flex items-center gap-1",children:[e.jsx(as,{size:12})," Registrar tácita"]})]})]})},c.id)}),u&&e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-md w-full p-6 no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-[15px] font-semibold text-zinc-900",children:[Ve[u.decision]," â rodada"," ",u.approval.round]}),e.jsx("button",{onClick:()=>p(null),className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),u.decision==="tacit"?e.jsxs("p",{className:"text-[12px] text-zinc-600 bg-blue-50 border border-blue-200 rounded-md p-2.5 mb-3",children:["A aprovação tácita é um ",e.jsx("strong",{children:"registro humano"}),": o prazo contratual de resposta (",s.approval_sla_days," dias úteis) venceu sem manifestação do parceiro e você está registrando, com seu usuário, que a cláusula de aprovação tácita se aplica. Nada é decidido automaticamente pelo sistema."]}):e.jsxs("p",{className:"text-[12px] text-zinc-500 mb-3",children:["Entrega: ",e.jsx("strong",{children:((m=u.approval.delivery)==null?void 0:m.title)||"â"}),". A decisão atualiza o status da entrega",u.decision==="approved"&&" para Aprovada",u.decision==="changes_requested"&&" de volta para Em produção","."]}),e.jsx("textarea",{value:j,onChange:c=>x(c.target.value),rows:3,placeholder:u.decision==="tacit"?"Observações (ex.: tentativas de contato, e-mails enviados)":"Comentários (opcional)",className:"w-full border border-zinc-200 rounded-md p-2 text-[13px] resize-none focus:outline-none focus:border-zinc-400"}),e.jsxs("div",{className:"flex gap-2 justify-end mt-4",children:[e.jsx("button",{onClick:()=>p(null),className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:h,disabled:_,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[_&&e.jsx(T,{size:13,className:"animate-spin"}),"Confirmar decisão"]})]})]})})})]})},ya={collected:{label:"Coletada",cls:"bg-zinc-100 text-zinc-600"},verified:{label:"Verificada",cls:"bg-emerald-50 text-emerald-600"},rejected:{label:"Rejeitada",cls:"bg-rose-50 text-rose-600"}};function wa(s){return s?new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}):"â"}const _a=({partnership:s,refresh:r})=>{const{user:i}=ne(),{currentPortal:f}=is(),[o,N]=t.useState([]),[y,w]=t.useState(!0),[v,u]=t.useState(null),[p,j]=t.useState(!1),x=t.useCallback(async()=>{try{N(await Ss(s.id))}catch(l){k.error("[Partnerships] load evidences error:",l),d.error("Erro ao carregar comprovações")}finally{w(!1)}},[s.id]);t.useEffect(()=>{x()},[x]);const _=async l=>{if(l.storage_path){u(l.id);try{const a=await _e(l.storage_path);if(!a){d.error("Não foi possÃvel gerar o link do arquivo");return}window.open(a,"_blank","noopener")}catch(a){k.error("[Partnerships] open evidence file error:",a),d.error("Erro ao abrir arquivo")}finally{u(null)}}},g=async(l,a)=>{try{await ot(l.id,a,i==null?void 0:i.id),d.success(a==="verified"?"Evidência verificada":"Evidência rejeitada"),await x(),await r()}catch(h){k.error("[Partnerships] set evidence status error:",h),d.error("Erro ao atualizar evidência")}},n=async()=>{j(!0);try{const[l,a]=await Promise.all([Ps(s.id),Fe(s.portal_id,{partnershipId:s.id})]),{generatePartnershipDossier:h}=await Is(async()=>{const{generatePartnershipDossier:m}=await import("./partnershipReportPdfService-RLBiDvDL.js");return{generatePartnershipDossier:m}},__vite__mapDeps([0,1]));
6await h({partnership:s,balance:l,deliveries:a,evidences:o,portalName:f.name}),d.success("Dossiê gerado")}catch(l){k.error("[Partnerships] generate dossier error:",l),d.error("Erro ao gerar dossiê em PDF")}finally{j(!1)}};return y?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("p",{className:"text-[12px] text-zinc-500",children:[o.length," comprovação(ões) registradas â evidências são adicionadas pela aba Entregas."]}),e.jsxs("button",{onClick:n,disabled:p,className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-1.5",children:[p?e.jsx(T,{size:13,className:"animate-spin"}):e.jsx(Ms,{size:13}),"Gerar dossiê (PDF)"]})]}),o.length===0?e.jsxs("div",{className:"flex flex-col items-center py-12 text-zinc-400",children:[e.jsx($t,{size:32,className:"text-zinc-300"}),e.jsx("p",{className:"mt-2 text-[13px]",children:"Nenhuma comprovação registrada."})]}):e.jsx("div",{className:"space-y-1.5",children:o.map(l=>{const a=ya[l.status];return e.jsxs("div",{className:"flex items-center gap-3 p-3 border border-zinc-100 rounded-lg flex-wrap",children:[e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-zinc-100 text-zinc-600 text-[10px] font-semibold shrink-0",children:We[l.kind]}),e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold ${a.cls}`,children:a.label}),l.auto_captured&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 text-[10px] font-semibold",children:"Auto"}),e.jsxs("span",{className:"text-[11px] text-zinc-400",children:["capturada ",wa(l.captured_at)]})]}),l.notes&&e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5",children:l.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l.url&&e.jsxs("a",{href:l.url,target:"_blank",rel:"noreferrer",className:"text-[11px] text-blue-600 hover:underline flex items-center gap-1",children:[e.jsx(cs,{size:12})," Abrir link"]}),l.storage_path&&e.jsxs("button",{onClick:()=>_(l),disabled:v===l.id,className:"text-[11px] text-blue-600 hover:underline flex items-center gap-1 disabled:opacity-50",children:[v===l.id?e.jsx(T,{size:12,className:"animate-spin"}):e.jsx(Ee,{size:12}),"Abrir arquivo"]}),l.status==="collected"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>g(l,"verified"),className:"px-2 py-1 bg-emerald-600 text-white rounded text-[11px] font-semibold hover:bg-emerald-700 flex items-center gap-1",children:[e.jsx(ke,{size:11})," Verificar"]}),e.jsxs("button",{onClick:()=>g(l,"rejected"),className:"px-2 py-1 bg-white border border-rose-200 text-rose-600 rounded text-[11px] font-semibold hover:bg-rose-50 flex items-center gap-1",children:[e.jsx(ms,{size:11})," Rejeitar"]})]})]})]},l.id)})})]})},ie="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",te="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1",Re=({side:s})=>e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold whitespace-nowrap",style:{background:s==="portal"?"#eff6ff":"#f5f3ff",color:s==="portal"?"#3b82f6":"#8b5cf6"},children:s==="portal"?"Portal":"Parceiro"}),Ca=({partnership:s,balance:r,refresh:i})=>{const{user:f}=ne(),[o,N]=t.useState([]),[y,w]=t.useState([]),[v,u]=t.useState(!0),[p,j]=t.useState(!1),[x,_]=t.useState(null),[g,n]=t.useState(!1),l=t.useCallback(async()=>{try{const[z,R]=await Promise.all([ct(s.id),Fe(s.portal_id,{partnershipId:s.id})]);N(z),w(R)}catch(z){k.error("[Partnerships] load ledger error:",z),d.error("Erro ao carregar lançamentos")}finally{u(!1)}},[s.id,s.portal_id]);t.useEffect(()=>{l()},[l]);const a=t.useMemo(()=>{const z={};return y.forEach(R=>{z[R.id]=R.title}),z},[y]),h=async()=>{n(!0);try{_(await dt(s.id))}catch(z){k.error("[Partnerships] settlement error:",z),d.error("Erro ao gerar apuração de rescisão")}finally{n(!1)}},m=(r==null?void 0:r.balance)??0,c=m>0?"text-emerald-600":m<0?"text-rose-600":"text-zinc-900",$=!!(s.coupon_code||s.commission_pct!=null||o.some(z=>z.entry_kind==="commission")),C=z=>{const R=z==="portal"?r==null?void 0:r.contracted_portal:r==null?void 0:r.contracted_partner,I=z==="portal"?r==null?void 0:r.executed_portal:r==null?void 0:r.executed_partner,O=z==="portal"?r==null?void 0:r.pending_portal:r==null?void 0:r.pending_partner,B=R?Math.round((I??0)/R*100):0;return e.jsxs("div",{style:{padding:"14px 16px",border:"1px solid #f0f
60f0",borderRadius:8},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Re,{side:z}),e.jsxs("span",{className:"text-[12px] font-bold text-zinc-700",children:[B,"%"]})]}),e.jsx("div",{className:"h-1.5 bg-zinc-100 rounded-full overflow-hidden mb-3",children:e.jsx("div",{className:`h-full rounded-full ${z==="portal"?"bg-blue-500":"bg-violet-500"}`,style:{width:`${Math.min(100,B)}%`}})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-[11px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-zinc-400 uppercase tracking-wider text-[9px]",children:"Contratado"}),e.jsx("div",{className:"font-semibold text-zinc-800",children:q(R)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-zinc-400 uppercase tracking-wider text-[9px]",children:"Executado"}),e.jsx("div",{className:"font-semibold text-zinc-800",children:q(I)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-zinc-400 uppercase tracking-wider text-[9px]",children:"Pendente"}),e.jsx("div",{className:"font-semibold text-zinc-800",children:q(O)})]})]})]})};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid md:grid-cols-3 gap-3",children:[C("portal"),C("partner"),e.jsxs("div",{style:{padding:"14px 16px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-1",children:"Saldo"}),e.jsx("div",{className:`text-[22px] font-bold ${c}`,children:q(r==null?void 0:r.balance)}),e.jsx("div",{className:"text-[10px] text-zinc-400 mt-1",children:"executado portal â executado parceiro. Valores referenciais."})]})]}),e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("h2",{className:"text-[14px] font-semibold text-zinc-800 flex items-center gap-2",children:[e.jsx(Ot,{size:14})," Lançamentos",e.jsxs("span",{className:"text-[11px] text-zinc-400 font-normal",children:["(",o.length,")"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:()=>j(!0),className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 flex items-center gap-1.5",children:[e.jsx(oe,{size:13})," Novo lançamento"]}),e.jsxs("button",{onClick:h,disabled:g,className:"px-3 py-1.5 bg-white border border-zinc-200 text-zinc-700 rounded-md text-[12px] font-semibold hover:bg-zinc-50 disabled:opacity-50 flex items-center gap-1.5",children:[g?e.jsx(T,{size:13,className:"animate-spin"}):e.jsx(es,{size:13}),"Apuração de rescisão"]})]})]}),v?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(T,{size:16,className:"animate-spin text-zinc-400"})}):o.length===0?e.jsx("p",{className:"text-[12px] text-zinc-400 py-4",children:"Nenhum lançamento â entregas concluÃdas geram lançamentos de execução automaticamente, e você pode registrar ajustes manuais."}):e.jsx("div",{className:"border border-zinc-100 rounded-lg overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] text-zinc-400 uppercase tracking-wider border-b border-zinc-100",children:[e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Data"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Lado"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Tipo"}),e.jsx("th",{className:"px-3 py-2 font-semibold text-right",children:"Valor"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Descrição"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Entrega"})]})}),e.jsx("tbody",{children:o.map(z=>e.jsxs("tr",{className:"border-b border-zinc-50 last:border-0",children:[e.jsx("td",{className:"px-3 py-2.5 text-[12px] text-zinc-600 whitespace-nowrap",children:G(z.occurred_at)}),e.jsx("td",{className:"px-3 py-2.5",children:e.jsx(Re,{side:z.side})}),e.jsx("td",{className:"px-3 py-2.5 text-[12px] text-zinc-600",children:Xe[z.entry_kind]}),e.jsx("td",{className:"px-3 py-2.5 text-[12px] font-semibold text-zinc-800 text-right whitespace-nowrap",children:q(z.amount)}),e.jsx("td",{className:"px-3 py-2.5 text-[12px] text-zinc-500",children:z.description||"â"}),e.jsx("td",{className:"px-3 py-2.5 text-[12px] text-zinc-500",children:z.delivery_id&&a[z.delivery_id]||"â"})]},z.id))})]})}),$&&e.jsx(Sa,{partnership:s,onLedgerChanged:async()=>{await l(),await i()}}),p&&e.jsx(Ea,{partnership:s,deliveries:y,createdBy:(f==null?void 0:f.id)??null,onClose:()=>j(!1),onSaved:async()=>{j(!1),await l(),await i()}}),x&&e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-[15px] font-semibold text-zinc-900 flex items-center gap-2",children:[e.jsx(es,{size:15})," Apuração de rescisão"]}),e.jsx("button",{onClick:()=>_(null),className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("div",{className:"flex items-start gap-2.5 p-3 bg-amber-50 border border-amber-200 rounded-lg text-[12px] text-amber-800 mb-4",children:[e.jsx(Ls,{size:15,className:"shrink-0 mt-0.5"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Valores referenciais"})," â cobrança só por acordo formal entre as partes (aviso prévio de ",s.notice_period_days," dias)."]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-4",children:["portal","partner"].map(z=>{const R=z==="portal"?x.executed_portal:x.executed_partner,I=z==="portal"?x.contracted_portal:x.contracted_partner;return e.jsxs("div",{style:{padding:"12px 14px",border:"1px solid #f0f
60f0",borderRadius:8},children:[e.jsx(Re,{side:z}),e.jsxs("div",{className:"text-[13px] text-zinc-800 mt-2",children:["Executado ",e.jsx("strong",{children:q(R)}),e.jsxs("span",{className:"text-zinc-400",children:[" ","à contratado ",q(I)]})]})]},z)})}),e.jsxs("div",{className:"text-[13px] text-zinc-800 mb-4",children:["Saldo na data:"," ",e.jsx("strong",{className:x.balance>0?"text-emerald-600":x.balance<0?"text-rose-600":"",children:q(x.balance)})]}),e.jsxs("h4",{className:"text-[13px] font-semibold text-zinc-800 mb-2",children:["Entregas abertas (",x.open_deliveries.length,")"]}),x.open_deliveries.length===0?e.jsx("p",{className:"text-[12px] text-zinc-400",children:"Nenhuma entrega aberta na data da apuração."}):e.jsx("div",{className:"border border-zinc-100 rounded-lg overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] text-zinc-400 uppercase tracking-wider border-b border-zinc-100",children:[e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Entrega"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Lado"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Status"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Prazo"}),e.jsx("th",{className:"px-3 py-2 font-semibold text-right",children:"Valor ref."})]})}),e.jsx("tbody",{children:x.open_deliveries.map(z=>e.jsxs("tr",{className:"border-b border-zinc-50 last:border-0",children:[e.jsx("td",{className:"px-3 py-2 text-[12px] text-zinc-800",children:z.title}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(Re,{side:z.side})}),e.jsx("td",{className:"px-3 py-2 text-[12px]",style:{color:de[z.status].color},children:de[z.status].label}),e.jsx("td",{className:"px-3 py-2 text-[12px] text-zinc-600 whitespace-nowrap",children:G(z.due_date)}),e.jsx("td",{className:"px-3 py-2 text-[12px] text-zinc-800 text-right whitespace-nowrap",children:q(z.reference_value)})]},z.delivery_id))})]})}),e.jsxs("div",{className:"text-[10px] text-zinc-400 mt-3",children:["Gerada em ",new Date(x.generated_at).toLocaleString("pt-BR")]})]})})})]})},Sa=({partnership:s,onLedgerChanged:r})=>{const{user:i}=ne(),f=ge(),[o,N]=t.useState([]),[y,w]=t.useState(!0),[v,u]=t.useState(null),[p,j]=t.useState(null),x=t.useCallback(async()=>{try{N(await xt(s.id))}catch(a){k.error("[Partnerships] load commission periods error:",a),d.error("Erro ao carregar apuração de comissão")}finally{w(!1)}},[s.id]);t.useEffect(()=>{x()},[x]);const _=t.useMemo(()=>o.reduce((a,h)=>({sales:a.sales+Number(h.gross_sales_reported||0),due:a.due+Number(h.commission_due||0),paid:a.paid+(h.status==="paid"?Number(h.commission_due||0):0)}),{sales:0,due:0,paid:0}),[o]),g=async(a,h)=>{if(h!==a.status){j(a.id);try{const m=!a.ledger_entry_id&&Number(a.commission_due)>0&&h!=="reported"&&h!=="disputed";await mt(a,h,(i==null?void 0:i.id)??null),d.success(m?"Comissão confirmada e lançada no ledger":"Status atualizado"),await x(),m&&await r()}catch(m){k.error("[Partnerships] commission status error:",m),d.error("Erro ao atualizar o perÃodo")}finally{j(null)}}},n=async a=>{const h=!!a.ledger_entry_id;if(await f({title:"Excluir perÃodo de apuração",message:h?"Este perÃodo já gerou um lançamento de comissão no ledger. Excluir aqui NÃO remove o lançamento â remova-o manualmente se for o caso. Continuar?":"Excluir este perÃodo de apuração? Esta ação não pode ser desfeita.",confirmLabel:"Excluir"})){j(a.id);try{await ut(a.id),d.success("PerÃodo excluÃdo"),await x()}catch(m){k.error("[Partnerships] delete commission period error:",m),d.error("Erro ao excluir perÃodo")}finally{j(null)}}},l=async a=>{if(a.proof_storage_path){j(a.id);try{const h=await _e(a.proof_storage_path);if(!h){d.error("Não foi possÃvel gerar o link do comprovante");return}window.open(h,"_blank","noopener")}catch(h){k.error("[Partnerships] open commission proof error:",h),d.error("Erro ao abrir comprovante")}finally{j(null)}}};return e.jsxs("section",{className:"pt-5 border-t border-zinc-100",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2 mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[14px] font-semibold text-zinc-800 flex items-center gap-2",children:[e.jsx(Be,{size:14})," Apuração de comissão",s.coupon_code&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-zinc-100 text-zinc-700 text-[11px] font-mono font-semibold",children:s.coupon_code})]}),e.jsx("p",{className:"text-[11px] text-zinc-400 mt-0.5",children:s.commission_pct!=null?`${Te(s.commission_pct)} sobre as vendas informadas pelo parceiro.`:"Percentual não cadastrado â defina na aba Visão Geral."})]}),e.jsxs("button",{onClick:()=>u("new"),className:"px-3 py-1.5 bg-white border border-zinc-200 text-zinc-700 rounded-md text-[12px] font-semibold hover:bg-zinc-50 flex items-center gap-1.5",children:[e.jsx(oe,{size:13})," Novo perÃodo"]})]}),y?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(T,{size:16,className:"animate-spin text-zinc-400"})}):o.length===0?e.jsx("p",{className:"text-[12px] text-zinc-400 py-2",children:"Nenhum perÃodo apurado. Registre as vendas informadas pelo parceiro e anexe o relatório como comprovante â ao confirmar, a comissão vira lançamento no ledger."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-3 gap-3 mb-3",children:[{label:"Vendas informadas",value:_.sales,cls:"text-zinc-900"},{label:"Comissão apurada",value:_.due,cls:"text-zinc-900"},{label:"Comissão paga",value:_.paid,cls:"text-emerald-600"}].map(a=>
6e.jsxs("div",{style:{padding:"10px 12px",border:"1px solid #f0f0f0",borderRadius:8},children:[e.jsx("div",{className:"text-[10px] text-zinc-500 uppercase tracking-wider mb-0.5",children:a.label}),e.jsx("div",{className:`text-[15px] font-bold ${a.cls}`,children:q(a.value)})]},a.label))}),e.jsx("div",{className:"border border-zinc-100 rounded-lg overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] text-zinc-400 uppercase tracking-wider border-b border-zinc-100",children:[e.jsx("th",{className:"px-3 py-2 font-semibold",children:"PerÃodo"}),e.jsx("th",{className:"px-3 py-2 font-semibold text-right",children:"Vendas informadas"}),e.jsx("th",{className:"px-3 py-2 font-semibold text-right",children:"Comissão devida"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Status"}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:"Comprovante"}),e.jsx("th",{className:"px-3 py-2 font-semibold text-right",children:"Ações"})]})}),e.jsx("tbody",{children:o.map(a=>{const h=qe[a.status];return e.jsxs("tr",{className:"border-b border-zinc-50 last:border-0",children:[e.jsxs("td",{className:"px-3 py-2.5 text-[12px] text-zinc-700 whitespace-nowrap",children:[G(a.period_start)," â ",G(a.period_end),a.notes&&e.jsx("div",{className:"text-[11px] text-zinc-400 truncate max-w-[220px]",children:a.notes})]}),e.jsx("td",{className:"px-3 py-2.5 text-[12px] text-zinc-700 text-right whitespace-nowrap",children:q(a.gross_sales_reported)}),e.jsxs("td",{className:"px-3 py-2.5 text-[12px] font-semibold text-zinc-900 text-right whitespace-nowrap",children:[q(a.commission_due),a.ledger_entry_id&&e.jsx("div",{className:"text-[10px] text-emerald-600 font-normal",children:"no ledger"})]}),e.jsx("td",{className:"px-3 py-2.5",children:e.jsx("select",{value:a.status,disabled:p===a.id,onChange:m=>g(a,m.target.value),className:"px-1.5 py-1 rounded text-[11px] font-semibold border-0 focus:outline-none disabled:opacity-50",style:{background:h.bg,color:h.color},children:Object.keys(qe).map(m=>e.jsx("option",{value:m,children:qe[m].label},m))})}),e.jsx("td",{className:"px-3 py-2.5",children:a.proof_storage_path?e.jsxs("button",{onClick:()=>l(a),disabled:p===a.id,className:"text-[12px] text-blue-600 hover:underline flex items-center gap-1 disabled:opacity-50",children:[e.jsx(Ee,{size:12})," Abrir"]}):e.jsx("span",{className:"text-[12px] text-zinc-300",children:"â"})}),e.jsxs("td",{className:"px-3 py-2.5 text-right whitespace-nowrap",children:[e.jsx("button",{onClick:()=>u(a),className:"text-[12px] text-zinc-500 hover:text-zinc-800 mr-3",children:"Editar"}),e.jsx("button",{onClick:()=>n(a),disabled:p===a.id,className:"text-zinc-300 hover:text-rose-600 disabled:opacity-50",title:"Excluir perÃodo",children:e.jsx(ve,{size:13})})]})]},a.id)})})]})})]}),v&&e.jsx(ka,{partnership:s,period:v==="new"?null:v,createdBy:(i==null?void 0:i.id)??null,onClose:()=>u(null),onSaved:async()=>{u(null),await x()}})]})},ka=({partnership:s,period:r,createdBy:i,onClose:f,onSaved:o})=>{var R,I;const[N,y]=t.useState(((R=r==null?void 0:r.period_start)==null?void 0:R.slice(0,10))??""),[w,v]=t.useState(((I=r==null?void 0:r.period_end)==null?void 0:I.slice(0,10))??""),[u,p]=t.useState(r?String(r.gross_sales_reported):""),[j,x]=t.useState(r?String(r.commission_due):""),[_,g]=t.useState(!!r),[n,l]=t.useState((r==null?void 0:r.notes)??""),[a,h]=t.useState(null),[m,c]=t.useState(!1),$=s.commission_pct!=null?Number(s.commission_pct):null,C=O=>{if(p(O),_||$===null)return;const B=Number(O.replace(",","."));x(Number.isNaN(B)||!O.trim()?"":(B*$/100).toFixed(2))},z=async()=>{if(!N||!w){d.error("Informe inÃcio e fim do perÃodo");return}if(w<N){d.error("O fim do perÃodo não pode ser anterior ao inÃcio");return}const O=Number(u.replace(",",".")||"0"),B=Number(j.replace(",",".")||"0");if(Number.isNaN(O)||O<0||Number.isNaN(B)||B<0){d.error("Valores inválidos");return}c(!0);try{let Y=(r==null?void 0:r.proof_storage_path)??null;a&&(Y=await Ce(s.portal_id,s.id,"commission-proof",a)),await ht({...r?{...r}:{},partnership_id:s.id,portal_id:s.portal_id,organization_id:s.organization_id??null,period_start:N,period_end:w,gross_sales_reported:O,commission_due:B,status:(r==null?void 0:r.status)??"reported",proof_storage_path:Y,notes:n.trim()||null,...r?{}:{created_by:i}}),d.success(r?"PerÃodo atualizado":"PerÃodo registrado"),await o()}catch(Y){k.error("[Partnerships] save commission period error:",Y),d.error("Erro ao salvar perÃodo")}finally{c(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-lg w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-[15px] font-semibold text-zinc-900 flex items-center gap-2",children:[e.jsx(Be,{size:15})," ",r?"Editar perÃodo":"Novo perÃodo de apuração"]}),e.jsx("button",{onClick:f,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("p",{className:"text-[12px] text-zinc-500 mb-3",children:["As vendas são ",e.jsx("strong",{children:"informadas pelo parceiro"})," â o portal não tem acesso ao checkout dele. Anexe o relatório/extrato como comprovante."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:te,children:"InÃcio do perÃodo *"}),e.jsx("input",{type:"date",value:N,onChange:O=>y(O.target.value),className:ie})]}),e.jsxs("div",{children:[e.jsx("label",{className:te,children:"Fim do perÃodo *"}),e.jsx("input",{type:"date",value:w,onChange:O=>v(O.target.value),className:ie})]}),e.jsxs("div",{children:[e.jsx("label",{className:te,children:"Vendas informadas (R$)"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:u,onChange:O=>C(O.target.value),className:ie})]}),e.jsxs("div",{children:[e.jsx("label",{className:te,children:"Comissão devida (R$)"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:j,onChange:O=>{g(!0),x(O.target.value)},className:ie}),$!==null&&!_&&e.jsxs("div",{className:"text-[10px] text-zinc-400 mt-1",children:["sugerido a ",Te($)," das vendas"]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:te,children:"Observações"}),e.jsx("input",{value:n,onChange:O=>l(O.target.value),className:ie,placeholder:"Ex.: relatório envi
6ado por e-mail em 05/09"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:te,children:"Comprovante (PDF ou imagem)"}),e.jsx("input",{type:"file",accept:"image/jpeg,image/png,image/webp,image/gif,application/pdf",onChange:O=>{var B;return h(((B=O.target.files)==null?void 0:B[0])??null)},className:"text-[12px] text-zinc-600"}),(r==null?void 0:r.proof_storage_path)&&!a&&e.jsx("div",{className:"text-[11px] text-zinc-400 mt-1",children:"Já existe um comprovante anexado â enviar outro arquivo substitui a referência."})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:f,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:z,disabled:m,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[m&&e.jsx(T,{size:13,className:"animate-spin"}),"Salvar"]})]})]})})})},Ea=({partnership:s,deliveries:r,createdBy:i,onClose:f,onSaved:o})=>{const[N,y]=t.useState("partner"),[w,v]=t.useState("consumption"),[u,p]=t.useState(""),[j,x]=t.useState(new Date().toISOString().slice(0,10)),[_,g]=t.useState(""),[n,l]=t.useState(""),[a,h]=t.useState(!1),m=async()=>{const c=Number(u);if(!u.trim()||Number.isNaN(c)||c<=0){d.error("Informe um valor válido");return}h(!0);try{await pt({partnership_id:s.id,portal_id:s.portal_id,organization_id:s.organization_id??null,side:N,entry_kind:w,amount:c,occurred_at:new Date(`${j}T12:00:00`).toISOString(),description:_.trim()||null,delivery_id:n||null,created_by:i}),d.success("Lançamento registrado"),await o()}catch($){k.error("[Partnerships] add ledger entry error:",$),d.error("Erro ao registrar lançamento")}finally{h(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-lg w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:"Novo lançamento"}),e.jsx("button",{onClick:f,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsx("p",{className:"text-[12px] text-zinc-500 mb-3",children:"Registro manual (ex.: consumo de contrapartida, ajuste, compensação). Valores referenciais."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:te,children:"Lado"}),e.jsxs("select",{value:N,onChange:c=>y(c.target.value),className:ie,children:[e.jsx("option",{value:"portal",children:"Portal"}),e.jsx("option",{value:"partner",children:"Parceiro"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:te,children:"Tipo"}),e.jsx("select",{value:w,onChange:c=>v(c.target.value),className:ie,children:Object.keys(Xe).map(c=>e.jsx("option",{value:c,children:Xe[c]},c))})]}),e.jsxs("div",{children:[e.jsx("label",{className:te,children:"Valor (R$) *"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:u,onChange:c=>p(c.target.value),className:ie})]}),e.jsxs("div",{children:[e.jsx("label",{className:te,children:"Ocorrido em"}),e.jsx("input",{type:"date",value:j,onChange:c=>x(c.target.value),className:ie})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:te,children:"Descrição"}),e.jsx("input",{value:_,onChange:c=>g(c.target.value),className:ie,placeholder:"Ex.: consumo de 10 ingressos do lote contratado"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:te,children:"Vincular à entrega (opcional)"}),e.jsxs("select",{value:n,onChange:c=>l(c.target.value),className:ie,children:[e.jsx("option",{value:"",children:"â sem vÃnculo â"}),r.map(c=>e.jsx("option",{value:c.id,children:c.title},c.id))]})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:f,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:m,disabled:a,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[a&&e.jsx(T,{size:13,className:"animate-spin"}),"Registrar"]})]})]})})})},De="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",ye="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1",Pa=({partnership:s,refresh:r})=>{const{user:i}=ne(),f=ge(),[o,N]=t.useState([]),[y,w]=t.useState(!0),[v,u]=t.useState(!1),[p,j]=t.useState(null),x=t.useCallback(async()=>{try{N(await zs(s.id))}catch(n){k.error("[Partnerships] load documents error:",n),d.error("Erro ao carregar documentos")}finally{w(!1)}},[s.id]);t.useEffect(()=>{x()},[x]);const _=async n=>
6{if(n.storage_path){j(n.id);try{const l=await _e(n.storage_path);if(!l){d.error("Não foi possÃvel gerar o link do documento");return}window.open(l,"_blank","noopener")}catch(l){k.error("[Partnerships] open document error:",l),d.error("Erro ao abrir documento")}finally{j(null)}}},g=async n=>{if(await f({title:"Excluir documento",message:`Excluir o documento "${n.title}"? Esta ação não pode ser desfeita.`,confirmLabel:"Excluir"}))try{await ft(n.id),d.success("Documento excluÃdo"),await x(),await r()}catch(l){k.error("[Partnerships] delete document error:",l),d.error("Erro ao excluir documento")}};return y?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("p",{className:"text-[12px] text-zinc-500",children:[o.length," documento(s) no bucket privado da parceria."]}),e.jsxs("button",{onClick:()=>u(!0),className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 flex items-center gap-1.5",children:[e.jsx(oe,{size:13})," Enviar documento"]})]}),o.length===0?e.jsxs("div",{className:"flex flex-col items-center py-12 text-zinc-400",children:[e.jsx(Oe,{size:32,className:"text-zinc-300"}),e.jsx("p",{className:"mt-2 text-[13px]",children:"Nenhum documento anexado."}),e.jsx("p",{className:"text-[11px]",children:"Contrato, plano comercial, autorizações de imagem etc."})]}):e.jsx("div",{className:"space-y-1.5",children:o.map(n=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border border-zinc-100 rounded-lg flex-wrap",children:[e.jsx(Oe,{size:16,className:"text-zinc-400 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[13px] text-zinc-800 font-medium",children:n.title}),e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-zinc-100 text-zinc-600 text-[10px] font-semibold",children:He[n.kind]}),e.jsxs("span",{className:"text-[10px] text-zinc-400",children:["v",n.version]}),n.signed_at&&e.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-600 text-[10px] font-semibold flex items-center gap-1",children:[e.jsx(Rs,{size:10})," Assinado em ",G(n.signed_at)]})]}),e.jsxs("div",{className:"text-[11px] text-zinc-400 mt-0.5",children:[n.valid_from||n.valid_until?e.jsxs(e.Fragment,{children:["Validade: ",G(n.valid_from)," â ",G(n.valid_until)]}):"Sem validade definida"," ⢠","enviado ",G(n.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.storage_path&&e.jsxs("button",{onClick:()=>_(n),disabled:p===n.id,className:"text-[11px] text-blue-600 hover:underline flex items-center gap-1 disabled:opacity-50",children:[p===n.id?e.jsx(T,{size:12,className:"animate-spin"}):e.jsx(Ee,{size:12}),"Abrir"]}),e.jsx("button",{onClick:()=>g(n),className:"p-1 text-zinc-400 hover:text-rose-600",title:"Excluir",children:e.jsx(ve,{size:14})})]})]},n.id))}),v&&e.jsx(La,{partnership:s,uploadedBy:(i==null?void 0:i.id)??null,onClose:()=>u(!1),onSaved:async()=>{u(!1),await x(),await r()}})]})},La=({partnership:s,uploadedBy:r,onClose:i,onSaved:f})=>{const[o,N]=t.useState("contract"),[y,w]=t.useState(""),[v,u]=t.useState(""),[p,j]=t.useState(""),[x,_]=t.useState(null),[g,n]=t.useState(!1),l=async()=>{if(!y.trim()){d.error("Informe o tÃtulo do documento");return}if(!x){d.error("Selecione o arquivo");return}n(!0);try{const a=await Ce(s.portal_id,s.id,o,x);await ys({partnership_id:s.id,portal_id:s.portal_id,kind:o,title:y.trim(),storage_path:a,valid_from:v||null,valid_until:p||null,uploaded_by:r}),d.success("Documento enviado"),await f()}catch(a){k.error("[Partnerships] upload document error:",a),d.error("Erro ao enviar documento")}finally{n(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-lg w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:"Enviar documento"}),e.jsx("button",{onClick:i,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Tipo"}),e.jsx("select",{value:o,onChange:a=>N(a.target.value),className:De,children:Object.keys(He).map(a=>e.jsx("option",{value:a,children:He[a]},a))})]}),e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"TÃtulo *"}),e.jsx("input",{value:y,onChange:a=>w(a.target.value),className:De,placeholder:"Ex.: Contrato de parceria assinad
6o"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Válido de"}),e.jsx("input",{type:"date",value:v,onChange:a=>u(a.target.value),className:De})]}),e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Válido até"}),e.jsx("input",{type:"date",value:p,onChange:a=>j(a.target.value),className:De})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Arquivo *"}),e.jsx("input",{type:"file",onChange:a=>{var h;return _(((h=a.target.files)==null?void 0:h[0])??null)},className:"w-full text-[12px] text-zinc-600 file:mr-3 file:px-3 file:py-1.5 file:rounded-md file:border-0 file:bg-zinc-100 file:text-zinc-700 file:text-[12px] file:font-semibold hover:file:bg-zinc-200"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:l,disabled:g,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[g&&e.jsx(T,{size:13,className:"animate-spin"}),"Enviar"]})]})]})})})},pe="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",he="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1",Aa=({partnership:s})=>{const r=ge(),[i,f]=t.useState([]),[o,N]=t.useState([]),[y,w]=t.useState(!0),[v,u]=t.useState(!1),[p,j]=t.useState(null),x=t.useCallback(async()=>{try{const[n,l]=await Promise.all([Es(s.id),Se(s.id)]);f(n),N(l)}catch(n){k.error("[Partnerships] load people error:",n),d.error("Erro ao carregar pessoas")}finally{w(!1)}},[s.id]);t.useEffect(()=>{x()},[x]);const _=async n=>{var a,h;const l=((a=n.profile)==null?void 0:a.full_name)||((h=n.profile)==null?void 0:h.email)||"este membro";if(await r({title:"Remover membro",message:`Remover ${l} da equipe da parceria?`,confirmLabel:"Remover"}))try{await bt(n.id),d.success("Membro removido"),await x()}catch(m){k.error("[Partnerships] remove member error:",m),d.error("Erro ao remover membro")}},g=async n=>{if(await r({title:"Excluir contato",message:`Excluir o contato "${n.name}"?`,confirmLabel:"Excluir"}))try{await jt(n.id),d.success("Contato excluÃdo"),await x()}catch(l){k.error("[Partnerships] delete contact error:",l),d.error("Erro ao excluir contato")}};return y?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):e.jsxs("div",{className:"grid md:grid-cols-2 gap-8",children:[e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h2",{className:"text-[14px] font-semibold text-zinc-800 flex items-center gap-2",children:[e.jsx(Ft,{size:14})," Equipe interna",e.jsxs("span",{className:"text-[11px] text-zinc-400 font-normal",children:["(",i.length,")"]})]}),e.jsxs("button",{onClick:()=>u(!0),className:"px-2.5 py-1.5 bg-zinc-900 text-white rounded-md text-[11px] font-semibold hover:bg-zinc-800 flex items-center gap-1",children:[e.jsx(Bt,{size:12})," Adicionar"]})]}),i.length===0?e.jsx("p",{className:"text-[12px] text-zinc-400",children:"Nenhum membro vinculado."}):e.jsx("div",{className:"space-y-1.5",children:i.map(n=>{var l,a,h,m;return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 border border-zinc-100 rounded-md",children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-zinc-100 flex items-center justify-center text-[11px] font-bold text-zinc-500 shrink-0",children:(((l=n.profile)==null?void 0:l.full_name)||((a=n.profile)==null?void 0:a.email)||"?").charAt(0).toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] text-zinc-800 font-medium truncate",children:((h=n.profile)==null?void 0:h.full_name)||((m=n.profile)==null?void 0:m.email)||n.user_id}),e.jsx("div",{className:"text-[11px] text-zinc-400",children:Je[n.member_role]})]}),e.jsx("button",{onClick:()=>_(n),title:"Remover",className:"p-1 text-zinc-400 hover:text-rose-600",children:e.jsx(ve,{size:13})})]},n.id)})})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h2",{className:"text-[14px] font-semibold text-zinc-800 flex items-center gap-2",children:[e.jsx(as,{size:14})," Contatos do parceiro",e.jsxs("span",{className:"text-[11px] text-zinc-400 font-normal",children:["(",o.length,")"]})]}),e.jsxs("button",{onClick:()=>j({contact:null}),className:"px-2.5 py-1.5 bg-zinc-900 text-white rounded-md text-[11px] font-semibold hover:bg-zinc-800 flex items-center gap-1",children:[e.jsx(oe,{size:12})," Novo contato"]})]}),o.length===0?e.jsx("p",{className:"text-[12px] text-zinc-400",children:"Nenhum contato â cadastre o aprovador do parceiro para as rodadas de aprovação."}):e.jsx("div",{className:"space-y-1.5",children:o.map(n=>e.jsxs("div",{className:"flex items-start gap-3 p-2.5 border border-zinc-100 rounded-md",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[13px] text-zinc-800 font-medium",children:n.name}),e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-zinc-100 text-zinc-600 text-[10px] font-semibold",children:Ze[n.contact_role]}
6),n.is_default_approver&&e.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-600 text-[10px] font-semibold flex items-center gap-0.5",children:[e.jsx(Ut,{size:10})," Aprovador padrão"]})]}),e.jsxs("div",{className:"text-[11px] text-zinc-400 mt-0.5 flex items-center gap-3 flex-wrap",children:[n.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(as,{size:10})," ",n.email]}),n.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vt,{size:10})," ",n.phone]})]}),n.notes&&e.jsx("p",{className:"text-[11px] text-zinc-400 italic mt-0.5",children:n.notes})]}),e.jsxs("div",{className:"flex gap-1 shrink-0",children:[e.jsx("button",{onClick:()=>j({contact:n}),title:"Editar",className:"p-1 text-zinc-400 hover:text-zinc-700",children:e.jsx(os,{size:13})}),e.jsx("button",{onClick:()=>g(n),title:"Excluir",className:"p-1 text-zinc-400 hover:text-rose-600",children:e.jsx(ve,{size:13})})]})]},n.id))})]}),v&&e.jsx(Ra,{partnership:s,existingUserIds:i.map(n=>n.user_id),onClose:()=>u(!1),onSaved:async()=>{u(!1),await x()}}),p&&e.jsx(Da,{partnership:s,contact:p.contact,onClose:()=>j(null),onSaved:async()=>{j(null),await x()}})]})},Ra=({partnership:s,existingUserIds:r,onClose:i,onSaved:f})=>{const[o,N]=t.useState(""),[y,w]=t.useState([]),[v,u]=t.useState(!1),[p,j]=t.useState(null),[x,_]=t.useState("executor"),[g,n]=t.useState(!1);t.useEffect(()=>{if(o.trim().length<2){w([]);return}const a=setTimeout(async()=>{u(!0);try{const{data:h,error:m}=await Ns.from("profiles").select("id, full_name, email").ilike("full_name",`%${o.trim()}%`).limit(15);if(m)throw m;w(h||[])}catch(h){k.error("[Partnerships] profile search error:",h),d.error("Erro ao buscar usuários")}finally{u(!1)}},300);return()=>clearTimeout(a)},[o]);const l=async()=>{if(!p){d.error("Selecione um usuário");return}if(r.includes(p.id)){d.error("Este usuário já faz parte da equipe");return}n(!0);try{await vt({partnership_id:s.id,portal_id:s.portal_id,user_id:p.id,member_role:x}),d.success("Membro adicionado"),await f()}catch(a){k.error("[Partnerships] add member error:",a),d.error("Erro ao adicionar membro")}finally{n(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-md w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:"Adicionar membro da equipe"}),e.jsx("button",{onClick:i,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:he,children:"Buscar usuário"}),e.jsxs("div",{className:"relative",children:[e.jsx(qt,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-zinc-400"}),e.jsx("input",{value:o,onChange:a=>{N(a.target.value),j(null)},placeholder:"Nome do usuário (mÃn. 2 letras)",className:`${pe} pl-8`})]})]}),v&&e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-zinc-400",children:[e.jsx(T,{size:12,className:"animate-spin"})," Buscandoâ¦"]}),!v&&y.length>0&&!p&&e.jsx("div",{className:"border border-zinc-100 rounded-md max-h-48 overflow-auto",children:y.map(a=>e.jsxs("button",{onClick:()=>j(a),disabled:r.includes(a.id),className:"w-full text-left px-3 py-2 hover:bg-zinc-50 disabled:opacity-40 disabled:cursor-not-allowed",children:[e.jsx("div",{className:"text-[13px] text-zinc-800",children:a.full_name||"(sem nome)"}),e.jsxs("div",{className:"text-[11px] text-zinc-400",children:[a.email,r.includes(a.id)&&" ⢠já na equipe"]})]},a.id))}),p&&e.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-zinc-50 border border-zinc-200 rounded-md",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] text-zinc-800 font-medium truncate",children:p.full_name||p.email}),e.jsx("div",{className:"text-[11px] text-zinc-400 truncate",children:p.email})]}),e.jsx("button",{onClick:()=>j(null),className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:14})})]}),e.jsxs("div",{children:[e.jsx("label",{className:he,children:"Papel"}),e.jsx("select",{value:x,onChange:a=>_(a.target.value),className:pe,children:Object.keys(Je).map(a=>e.jsx("option",{value:a,children:Je[a]},a))})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:l,disabled:g||!p,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[g&&e.jsx(T,{size:13,className:"animate-spin"}),"Adicionar"]})]})]})})})},Da=({partnership:s,contact:r,onClose:i,onSaved:f})=>{const[o,N]=t.useState((r==null?void 0:r.name)||""),[y,w]=t.useState((r==null?void 0:r.contact_role)||"partner_approver"),[v,u]=t.useState((r==null?void 0:r.email)||""),[p,j]=t.useState((r==null?void 0:r.phone)||""),[x,_]=t.useState((r==null?void 0:r.is_default_approver)??!1),[g,n]=t.useState((r==null?void 0:r.notes)||""),[l,a]=t.useState(!1),h=async()=>
6{if(!o.trim()){d.error("Informe o nome do contato");return}a(!0);try{await gt({...r?{...r}:{partnership_id:s.id,portal_id:s.portal_id},name:o.trim(),contact_role:y,email:v.trim()||null,phone:p.trim()||null,is_default_approver:x,notes:g.trim()||null}),d.success(r?"Contato atualizado":"Contato criado"),await f()}catch(m){k.error("[Partnerships] save contact error:",m),d.error("Erro ao salvar contato")}finally{a(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-md w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:r?"Editar contato":"Novo contato do parceiro"}),e.jsx("button",{onClick:i,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:he,children:"Nome *"}),e.jsx("input",{value:o,onChange:m=>N(m.target.value),className:pe})]}),e.jsxs("div",{children:[e.jsx("label",{className:he,children:"Papel"}),e.jsx("select",{value:y,onChange:m=>w(m.target.value),className:pe,children:Object.keys(Ze).map(m=>e.jsx("option",{value:m,children:Ze[m]},m))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:he,children:"E-mail"}),e.jsx("input",{type:"email",value:v,onChange:m=>u(m.target.value),className:pe})]}),e.jsxs("div",{children:[e.jsx("label",{className:he,children:"Telefone"}),e.jsx("input",{value:p,onChange:m=>j(m.target.value),className:pe})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-zinc-700",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:m=>_(m.target.checked)}),"Aprovador padrão das rodadas externas"]}),e.jsxs("div",{children:[e.jsx("label",{className:he,children:"Notas"}),e.jsx("textarea",{value:g,onChange:m=>n(m.target.value),rows:2,className:`${pe} resize-none`})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:h,disabled:l,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[l&&e.jsx(T,{size:13,className:"animate-spin"}),"Salvar contato"]})]})]})})})},rs={approval_request:"Pedido de aprovação",breach_notice:"Notificação de descumprimento",cure_notice:"Notificação de cura",termination_notice:"Notificação de rescisão",renewal_notice:"Aviso de renovação",general:"Comunicação geral"},Ma={approval_request:"bg-violet-50 text-violet-600",breach_notice:"bg-rose-50 text-rose-600",cure_notice:"bg-amber-50 text-amber-600",termination_notice:"bg-rose-50 text-rose-600",renewal_notice:"bg-blue-50 text-blue-600",general:"bg-zinc-100 text-zinc-600"},$s={email:"E-mail",whatsapp:"WhatsApp",phone:"Telefone",letter:"Carta/AR",meeting:"Reunião",other:"Outro"},fe="w-full border border-zinc-200 rounded-md p-2 text-[13px] focus:outline-none focus:border-zinc-400",be="text-[11px] font-semibold text-zinc-600 uppercase tracking-wider block mb-1";function Ta(s){return s?new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}):"â"}const Ia=({partnership:s})=>{const{user:r}=ne(),[i,f]=t.useState([]),[o,N]=t.useState([]),[y,w]=t.useState(!0),[v,u]=t.useState(!1),p=t.useCallback(async()=>{try{const[x,_]=await Promise.all([Nt(s.id),Se(s.id)]);f(x),N(_)}catch(x){k.error("[Partnerships] load communications error:",x),d.error("Erro ao carregar comunicações")}finally{w(!1)}},[s.id]);t.useEffect(()=>{p()},[p]);const j=x=>{var _;return x&&((_=o.find(g=>g.id===x))==null?void 0:_.name)||null};return y?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(T,{size:18,className:"animate-spin text-zinc-400"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("p",{className:"text-[12px] text-zinc-500",children:["Registro das comunicações formais com o parceiro",s.formal_channel&&e.jsxs(e.Fragment,{children:[" ","â canal formal do contrato: ",e.jsx("strong",{children:s.formal_channel})]}),"."]}),e.jsxs("button",{onClick:()=>u(!0),className:"px-3 py-1.5 bg-zinc-900 text-white rounded-md text-[12px] font-semibold hover:bg-zinc-800 flex items-center gap-1.5",children:[e.jsx(oe,{size:13}
6)," Registrar comunicação"]})]}),i.length===0?e.jsxs("div",{className:"flex flex-col items-center py-12 text-zinc-400",children:[e.jsx(Gt,{size:32,className:"text-zinc-300"}),e.jsx("p",{className:"mt-2 text-[13px]",children:"Nenhuma comunicação registrada."})]}):e.jsx("div",{className:"relative pl-5 space-y-4 before:absolute before:left-[5px] before:top-1 before:bottom-1 before:w-px before:bg-zinc-100",children:i.map(x=>e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute -left-5 top-1.5 w-[11px] h-[11px] rounded-full bg-white border-2 border-zinc-300"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-0.5",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold ${Ma[x.comm_type]}`,children:rs[x.comm_type]}),e.jsx("span",{className:"flex items-center gap-0.5 text-[10px] font-semibold text-zinc-500",children:x.direction==="outbound"?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{size:11})," Enviada"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yt,{size:11})," Recebida"]})}),e.jsxs("span",{className:"text-[11px] text-zinc-400",children:[$s[x.channel]||x.channel," ⢠",Ta(x.sent_at)]})]}),x.subject&&e.jsx("div",{className:"text-[13px] text-zinc-800 font-medium",children:x.subject}),x.body_excerpt&&e.jsx("p",{className:"text-[12px] text-zinc-500 mt-0.5 whitespace-pre-line",children:x.body_excerpt}),j(x.to_contact_id)&&e.jsxs("div",{className:"text-[11px] text-zinc-400 mt-0.5",children:["Destinatário: ",j(x.to_contact_id)]})]},x.id))}),v&&e.jsx($a,{partnership:s,contacts:o,createdBy:(r==null?void 0:r.id)??null,onClose:()=>u(!1),onSaved:async()=>{u(!1),await p()}})]})},$a=({partnership:s,contacts:r,createdBy:i,onClose:f,onSaved:o})=>{const[N,y]=t.useState("general"),[w,v]=t.useState("email"),[u,p]=t.useState("outbound"),[j,x]=t.useState(""),[_,g]=t.useState(""),[n,l]=t.useState(""),[a,h]=t.useState(!1),m=async()=>{if(!j.trim()){d.error("Informe o assunto");return}h(!0);try{await zt({partnership_id:s.id,portal_id:s.portal_id,comm_type:N,channel:w,direction:u,sent_at:new Date().toISOString(),subject:j.trim(),body_excerpt:_.trim()||null,to_contact_id:n||null,created_by:i}),d.success("Comunicação registrada"),await o()}catch(c){k.error("[Partnerships] add communication error:",c),d.error("Erro ao registrar comunicação")}finally{h(!1)}};return e.jsx(J,{children:e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[10000] p-4",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-xl max-w-lg w-full p-6 max-h-[90vh] overflow-auto no-mobile-fullscreen",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-zinc-900",children:"Registrar comunicação"}),e.jsx("button",{onClick:f,className:"text-zinc-400 hover:text-zinc-700",children:e.jsx(X,{size:18})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:be,children:"Tipo"}),e.jsx("select",{value:N,onChange:c=>y(c.target.value),className:fe,children:Object.keys(rs).map(c=>e.jsx("option",{value:c,children:rs[c]},c))})]}),e.jsxs("div",{children:[e.jsx("label",{className:be,children:"Canal"}),e.jsx("select",{value:w,onChange:c=>v(c.target.value),className:fe,children:Object.entries($s).map(([c,$])=>e.jsx("option",{value:c,children:$},c))})]}),e.jsxs("div",{children:[e.jsx("label",{className:be,children:"Direção"}),e.jsxs("select",{value:u,onChange:c=>p(c.target.value),className:fe,children:[e.jsx("option",{value:"outbound",children:"Enviada (portal â parceiro)"}),e.jsx("option",{value:"inbound",children:"Recebida (parceiro â portal)"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:be,children:"Contato"}),e.jsxs("select",{value:n,onChange:c=>l(c.target.value),className:fe,children:[e.jsx("option",{value:"",children:"â nenhum â"}),r.map(c=>e.jsx("option",{value:c.id,children:c.name},c.id))]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:be,children:"Assunto *"}),e.jsx("input",{value:j,onChange:c=>x(c.target.value),className:fe,placeholder:"Ex.: Notificação de atraso nas contrapartidas de maio"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:be,children:"Resumo do conteúdo"}
6),e.jsx("textarea",{value:_,onChange:c=>g(c.target.value),rows:4,className:`${fe} resize-none`,placeholder:"Trecho ou resumo da mensagem enviada/recebidaâ¦"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end mt-5 pt-4 border-t border-zinc-100",children:[e.jsx("button",{onClick:f,className:"px-4 py-2 text-zinc-600 text-[13px] hover:bg-zinc-100 rounded-md",children:"Cancelar"}),e.jsxs("button",{onClick:m,disabled:a,className:"px-4 py-2 bg-zinc-900 text-white text-[13px] font-semibold rounded-md hover:bg-zinc-800 disabled:opacity-50 flex items-center gap-2",children:[a&&e.jsx(T,{size:13,className:"animate-spin"}),"Registrar"]})]})]})})})},Oa=[{id:"overview",label:"Visão Geral"},{id:"contract",label:"Contrato"},{id:"plan",label:"Plano"},{id:"materials",label:"Materiais"},{id:"deliveries",label:"Entregas"},{id:"approvals",label:"Aprovações"},{id:"evidences",label:"Comprovações"},{id:"finance",label:"Financeiro"},{id:"documents",label:"Documentos"},{id:"people",label:"Pessoas"},{id:"communications",label:"Comunicações"}];function Ke({groupLabel:s,value:r,config:i,open:f,onToggle:o,onSelect:N}){const y=i[r],w=y.icon;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:o,title:`${s}: ${y.label}`,className:"flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-semibold hover:opacity-80 transition-opacity",style:{background:y.bg,color:y.color},children:[e.jsx(w,{size:12}),e.jsx("span",{className:"text-[9px] uppercase tracking-wider opacity-70",children:s}),y.label,e.jsx(Ht,{size:12})]}),f&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-30",onClick:o}),e.jsx("div",{className:"absolute left-0 top-full mt-1 z-40 bg-white border border-zinc-200 rounded-lg shadow-lg py-1 min-w-[200px]",children:Object.keys(i).map(v=>{const u=i[v],p=u.icon;return e.jsxs("button",{onClick:()=>N(v),className:"w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-zinc-700 hover:bg-zinc-50 text-left",children:[e.jsx(p,{size:13,style:{color:u.color}}),e.jsx("span",{className:"flex-1",children:u.label}),v===r&&e.jsx($e,{size:13,className:"text-zinc-400"})]},v)})})]})]})}const sr=()=>{var h;const{partnershipId:s}=qs(),r=Gs(),{currentPortal:i}=is(),f=i==null?void 0:i.id,[o,N]=t.useState(null),[y,w]=t.useState(null),[v,u]=t.useState(!0),[p,j]=t.useState("overview"),[x,_]=t.useState(null),g=t.useCallback(async()=>{if(s)try{const[m,c]=await Promise.allSettled([yt(s),Ps(s)]);if(m.status==="rejected")throw m.reason;if(f&&m.value&&m.value.portal_id!==f){N(null),u(!1);return}N(m.value),c.status==="fulfilled"?w(c.value):(k.error("[Partnerships] balance error:",c.reason),w(null))}catch(m){k.error("[Partnerships] load error:",m),d.error("Erro ao carregar parceria")}finally{u(!1)}},[s,f]);t.useEffect(()=>{g()},[g]);const n=t.useCallback(async m=>{if(o){_(null);try{await ns({...o,...m}),d.success("Status atualizado"),await g()}catch(c){k.error("[Partnerships] status update error:",c),d.error("Erro ao atualizar status")}}},[o,g]),l=t.useMemo(()=>{if(!(o!=null&&o.start_date)||!(o!=null&&o.end_date))return null;const m=(z,R)=>new Date(z.length===10?`${z}${R}`:z).getTime(),c=m(o.start_date,"T00:00:00"),$=m(o.end_date,"T23:59:59");if($<=c)return null;const C=Math.min(100,Math.max(0,(Date.now()-c)/($-c)*100));return{pct:Math.round(C),daysLeft:we(o.end_date)}},[o]);if(v)return e.jsx("div",{className:"h-full flex items-center justify-center bg-white",children:e.jsx(T,{size:20,className:"animate-spin text-zinc-400"})});if(!o)return e.jsxs("div",{className:"h-full flex flex-col items-center justify-center bg-white text-zinc-500",children:[e.jsx(Qt,{size:40}),e.jsx("p",{className:"mt-3 text-sm",children:"Parceria não encontrada"}),e.jsx("button",{onClick:()=>r("/admin/ads/partnerships"),className:"mt-4 text-blue-600 text-sm hover:underline",children:"â Voltar para listagem"})]});const a={partnership:o,refresh:g};return e.jsxs("div",{className:"h-full flex flex-col bg-white overflow-auto",children:[e.jsxs("div",{style:{padding:"20px 24px 0",borderBottom:"1px solid #e5e7eb"},children:[e.jsxs("button",{onClick:()=>r("/admin/ads/partnerships"),className:"flex items-center gap-1 text-[12px] text-zinc-500 hover:text-zinc-700 mb-3",children:[e.jsx(Wt,{size:14})," Voltar"]}),e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-[18px] font-semibold text-zinc-900 mb-1 truncate",children:o.title}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-zinc-500 flex-wrap",children:[((h=o.company)==null?void 0:h.name)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xt,{size:12})," ",o.company.name]}),e.jsx("span",{className:"px-2 py-0.5 rounded bg-zinc-100 text-zinc-600 font-semibold",children:wt[o.partnership_type]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(Ke,{groupLabel:"Operacional",value:o.status_operational,config:_t,open:x==="operational",onToggle:()=>_(m=>m==="operational"?null:"operational"),onSelect:m=>n({status_operational:m})}),e.jsx(Ke,{groupLabel:"Comercial",value:o.status_commercial,config:Ct,open:x==="commercial",onToggle:()=>_(m=>m==="commercial"?null:"commercial"),onSelect:m=>n({status_commercial:m})}),e.jsx(Ke,{groupLabel:"JurÃdico",value:o.status_legal,config:je,open:x==="legal",onToggle:()=>_(m=>m==="legal"?null:"legal"),onSelect:m=>n({status_legal:m})})]})]}),(o.start_date||o.end_date)&&e.jsxs("div",{className:"mt-4 max-w-xl",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] text-zinc-500 mb-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ds,{size:12}),G(o.start_date)," â ",G(o.end_date)]}),l&&e.jsx("span",{className:l.daysLeft!==null&&l.daysLeft<0?"text-rose-600 font-semibold":l.daysLeft!==null&&l.daysLeft<=60?"text-amber-600 font-semibold":"",children:l.daysLeft===null?"":l.daysLeft<0?`Vencida há ${Math.abs(l.daysLeft)} dias`:l.daysLeft===0?"Vence hoje":`${l.daysLeft} dias restantes`})]}),l&&e.jsx("div",{className:"h-1.5 bg-zinc-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${l.pct>=90?"bg-rose-500":l.pct>
6=70?"bg-amber-500":"bg-emerald-500"}`,style:{width:`${l.pct}%`}})})]}),e.jsx("div",{className:"flex gap-1 mt-4 overflow-x-auto",children:Oa.map(m=>e.jsx("button",{onClick:()=>j(m.id),className:`px-3 py-2 text-[12px] font-semibold whitespace-nowrap border-b-2 transition-colors ${p===m.id?"border-zinc-900 text-zinc-900":"border-transparent text-zinc-500 hover:text-zinc-700"}`,children:m.label},m.id))})]}),e.jsxs("div",{className:"flex-1 p-6 overflow-auto",children:[p==="overview"&&e.jsx(Zt,{...a,balance:y}),p==="contract"&&e.jsx(sa,{...a}),p==="materials"&&e.jsx(na,{...a}),p==="plan"&&e.jsx(ma,{...a}),p==="deliveries"&&e.jsx(ha,{...a}),p==="approvals"&&e.jsx(za,{...a}),p==="evidences"&&e.jsx(_a,{...a}),p==="finance"&&e.jsx(Ca,{...a,balance:y}),p==="documents"&&e.jsx(Pa,{...a}),p==="people"&&e.jsx(Aa,{...a}),p==="communications"&&e.jsx(Ia,{...a})]})]})};export{sr as PartnershipDetailPage,sr 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.