@danhachuel/leadmaster 0.1.17 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/backend/__pycache__/main.cpython-311.pyc +0 -0
  3. package/backend/main.py +42 -2
  4. package/backend/services/__pycache__/__init__.cpython-311.pyc +0 -0
  5. package/backend/services/__pycache__/agents.cpython-311.pyc +0 -0
  6. package/backend/services/__pycache__/crm_agent.cpython-311.pyc +0 -0
  7. package/backend/services/__pycache__/extractors.cpython-311.pyc +0 -0
  8. package/backend/services/__pycache__/flags.cpython-311.pyc +0 -0
  9. package/backend/services/__pycache__/llm.cpython-311.pyc +0 -0
  10. package/backend/services/__pycache__/storage.cpython-311.pyc +0 -0
  11. package/backend/tests/__pycache__/conftest.cpython-311-pytest-8.4.2.pyc +0 -0
  12. package/backend/tests/__pycache__/test_campaigns_routes.cpython-311-pytest-8.4.2.pyc +0 -0
  13. package/backend/tests/__pycache__/test_cnpj_extractor.cpython-311-pytest-8.4.2.pyc +0 -0
  14. package/backend/tests/__pycache__/test_config.cpython-311-pytest-8.4.2.pyc +0 -0
  15. package/backend/tests/__pycache__/test_crm_routes.cpython-311-pytest-8.4.2.pyc +0 -0
  16. package/backend/tests/__pycache__/test_instagram_extractor.cpython-311-pytest-8.4.2.pyc +0 -0
  17. package/backend/tests/__pycache__/test_launcher_protections.cpython-311-pytest-8.4.2.pyc +0 -0
  18. package/backend/tests/__pycache__/test_maps_extractor.cpython-311-pytest-8.4.2.pyc +0 -0
  19. package/backend/tests/__pycache__/test_metrics.cpython-311-pytest-8.4.2.pyc +0 -0
  20. package/backend/tests/__pycache__/test_process_flags.cpython-311-pytest-8.4.2.pyc +0 -0
  21. package/backend/tests/test_config.py +90 -0
  22. package/backend/tests/test_metrics.py +112 -0
  23. package/frontend/dist/assets/{index-BWyDEt5a.js → index-CXuYUAoQ.js} +4 -4
  24. package/frontend/dist/assets/{index-BKo_OphM.css → index-ib1LXo9v.css} +1 -1
  25. package/frontend/dist/index.html +2 -2
  26. package/package.json +1 -1
@@ -64,7 +64,7 @@ Error generating stack: `+i.message+`
64
64
  * LICENSE.md file in the root directory of this source tree.
65
65
  *
66
66
  * @license MIT
67
- */function Al(){return Al=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var s in n)({}).hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Al.apply(null,arguments)}function py(t,e){if(t==null)return{};var n={};for(var s in t)if({}.hasOwnProperty.call(t,s)){if(e.indexOf(s)!==-1)continue;n[s]=t[s]}return n}function WS(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function HS(t,e){return t.button===0&&(!e||e==="_self")&&!WS(t)}function Rd(t){return t===void 0&&(t=""),new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,n)=>{let s=t[n];return e.concat(Array.isArray(s)?s.map(r=>[n,r]):[[n,s]])},[]))}function VS(t,e){let n=Rd(t);return e&&e.forEach((s,r)=>{n.has(r)||e.getAll(r).forEach(i=>{n.append(r,i)})}),n}const QS=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],KS=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],YS="6";try{window.__reactRouterVersion=YS}catch{}const XS=S.createContext({isTransitioning:!1}),qS="startTransition",Qp=ib[qS];function GS(t){let{basename:e,children:n,future:s,window:r}=t,i=S.useRef();i.current==null&&(i.current=tS({window:r,v5Compat:!0}));let o=i.current,[a,l]=S.useState({action:o.action,location:o.location}),{v7_startTransition:c}=s||{},d=S.useCallback(f=>{c&&Qp?Qp(()=>l(f)):l(f)},[l,c]);return S.useLayoutEffect(()=>o.listen(d),[o,d]),S.useEffect(()=>BS(s),[s]),S.createElement($S,{basename:e,children:n,location:a.location,navigationType:a.action,navigator:o,future:s})}const JS=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ZS=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,e_=S.forwardRef(function(e,n){let{onClick:s,relative:r,reloadDocument:i,replace:o,state:a,target:l,to:c,preventScrollReset:d,viewTransition:f}=e,h=py(e,QS),{basename:p}=S.useContext(Rs),m,g=!1;if(typeof c=="string"&&ZS.test(c)&&(m=c,JS))try{let v=new URL(window.location.href),_=c.startsWith("//")?new URL(v.protocol+c):new URL(c),w=pi(_.pathname,p);_.origin===v.origin&&w!=null?c=w+_.search+_.hash:g=!0}catch{}let b=CS(c,{relative:r}),y=n_(c,{replace:o,state:a,target:l,preventScrollReset:d,relative:r,viewTransition:f});function x(v){s&&s(v),v.defaultPrevented||y(v)}return S.createElement("a",Al({},h,{href:m||b,onClick:g||i?s:x,ref:n,target:l}))}),gy=S.forwardRef(function(e,n){let{"aria-current":s="page",caseSensitive:r=!1,className:i="",end:o=!1,style:a,to:l,viewTransition:c,children:d}=e,f=py(e,KS),h=vc(l,{relative:f.relative}),p=Os(),m=S.useContext(ly),{navigator:g,basename:b}=S.useContext(Rs),y=m!=null&&r_(h)&&c===!0,x=g.encodeLocation?g.encodeLocation(h).pathname:h.pathname,v=p.pathname,_=m&&m.navigation&&m.navigation.location?m.navigation.location.pathname:null;r||(v=v.toLowerCase(),_=_?_.toLowerCase():null,x=x.toLowerCase()),_&&b&&(_=pi(_,b)||_);const w=x!=="/"&&x.endsWith("/")?x.length-1:x.length;let k=v===x||!o&&v.startsWith(x)&&v.charAt(w)==="/",C=_!=null&&(_===x||!o&&_.startsWith(x)&&_.charAt(x.length)==="/"),j={isActive:k,isPending:C,isTransitioning:y},M=k?s:void 0,E;typeof i=="function"?E=i(j):E=[i,k?"active":null,C?"pending":null,y?"transitioning":null].filter(Boolean).join(" ");let P=typeof a=="function"?a(j):a;return S.createElement(e_,Al({},f,{"aria-current":M,className:E,ref:n,style:P,to:l,viewTransition:c}),typeof d=="function"?d(j):d)});var Od;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(Od||(Od={}));var Kp;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Kp||(Kp={}));function t_(t){let e=S.useContext(xc);return e||je(!1),e}function n_(t,e){let{target:n,replace:s,state:r,preventScrollReset:i,relative:o,viewTransition:a}=e===void 0?{}:e,l=bi(),c=Os(),d=vc(t,{relative:o});return S.useCallback(f=>{if(HS(f,n)){f.preventDefault();let h=s!==void 0?s:Ll(c)===Ll(d);l(t,{replace:h,state:r,preventScrollReset:i,relative:o,viewTransition:a})}},[c,l,d,s,r,n,t,i,o,a])}function s_(t){let e=S.useRef(Rd(t)),n=S.useRef(!1),s=Os(),r=S.useMemo(()=>VS(s.search,n.current?null:e.current),[s.search]),i=bi(),o=S.useCallback((a,l)=>{const c=Rd(typeof a=="function"?a(r):a);n.current=!0,i("?"+c,l)},[i,r]);return[r,o]}function r_(t,e){e===void 0&&(e={});let n=S.useContext(XS);n==null&&je(!1);let{basename:s}=t_(Od.useViewTransitionState),r=vc(t,{relative:e.relative});if(!n.isTransitioning)return!1;let i=pi(n.currentLocation.pathname,s)||n.currentLocation.pathname,o=pi(n.nextLocation.pathname,s)||n.nextLocation.pathname;return Md(r.pathname,o)!=null||Md(r.pathname,i)!=null}const i_="/api";class o_ extends Error{constructor(n,s){super(s);B(this,"status");this.status=n,this.name="ApiError"}}async function U(t,e={}){const n=await fetch(i_+t,{...e,headers:e.body?{"Content-Type":"application/json",...e.headers||{}}:e.headers});if(!n.ok){let s=`Erro HTTP ${n.status}`;try{const r=await n.json();s=String(r.detail||r.mensagem||s)}catch{}throw new o_(n.status,s)}if(n.status!==204)return n.json()}const Me=t=>({method:"POST",body:JSON.stringify(t)}),W={health:()=>U("/health"),doctor:()=>U("/doctor"),shutdown:()=>U("/shutdown",Me({})),metricas:()=>U("/metrics"),leads:{listar:()=>U("/leads"),criar:t=>U("/leads",Me(t)),atualizar:(t,e)=>U(`/leads/${t}`,{method:"PATCH",body:JSON.stringify(e)}),remover:t=>U(`/leads/${t}`,{method:"DELETE"}),importar:t=>U("/leads/import",Me({leads:t})),enriquecer:t=>U(`/leads/${t}/enrich`,Me({}))},crm:{leadsListar:()=>U("/crm/leads"),criarLead:t=>U("/crm/leads",Me(t)),moverLead:(t,e)=>U(`/crm/leads/${t}/etapa`,{method:"PUT",body:JSON.stringify({etapa:e})}),sugestoes:()=>U("/crm/sugestoes"),aplicar:(t,e)=>U("/crm/sugestoes/aplicar",Me({lead_id:t,para:e}))},campanhas:{listar:()=>U("/campaigns"),criar:t=>U("/campaigns",Me(t)),status:(t,e)=>U(`/campaigns/${t}/status`,{method:"PUT",body:JSON.stringify({status:e})}),iniciar:t=>U(`/campaigns/${t}/start`,Me({})),pausar:t=>U(`/campaigns/${t}/pause`,Me({})),parar:t=>U(`/campaigns/${t}/stop`,Me({})),remover:t=>U(`/campaigns/${t}`,{method:"DELETE"})},extrair:{maps:t=>U("/extractors/maps",Me(t)),instagram:(t,e)=>U("/extractors/instagram",Me({profile_url:t,limit:e})),cnpj:t=>U("/extract/cnpj",Me({cnpj:t})),cnpjBusca:t=>U("/extract/cnpj/search",Me(t)),cnpjExtract:t=>U("/extractors/cnpj",Me(t))},config:{obter:()=>U("/config"),salvar:t=>U("/config",{method:"PUT",body:JSON.stringify(t)}),testarLlm:()=>U("/config/test/llm",Me({})),testarIntegracao:t=>U("/config/test/integracao",Me({url:t}))},integracoes:()=>U("/integrations/status"),agentes:{templates:()=>U("/agents/templates"),salvarTemplates:t=>U("/agents/templates",{method:"PUT",body:JSON.stringify(t)}),testarTemplate:(t,e)=>U("/agents/templates/test",Me({template:t,lead_id:e})),chat:t=>U("/agents/attendance/chat",Me({mensagens:t}))},webhook:{obter:()=>U("/webhook"),salvar:t=>U("/webhook",{method:"PUT",body:JSON.stringify(t)}),testar:t=>U("/webhook/test",Me({url:t}))}};function H(...t){return t.filter(Boolean).join(" ")}function a_(t){return(t||"?").trim().charAt(0).toUpperCase()||"?"}function Il(t){if(!t)return"—";try{return new Date(t).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return t}}function na(t){const e=(t||"").replace(/\D/g,"");return e?e.length===11?`(${e.slice(0,2)}) ${e.slice(2,7)}-${e.slice(7)}`:e.length===10?`(${e.slice(0,2)}) ${e.slice(2,6)}-${e.slice(6)}`:t||"—":"—"}function l_(t){const e=["nome","telefone","email","empresa","cidade","observacoes"],n=e.filter(s=>String(t[s]||"").trim().length>0);return Math.round(n.length/e.length*100)}function c_(t){const e={nome:"nome",telefone:"telefone",email:"e-mail",empresa:"empresa",cidade:"cidade",observacoes:"observações"};return["nome","telefone","email","empresa","cidade","observacoes"].filter(s=>String(t[s]||"").trim().length===0).map(s=>e[s])}function u_(t,e){if(t>=100)return"Lead 100% completo — excelente! 🎉";const n=e.slice(0,2).join(" e ");return`Faltam ${100-t}% (${n}${e.length>2?"...":""}) para o lead ficar completo`}function d_(t,e){const n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),s=URL.createObjectURL(n),r=document.createElement("a");r.href=s,r.download=e,r.click(),URL.revokeObjectURL(s)}const f_={md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"};function Xt({aberto:t,onFechar:e,titulo:n,children:s,icone:r="fas fa-circle-info",largura:i="md"}){return S.useEffect(()=>{const o=a=>{a.key==="Escape"&&e()};return t&&window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[t,e]),t?u.jsx("div",{className:"fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4",onMouseDown:o=>{o.target===o.currentTarget&&e()},children:u.jsxs("div",{className:H("bg-white rounded-2xl shadow-xl w-full",f_[i]),children:[u.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-100",children:[u.jsxs("h3",{className:"text-base font-semibold text-gray-800 flex items-center gap-2",children:[u.jsx("i",{className:H(r,"text-indigo-500")})," ",n]}),u.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-600","aria-label":"Fechar",children:u.jsx("i",{className:"fas fa-times"})})]}),u.jsx("div",{className:"px-6 py-5 max-h-[70vh] overflow-y-auto",children:s})]})}):null}const h_=[{icone:"fas fa-users",texto:"Cadastre leads manualmente ou importe pelos Extratores (Maps, Instagram, CNPJ)."},{icone:"fas fa-columns",texto:"Arraste os cards no CRM conforme avança no funil (Leads → Em contato → Proposta → Fechado)."},{icone:"fas fa-bullhorn",texto:"Monte campanhas de disparo com seus templates e acompanhe as taxas no Painel."},{icone:"fas fa-robot",texto:"Use os Agentes (disparo e atendimento) e configure o LLM em Ferramentas para turbiná-los."}];function p_({titulo:t,nomeUsuario:e}){const[n,s]=S.useState(!1);return u.jsxs("header",{className:"bg-white shadow-sm px-8 py-4 flex items-center justify-between shrink-0",children:[u.jsx("div",{children:u.jsx("h2",{className:"text-lg font-semibold text-gray-800",children:t})}),u.jsxs("div",{className:"flex items-center space-x-4",children:[u.jsxs("button",{onClick:()=>s(!0),className:"text-sm text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-play-circle mr-1"})," Ver tutorial"]}),u.jsx("div",{className:"w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 font-bold text-sm",children:a_(e)}),u.jsx("span",{className:"text-sm font-medium text-gray-700",children:e})]}),u.jsxs(Xt,{aberto:n,onFechar:()=>s(!1),titulo:"Tutorial rápido",icone:"fas fa-graduation-cap",children:[u.jsx("ol",{className:"space-y-4",children:h_.map((r,i)=>u.jsxs("li",{className:"flex gap-3 items-start",children:[u.jsx("span",{className:"w-8 h-8 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0",children:u.jsx("i",{className:r.icone})}),u.jsx("p",{className:"text-sm text-gray-600 pt-1.5",children:r.texto})]},i))}),u.jsx("p",{className:"text-xs text-gray-400 mt-5",children:"Dica: o LLM (para enriquecimento e agentes) é configurado em Ferramentas."})]})]})}const g_=[{itens:[{para:"/",icone:"fas fa-chart-pie text-indigo-300",rotulo:"Painel",fim:!0}]},{secao:"Conexões",itens:[{para:"/leads",icone:"fas fa-users",rotulo:"Leads"},{para:"/agentes",icone:"fas fa-robot",rotulo:"Agentes"},{para:"/ferramentas",icone:"fas fa-tools",rotulo:"Ferramentas"}]},{itens:[{para:"/extrator-maps",icone:"fas fa-map-marked-alt",rotulo:"Extrator Maps"},{para:"/extrator-instagram",icone:"fab fa-instagram",rotulo:"Extrator Instagram"},{para:"/extrator-cnpj",icone:"fas fa-building",rotulo:"Extrator CNPJ"}]},{secao:"Gestão",itens:[{para:"/disparos",icone:"fas fa-bullhorn",rotulo:"Disparos"},{para:"/crm",icone:"fas fa-columns",rotulo:"CRM"}]},{secao:"Integrações",itens:[{para:"/webhook",icone:"fas fa-link",rotulo:"Webhook"},{para:"/suporte",icone:"fas fa-headset",rotulo:"Suporte"}]}];function m_({onSair:t}){const e=Os(),[n,s]=S.useState(!1);S.useEffect(()=>{e.pathname==="/agentes"&&s(!0)},[e.pathname]);const r=i=>{if(i.rotulo==="Agentes")return e.pathname==="/agentes";const[o,a]=i.para.split("?");return a?e.pathname===o&&e.search.includes(a):i.fim?e.pathname===o:e.pathname.startsWith(o)};return u.jsxs("aside",{className:"w-64 bg-[#1e1b4b] text-white flex flex-col shrink-0 h-screen sticky top-0",children:[u.jsx("div",{className:"p-6 border-b border-gray-700",children:u.jsxs("h1",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[u.jsx("span",{className:"text-2xl",children:"⚡"}),"LeadMaster",u.jsxs("span",{className:"text-[10px] font-medium text-indigo-300 border border-indigo-400/40 rounded-md px-1.5 py-0.5",children:["v","0.1.17"]})]})}),u.jsx("nav",{className:"flex-1 overflow-y-auto py-4",children:u.jsx("ul",{className:"space-y-1",children:g_.map((i,o)=>u.jsx("li",{children:u.jsxs("ul",{children:[i.secao&&u.jsx("li",{className:"px-6 py-2 text-xs font-semibold text-gray-400 uppercase tracking-wider list-none",children:i.secao}),i.itens.map(a=>a.rotulo==="Agentes"?u.jsxs("li",{children:[u.jsxs("button",{type:"button",onClick:()=>s(l=>!l),className:H("sidebar-link w-full flex items-center px-6 py-2.5 text-sm",r(a)&&"active"),children:[u.jsx("i",{className:H(a.icone,"w-5 text-gray-400")}),u.jsx("span",{className:"ml-3",children:a.rotulo}),u.jsx("i",{className:H("fas fa-chevron-down ml-auto text-xs text-gray-400 transition-transform",n&&"rotate-180")})]}),n&&u.jsxs("ul",{className:"pl-12 space-y-1 mt-1",children:[u.jsx("li",{children:u.jsx(Yp,{para:"/agentes?tab=disparo",rotulo:"Agente de Disparo",ativo:e.pathname==="/agentes"&&e.search.includes("disparo")})}),u.jsx("li",{children:u.jsx(Yp,{para:"/agentes?tab=atendimento",rotulo:"Agente de Atendimento",ativo:e.pathname==="/agentes"&&e.search.includes("atendimento")})})]})]},"agentes"):u.jsx("li",{children:u.jsxs(gy,{to:a.para,className:H("sidebar-link flex items-center px-6 py-2.5 text-sm",r(a)&&"active"),children:[u.jsx("i",{className:H(a.icone,"w-5 text-gray-400")}),u.jsx("span",{className:"ml-3",children:a.rotulo})]})},a.para))]})},o))})}),u.jsx("div",{className:"p-4 border-t border-gray-700",children:u.jsxs("button",{onClick:t,className:"w-full flex items-center justify-center px-4 py-2.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg text-sm font-medium hover:opacity-90 transition",children:[u.jsx("i",{className:"fas fa-sign-out-alt mr-2"})," Sair"]})})]})}function Yp({para:t,rotulo:e,ativo:n}){return u.jsx(gy,{to:t,className:H("sidebar-link block px-4 py-2 text-xs text-gray-300 rounded",n&&"active"),children:e})}const my=S.createContext({toast:()=>{}});function en(){return S.useContext(my)}const x_={sucesso:"bg-green-600",erro:"bg-red-600",info:"bg-indigo-600"},y_={sucesso:"fas fa-check-circle",erro:"fas fa-exclamation-circle",info:"fas fa-info-circle"};function v_({children:t}){const[e,n]=S.useState([]),s=S.useRef(0),r=S.useCallback((i,o)=>{const a=++s.current;n(l=>[...l,{id:a,tipo:i,mensagem:o}]),setTimeout(()=>n(l=>l.filter(c=>c.id!==a)),4500)},[]);return u.jsxs(my.Provider,{value:{toast:r},children:[t,u.jsx("div",{className:"fixed top-4 right-4 z-[100] space-y-2 w-80",children:e.map(i=>u.jsxs("div",{className:H(x_[i.tipo],"text-white text-sm rounded-lg shadow-lg px-4 py-3 flex items-start gap-2 animate-pulse-once"),role:"status",children:[u.jsx("i",{className:H(y_[i.tipo],"mt-0.5")}),u.jsx("span",{className:"flex-1",children:i.mensagem}),u.jsx("button",{className:"opacity-70 hover:opacity-100",onClick:()=>n(o=>o.filter(a=>a.id!==i.id)),"aria-label":"Fechar",children:u.jsx("i",{className:"fas fa-times"})})]},i.id))})]})}function Pa({rotulo:t,valor:e,subtitulo:n,children:s,icone:r}){return u.jsxs("div",{className:"bg-white rounded-xl shadow-sm p-5 border border-gray-100",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"text-sm text-gray-500 font-medium",children:t}),r&&u.jsx("i",{className:`${r} text-indigo-300`})]}),s??u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"text-2xl font-bold text-gray-800 mt-1",children:e}),n&&u.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:n})]})]})}/*!
67
+ */function Al(){return Al=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var s in n)({}).hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Al.apply(null,arguments)}function py(t,e){if(t==null)return{};var n={};for(var s in t)if({}.hasOwnProperty.call(t,s)){if(e.indexOf(s)!==-1)continue;n[s]=t[s]}return n}function WS(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function HS(t,e){return t.button===0&&(!e||e==="_self")&&!WS(t)}function Rd(t){return t===void 0&&(t=""),new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,n)=>{let s=t[n];return e.concat(Array.isArray(s)?s.map(r=>[n,r]):[[n,s]])},[]))}function VS(t,e){let n=Rd(t);return e&&e.forEach((s,r)=>{n.has(r)||e.getAll(r).forEach(i=>{n.append(r,i)})}),n}const QS=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],KS=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],YS="6";try{window.__reactRouterVersion=YS}catch{}const XS=S.createContext({isTransitioning:!1}),qS="startTransition",Qp=ib[qS];function GS(t){let{basename:e,children:n,future:s,window:r}=t,i=S.useRef();i.current==null&&(i.current=tS({window:r,v5Compat:!0}));let o=i.current,[a,l]=S.useState({action:o.action,location:o.location}),{v7_startTransition:c}=s||{},d=S.useCallback(f=>{c&&Qp?Qp(()=>l(f)):l(f)},[l,c]);return S.useLayoutEffect(()=>o.listen(d),[o,d]),S.useEffect(()=>BS(s),[s]),S.createElement($S,{basename:e,children:n,location:a.location,navigationType:a.action,navigator:o,future:s})}const JS=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ZS=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,e_=S.forwardRef(function(e,n){let{onClick:s,relative:r,reloadDocument:i,replace:o,state:a,target:l,to:c,preventScrollReset:d,viewTransition:f}=e,h=py(e,QS),{basename:p}=S.useContext(Rs),m,g=!1;if(typeof c=="string"&&ZS.test(c)&&(m=c,JS))try{let v=new URL(window.location.href),_=c.startsWith("//")?new URL(v.protocol+c):new URL(c),w=pi(_.pathname,p);_.origin===v.origin&&w!=null?c=w+_.search+_.hash:g=!0}catch{}let b=CS(c,{relative:r}),y=n_(c,{replace:o,state:a,target:l,preventScrollReset:d,relative:r,viewTransition:f});function x(v){s&&s(v),v.defaultPrevented||y(v)}return S.createElement("a",Al({},h,{href:m||b,onClick:g||i?s:x,ref:n,target:l}))}),gy=S.forwardRef(function(e,n){let{"aria-current":s="page",caseSensitive:r=!1,className:i="",end:o=!1,style:a,to:l,viewTransition:c,children:d}=e,f=py(e,KS),h=vc(l,{relative:f.relative}),p=Os(),m=S.useContext(ly),{navigator:g,basename:b}=S.useContext(Rs),y=m!=null&&r_(h)&&c===!0,x=g.encodeLocation?g.encodeLocation(h).pathname:h.pathname,v=p.pathname,_=m&&m.navigation&&m.navigation.location?m.navigation.location.pathname:null;r||(v=v.toLowerCase(),_=_?_.toLowerCase():null,x=x.toLowerCase()),_&&b&&(_=pi(_,b)||_);const w=x!=="/"&&x.endsWith("/")?x.length-1:x.length;let k=v===x||!o&&v.startsWith(x)&&v.charAt(w)==="/",C=_!=null&&(_===x||!o&&_.startsWith(x)&&_.charAt(x.length)==="/"),j={isActive:k,isPending:C,isTransitioning:y},M=k?s:void 0,E;typeof i=="function"?E=i(j):E=[i,k?"active":null,C?"pending":null,y?"transitioning":null].filter(Boolean).join(" ");let P=typeof a=="function"?a(j):a;return S.createElement(e_,Al({},f,{"aria-current":M,className:E,ref:n,style:P,to:l,viewTransition:c}),typeof d=="function"?d(j):d)});var Od;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(Od||(Od={}));var Kp;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Kp||(Kp={}));function t_(t){let e=S.useContext(xc);return e||je(!1),e}function n_(t,e){let{target:n,replace:s,state:r,preventScrollReset:i,relative:o,viewTransition:a}=e===void 0?{}:e,l=bi(),c=Os(),d=vc(t,{relative:o});return S.useCallback(f=>{if(HS(f,n)){f.preventDefault();let h=s!==void 0?s:Ll(c)===Ll(d);l(t,{replace:h,state:r,preventScrollReset:i,relative:o,viewTransition:a})}},[c,l,d,s,r,n,t,i,o,a])}function s_(t){let e=S.useRef(Rd(t)),n=S.useRef(!1),s=Os(),r=S.useMemo(()=>VS(s.search,n.current?null:e.current),[s.search]),i=bi(),o=S.useCallback((a,l)=>{const c=Rd(typeof a=="function"?a(r):a);n.current=!0,i("?"+c,l)},[i,r]);return[r,o]}function r_(t,e){e===void 0&&(e={});let n=S.useContext(XS);n==null&&je(!1);let{basename:s}=t_(Od.useViewTransitionState),r=vc(t,{relative:e.relative});if(!n.isTransitioning)return!1;let i=pi(n.currentLocation.pathname,s)||n.currentLocation.pathname,o=pi(n.nextLocation.pathname,s)||n.nextLocation.pathname;return Md(r.pathname,o)!=null||Md(r.pathname,i)!=null}const i_="/api";class o_ extends Error{constructor(n,s){super(s);B(this,"status");this.status=n,this.name="ApiError"}}async function U(t,e={}){const n=await fetch(i_+t,{...e,headers:e.body?{"Content-Type":"application/json",...e.headers||{}}:e.headers});if(!n.ok){let s=`Erro HTTP ${n.status}`;try{const r=await n.json();s=String(r.detail||r.mensagem||s)}catch{}throw new o_(n.status,s)}if(n.status!==204)return n.json()}const Me=t=>({method:"POST",body:JSON.stringify(t)}),W={health:()=>U("/health"),doctor:()=>U("/doctor"),shutdown:()=>U("/shutdown",Me({})),metricas:()=>U("/metrics"),leads:{listar:()=>U("/leads"),criar:t=>U("/leads",Me(t)),atualizar:(t,e)=>U(`/leads/${t}`,{method:"PATCH",body:JSON.stringify(e)}),remover:t=>U(`/leads/${t}`,{method:"DELETE"}),importar:t=>U("/leads/import",Me({leads:t})),enriquecer:t=>U(`/leads/${t}/enrich`,Me({}))},crm:{leadsListar:()=>U("/crm/leads"),criarLead:t=>U("/crm/leads",Me(t)),moverLead:(t,e)=>U(`/crm/leads/${t}/etapa`,{method:"PUT",body:JSON.stringify({etapa:e})}),sugestoes:()=>U("/crm/sugestoes"),aplicar:(t,e)=>U("/crm/sugestoes/aplicar",Me({lead_id:t,para:e}))},campanhas:{listar:()=>U("/campaigns"),criar:t=>U("/campaigns",Me(t)),status:(t,e)=>U(`/campaigns/${t}/status`,{method:"PUT",body:JSON.stringify({status:e})}),iniciar:t=>U(`/campaigns/${t}/start`,Me({})),pausar:t=>U(`/campaigns/${t}/pause`,Me({})),parar:t=>U(`/campaigns/${t}/stop`,Me({})),remover:t=>U(`/campaigns/${t}`,{method:"DELETE"})},extrair:{maps:t=>U("/extractors/maps",Me(t)),instagram:(t,e)=>U("/extractors/instagram",Me({profile_url:t,limit:e})),cnpj:t=>U("/extract/cnpj",Me({cnpj:t})),cnpjBusca:t=>U("/extract/cnpj/search",Me(t)),cnpjExtract:t=>U("/extractors/cnpj",Me(t))},config:{obter:()=>U("/config"),salvar:t=>U("/config",{method:"PUT",body:JSON.stringify(t)}),testarLlm:()=>U("/config/test/llm",Me({})),testarIntegracao:t=>U("/config/test/integracao",Me({url:t}))},integracoes:()=>U("/integrations/status"),agentes:{templates:()=>U("/agents/templates"),salvarTemplates:t=>U("/agents/templates",{method:"PUT",body:JSON.stringify(t)}),testarTemplate:(t,e)=>U("/agents/templates/test",Me({template:t,lead_id:e})),chat:t=>U("/agents/attendance/chat",Me({mensagens:t}))},webhook:{obter:()=>U("/webhook"),salvar:t=>U("/webhook",{method:"PUT",body:JSON.stringify(t)}),testar:t=>U("/webhook/test",Me({url:t}))}};function H(...t){return t.filter(Boolean).join(" ")}function a_(t){return(t||"?").trim().charAt(0).toUpperCase()||"?"}function Il(t){if(!t)return"—";try{return new Date(t).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return t}}function na(t){const e=(t||"").replace(/\D/g,"");return e?e.length===11?`(${e.slice(0,2)}) ${e.slice(2,7)}-${e.slice(7)}`:e.length===10?`(${e.slice(0,2)}) ${e.slice(2,6)}-${e.slice(6)}`:t||"—":"—"}function l_(t){const e=["nome","telefone","email","empresa","cidade","observacoes"],n=e.filter(s=>String(t[s]||"").trim().length>0);return Math.round(n.length/e.length*100)}function c_(t){const e={nome:"nome",telefone:"telefone",email:"e-mail",empresa:"empresa",cidade:"cidade",observacoes:"observações"};return["nome","telefone","email","empresa","cidade","observacoes"].filter(s=>String(t[s]||"").trim().length===0).map(s=>e[s])}function u_(t,e){if(t>=100)return"Lead 100% completo — excelente! 🎉";const n=e.slice(0,2).join(" e ");return`Faltam ${100-t}% (${n}${e.length>2?"...":""}) para o lead ficar completo`}function d_(t,e){const n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),s=URL.createObjectURL(n),r=document.createElement("a");r.href=s,r.download=e,r.click(),URL.revokeObjectURL(s)}const f_={md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"};function Xt({aberto:t,onFechar:e,titulo:n,children:s,icone:r="fas fa-circle-info",largura:i="md"}){return S.useEffect(()=>{const o=a=>{a.key==="Escape"&&e()};return t&&window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[t,e]),t?u.jsx("div",{className:"fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4",onMouseDown:o=>{o.target===o.currentTarget&&e()},children:u.jsxs("div",{className:H("bg-white rounded-2xl shadow-xl w-full",f_[i]),children:[u.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-100",children:[u.jsxs("h3",{className:"text-base font-semibold text-gray-800 flex items-center gap-2",children:[u.jsx("i",{className:H(r,"text-indigo-500")})," ",n]}),u.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-600","aria-label":"Fechar",children:u.jsx("i",{className:"fas fa-times"})})]}),u.jsx("div",{className:"px-6 py-5 max-h-[70vh] overflow-y-auto",children:s})]})}):null}const h_=[{icone:"fas fa-users",texto:"Cadastre leads manualmente ou importe pelos Extratores (Maps, Instagram, CNPJ)."},{icone:"fas fa-columns",texto:"Arraste os cards no CRM conforme avança no funil (Leads → Em contato → Proposta → Fechado)."},{icone:"fas fa-bullhorn",texto:"Monte campanhas de disparo com seus templates e acompanhe as taxas no Painel."},{icone:"fas fa-robot",texto:"Use os Agentes (disparo e atendimento) e configure o LLM em Ferramentas para turbiná-los."}];function p_({titulo:t,nomeUsuario:e}){const[n,s]=S.useState(!1);return u.jsxs("header",{className:"bg-white shadow-sm px-8 py-4 flex items-center justify-between shrink-0",children:[u.jsx("div",{children:u.jsx("h2",{className:"text-lg font-semibold text-gray-800",children:t})}),u.jsxs("div",{className:"flex items-center space-x-4",children:[u.jsxs("button",{onClick:()=>s(!0),className:"text-sm text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-play-circle mr-1"})," Ver tutorial"]}),u.jsx("div",{className:"w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 font-bold text-sm",children:a_(e)}),u.jsx("span",{className:"text-sm font-medium text-gray-700",children:e})]}),u.jsxs(Xt,{aberto:n,onFechar:()=>s(!1),titulo:"Tutorial rápido",icone:"fas fa-graduation-cap",children:[u.jsx("ol",{className:"space-y-4",children:h_.map((r,i)=>u.jsxs("li",{className:"flex gap-3 items-start",children:[u.jsx("span",{className:"w-8 h-8 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0",children:u.jsx("i",{className:r.icone})}),u.jsx("p",{className:"text-sm text-gray-600 pt-1.5",children:r.texto})]},i))}),u.jsx("p",{className:"text-xs text-gray-400 mt-5",children:"Dica: o LLM (para enriquecimento e agentes) é configurado em Ferramentas."})]})]})}const g_=[{itens:[{para:"/",icone:"fas fa-chart-pie text-indigo-300",rotulo:"Painel",fim:!0}]},{secao:"Conexões",itens:[{para:"/leads",icone:"fas fa-users",rotulo:"Leads"},{para:"/agentes",icone:"fas fa-robot",rotulo:"Agentes"},{para:"/ferramentas",icone:"fas fa-tools",rotulo:"Ferramentas"}]},{itens:[{para:"/extrator-maps",icone:"fas fa-map-marked-alt",rotulo:"Extrator Maps"},{para:"/extrator-instagram",icone:"fab fa-instagram",rotulo:"Extrator Instagram"},{para:"/extrator-cnpj",icone:"fas fa-building",rotulo:"Extrator CNPJ"}]},{secao:"Gestão",itens:[{para:"/disparos",icone:"fas fa-bullhorn",rotulo:"Disparos"},{para:"/crm",icone:"fas fa-columns",rotulo:"CRM"}]},{secao:"Integrações",itens:[{para:"/webhook",icone:"fas fa-link",rotulo:"Webhook"},{para:"/suporte",icone:"fas fa-headset",rotulo:"Suporte"}]}];function m_({onSair:t}){const e=Os(),[n,s]=S.useState(!1);S.useEffect(()=>{e.pathname==="/agentes"&&s(!0)},[e.pathname]);const r=i=>{if(i.rotulo==="Agentes")return e.pathname==="/agentes";const[o,a]=i.para.split("?");return a?e.pathname===o&&e.search.includes(a):i.fim?e.pathname===o:e.pathname.startsWith(o)};return u.jsxs("aside",{className:"w-64 bg-[#1e1b4b] text-white flex flex-col shrink-0 h-screen sticky top-0",children:[u.jsx("div",{className:"p-6 border-b border-gray-700",children:u.jsxs("h1",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[u.jsx("span",{className:"text-2xl",children:"⚡"}),"LeadMaster",u.jsxs("span",{className:"text-[10px] font-medium text-indigo-300 border border-indigo-400/40 rounded-md px-1.5 py-0.5",children:["v","0.1.19"]})]})}),u.jsx("nav",{className:"flex-1 overflow-y-auto py-4",children:u.jsx("ul",{className:"space-y-1",children:g_.map((i,o)=>u.jsx("li",{children:u.jsxs("ul",{children:[i.secao&&u.jsx("li",{className:"px-6 py-2 text-xs font-semibold text-gray-400 uppercase tracking-wider list-none",children:i.secao}),i.itens.map(a=>a.rotulo==="Agentes"?u.jsxs("li",{children:[u.jsxs("button",{type:"button",onClick:()=>s(l=>!l),className:H("sidebar-link w-full flex items-center px-6 py-2.5 text-sm",r(a)&&"active"),children:[u.jsx("i",{className:H(a.icone,"w-5 text-gray-400")}),u.jsx("span",{className:"ml-3",children:a.rotulo}),u.jsx("i",{className:H("fas fa-chevron-down ml-auto text-xs text-gray-400 transition-transform",n&&"rotate-180")})]}),n&&u.jsxs("ul",{className:"pl-12 space-y-1 mt-1",children:[u.jsx("li",{children:u.jsx(Yp,{para:"/agentes?tab=disparo",rotulo:"Agente de Disparo",ativo:e.pathname==="/agentes"&&e.search.includes("disparo")})}),u.jsx("li",{children:u.jsx(Yp,{para:"/agentes?tab=atendimento",rotulo:"Agente de Atendimento",ativo:e.pathname==="/agentes"&&e.search.includes("atendimento")})})]})]},"agentes"):u.jsx("li",{children:u.jsxs(gy,{to:a.para,className:H("sidebar-link flex items-center px-6 py-2.5 text-sm",r(a)&&"active"),children:[u.jsx("i",{className:H(a.icone,"w-5 text-gray-400")}),u.jsx("span",{className:"ml-3",children:a.rotulo})]})},a.para))]})},o))})}),u.jsx("div",{className:"p-4 border-t border-gray-700",children:u.jsxs("button",{onClick:t,className:"w-full flex items-center justify-center px-4 py-2.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg text-sm font-medium hover:opacity-90 transition",children:[u.jsx("i",{className:"fas fa-sign-out-alt mr-2"})," Sair"]})})]})}function Yp({para:t,rotulo:e,ativo:n}){return u.jsx(gy,{to:t,className:H("sidebar-link block px-4 py-2 text-xs text-gray-300 rounded",n&&"active"),children:e})}const my=S.createContext({toast:()=>{}});function en(){return S.useContext(my)}const x_={sucesso:"bg-green-600",erro:"bg-red-600",info:"bg-indigo-600"},y_={sucesso:"fas fa-check-circle",erro:"fas fa-exclamation-circle",info:"fas fa-info-circle"};function v_({children:t}){const[e,n]=S.useState([]),s=S.useRef(0),r=S.useCallback((i,o)=>{const a=++s.current;n(l=>[...l,{id:a,tipo:i,mensagem:o}]),setTimeout(()=>n(l=>l.filter(c=>c.id!==a)),4500)},[]);return u.jsxs(my.Provider,{value:{toast:r},children:[t,u.jsx("div",{className:"fixed top-4 right-4 z-[100] space-y-2 w-80",children:e.map(i=>u.jsxs("div",{className:H(x_[i.tipo],"text-white text-sm rounded-lg shadow-lg px-4 py-3 flex items-start gap-2 animate-pulse-once"),role:"status",children:[u.jsx("i",{className:H(y_[i.tipo],"mt-0.5")}),u.jsx("span",{className:"flex-1",children:i.mensagem}),u.jsx("button",{className:"opacity-70 hover:opacity-100",onClick:()=>n(o=>o.filter(a=>a.id!==i.id)),"aria-label":"Fechar",children:u.jsx("i",{className:"fas fa-times"})})]},i.id))})]})}function Pa({rotulo:t,valor:e,subtitulo:n,children:s,icone:r}){return u.jsxs("div",{className:"bg-white rounded-xl shadow-sm p-5 border border-gray-100",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("p",{className:"text-sm text-gray-500 font-medium",children:t}),r&&u.jsx("i",{className:`${r} text-indigo-300`})]}),s??u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"text-2xl font-bold text-gray-800 mt-1",children:e}),n&&u.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:n})]})]})}/*!
68
68
  * @kurkle/color v0.3.4
69
69
  * https://github.com/kurkle/color#readme
70
70
  * (c) 2024 Jukka Kurkela
@@ -81,10 +81,10 @@ Error generating stack: `+i.message+`
81
81
  * Released under the MIT License
82
82
  */class Qk{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(e,n,s,r){const i=n.listeners[r],o=n.duration;i.forEach(a=>a({chart:e,initial:n.initial,numSteps:o,currentStep:Math.min(s-n.start,o)}))}_refresh(){this._request||(this._running=!0,this._request=jy.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(e=Date.now()){let n=0;this._charts.forEach((s,r)=>{if(!s.running||!s.items.length)return;const i=s.items;let o=i.length-1,a=!1,l;for(;o>=0;--o)l=i[o],l._active?(l._total>s.duration&&(s.duration=l._total),l.tick(e),a=!0):(i[o]=i[i.length-1],i.pop());a&&(r.draw(),this._notify(r,s,e,"progress")),i.length||(s.running=!1,this._notify(r,s,e,"complete"),s.initial=!1),n+=i.length}),this._lastDate=e,n===0&&(this._running=!1)}_getAnims(e){const n=this._charts;let s=n.get(e);return s||(s={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},n.set(e,s)),s}listen(e,n,s){this._getAnims(e).listeners[n].push(s)}add(e,n){!n||!n.length||this._getAnims(e).items.push(...n)}has(e){return this._getAnims(e).items.length>0}start(e){const n=this._charts.get(e);n&&(n.running=!0,n.start=Date.now(),n.duration=n.items.reduce((s,r)=>Math.max(s,r._duration),0),this._refresh())}running(e){if(!this._running)return!1;const n=this._charts.get(e);return!(!n||!n.running||!n.items.length)}stop(e){const n=this._charts.get(e);if(!n||!n.items.length)return;const s=n.items;let r=s.length-1;for(;r>=0;--r)s[r].cancel();n.items=[],this._notify(e,n,Date.now(),"complete")}remove(e){return this._charts.delete(e)}}var _n=new Qk;const mg="transparent",Kk={boolean(t,e,n){return n>.5?e:t},color(t,e,n){const s=ag(t||mg),r=s.valid&&ag(e||mg);return r&&r.valid?r.mix(s,n).hexString():e},number(t,e,n){return t+(e-t)*n}};class Yk{constructor(e,n,s,r){const i=n[s];r=La([e.to,r,i,e.from]);const o=La([e.from,i,r]);this._active=!0,this._fn=e.fn||Kk[e.type||typeof o],this._easing=ho[e.easing]||ho.linear,this._start=Math.floor(Date.now()+(e.delay||0)),this._duration=this._total=Math.floor(e.duration),this._loop=!!e.loop,this._target=n,this._prop=s,this._from=o,this._to=r,this._promises=void 0}active(){return this._active}update(e,n,s){if(this._active){this._notify(!1);const r=this._target[this._prop],i=s-this._start,o=this._duration-i;this._start=s,this._duration=Math.floor(Math.max(o,e.duration)),this._total+=i,this._loop=!!e.loop,this._to=La([e.to,n,r,e.from]),this._from=La([e.from,r,n])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(e){const n=e-this._start,s=this._duration,r=this._prop,i=this._from,o=this._loop,a=this._to;let l;if(this._active=i!==a&&(o||n<s),!this._active){this._target[r]=a,this._notify(!0);return}if(n<0){this._target[r]=i;return}l=n/s%2,l=o&&l>1?2-l:l,l=this._easing(Math.min(1,Math.max(0,l))),this._target[r]=this._fn(i,a,l)}wait(){const e=this._promises||(this._promises=[]);return new Promise((n,s)=>{e.push({res:n,rej:s})})}_notify(e){const n=e?"res":"rej",s=this._promises||[];for(let r=0;r<s.length;r++)s[r][n]()}}class By{constructor(e,n){this._chart=e,this._properties=new Map,this.configure(n)}configure(e){if(!te(e))return;const n=Object.keys(Ee.animation),s=this._properties;Object.getOwnPropertyNames(e).forEach(r=>{const i=e[r];if(!te(i))return;const o={};for(const a of n)o[a]=i[a];(Fe(i.properties)&&i.properties||[r]).forEach(a=>{(a===r||!s.has(a))&&s.set(a,o)})})}_animateOptions(e,n){const s=n.options,r=qk(e,s);if(!r)return[];const i=this._createAnimations(r,s);return s.$shared&&Xk(e.options.$animations,s).then(()=>{e.options=s},()=>{}),i}_createAnimations(e,n){const s=this._properties,r=[],i=e.$animations||(e.$animations={}),o=Object.keys(n),a=Date.now();let l;for(l=o.length-1;l>=0;--l){const c=o[l];if(c.charAt(0)==="$")continue;if(c==="options"){r.push(...this._animateOptions(e,n));continue}const d=n[c];let f=i[c];const h=s.get(c);if(f)if(h&&f.active()){f.update(h,d,a);continue}else f.cancel();if(!h||!h.duration){e[c]=d;continue}i[c]=f=new Yk(h,e,c,d),r.push(f)}return r}update(e,n){if(this._properties.size===0){Object.assign(e,n);return}const s=this._createAnimations(e,n);if(s.length)return _n.add(this._chart,s),!0}}function Xk(t,e){const n=[],s=Object.keys(e);for(let r=0;r<s.length;r++){const i=t[s[r]];i&&i.active()&&n.push(i.wait())}return Promise.all(n)}function qk(t,e){if(!e)return;let n=t.options;if(!n){t.options=e;return}return n.$shared&&(t.options=n=Object.assign({},n,{$shared:!1,$animations:{}})),n}function xg(t,e){const n=t&&t.options||{},s=n.reverse,r=n.min===void 0?e:0,i=n.max===void 0?e:0;return{start:s?i:r,end:s?r:i}}function Gk(t,e,n){if(n===!1)return!1;const s=xg(t,n),r=xg(e,n);return{top:r.end,right:s.end,bottom:r.start,left:s.start}}function Jk(t){let e,n,s,r;return te(t)?(e=t.top,n=t.right,s=t.bottom,r=t.left):e=n=s=r=t,{top:e,right:n,bottom:s,left:r,disabled:t===!1}}function $y(t,e){const n=[],s=t._getSortedDatasetMetas(e);let r,i;for(r=0,i=s.length;r<i;++r)n.push(s[r].index);return n}function yg(t,e,n,s={}){const r=t.keys,i=s.mode==="single";let o,a,l,c;if(e===null)return;let d=!1;for(o=0,a=r.length;o<a;++o){if(l=+r[o],l===n){if(d=!0,s.all)continue;break}c=t.values[l],It(c)&&(i||e===0||Ss(e)===Ss(c))&&(e+=c)}return!d&&!s.all?0:e}function Zk(t,e){const{iScale:n,vScale:s}=e,r=n.axis==="x"?"x":"y",i=s.axis==="x"?"x":"y",o=Object.keys(t),a=new Array(o.length);let l,c,d;for(l=0,c=o.length;l<c;++l)d=o[l],a[l]={[r]:d,[i]:t[d]};return a}function uu(t,e){const n=t&&t.options.stacked;return n||n===void 0&&e.stack!==void 0}function eC(t,e,n){return`${t.id}.${e.id}.${n.stack||n.type}`}function tC(t){const{min:e,max:n,minDefined:s,maxDefined:r}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:r?n:Number.POSITIVE_INFINITY}}function nC(t,e,n){const s=t[e]||(t[e]={});return s[n]||(s[n]={})}function vg(t,e,n,s){for(const r of e.getMatchingVisibleMetas(s).reverse()){const i=t[r.index];if(n&&i>0||!n&&i<0)return r.index}return null}function bg(t,e){const{chart:n,_cachedMeta:s}=t,r=n._stacks||(n._stacks={}),{iScale:i,vScale:o,index:a}=s,l=i.axis,c=o.axis,d=eC(i,o,s),f=e.length;let h;for(let p=0;p<f;++p){const m=e[p],{[l]:g,[c]:b}=m,y=m._stacks||(m._stacks={});h=y[c]=nC(r,d,g),h[a]=b,h._top=vg(h,o,!0,s.type),h._bottom=vg(h,o,!1,s.type);const x=h._visualValues||(h._visualValues={});x[a]=b}}function du(t,e){const n=t.scales;return Object.keys(n).filter(s=>n[s].axis===e).shift()}function sC(t,e){return wi(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}function rC(t,e,n){return wi(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:n,index:e,mode:"default",type:"data"})}function zi(t,e){const n=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const r of e){const i=r._stacks;!i||i[s]===void 0||i[s][n]===void 0||(delete i[s][n],i[s]._visualValues!==void 0&&i[s]._visualValues[n]!==void 0&&delete i[s]._visualValues[n])}}}const fu=t=>t==="reset"||t==="none",wg=(t,e)=>e?t:Object.assign({},t),iC=(t,e,n)=>t&&!e.hidden&&e._stacked&&{keys:$y(n,!0),values:null};class Vr{constructor(e,n){this.chart=e,this._ctx=e.ctx,this.index=n,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const e=this._cachedMeta;this.configure(),this.linkScales(),e._stacked=uu(e.vScale,e),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(e){this.index!==e&&zi(this._cachedMeta),this.index=e}linkScales(){const e=this.chart,n=this._cachedMeta,s=this.getDataset(),r=(f,h,p,m)=>f==="x"?h:f==="r"?m:p,i=n.xAxisID=Z(s.xAxisID,du(e,"x")),o=n.yAxisID=Z(s.yAxisID,du(e,"y")),a=n.rAxisID=Z(s.rAxisID,du(e,"r")),l=n.indexAxis,c=n.iAxisID=r(l,i,o,a),d=n.vAxisID=r(l,o,i,a);n.xScale=this.getScaleForId(i),n.yScale=this.getScaleForId(o),n.rScale=this.getScaleForId(a),n.iScale=this.getScaleForId(c),n.vScale=this.getScaleForId(d)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(e){return this.chart.scales[e]}_getOtherScale(e){const n=this._cachedMeta;return e===n.iScale?n.vScale:n.iScale}reset(){this._update("reset")}_destroy(){const e=this._cachedMeta;this._data&&rg(this._data,this),e._stacked&&zi(e)}_dataCheck(){const e=this.getDataset(),n=e.data||(e.data=[]),s=this._data;if(te(n)){const r=this._cachedMeta;this._data=Zk(n,r)}else if(s!==n){if(s){rg(s,this);const r=this._cachedMeta;zi(r),r._parsed=[]}n&&Object.isExtensible(n)&&ik(n,this),this._syncList=[],this._data=n}}addElements(){const e=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(e.dataset=new this.datasetElementType)}buildOrUpdateElements(e){const n=this._cachedMeta,s=this.getDataset();let r=!1;this._dataCheck();const i=n._stacked;n._stacked=uu(n.vScale,n),n.stack!==s.stack&&(r=!0,zi(n),n.stack=s.stack),this._resyncElements(e),(r||i!==n._stacked)&&(bg(this,n._parsed),n._stacked=uu(n.vScale,n))}configure(){const e=this.chart.config,n=e.datasetScopeKeys(this._type),s=e.getOptionScopes(this.getDataset(),n,!0);this.options=e.createResolver(s,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(e,n){const{_cachedMeta:s,_data:r}=this,{iScale:i,_stacked:o}=s,a=i.axis;let l=e===0&&n===r.length?!0:s._sorted,c=e>0&&s._parsed[e-1],d,f,h;if(this._parsing===!1)s._parsed=r,s._sorted=!0,h=r;else{Fe(r[e])?h=this.parseArrayData(s,r,e,n):te(r[e])?h=this.parseObjectData(s,r,e,n):h=this.parsePrimitiveData(s,r,e,n);const p=()=>f[a]===null||c&&f[a]<c[a];for(d=0;d<n;++d)s._parsed[d+e]=f=h[d],l&&(p()&&(l=!1),c=f);s._sorted=l}o&&bg(this,h)}parsePrimitiveData(e,n,s,r){const{iScale:i,vScale:o}=e,a=i.axis,l=o.axis,c=i.getLabels(),d=i===o,f=new Array(r);let h,p,m;for(h=0,p=r;h<p;++h)m=h+s,f[h]={[a]:d||i.parse(c[m],m),[l]:o.parse(n[m],m)};return f}parseArrayData(e,n,s,r){const{xScale:i,yScale:o}=e,a=new Array(r);let l,c,d,f;for(l=0,c=r;l<c;++l)d=l+s,f=n[d],a[l]={x:i.parse(f[0],d),y:o.parse(f[1],d)};return a}parseObjectData(e,n,s,r){const{xScale:i,yScale:o}=e,{xAxisKey:a="x",yAxisKey:l="y"}=this._parsing,c=new Array(r);let d,f,h,p;for(d=0,f=r;d<f;++d)h=d+s,p=n[h],c[d]={x:i.parse(cr(p,a),h),y:o.parse(cr(p,l),h)};return c}getParsed(e){return this._cachedMeta._parsed[e]}getDataElement(e){return this._cachedMeta.data[e]}applyStack(e,n,s){const r=this.chart,i=this._cachedMeta,o=n[e.axis],a={keys:$y(r,!0),values:n._stacks[e.axis]._visualValues};return yg(a,o,i.index,{mode:s})}updateRangeFromParsed(e,n,s,r){const i=s[n.axis];let o=i===null?NaN:i;const a=r&&s._stacks[n.axis];r&&a&&(r.values=a,o=yg(r,i,this._cachedMeta.index)),e.min=Math.min(e.min,o),e.max=Math.max(e.max,o)}getMinMax(e,n){const s=this._cachedMeta,r=s._parsed,i=s._sorted&&e===s.iScale,o=r.length,a=this._getOtherScale(e),l=iC(n,s,this.chart),c={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:d,max:f}=tC(a);let h,p;function m(){p=r[h];const g=p[a.axis];return!It(p[e.axis])||d>g||f<g}for(h=0;h<o&&!(!m()&&(this.updateRangeFromParsed(c,e,p,l),i));++h);if(i){for(h=o-1;h>=0;--h)if(!m()){this.updateRangeFromParsed(c,e,p,l);break}}return c}getAllParsedValues(e){const n=this._cachedMeta._parsed,s=[];let r,i,o;for(r=0,i=n.length;r<i;++r)o=n[r][e.axis],It(o)&&s.push(o);return s}getMaxOverflow(){return!1}getLabelAndValue(e){const n=this._cachedMeta,s=n.iScale,r=n.vScale,i=this.getParsed(e);return{label:s?""+s.getLabelForValue(i[s.axis]):"",value:r?""+r.getLabelForValue(i[r.axis]):""}}_update(e){const n=this._cachedMeta;this.update(e||"default"),n._clip=Jk(Z(this.options.clip,Gk(n.xScale,n.yScale,this.getMaxOverflow())))}update(e){}draw(){const e=this._ctx,n=this.chart,s=this._cachedMeta,r=s.data||[],i=n.chartArea,o=[],a=this._drawStart||0,l=this._drawCount||r.length-a,c=this.options.drawActiveElementsOnTop;let d;for(s.dataset&&s.dataset.draw(e,i,a,l),d=a;d<a+l;++d){const f=r[d];f.hidden||(f.active&&c?o.push(f):f.draw(e,i))}for(d=0;d<o.length;++d)o[d].draw(e,i)}getStyle(e,n){const s=n?"active":"default";return e===void 0&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(s):this.resolveDataElementOptions(e||0,s)}getContext(e,n,s){const r=this.getDataset();let i;if(e>=0&&e<this._cachedMeta.data.length){const o=this._cachedMeta.data[e];i=o.$context||(o.$context=rC(this.getContext(),e,o)),i.parsed=this.getParsed(e),i.raw=r.data[e],i.index=i.dataIndex=e}else i=this.$context||(this.$context=sC(this.chart.getContext(),this.index)),i.dataset=r,i.index=i.datasetIndex=this.index;return i.active=!!n,i.mode=s,i}resolveDatasetElementOptions(e){return this._resolveElementOptions(this.datasetElementType.id,e)}resolveDataElementOptions(e,n){return this._resolveElementOptions(this.dataElementType.id,n,e)}_resolveElementOptions(e,n="default",s){const r=n==="active",i=this._cachedDataOpts,o=e+"-"+n,a=i[o],l=this.enableOptionSharing&&Bo(s);if(a)return wg(a,l);const c=this.chart.config,d=c.datasetElementScopeKeys(this._type,e),f=r?[`${e}Hover`,"hover",e,""]:[e,""],h=c.getOptionScopes(this.getDataset(),d),p=Object.keys(Ee.elements[e]),m=()=>this.getContext(s,r,n),g=c.resolveNamedOptions(h,p,m,f);return g.$shared&&(g.$shared=l,i[o]=Object.freeze(wg(g,l))),g}_resolveAnimations(e,n,s){const r=this.chart,i=this._cachedDataOpts,o=`animation-${n}`,a=i[o];if(a)return a;let l;if(r.options.animation!==!1){const d=this.chart.config,f=d.datasetAnimationScopeKeys(this._type,n),h=d.getOptionScopes(this.getDataset(),f);l=d.createResolver(h,this.getContext(e,s,n))}const c=new By(r,l&&l.animations);return l&&l._cacheable&&(i[o]=Object.freeze(c)),c}getSharedOptions(e){if(e.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},e))}includeOptions(e,n){return!n||fu(e)||this.chart._animationsDisabled}_getSharedOptions(e,n){const s=this.resolveDataElementOptions(e,n),r=this._sharedOptions,i=this.getSharedOptions(s),o=this.includeOptions(n,i)||i!==r;return this.updateSharedOptions(i,n,s),{sharedOptions:i,includeOptions:o}}updateElement(e,n,s,r){fu(r)?Object.assign(e,s):this._resolveAnimations(n,r).update(e,s)}updateSharedOptions(e,n,s){e&&!fu(n)&&this._resolveAnimations(void 0,n).update(e,s)}_setStyle(e,n,s,r){e.active=r;const i=this.getStyle(n,r);this._resolveAnimations(n,s,r).update(e,{options:!r&&this.getSharedOptions(i)||i})}removeHoverStyle(e,n,s){this._setStyle(e,s,"active",!1)}setHoverStyle(e,n,s){this._setStyle(e,s,"active",!0)}_removeDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!1)}_setDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!0)}_resyncElements(e){const n=this._data,s=this._cachedMeta.data;for(const[a,l,c]of this._syncList)this[a](l,c);this._syncList=[];const r=s.length,i=n.length,o=Math.min(i,r);o&&this.parse(0,o),i>r?this._insertElements(r,i-r,e):i<r&&this._removeElements(i,r-i)}_insertElements(e,n,s=!0){const r=this._cachedMeta,i=r.data,o=e+n;let a;const l=c=>{for(c.length+=n,a=c.length-1;a>=o;a--)c[a]=c[a-n]};for(l(i),a=e;a<o;++a)i[a]=new this.dataElementType;this._parsing&&l(r._parsed),this.parse(e,n),s&&this.updateElements(i,e,n,"reset")}updateElements(e,n,s,r){}_removeElements(e,n){const s=this._cachedMeta;if(this._parsing){const r=s._parsed.splice(e,n);s._stacked&&zi(s,r)}s.data.splice(e,n)}_sync(e){if(this._parsing)this._syncList.push(e);else{const[n,s,r]=e;this[n](s,r)}this.chart._dataChanges.push([this.index,...e])}_onDataPush(){const e=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-e,e])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(e,n){n&&this._sync(["_removeElements",e,n]);const s=arguments.length-2;s&&this._sync(["_insertElements",e,s])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}B(Vr,"defaults",{}),B(Vr,"datasetElementType",null),B(Vr,"dataElementType",null);function oC(t,e){if(!t._cache.$bar){const n=t.getMatchingVisibleMetas(e);let s=[];for(let r=0,i=n.length;r<i;r++)s=s.concat(n[r].controller.getAllParsedValues(t));t._cache.$bar=Cy(s.sort((r,i)=>r-i))}return t._cache.$bar}function aC(t){const e=t.iScale,n=oC(e,t.type);let s=e._length,r,i,o,a;const l=()=>{o===32767||o===-32768||(Bo(a)&&(s=Math.min(s,Math.abs(o-a)||s)),a=o)};for(r=0,i=n.length;r<i;++r)o=e.getPixelForValue(n[r]),l();for(a=void 0,r=0,i=e.ticks.length;r<i;++r)o=e.getPixelForTick(r),l();return s}function lC(t,e,n,s){const r=n.barThickness;let i,o;return ue(r)?(i=e.min*n.categoryPercentage,o=n.barPercentage):(i=r*s,o=1),{chunk:i/s,ratio:o,start:e.pixels[t]-i/2}}function cC(t,e,n,s){const r=e.pixels,i=r[t];let o=t>0?r[t-1]:null,a=t<r.length-1?r[t+1]:null;const l=n.categoryPercentage;o===null&&(o=i-(a===null?e.end-e.start:a-i)),a===null&&(a=i+i-o);const c=i-(i-Math.min(o,a))/2*l;return{chunk:Math.abs(a-o)/2*l/s,ratio:n.barPercentage,start:c}}function uC(t,e,n,s){const r=n.parse(t[0],s),i=n.parse(t[1],s),o=Math.min(r,i),a=Math.max(r,i);let l=o,c=a;Math.abs(o)>Math.abs(a)&&(l=a,c=o),e[n.axis]=c,e._custom={barStart:l,barEnd:c,start:r,end:i,min:o,max:a}}function Uy(t,e,n,s){return Fe(t)?uC(t,e,n,s):e[n.axis]=n.parse(t,s),e}function Sg(t,e,n,s){const r=t.iScale,i=t.vScale,o=r.getLabels(),a=r===i,l=[];let c,d,f,h;for(c=n,d=n+s;c<d;++c)h=e[c],f={},f[r.axis]=a||r.parse(o[c],c),l.push(Uy(h,f,i,c));return l}function hu(t){return t&&t.barStart!==void 0&&t.barEnd!==void 0}function dC(t,e,n){return t!==0?Ss(t):(e.isHorizontal()?1:-1)*(e.min>=n?1:-1)}function fC(t){let e,n,s,r,i;return t.horizontal?(e=t.base>t.x,n="left",s="right"):(e=t.base<t.y,n="bottom",s="top"),e?(r="end",i="start"):(r="start",i="end"),{start:n,end:s,reverse:e,top:r,bottom:i}}function hC(t,e,n,s){let r=e.borderSkipped;const i={};if(!r){t.borderSkipped=i;return}if(r===!0){t.borderSkipped={top:!0,right:!0,bottom:!0,left:!0};return}const{start:o,end:a,reverse:l,top:c,bottom:d}=fC(t);r==="middle"&&n&&(t.enableBorderRadius=!0,(n._top||0)===s?r=c:(n._bottom||0)===s?r=d:(i[_g(d,o,a,l)]=!0,r=c)),i[_g(r,o,a,l)]=!0,t.borderSkipped=i}function _g(t,e,n,s){return s?(t=pC(t,e,n),t=kg(t,n,e)):t=kg(t,e,n),t}function pC(t,e,n){return t===e?n:t===n?e:t}function kg(t,e,n){return t==="start"?e:t==="end"?n:t}function gC(t,{inflateAmount:e},n){t.inflateAmount=e==="auto"?n===1?.33:0:e}class il extends Vr{parsePrimitiveData(e,n,s,r){return Sg(e,n,s,r)}parseArrayData(e,n,s,r){return Sg(e,n,s,r)}parseObjectData(e,n,s,r){const{iScale:i,vScale:o}=e,{xAxisKey:a="x",yAxisKey:l="y"}=this._parsing,c=i.axis==="x"?a:l,d=o.axis==="x"?a:l,f=[];let h,p,m,g;for(h=s,p=s+r;h<p;++h)g=n[h],m={},m[i.axis]=i.parse(cr(g,c),h),f.push(Uy(cr(g,d),m,o,h));return f}updateRangeFromParsed(e,n,s,r){super.updateRangeFromParsed(e,n,s,r);const i=s._custom;i&&n===this._cachedMeta.vScale&&(e.min=Math.min(e.min,i.min),e.max=Math.max(e.max,i.max))}getMaxOverflow(){return 0}getLabelAndValue(e){const n=this._cachedMeta,{iScale:s,vScale:r}=n,i=this.getParsed(e),o=i._custom,a=hu(o)?"["+o.start+", "+o.end+"]":""+r.getLabelForValue(i[r.axis]);return{label:""+s.getLabelForValue(i[s.axis]),value:a}}initialize(){this.enableOptionSharing=!0,super.initialize();const e=this._cachedMeta;e.stack=this.getDataset().stack}update(e){const n=this._cachedMeta;this.updateElements(n.data,0,n.data.length,e)}updateElements(e,n,s,r){const i=r==="reset",{index:o,_cachedMeta:{vScale:a}}=this,l=a.getBasePixel(),c=a.isHorizontal(),d=this._getRuler(),{sharedOptions:f,includeOptions:h}=this._getSharedOptions(n,r);for(let p=n;p<n+s;p++){const m=this.getParsed(p),g=i||ue(m[a.axis])?{base:l,head:l}:this._calculateBarValuePixels(p),b=this._calculateBarIndexPixels(p,d),y=(m._stacks||{})[a.axis],x={horizontal:c,base:g.base,enableBorderRadius:!y||hu(m._custom)||o===y._top||o===y._bottom,x:c?g.head:b.center,y:c?b.center:g.head,height:c?b.size:Math.abs(g.size),width:c?Math.abs(g.size):b.size};h&&(x.options=f||this.resolveDataElementOptions(p,e[p].active?"active":r));const v=x.options||e[p].options;hC(x,v,y,o),gC(x,v,d.ratio),this.updateElement(e[p],p,x,r)}}_getStacks(e,n){const{iScale:s}=this._cachedMeta,r=s.getMatchingVisibleMetas(this._type).filter(d=>d.controller.options.grouped),i=s.options.stacked,o=[],a=this._cachedMeta.controller.getParsed(n),l=a&&a[s.axis],c=d=>{const f=d._parsed.find(p=>p[s.axis]===l),h=f&&f[d.vScale.axis];if(ue(h)||isNaN(h))return!0};for(const d of r)if(!(n!==void 0&&c(d))&&((i===!1||o.indexOf(d.stack)===-1||i===void 0&&d.stack===void 0)&&o.push(d.stack),d.index===e))break;return o.length||o.push(void 0),o}_getStackCount(e){return this._getStacks(void 0,e).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const e=this.chart.scales,n=this.chart.options.indexAxis;return Object.keys(e).filter(s=>e[s].axis===n).shift()}_getAxis(){const e={},n=this.getFirstScaleIdForIndexAxis();for(const s of this.chart.data.datasets)e[Z(this.chart.options.indexAxis==="x"?s.xAxisID:s.yAxisID,n)]=!0;return Object.keys(e)}_getStackIndex(e,n,s){const r=this._getStacks(e,s),i=n!==void 0?r.indexOf(n):-1;return i===-1?r.length-1:i}_getRuler(){const e=this.options,n=this._cachedMeta,s=n.iScale,r=[];let i,o;for(i=0,o=n.data.length;i<o;++i)r.push(s.getPixelForValue(this.getParsed(i)[s.axis],i));const a=e.barThickness;return{min:a||aC(n),pixels:r,start:s._startPixel,end:s._endPixel,stackCount:this._getStackCount(),scale:s,grouped:e.grouped,ratio:a?1:e.categoryPercentage*e.barPercentage}}_calculateBarValuePixels(e){const{_cachedMeta:{vScale:n,_stacked:s,index:r},options:{base:i,minBarLength:o}}=this,a=i||0,l=this.getParsed(e),c=l._custom,d=hu(c);let f=l[n.axis],h=0,p=s?this.applyStack(n,l,s):f,m,g;p!==f&&(h=p-f,p=f),d&&(f=c.barStart,p=c.barEnd-c.barStart,f!==0&&Ss(f)!==Ss(c.barEnd)&&(h=0),h+=f);const b=!ue(i)&&!d?i:h;let y=n.getPixelForValue(b);if(this.chart.getDataVisibility(e)?m=n.getPixelForValue(h+p):m=y,g=m-y,Math.abs(g)<o){g=dC(g,n,a)*o,f===a&&(y-=g/2);const x=n.getPixelForDecimal(0),v=n.getPixelForDecimal(1),_=Math.min(x,v),w=Math.max(x,v);y=Math.max(Math.min(y,w),_),m=y+g,s&&!d&&(l._stacks[n.axis]._visualValues[r]=n.getValueForPixel(m)-n.getValueForPixel(y))}if(y===n.getPixelForValue(a)){const x=Ss(g)*n.getLineWidthForValue(a)/2;y+=x,g-=x}return{size:g,base:y,head:m,center:m+g/2}}_calculateBarIndexPixels(e,n){const s=n.scale,r=this.options,i=r.skipNull,o=Z(r.maxBarThickness,1/0);let a,l;const c=this._getAxisCount();if(n.grouped){const d=i?this._getStackCount(e):n.stackCount,f=r.barThickness==="flex"?cC(e,n,r,d*c):lC(e,n,r,d*c),h=this.chart.options.indexAxis==="x"?this.getDataset().xAxisID:this.getDataset().yAxisID,p=this._getAxis().indexOf(Z(h,this.getFirstScaleIdForIndexAxis())),m=this._getStackIndex(this.index,this._cachedMeta.stack,i?e:void 0)+p;a=f.start+f.chunk*m+f.chunk/2,l=Math.min(o,f.chunk*f.ratio)}else a=s.getPixelForValue(this.getParsed(e)[s.axis],e),l=Math.min(o,n.min*n.ratio);return{base:a-l/2,head:a+l/2,center:a,size:l}}draw(){const e=this._cachedMeta,n=e.vScale,s=e.data,r=s.length;let i=0;for(;i<r;++i)this.getParsed(i)[n.axis]!==null&&!s[i].hidden&&s[i].draw(this._ctx)}}B(il,"id","bar"),B(il,"defaults",{datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}}),B(il,"overrides",{scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}});function mC(t,e,n){let s=1,r=1,i=0,o=0;if(e<ve){const a=t,l=a+e,c=Math.cos(a),d=Math.sin(a),f=Math.cos(l),h=Math.sin(l),p=(v,_,w)=>Ul(v,a,l,!0)?1:Math.max(_,_*n,w,w*n),m=(v,_,w)=>Ul(v,a,l,!0)?-1:Math.min(_,_*n,w,w*n),g=p(0,c,f),b=p(Le,d,h),y=m(ge,c,f),x=m(ge+Le,d,h);s=(g-y)/2,r=(b-x)/2,i=-(g+y)/2,o=-(b+x)/2}return{ratioX:s,ratioY:r,offsetX:i,offsetY:o}}class Ji extends Vr{constructor(e,n){super(e,n),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(e,n){const s=this.getDataset().data,r=this._cachedMeta;if(this._parsing===!1)r._parsed=s;else{let i=l=>+s[l];if(te(s[e])){const{key:l="value"}=this._parsing;i=c=>+cr(s[c],l)}let o,a;for(o=e,a=e+n;o<a;++o)r._parsed[o]=i(o)}}_getRotation(){return Rn(this.options.rotation-90)}_getCircumference(){return Rn(this.options.circumference)}_getRotationExtents(){let e=ve,n=-ve;for(let s=0;s<this.chart.data.datasets.length;++s)if(this.chart.isDatasetVisible(s)&&this.chart.getDatasetMeta(s).type===this._type){const r=this.chart.getDatasetMeta(s).controller,i=r._getRotation(),o=r._getCircumference();e=Math.min(e,i),n=Math.max(n,i+o)}return{rotation:e,circumference:n-e}}update(e){const n=this.chart,{chartArea:s}=n,r=this._cachedMeta,i=r.data,o=this.getMaxBorderWidth()+this.getMaxOffset(i)+this.options.spacing,a=Math.max((Math.min(s.width,s.height)-o)/2,0),l=Math.min(W_(this.options.cutout,a),1),c=this._getRingWeight(this.index),{circumference:d,rotation:f}=this._getRotationExtents(),{ratioX:h,ratioY:p,offsetX:m,offsetY:g}=mC(f,d,l),b=(s.width-o)/h,y=(s.height-o)/p,x=Math.max(Math.min(b,y)/2,0),v=by(this.options.radius,x),_=Math.max(v*l,0),w=(v-_)/this._getVisibleDatasetWeightTotal();this.offsetX=m*v,this.offsetY=g*v,r.total=this.calculateTotal(),this.outerRadius=v-w*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-w*c,0),this.updateElements(i,0,i.length,e)}_circumference(e,n){const s=this.options,r=this._cachedMeta,i=this._getCircumference();return n&&s.animation.animateRotate||!this.chart.getDataVisibility(e)||r._parsed[e]===null||r.data[e].hidden?0:this.calculateCircumference(r._parsed[e]*i/ve)}updateElements(e,n,s,r){const i=r==="reset",o=this.chart,a=o.chartArea,c=o.options.animation,d=(a.left+a.right)/2,f=(a.top+a.bottom)/2,h=i&&c.animateScale,p=h?0:this.innerRadius,m=h?0:this.outerRadius,{sharedOptions:g,includeOptions:b}=this._getSharedOptions(n,r);let y=this._getRotation(),x;for(x=0;x<n;++x)y+=this._circumference(x,i);for(x=n;x<n+s;++x){const v=this._circumference(x,i),_=e[x],w={x:d+this.offsetX,y:f+this.offsetY,startAngle:y,endAngle:y+v,circumference:v,outerRadius:m,innerRadius:p};b&&(w.options=g||this.resolveDataElementOptions(x,_.active?"active":r)),y+=v,this.updateElement(_,x,w,r)}}calculateTotal(){const e=this._cachedMeta,n=e.data;let s=0,r;for(r=0;r<n.length;r++){const i=e._parsed[r];i!==null&&!isNaN(i)&&this.chart.getDataVisibility(r)&&!n[r].hidden&&(s+=Math.abs(i))}return s}calculateCircumference(e){const n=this._cachedMeta.total;return n>0&&!isNaN(e)?ve*(Math.abs(e)/n):0}getLabelAndValue(e){const n=this._cachedMeta,s=this.chart,r=s.data.labels||[],i=qf(n._parsed[e],s.options.locale);return{label:r[e]||"",value:i}}getMaxBorderWidth(e){let n=0;const s=this.chart;let r,i,o,a,l;if(!e){for(r=0,i=s.data.datasets.length;r<i;++r)if(s.isDatasetVisible(r)){o=s.getDatasetMeta(r),e=o.data,a=o.controller;break}}if(!e)return 0;for(r=0,i=e.length;r<i;++r)l=a.resolveDataElementOptions(r),l.borderAlign!=="inner"&&(n=Math.max(n,l.borderWidth||0,l.hoverBorderWidth||0));return n}getMaxOffset(e){let n=0;for(let s=0,r=e.length;s<r;++s){const i=this.resolveDataElementOptions(s);n=Math.max(n,i.offset||0,i.hoverOffset||0)}return n}_getRingWeightOffset(e){let n=0;for(let s=0;s<e;++s)this.chart.isDatasetVisible(s)&&(n+=this._getRingWeight(s));return n}_getRingWeight(e){return Math.max(Z(this.chart.data.datasets[e].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}B(Ji,"id","doughnut"),B(Ji,"defaults",{datasetElementType:!1,dataElementType:"arc",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:"number",properties:["circumference","endAngle","innerRadius","outerRadius","startAngle","x","y","offset","borderWidth","spacing"]}},cutout:"50%",rotation:0,circumference:360,radius:"100%",spacing:0,spacingMode:"angular",indexAxis:"r"}),B(Ji,"descriptors",{_scriptable:e=>e!=="spacing"&&e!=="spacingMode",_indexable:e=>e!=="spacing"&&e!=="spacingMode"&&!e.startsWith("borderDash")&&!e.startsWith("hoverBorderDash")}),B(Ji,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(e){const n=e.data,{labels:{pointStyle:s,textAlign:r,color:i,useBorderRadius:o,borderRadius:a}}=e.legend.options;return n.labels.length&&n.datasets.length?n.labels.map((l,c)=>{const f=e.getDatasetMeta(0).controller.getStyle(c);return{text:l,fillStyle:f.backgroundColor,fontColor:i,hidden:!e.getDataVisibility(c),lineDash:f.borderDash,lineDashOffset:f.borderDashOffset,lineJoin:f.borderJoinStyle,lineWidth:f.borderWidth,strokeStyle:f.borderColor,textAlign:r,pointStyle:s,borderRadius:o&&(a||f.borderRadius),index:c}}):[]}},onClick(e,n,s){s.chart.toggleDataVisibility(n.index),s.chart.update()}}}});function Ls(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class ih{constructor(e){B(this,"options");this.options=e||{}}static override(e){Object.assign(ih.prototype,e)}init(){}formats(){return Ls()}parse(){return Ls()}format(){return Ls()}add(){return Ls()}diff(){return Ls()}startOf(){return Ls()}endOf(){return Ls()}}var xC={_date:ih};function yC(t,e,n,s){const{controller:r,data:i,_sorted:o}=t,a=r._cachedMeta.iScale,l=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null;if(a&&e===a.axis&&e!=="r"&&o&&i.length){const c=a._reversePixels?sk:Dd;if(s){if(r._sharedOptions){const d=i[0],f=typeof d.getRange=="function"&&d.getRange(e);if(f){const h=c(i,e,n-f),p=c(i,e,n+f);return{lo:h.lo,hi:p.hi}}}}else{const d=c(i,e,n);if(l){const{vScale:f}=r._cachedMeta,{_parsed:h}=t,p=h.slice(0,d.lo+1).reverse().findIndex(g=>!ue(g[f.axis]));d.lo-=Math.max(0,p);const m=h.slice(d.hi).findIndex(g=>!ue(g[f.axis]));d.hi+=Math.max(0,m)}return d}}return{lo:0,hi:i.length-1}}function wc(t,e,n,s,r){const i=t.getSortedVisibleDatasetMetas(),o=n[e];for(let a=0,l=i.length;a<l;++a){const{index:c,data:d}=i[a],{lo:f,hi:h}=yC(i[a],e,o,r);for(let p=f;p<=h;++p){const m=d[p];m.skip||s(m,c,p)}}}function vC(t){const e=t.indexOf("x")!==-1,n=t.indexOf("y")!==-1;return function(s,r){const i=e?Math.abs(s.x-r.x):0,o=n?Math.abs(s.y-r.y):0;return Math.sqrt(Math.pow(i,2)+Math.pow(o,2))}}function pu(t,e,n,s,r){const i=[];return!r&&!t.isPointInArea(e)||wc(t,n,e,function(a,l,c){!r&&!Oy(a,t.chartArea,0)||a.inRange(e.x,e.y,s)&&i.push({element:a,datasetIndex:l,index:c})},!0),i}function bC(t,e,n,s){let r=[];function i(o,a,l){const{startAngle:c,endAngle:d}=o.getProps(["startAngle","endAngle"],s),{angle:f}=_y(o,{x:e.x,y:e.y});Ul(f,c,d)&&r.push({element:o,datasetIndex:a,index:l})}return wc(t,n,e,i),r}function wC(t,e,n,s,r,i){let o=[];const a=vC(n);let l=Number.POSITIVE_INFINITY;function c(d,f,h){const p=d.inRange(e.x,e.y,r);if(s&&!p)return;const m=d.getCenterPoint(r);if(!(!!i||t.isPointInArea(m))&&!p)return;const b=a(e,m);b<l?(o=[{element:d,datasetIndex:f,index:h}],l=b):b===l&&o.push({element:d,datasetIndex:f,index:h})}return wc(t,n,e,c),o}function gu(t,e,n,s,r,i){return!i&&!t.isPointInArea(e)?[]:n==="r"&&!s?bC(t,e,n,r):wC(t,e,n,s,r,i)}function Cg(t,e,n,s,r){const i=[],o=n==="x"?"inXRange":"inYRange";let a=!1;return wc(t,n,e,(l,c,d)=>{l[o]&&l[o](e[n],r)&&(i.push({element:l,datasetIndex:c,index:d}),a=a||l.inRange(e.x,e.y,r))}),s&&!a?[]:i}var SC={modes:{index(t,e,n,s){const r=zs(e,t),i=n.axis||"x",o=n.includeInvisible||!1,a=n.intersect?pu(t,r,i,s,o):gu(t,r,i,!1,s,o),l=[];return a.length?(t.getSortedVisibleDatasetMetas().forEach(c=>{const d=a[0].index,f=c.data[d];f&&!f.skip&&l.push({element:f,datasetIndex:c.index,index:d})}),l):[]},dataset(t,e,n,s){const r=zs(e,t),i=n.axis||"xy",o=n.includeInvisible||!1;let a=n.intersect?pu(t,r,i,s,o):gu(t,r,i,!1,s,o);if(a.length>0){const l=a[0].datasetIndex,c=t.getDatasetMeta(l).data;a=[];for(let d=0;d<c.length;++d)a.push({element:c[d],datasetIndex:l,index:d})}return a},point(t,e,n,s){const r=zs(e,t),i=n.axis||"xy",o=n.includeInvisible||!1;return pu(t,r,i,s,o)},nearest(t,e,n,s){const r=zs(e,t),i=n.axis||"xy",o=n.includeInvisible||!1;return gu(t,r,i,n.intersect,s,o)},x(t,e,n,s){const r=zs(e,t);return Cg(t,r,"x",n.intersect,s)},y(t,e,n,s){const r=zs(e,t);return Cg(t,r,"y",n.intersect,s)}}};const Wy=["left","top","right","bottom"];function Bi(t,e){return t.filter(n=>n.pos===e)}function jg(t,e){return t.filter(n=>Wy.indexOf(n.pos)===-1&&n.box.axis===e)}function $i(t,e){return t.sort((n,s)=>{const r=e?s:n,i=e?n:s;return r.weight===i.weight?r.index-i.index:r.weight-i.weight})}function _C(t){const e=[];let n,s,r,i,o,a;for(n=0,s=(t||[]).length;n<s;++n)r=t[n],{position:i,options:{stack:o,stackWeight:a=1}}=r,e.push({index:n,box:r,pos:i,horizontal:r.isHorizontal(),weight:r.weight,stack:o&&i+o,stackWeight:a});return e}function kC(t){const e={};for(const n of t){const{stack:s,pos:r,stackWeight:i}=n;if(!s||!Wy.includes(r))continue;const o=e[s]||(e[s]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=i}return e}function CC(t,e){const n=kC(t),{vBoxMaxWidth:s,hBoxMaxHeight:r}=e;let i,o,a;for(i=0,o=t.length;i<o;++i){a=t[i];const{fullSize:l}=a.box,c=n[a.stack],d=c&&a.stackWeight/c.weight;a.horizontal?(a.width=d?d*s:l&&e.availableWidth,a.height=r):(a.width=s,a.height=d?d*r:l&&e.availableHeight)}return n}function jC(t){const e=_C(t),n=$i(e.filter(c=>c.box.fullSize),!0),s=$i(Bi(e,"left"),!0),r=$i(Bi(e,"right")),i=$i(Bi(e,"top"),!0),o=$i(Bi(e,"bottom")),a=jg(e,"x"),l=jg(e,"y");return{fullSize:n,leftAndTop:s.concat(i),rightAndBottom:r.concat(l).concat(o).concat(a),chartArea:Bi(e,"chartArea"),vertical:s.concat(r).concat(l),horizontal:i.concat(o).concat(a)}}function Ng(t,e,n,s){return Math.max(t[n],e[n])+Math.max(t[s],e[s])}function Hy(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function NC(t,e,n,s){const{pos:r,box:i}=n,o=t.maxPadding;if(!te(r)){n.size&&(t[r]-=n.size);const f=s[n.stack]||{size:0,count:1};f.size=Math.max(f.size,n.horizontal?i.height:i.width),n.size=f.size/f.count,t[r]+=n.size}i.getPadding&&Hy(o,i.getPadding());const a=Math.max(0,e.outerWidth-Ng(o,t,"left","right")),l=Math.max(0,e.outerHeight-Ng(o,t,"top","bottom")),c=a!==t.w,d=l!==t.h;return t.w=a,t.h=l,n.horizontal?{same:c,other:d}:{same:d,other:c}}function EC(t){const e=t.maxPadding;function n(s){const r=Math.max(e[s]-t[s],0);return t[s]+=r,r}t.y+=n("top"),t.x+=n("left"),n("right"),n("bottom")}function MC(t,e){const n=e.maxPadding;function s(r){const i={left:0,top:0,right:0,bottom:0};return r.forEach(o=>{i[o]=Math.max(e[o],n[o])}),i}return s(t?["left","right"]:["top","bottom"])}function Zi(t,e,n,s){const r=[];let i,o,a,l,c,d;for(i=0,o=t.length,c=0;i<o;++i){a=t[i],l=a.box,l.update(a.width||e.w,a.height||e.h,MC(a.horizontal,e));const{same:f,other:h}=NC(e,n,a,s);c|=f&&r.length,d=d||h,l.fullSize||r.push(a)}return c&&Zi(r,e,n,s)||d}function Ia(t,e,n,s,r){t.top=n,t.left=e,t.right=e+s,t.bottom=n+r,t.width=s,t.height=r}function Eg(t,e,n,s){const r=n.padding;let{x:i,y:o}=e;for(const a of t){const l=a.box,c=s[a.stack]||{placed:0,weight:1},d=a.stackWeight/c.weight||1;if(a.horizontal){const f=e.w*d,h=c.size||l.height;Bo(c.start)&&(o=c.start),l.fullSize?Ia(l,r.left,o,n.outerWidth-r.right-r.left,h):Ia(l,e.left+c.placed,o,f,h),c.start=o,c.placed+=f,o=l.bottom}else{const f=e.h*d,h=c.size||l.width;Bo(c.start)&&(i=c.start),l.fullSize?Ia(l,i,r.top,h,n.outerHeight-r.bottom-r.top):Ia(l,i,e.top+c.placed,h,f),c.start=i,c.placed+=f,i=l.right}}e.x=i,e.y=o}var us={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(n){e.draw(n)}}]},t.boxes.push(e)},removeBox(t,e){const n=t.boxes?t.boxes.indexOf(e):-1;n!==-1&&t.boxes.splice(n,1)},configure(t,e,n){e.fullSize=n.fullSize,e.position=n.position,e.weight=n.weight},update(t,e,n,s){if(!t)return;const r=Gt(t.options.layout.padding),i=Math.max(e-r.width,0),o=Math.max(n-r.height,0),a=jC(t.boxes),l=a.vertical,c=a.horizontal;ae(t.boxes,g=>{typeof g.beforeLayout=="function"&&g.beforeLayout()});const d=l.reduce((g,b)=>b.box.options&&b.box.options.display===!1?g:g+1,0)||1,f=Object.freeze({outerWidth:e,outerHeight:n,padding:r,availableWidth:i,availableHeight:o,vBoxMaxWidth:i/2/d,hBoxMaxHeight:o/2}),h=Object.assign({},r);Hy(h,Gt(s));const p=Object.assign({maxPadding:h,w:i,h:o,x:r.left,y:r.top},r),m=CC(l.concat(c),f);Zi(a.fullSize,p,f,m),Zi(l,p,f,m),Zi(c,p,f,m)&&Zi(l,p,f,m),EC(p),Eg(a.leftAndTop,p,f,m),p.x+=p.w,p.y+=p.h,Eg(a.rightAndBottom,p,f,m),t.chartArea={left:p.left,top:p.top,right:p.left+p.w,bottom:p.top+p.h,height:p.h,width:p.w},ae(a.chartArea,g=>{const b=g.box;Object.assign(b,t.chartArea),b.update(p.w,p.h,{left:0,top:0,right:0,bottom:0})})}};class Vy{acquireContext(e,n){}releaseContext(e){return!1}addEventListener(e,n,s){}removeEventListener(e,n,s){}getDevicePixelRatio(){return 1}getMaximumSize(e,n,s,r){return n=Math.max(0,n||e.width),s=s||e.height,{width:n,height:Math.max(0,r?Math.floor(n/r):s)}}isAttached(e){return!0}updateConfig(e){}}class PC extends Vy{acquireContext(e){return e&&e.getContext&&e.getContext("2d")||null}updateConfig(e){e.options.animation=!1}}const ol="$chartjs",RC={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},Mg=t=>t===null||t==="";function OC(t,e){const n=t.style,s=t.getAttribute("height"),r=t.getAttribute("width");if(t[ol]={initial:{height:s,width:r,style:{display:n.display,height:n.height,width:n.width}}},n.display=n.display||"block",n.boxSizing=n.boxSizing||"border-box",Mg(r)){const i=gg(t,"width");i!==void 0&&(t.width=i)}if(Mg(s))if(t.style.height==="")t.height=t.width/(e||2);else{const i=gg(t,"height");i!==void 0&&(t.height=i)}return t}const Qy=$k?{passive:!0}:!1;function TC(t,e,n){t&&t.addEventListener(e,n,Qy)}function DC(t,e,n){t&&t.canvas&&t.canvas.removeEventListener(e,n,Qy)}function LC(t,e){const n=RC[t.type]||t.type,{x:s,y:r}=zs(t,e);return{type:n,chart:e,native:t,x:s!==void 0?s:null,y:r!==void 0?r:null}}function Ql(t,e){for(const n of t)if(n===e||n.contains(e))return!0}function AC(t,e,n){const s=t.canvas,r=new MutationObserver(i=>{let o=!1;for(const a of i)o=o||Ql(a.addedNodes,s),o=o&&!Ql(a.removedNodes,s);o&&n()});return r.observe(document,{childList:!0,subtree:!0}),r}function IC(t,e,n){const s=t.canvas,r=new MutationObserver(i=>{let o=!1;for(const a of i)o=o||Ql(a.removedNodes,s),o=o&&!Ql(a.addedNodes,s);o&&n()});return r.observe(document,{childList:!0,subtree:!0}),r}const $o=new Map;let Pg=0;function Ky(){const t=window.devicePixelRatio;t!==Pg&&(Pg=t,$o.forEach((e,n)=>{n.currentDevicePixelRatio!==t&&e()}))}function FC(t,e){$o.size||window.addEventListener("resize",Ky),$o.set(t,e)}function zC(t){$o.delete(t),$o.size||window.removeEventListener("resize",Ky)}function BC(t,e,n){const s=t.canvas,r=s&&rh(s);if(!r)return;const i=Ny((a,l)=>{const c=r.clientWidth;n(a,l),c<r.clientWidth&&n()},window),o=new ResizeObserver(a=>{const l=a[0],c=l.contentRect.width,d=l.contentRect.height;c===0&&d===0||i(c,d)});return o.observe(r),FC(t,i),o}function mu(t,e,n){n&&n.disconnect(),e==="resize"&&zC(t)}function $C(t,e,n){const s=t.canvas,r=Ny(i=>{t.ctx!==null&&n(LC(i,t))},t);return TC(s,e,r),r}class UC extends Vy{acquireContext(e,n){const s=e&&e.getContext&&e.getContext("2d");return s&&s.canvas===e?(OC(e,n),s):null}releaseContext(e){const n=e.canvas;if(!n[ol])return!1;const s=n[ol].initial;["height","width"].forEach(i=>{const o=s[i];ue(o)?n.removeAttribute(i):n.setAttribute(i,o)});const r=s.style||{};return Object.keys(r).forEach(i=>{n.style[i]=r[i]}),n.width=n.width,delete n[ol],!0}addEventListener(e,n,s){this.removeEventListener(e,n);const r=e.$proxies||(e.$proxies={}),o={attach:AC,detach:IC,resize:BC}[n]||$C;r[n]=o(e,n,s)}removeEventListener(e,n){const s=e.$proxies||(e.$proxies={}),r=s[n];if(!r)return;({attach:mu,detach:mu,resize:mu}[n]||DC)(e,n,r),s[n]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(e,n,s,r){return Bk(e,n,s,r)}isAttached(e){const n=e&&rh(e);return!!(n&&n.isConnected)}}function WC(t){return!sh()||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas?PC:UC}class js{constructor(){B(this,"x");B(this,"y");B(this,"active",!1);B(this,"options");B(this,"$animations")}tooltipPosition(e){const{x:n,y:s}=this.getProps(["x","y"],e);return{x:n,y:s}}hasValue(){return $l(this.x)&&$l(this.y)}getProps(e,n){const s=this.$animations;if(!n||!s)return this;const r={};return e.forEach(i=>{r[i]=s[i]&&s[i].active()?s[i]._to:this[i]}),r}}B(js,"defaults",{}),B(js,"defaultRoutes");function HC(t,e){const n=t.options.ticks,s=VC(t),r=Math.min(n.maxTicksLimit||s,s),i=n.major.enabled?KC(e):[],o=i.length,a=i[0],l=i[o-1],c=[];if(o>r)return YC(e,c,i,o/r),c;const d=QC(i,e,r);if(o>0){let f,h;const p=o>1?Math.round((l-a)/(o-1)):null;for(Fa(e,c,d,ue(p)?0:a-p,a),f=0,h=o-1;f<h;f++)Fa(e,c,d,i[f],i[f+1]);return Fa(e,c,d,l,ue(p)?e.length:l+p),c}return Fa(e,c,d),c}function VC(t){const e=t.options.offset,n=t._tickSize(),s=t._length/n+(e?0:1),r=t._maxLength/n;return Math.floor(Math.min(s,r))}function QC(t,e,n){const s=XC(t),r=e.length/n;if(!s)return Math.max(r,1);const i=q_(s);for(let o=0,a=i.length-1;o<a;o++){const l=i[o];if(l>r)return l}return Math.max(r,1)}function KC(t){const e=[];let n,s;for(n=0,s=t.length;n<s;n++)t[n].major&&e.push(n);return e}function YC(t,e,n,s){let r=0,i=n[0],o;for(s=Math.ceil(s),o=0;o<t.length;o++)o===i&&(e.push(t[o]),r++,i=n[r*s])}function Fa(t,e,n,s,r){const i=Z(s,0),o=Math.min(Z(r,t.length),t.length);let a=0,l,c,d;for(n=Math.ceil(n),r&&(l=r-s,n=l/Math.floor(l/n)),d=i;d<0;)a++,d=Math.round(i+a*n);for(c=Math.max(i,0);c<o;c++)c===d&&(e.push(t[c]),a++,d=Math.round(i+a*n))}function XC(t){const e=t.length;let n,s;if(e<2)return!1;for(s=t[0],n=1;n<e;++n)if(t[n]-t[n-1]!==s)return!1;return s}const qC=t=>t==="left"?"right":t==="right"?"left":t,Rg=(t,e,n)=>e==="top"||e==="left"?t[e]+n:t[e]-n,Og=(t,e)=>Math.min(e||t,t);function Tg(t,e){const n=[],s=t.length/e,r=t.length;let i=0;for(;i<r;i+=s)n.push(t[Math.floor(i)]);return n}function GC(t,e,n){const s=t.ticks.length,r=Math.min(e,s-1),i=t._startPixel,o=t._endPixel,a=1e-6;let l=t.getPixelForTick(r),c;if(!(n&&(s===1?c=Math.max(l-i,o-l):e===0?c=(t.getPixelForTick(1)-l)/2:c=(l-t.getPixelForTick(r-1))/2,l+=r<e?c:-c,l<i-a||l>o+a)))return l}function JC(t,e){ae(t,n=>{const s=n.gc,r=s.length/2;let i;if(r>e){for(i=0;i<r;++i)delete n.data[s[i]];s.splice(0,r)}})}function Ui(t){return t.drawTicks?t.tickLength:0}function Dg(t,e){if(!t.display)return 0;const n=ut(t.font,e),s=Gt(t.padding);return(Fe(t.text)?t.text.length:1)*n.lineHeight+s.height}function ZC(t,e){return wi(t,{scale:e,type:"scale"})}function ej(t,e,n){return wi(t,{tick:n,index:e,type:"tick"})}function tj(t,e,n){let s=Ey(t);return(n&&e!=="right"||!n&&e==="right")&&(s=qC(s)),s}function nj(t,e,n,s){const{top:r,left:i,bottom:o,right:a,chart:l}=t,{chartArea:c,scales:d}=l;let f=0,h,p,m;const g=o-r,b=a-i;if(t.isHorizontal()){if(p=bt(s,i,a),te(n)){const y=Object.keys(n)[0],x=n[y];m=d[y].getPixelForValue(x)+g-e}else n==="center"?m=(c.bottom+c.top)/2+g-e:m=Rg(t,n,e);h=a-i}else{if(te(n)){const y=Object.keys(n)[0],x=n[y];p=d[y].getPixelForValue(x)-b+e}else n==="center"?p=(c.left+c.right)/2-b+e:p=Rg(t,n,e);m=bt(s,o,r),f=n==="left"?-Le:Le}return{titleX:p,titleY:m,maxWidth:h,rotation:f}}class Si extends js{constructor(e){super(),this.id=e.id,this.type=e.type,this.options=void 0,this.ctx=e.ctx,this.chart=e.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(e){this.options=e.setContext(this.getContext()),this.axis=e.axis,this._userMin=this.parse(e.min),this._userMax=this.parse(e.max),this._suggestedMin=this.parse(e.suggestedMin),this._suggestedMax=this.parse(e.suggestedMax)}parse(e,n){return e}getUserBounds(){let{_userMin:e,_userMax:n,_suggestedMin:s,_suggestedMax:r}=this;return e=on(e,Number.POSITIVE_INFINITY),n=on(n,Number.NEGATIVE_INFINITY),s=on(s,Number.POSITIVE_INFINITY),r=on(r,Number.NEGATIVE_INFINITY),{min:on(e,s),max:on(n,r),minDefined:It(e),maxDefined:It(n)}}getMinMax(e){let{min:n,max:s,minDefined:r,maxDefined:i}=this.getUserBounds(),o;if(r&&i)return{min:n,max:s};const a=this.getMatchingVisibleMetas();for(let l=0,c=a.length;l<c;++l)o=a[l].controller.getMinMax(this,e),r||(n=Math.min(n,o.min)),i||(s=Math.max(s,o.max));return n=i&&n>s?s:n,s=r&&n>s?n:s,{min:on(n,on(s,n)),max:on(s,on(n,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const e=this.chart.data;return this.options.labels||(this.isHorizontal()?e.xLabels:e.yLabels)||e.labels||[]}getLabelItems(e=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(e))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){he(this.options.beforeUpdate,[this])}update(e,n,s){const{beginAtZero:r,grace:i,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=e,this.maxHeight=n,this._margins=s=Object.assign({left:0,right:0,top:0,bottom:0},s),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+s.left+s.right:this.height+s.top+s.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Ck(this,i,r),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const l=a<this.ticks.length;this._convertTicksToLabels(l?Tg(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),o.display&&(o.autoSkip||o.source==="auto")&&(this.ticks=HC(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),l&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let e=this.options.reverse,n,s;this.isHorizontal()?(n=this.left,s=this.right):(n=this.top,s=this.bottom,e=!e),this._startPixel=n,this._endPixel=s,this._reversePixels=e,this._length=s-n,this._alignToPixels=this.options.alignToPixels}afterUpdate(){he(this.options.afterUpdate,[this])}beforeSetDimensions(){he(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){he(this.options.afterSetDimensions,[this])}_callHooks(e){this.chart.notifyPlugins(e,this.getContext()),he(this.options[e],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){he(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(e){const n=this.options.ticks;let s,r,i;for(s=0,r=e.length;s<r;s++)i=e[s],i.label=he(n.callback,[i.value,s,e],this)}afterTickToLabelConversion(){he(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){he(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const e=this.options,n=e.ticks,s=Og(this.ticks.length,e.ticks.maxTicksLimit),r=n.minRotation||0,i=n.maxRotation;let o=r,a,l,c;if(!this._isVisible()||!n.display||r>=i||s<=1||!this.isHorizontal()){this.labelRotation=r;return}const d=this._getLabelSizes(),f=d.widest.width,h=d.highest.height,p=ct(this.chart.width-f,0,this.maxWidth);a=e.offset?this.maxWidth/s:p/(s-1),f+6>a&&(a=p/(s-(e.offset?.5:1)),l=this.maxHeight-Ui(e.grid)-n.padding-Dg(e.title,this.chart.options.font),c=Math.sqrt(f*f+h*h),o=ek(Math.min(Math.asin(ct((d.highest.height+6)/a,-1,1)),Math.asin(ct(l/c,-1,1))-Math.asin(ct(h/c,-1,1)))),o=Math.max(r,Math.min(i,o))),this.labelRotation=o}afterCalculateLabelRotation(){he(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){he(this.options.beforeFit,[this])}fit(){const e={width:0,height:0},{chart:n,options:{ticks:s,title:r,grid:i}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const l=Dg(r,n.options.font);if(a?(e.width=this.maxWidth,e.height=Ui(i)+l):(e.height=this.maxHeight,e.width=Ui(i)+l),s.display&&this.ticks.length){const{first:c,last:d,widest:f,highest:h}=this._getLabelSizes(),p=s.padding*2,m=Rn(this.labelRotation),g=Math.cos(m),b=Math.sin(m);if(a){const y=s.mirror?0:b*f.width+g*h.height;e.height=Math.min(this.maxHeight,e.height+y+p)}else{const y=s.mirror?0:g*f.width+b*h.height;e.width=Math.min(this.maxWidth,e.width+y+p)}this._calculatePadding(c,d,b,g)}}this._handleMargins(),a?(this.width=this._length=n.width-this._margins.left-this._margins.right,this.height=e.height):(this.width=e.width,this.height=this._length=n.height-this._margins.top-this._margins.bottom)}_calculatePadding(e,n,s,r){const{ticks:{align:i,padding:o},position:a}=this.options,l=this.labelRotation!==0,c=a!=="top"&&this.axis==="x";if(this.isHorizontal()){const d=this.getPixelForTick(0)-this.left,f=this.right-this.getPixelForTick(this.ticks.length-1);let h=0,p=0;l?c?(h=r*e.width,p=s*n.height):(h=s*e.height,p=r*n.width):i==="start"?p=n.width:i==="end"?h=e.width:i!=="inner"&&(h=e.width/2,p=n.width/2),this.paddingLeft=Math.max((h-d+o)*this.width/(this.width-d),0),this.paddingRight=Math.max((p-f+o)*this.width/(this.width-f),0)}else{let d=n.height/2,f=e.height/2;i==="start"?(d=0,f=e.height):i==="end"&&(d=n.height,f=0),this.paddingTop=d+o,this.paddingBottom=f+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){he(this.options.afterFit,[this])}isHorizontal(){const{axis:e,position:n}=this.options;return n==="top"||n==="bottom"||e==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(e){this.beforeTickToLabelConversion(),this.generateTickLabels(e);let n,s;for(n=0,s=e.length;n<s;n++)ue(e[n].label)&&(e.splice(n,1),s--,n--);this.afterTickToLabelConversion()}_getLabelSizes(){let e=this._labelSizes;if(!e){const n=this.options.ticks.sampleSize;let s=this.ticks;n<s.length&&(s=Tg(s,n)),this._labelSizes=e=this._computeLabelSizes(s,s.length,this.options.ticks.maxTicksLimit)}return e}_computeLabelSizes(e,n,s){const{ctx:r,_longestTextCache:i}=this,o=[],a=[],l=Math.floor(n/Og(n,s));let c=0,d=0,f,h,p,m,g,b,y,x,v,_,w;for(f=0;f<n;f+=l){if(m=e[f].label,g=this._resolveTickFontOptions(f),r.font=b=g.string,y=i[b]=i[b]||{data:{},gc:[]},x=g.lineHeight,v=_=0,!ue(m)&&!Fe(m))v=cg(r,y.data,y.gc,v,m),_=x;else if(Fe(m))for(h=0,p=m.length;h<p;++h)w=m[h],!ue(w)&&!Fe(w)&&(v=cg(r,y.data,y.gc,v,w),_+=x);o.push(v),a.push(_),c=Math.max(v,c),d=Math.max(_,d)}JC(i,n);const k=o.indexOf(c),C=a.indexOf(d),j=M=>({width:o[M]||0,height:a[M]||0});return{first:j(0),last:j(n-1),widest:j(k),highest:j(C),widths:o,heights:a}}getLabelForValue(e){return e}getPixelForValue(e,n){return NaN}getValueForPixel(e){}getPixelForTick(e){const n=this.ticks;return e<0||e>n.length-1?null:this.getPixelForValue(n[e].value)}getPixelForDecimal(e){this._reversePixels&&(e=1-e);const n=this._startPixel+e*this._length;return nk(this._alignToPixels?Ds(this.chart,n,0):n)}getDecimalForPixel(e){const n=(e-this._startPixel)/this._length;return this._reversePixels?1-n:n}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:e,max:n}=this;return e<0&&n<0?n:e>0&&n>0?e:0}getContext(e){const n=this.ticks||[];if(e>=0&&e<n.length){const s=n[e];return s.$context||(s.$context=ej(this.getContext(),e,s))}return this.$context||(this.$context=ZC(this.chart.getContext(),this))}_tickSize(){const e=this.options.ticks,n=Rn(this.labelRotation),s=Math.abs(Math.cos(n)),r=Math.abs(Math.sin(n)),i=this._getLabelSizes(),o=e.autoSkipPadding||0,a=i?i.widest.width+o:0,l=i?i.highest.height+o:0;return this.isHorizontal()?l*s>a*r?a/s:l/r:l*r<a*s?l/s:a/r}_isVisible(){const e=this.options.display;return e!=="auto"?!!e:this.getMatchingVisibleMetas().length>0}_computeGridLineItems(e){const n=this.axis,s=this.chart,r=this.options,{grid:i,position:o,border:a}=r,l=i.offset,c=this.isHorizontal(),f=this.ticks.length+(l?1:0),h=Ui(i),p=[],m=a.setContext(this.getContext()),g=m.display?m.width:0,b=g/2,y=function(oe){return Ds(s,oe,g)};let x,v,_,w,k,C,j,M,E,P,A,Q;if(o==="top")x=y(this.bottom),C=this.bottom-h,M=x-b,P=y(e.top)+b,Q=e.bottom;else if(o==="bottom")x=y(this.top),P=e.top,Q=y(e.bottom)-b,C=x+b,M=this.top+h;else if(o==="left")x=y(this.right),k=this.right-h,j=x-b,E=y(e.left)+b,A=e.right;else if(o==="right")x=y(this.left),E=e.left,A=y(e.right)-b,k=x+b,j=this.left+h;else if(n==="x"){if(o==="center")x=y((e.top+e.bottom)/2+.5);else if(te(o)){const oe=Object.keys(o)[0],G=o[oe];x=y(this.chart.scales[oe].getPixelForValue(G))}P=e.top,Q=e.bottom,C=x+b,M=C+h}else if(n==="y"){if(o==="center")x=y((e.left+e.right)/2);else if(te(o)){const oe=Object.keys(o)[0],G=o[oe];x=y(this.chart.scales[oe].getPixelForValue(G))}k=x-b,j=k-h,E=e.left,A=e.right}const ne=Z(r.ticks.maxTicksLimit,f),Y=Math.max(1,Math.ceil(f/ne));for(v=0;v<f;v+=Y){const oe=this.getContext(v),G=i.setContext(oe),O=a.setContext(oe),L=G.lineWidth,I=G.color,V=O.dash||[],F=O.dashOffset,ce=G.tickWidth,$=G.tickColor,ke=G.tickBorderDash||[],J=G.tickBorderDashOffset;_=GC(this,v,l),_!==void 0&&(w=Ds(s,_,L),c?k=j=E=A=w:C=M=P=Q=w,p.push({tx1:k,ty1:C,tx2:j,ty2:M,x1:E,y1:P,x2:A,y2:Q,width:L,color:I,borderDash:V,borderDashOffset:F,tickWidth:ce,tickColor:$,tickBorderDash:ke,tickBorderDashOffset:J}))}return this._ticksLength=f,this._borderValue=x,p}_computeLabelItems(e){const n=this.axis,s=this.options,{position:r,ticks:i}=s,o=this.isHorizontal(),a=this.ticks,{align:l,crossAlign:c,padding:d,mirror:f}=i,h=Ui(s.grid),p=h+d,m=f?-d:p,g=-Rn(this.labelRotation),b=[];let y,x,v,_,w,k,C,j,M,E,P,A,Q="middle";if(r==="top")k=this.bottom-m,C=this._getXAxisLabelAlignment();else if(r==="bottom")k=this.top+m,C=this._getXAxisLabelAlignment();else if(r==="left"){const Y=this._getYAxisLabelAlignment(h);C=Y.textAlign,w=Y.x}else if(r==="right"){const Y=this._getYAxisLabelAlignment(h);C=Y.textAlign,w=Y.x}else if(n==="x"){if(r==="center")k=(e.top+e.bottom)/2+p;else if(te(r)){const Y=Object.keys(r)[0],oe=r[Y];k=this.chart.scales[Y].getPixelForValue(oe)+p}C=this._getXAxisLabelAlignment()}else if(n==="y"){if(r==="center")w=(e.left+e.right)/2-p;else if(te(r)){const Y=Object.keys(r)[0],oe=r[Y];w=this.chart.scales[Y].getPixelForValue(oe)}C=this._getYAxisLabelAlignment(h).textAlign}n==="y"&&(l==="start"?Q="top":l==="end"&&(Q="bottom"));const ne=this._getLabelSizes();for(y=0,x=a.length;y<x;++y){v=a[y],_=v.label;const Y=i.setContext(this.getContext(y));j=this.getPixelForTick(y)+i.labelOffset,M=this._resolveTickFontOptions(y),E=M.lineHeight,P=Fe(_)?_.length:1;const oe=P/2,G=Y.color,O=Y.textStrokeColor,L=Y.textStrokeWidth;let I=C;o?(w=j,C==="inner"&&(y===x-1?I=this.options.reverse?"left":"right":y===0?I=this.options.reverse?"right":"left":I="center"),r==="top"?c==="near"||g!==0?A=-P*E+E/2:c==="center"?A=-ne.highest.height/2-oe*E+E:A=-ne.highest.height+E/2:c==="near"||g!==0?A=E/2:c==="center"?A=ne.highest.height/2-oe*E:A=ne.highest.height-P*E,f&&(A*=-1),g!==0&&!Y.showLabelBackdrop&&(w+=E/2*Math.sin(g))):(k=j,A=(1-P)*E/2);let V;if(Y.showLabelBackdrop){const F=Gt(Y.backdropPadding),ce=ne.heights[y],$=ne.widths[y];let ke=A-F.top,J=0-F.left;switch(Q){case"middle":ke-=ce/2;break;case"bottom":ke-=ce;break}switch(C){case"center":J-=$/2;break;case"right":J-=$;break;case"inner":y===x-1?J-=$:y>0&&(J-=$/2);break}V={left:J,top:ke,width:$+F.width,height:ce+F.height,color:Y.backdropColor}}b.push({label:_,font:M,textOffset:A,options:{rotation:g,color:G,strokeColor:O,strokeWidth:L,textAlign:I,textBaseline:Q,translation:[w,k],backdrop:V}})}return b}_getXAxisLabelAlignment(){const{position:e,ticks:n}=this.options;if(-Rn(this.labelRotation))return e==="top"?"left":"right";let r="center";return n.align==="start"?r="left":n.align==="end"?r="right":n.align==="inner"&&(r="inner"),r}_getYAxisLabelAlignment(e){const{position:n,ticks:{crossAlign:s,mirror:r,padding:i}}=this.options,o=this._getLabelSizes(),a=e+i,l=o.widest.width;let c,d;return n==="left"?r?(d=this.right+i,s==="near"?c="left":s==="center"?(c="center",d+=l/2):(c="right",d+=l)):(d=this.right-a,s==="near"?c="right":s==="center"?(c="center",d-=l/2):(c="left",d=this.left)):n==="right"?r?(d=this.left+i,s==="near"?c="right":s==="center"?(c="center",d-=l/2):(c="left",d-=l)):(d=this.left+a,s==="near"?c="left":s==="center"?(c="center",d+=l/2):(c="right",d=this.right)):c="right",{textAlign:c,x:d}}_computeLabelArea(){if(this.options.ticks.mirror)return;const e=this.chart,n=this.options.position;if(n==="left"||n==="right")return{top:0,left:this.left,bottom:e.height,right:this.right};if(n==="top"||n==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:e.width}}drawBackground(){const{ctx:e,options:{backgroundColor:n},left:s,top:r,width:i,height:o}=this;n&&(e.save(),e.fillStyle=n,e.fillRect(s,r,i,o),e.restore())}getLineWidthForValue(e){const n=this.options.grid;if(!this._isVisible()||!n.display)return 0;const r=this.ticks.findIndex(i=>i.value===e);return r>=0?n.setContext(this.getContext(r)).lineWidth:0}drawGrid(e){const n=this.options.grid,s=this.ctx,r=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(e));let i,o;const a=(l,c,d)=>{!d.width||!d.color||(s.save(),s.lineWidth=d.width,s.strokeStyle=d.color,s.setLineDash(d.borderDash||[]),s.lineDashOffset=d.borderDashOffset,s.beginPath(),s.moveTo(l.x,l.y),s.lineTo(c.x,c.y),s.stroke(),s.restore())};if(n.display)for(i=0,o=r.length;i<o;++i){const l=r[i];n.drawOnChartArea&&a({x:l.x1,y:l.y1},{x:l.x2,y:l.y2},l),n.drawTicks&&a({x:l.tx1,y:l.ty1},{x:l.tx2,y:l.ty2},{color:l.tickColor,width:l.tickWidth,borderDash:l.tickBorderDash,borderDashOffset:l.tickBorderDashOffset})}}drawBorder(){const{chart:e,ctx:n,options:{border:s,grid:r}}=this,i=s.setContext(this.getContext()),o=s.display?i.width:0;if(!o)return;const a=r.setContext(this.getContext(0)).lineWidth,l=this._borderValue;let c,d,f,h;this.isHorizontal()?(c=Ds(e,this.left,o)-o/2,d=Ds(e,this.right,a)+a/2,f=h=l):(f=Ds(e,this.top,o)-o/2,h=Ds(e,this.bottom,a)+a/2,c=d=l),n.save(),n.lineWidth=i.width,n.strokeStyle=i.color,n.beginPath(),n.moveTo(c,f),n.lineTo(d,h),n.stroke(),n.restore()}drawLabels(e){if(!this.options.ticks.display)return;const s=this.ctx,r=this._computeLabelArea();r&&Gf(s,r);const i=this.getLabelItems(e);for(const o of i){const a=o.options,l=o.font,c=o.label,d=o.textOffset;Wl(s,c,0,d,l,a)}r&&Jf(s)}drawTitle(){const{ctx:e,options:{position:n,title:s,reverse:r}}=this;if(!s.display)return;const i=ut(s.font),o=Gt(s.padding),a=s.align;let l=i.lineHeight/2;n==="bottom"||n==="center"||te(n)?(l+=o.bottom,Fe(s.text)&&(l+=i.lineHeight*(s.text.length-1))):l+=o.top;const{titleX:c,titleY:d,maxWidth:f,rotation:h}=nj(this,l,n,a);Wl(e,s.text,0,0,i,{color:s.color,maxWidth:f,rotation:h,textAlign:tj(a,n,r),textBaseline:"middle",translation:[c,d],strokeColor:s.strokeColor,strokeWidth:s.strokeWidth})}draw(e){this._isVisible()&&(this.drawBackground(),this.drawGrid(e),this.drawBorder(),this.drawTitle(),this.drawLabels(e))}_layers(){const e=this.options,n=e.ticks&&e.ticks.z||0,s=Z(e.grid&&e.grid.z,-1),r=Z(e.border&&e.border.z,0);return!this._isVisible()||this.draw!==Si.prototype.draw?[{z:n,draw:i=>{this.draw(i)}}]:[{z:s,draw:i=>{this.drawBackground(),this.drawGrid(i),this.drawTitle()}},{z:r,draw:()=>{this.drawBorder()}},{z:n,draw:i=>{this.drawLabels(i)}}]}getMatchingVisibleMetas(e){const n=this.chart.getSortedVisibleDatasetMetas(),s=this.axis+"AxisID",r=[];let i,o;for(i=0,o=n.length;i<o;++i){const a=n[i];a[s]===this.id&&(!e||a.type===e)&&r.push(a)}return r}_resolveTickFontOptions(e){const n=this.options.ticks.setContext(this.getContext(e));return ut(n.font)}_maxDigits(){const e=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/e}}class za{constructor(e,n,s){this.type=e,this.scope=n,this.override=s,this.items=Object.create(null)}isForType(e){return Object.prototype.isPrototypeOf.call(this.type.prototype,e.prototype)}register(e){const n=Object.getPrototypeOf(e);let s;ij(n)&&(s=this.register(n));const r=this.items,i=e.id,o=this.scope+"."+i;if(!i)throw new Error("class does not have id: "+e);return i in r||(r[i]=e,sj(e,o,s),this.override&&Ee.override(e.id,e.overrides)),o}get(e){return this.items[e]}unregister(e){const n=this.items,s=e.id,r=this.scope;s in n&&delete n[s],r&&s in Ee[r]&&(delete Ee[r][s],this.override&&delete ur[s])}}function sj(t,e,n){const s=zo(Object.create(null),[n?Ee.get(n):{},Ee.get(e),t.defaults]);Ee.set(e,s),t.defaultRoutes&&rj(e,t.defaultRoutes),t.descriptors&&Ee.describe(e,t.descriptors)}function rj(t,e){Object.keys(e).forEach(n=>{const s=n.split("."),r=s.pop(),i=[t].concat(s).join("."),o=e[n].split("."),a=o.pop(),l=o.join(".");Ee.route(i,r,l,a)})}function ij(t){return"id"in t&&"defaults"in t}class oj{constructor(){this.controllers=new za(Vr,"datasets",!0),this.elements=new za(js,"elements"),this.plugins=new za(Object,"plugins"),this.scales=new za(Si,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...e){this._each("register",e)}remove(...e){this._each("unregister",e)}addControllers(...e){this._each("register",e,this.controllers)}addElements(...e){this._each("register",e,this.elements)}addPlugins(...e){this._each("register",e,this.plugins)}addScales(...e){this._each("register",e,this.scales)}getController(e){return this._get(e,this.controllers,"controller")}getElement(e){return this._get(e,this.elements,"element")}getPlugin(e){return this._get(e,this.plugins,"plugin")}getScale(e){return this._get(e,this.scales,"scale")}removeControllers(...e){this._each("unregister",e,this.controllers)}removeElements(...e){this._each("unregister",e,this.elements)}removePlugins(...e){this._each("unregister",e,this.plugins)}removeScales(...e){this._each("unregister",e,this.scales)}_each(e,n,s){[...n].forEach(r=>{const i=s||this._getRegistryForType(r);s||i.isForType(r)||i===this.plugins&&r.id?this._exec(e,i,r):ae(r,o=>{const a=s||this._getRegistryForType(o);this._exec(e,a,o)})})}_exec(e,n,s){const r=Yf(e);he(s["before"+r],[],s),n[e](s),he(s["after"+r],[],s)}_getRegistryForType(e){for(let n=0;n<this._typedRegistries.length;n++){const s=this._typedRegistries[n];if(s.isForType(e))return s}return this.plugins}_get(e,n,s){const r=n.get(e);if(r===void 0)throw new Error('"'+e+'" is not a registered '+s+".");return r}}var un=new oj;class aj{constructor(){this._init=void 0}notify(e,n,s,r){if(n==="beforeInit"&&(this._init=this._createDescriptors(e,!0),this._notify(this._init,e,"install")),this._init===void 0)return;const i=r?this._descriptors(e).filter(r):this._descriptors(e),o=this._notify(i,e,n,s);return n==="afterDestroy"&&(this._notify(i,e,"stop"),this._notify(this._init,e,"uninstall"),this._init=void 0),o}_notify(e,n,s,r){r=r||{};for(const i of e){const o=i.plugin,a=o[s],l=[n,r,i.options];if(he(a,l,o)===!1&&r.cancelable)return!1}return!0}invalidate(){ue(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(e){if(this._cache)return this._cache;const n=this._cache=this._createDescriptors(e);return this._notifyStateChanges(e),n}_createDescriptors(e,n){const s=e&&e.config,r=Z(s.options&&s.options.plugins,{}),i=lj(s);return r===!1&&!n?[]:uj(e,i,r,n)}_notifyStateChanges(e){const n=this._oldCache||[],s=this._cache,r=(i,o)=>i.filter(a=>!o.some(l=>a.plugin.id===l.plugin.id));this._notify(r(n,s),e,"stop"),this._notify(r(s,n),e,"start")}}function lj(t){const e={},n=[],s=Object.keys(un.plugins.items);for(let i=0;i<s.length;i++)n.push(un.getPlugin(s[i]));const r=t.plugins||[];for(let i=0;i<r.length;i++){const o=r[i];n.indexOf(o)===-1&&(n.push(o),e[o.id]=!0)}return{plugins:n,localIds:e}}function cj(t,e){return!e&&t===!1?null:t===!0?{}:t}function uj(t,{plugins:e,localIds:n},s,r){const i=[],o=t.getContext();for(const a of e){const l=a.id,c=cj(s[l],r);c!==null&&i.push({plugin:a,options:dj(t.config,{plugin:a,local:n[l]},c,o)})}return i}function dj(t,{plugin:e,local:n},s,r){const i=t.pluginScopeKeys(e),o=t.getOptionScopes(s,i);return n&&e.defaults&&o.push(e.defaults),t.createResolver(o,r,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function Ad(t,e){const n=Ee.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||n.indexAxis||"x"}function fj(t,e){let n=t;return t==="_index_"?n=e:t==="_value_"&&(n=e==="x"?"y":"x"),n}function hj(t,e){return t===e?"_index_":"_value_"}function Lg(t){if(t==="x"||t==="y"||t==="r")return t}function pj(t){if(t==="top"||t==="bottom")return"x";if(t==="left"||t==="right")return"y"}function Id(t,...e){if(Lg(t))return t;for(const n of e){const s=n.axis||pj(n.position)||t.length>1&&Lg(t[0].toLowerCase());if(s)return s}throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function Ag(t,e,n){if(n[e+"AxisID"]===t)return{axis:e}}function gj(t,e){if(e.data&&e.data.datasets){const n=e.data.datasets.filter(s=>s.xAxisID===t||s.yAxisID===t);if(n.length)return Ag(t,"x",n[0])||Ag(t,"y",n[0])}return{}}function mj(t,e){const n=ur[t.type]||{scales:{}},s=e.scales||{},r=Ad(t.type,e),i=Object.create(null);return Object.keys(s).forEach(o=>{const a=s[o];if(!te(a))return console.error(`Invalid scale configuration for scale: ${o}`);if(a._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${o}`);const l=Id(o,a,gj(o,t),Ee.scales[a.type]),c=hj(l,r),d=n.scales||{};i[o]=fo(Object.create(null),[{axis:l},a,d[l],d[c]])}),t.data.datasets.forEach(o=>{const a=o.type||t.type,l=o.indexAxis||Ad(a,e),d=(ur[a]||{}).scales||{};Object.keys(d).forEach(f=>{const h=fj(f,l),p=o[h+"AxisID"]||h;i[p]=i[p]||Object.create(null),fo(i[p],[{axis:h},s[p],d[f]])})}),Object.keys(i).forEach(o=>{const a=i[o];fo(a,[Ee.scales[a.type],Ee.scale])}),i}function Yy(t){const e=t.options||(t.options={});e.plugins=Z(e.plugins,{}),e.scales=mj(t,e)}function Xy(t){return t=t||{},t.datasets=t.datasets||[],t.labels=t.labels||[],t}function xj(t){return t=t||{},t.data=Xy(t.data),Yy(t),t}const Ig=new Map,qy=new Set;function Ba(t,e){let n=Ig.get(t);return n||(n=e(),Ig.set(t,n),qy.add(n)),n}const Wi=(t,e,n)=>{const s=cr(e,n);s!==void 0&&t.add(s)};class yj{constructor(e){this._config=xj(e),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(e){this._config.type=e}get data(){return this._config.data}set data(e){this._config.data=Xy(e)}get options(){return this._config.options}set options(e){this._config.options=e}get plugins(){return this._config.plugins}update(){const e=this._config;this.clearCache(),Yy(e)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(e){return Ba(e,()=>[[`datasets.${e}`,""]])}datasetAnimationScopeKeys(e,n){return Ba(`${e}.transition.${n}`,()=>[[`datasets.${e}.transitions.${n}`,`transitions.${n}`],[`datasets.${e}`,""]])}datasetElementScopeKeys(e,n){return Ba(`${e}-${n}`,()=>[[`datasets.${e}.elements.${n}`,`datasets.${e}`,`elements.${n}`,""]])}pluginScopeKeys(e){const n=e.id,s=this.type;return Ba(`${s}-plugin-${n}`,()=>[[`plugins.${n}`,...e.additionalOptionScopes||[]]])}_cachedScopes(e,n){const s=this._scopeCache;let r=s.get(e);return(!r||n)&&(r=new Map,s.set(e,r)),r}getOptionScopes(e,n,s){const{options:r,type:i}=this,o=this._cachedScopes(e,s),a=o.get(n);if(a)return a;const l=new Set;n.forEach(d=>{e&&(l.add(e),d.forEach(f=>Wi(l,e,f))),d.forEach(f=>Wi(l,r,f)),d.forEach(f=>Wi(l,ur[i]||{},f)),d.forEach(f=>Wi(l,Ee,f)),d.forEach(f=>Wi(l,Ld,f))});const c=Array.from(l);return c.length===0&&c.push(Object.create(null)),qy.has(n)&&o.set(n,c),c}chartOptionScopes(){const{options:e,type:n}=this;return[e,ur[n]||{},Ee.datasets[n]||{},{type:n},Ee,Ld]}resolveNamedOptions(e,n,s,r=[""]){const i={$shared:!0},{resolver:o,subPrefixes:a}=Fg(this._resolverCache,e,r);let l=o;if(bj(o,n)){i.$shared=!1,s=Cs(s)?s():s;const c=this.createResolver(e,s,a);l=gi(o,s,c)}for(const c of n)i[c]=l[c];return i}createResolver(e,n,s=[""],r){const{resolver:i}=Fg(this._resolverCache,e,s);return te(n)?gi(i,n,void 0,r):i}}function Fg(t,e,n){let s=t.get(e);s||(s=new Map,t.set(e,s));const r=n.join();let i=s.get(r);return i||(i={resolver:eh(e,n),subPrefixes:n.filter(a=>!a.toLowerCase().includes("hover"))},s.set(r,i)),i}const vj=t=>te(t)&&Object.getOwnPropertyNames(t).some(e=>Cs(t[e]));function bj(t,e){const{isScriptable:n,isIndexable:s}=Dy(t);for(const r of e){const i=n(r),o=s(r),a=(o||i)&&t[r];if(i&&(Cs(a)||vj(a))||o&&Fe(a))return!0}return!1}var wj="4.6.1";const Sj=["top","bottom","left","right","chartArea"];function zg(t,e){return t==="top"||t==="bottom"||Sj.indexOf(t)===-1&&e==="x"}function Bg(t,e){return function(n,s){return n[t]===s[t]?n[e]-s[e]:n[t]-s[t]}}function $g(t){const e=t.chart,n=e.options.animation;e.notifyPlugins("afterRender"),he(n&&n.onComplete,[t],e)}function _j(t){const e=t.chart,n=e.options.animation;he(n&&n.onProgress,[t],e)}function Gy(t){return sh()&&typeof t=="string"?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const al={},Ug=t=>{const e=Gy(t);return Object.values(al).filter(n=>n.canvas===e).pop()};function kj(t,e,n){const s=Object.keys(t);for(const r of s){const i=+r;if(i>=e){const o=t[r];delete t[r],(n>0||i>e)&&(t[i+n]=o)}}}function Cj(t,e,n,s){return!n||t.type==="mouseout"?null:s?e:t}var Hn;let Sc=(Hn=class{static register(...e){un.add(...e),Wg()}static unregister(...e){un.remove(...e),Wg()}constructor(e,n){const s=this.config=new yj(n),r=Gy(e),i=Ug(r);if(i)throw new Error("Canvas is already in use. Chart with ID '"+i.id+"' must be destroyed before the canvas with ID '"+i.canvas.id+"' can be reused.");const o=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||WC(r)),this.platform.updateConfig(s);const a=this.platform.acquireContext(r,o.aspectRatio),l=a&&a.canvas,c=l&&l.height,d=l&&l.width;if(this.id=U_(),this.ctx=a,this.canvas=l,this.width=d,this.height=c,this._options=o,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new aj,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=ok(f=>this.update(f),o.resizeDelay||0),this._dataChanges=[],al[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}_n.listen(this,"complete",$g),_n.listen(this,"progress",_j),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:e,maintainAspectRatio:n},width:s,height:r,_aspectRatio:i}=this;return ue(e)?n&&i?i:r?s/r:null:e}get data(){return this.config.data}set data(e){this.config.data=e}get options(){return this._options}set options(e){this.config.options=e}get registry(){return un}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():pg(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return ug(this.canvas,this.ctx),this}stop(){return _n.stop(this),this}resize(e,n){_n.running(this)?this._resizeBeforeDraw={width:e,height:n}:this._resize(e,n)}_resize(e,n){const s=this.options,r=this.canvas,i=s.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(r,e,n,i),a=s.devicePixelRatio||this.platform.getDevicePixelRatio(),l=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,pg(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),he(s.onResize,[this,o],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){const n=this.options.scales||{};ae(n,(s,r)=>{s.id=r})}buildOrUpdateScales(){const e=this.options,n=e.scales,s=this.scales,r=Object.keys(s).reduce((o,a)=>(o[a]=!1,o),{});let i=[];n&&(i=i.concat(Object.keys(n).map(o=>{const a=n[o],l=Id(o,a),c=l==="r",d=l==="x";return{options:a,dposition:c?"chartArea":d?"bottom":"left",dtype:c?"radialLinear":d?"category":"linear"}}))),ae(i,o=>{const a=o.options,l=a.id,c=Id(l,a),d=Z(a.type,o.dtype);(a.position===void 0||zg(a.position,c)!==zg(o.dposition))&&(a.position=o.dposition),r[l]=!0;let f=null;if(l in s&&s[l].type===d)f=s[l];else{const h=un.getScale(d);f=new h({id:l,type:d,ctx:this.ctx,chart:this}),s[f.id]=f}f.init(a,e)}),ae(r,(o,a)=>{o||delete s[a]}),ae(s,o=>{us.configure(this,o,o.options),us.addBox(this,o)})}_updateMetasets(){const e=this._metasets,n=this.data.datasets.length,s=e.length;if(e.sort((r,i)=>r.index-i.index),s>n){for(let r=n;r<s;++r)this._destroyDatasetMeta(r);e.splice(n,s-n)}this._sortedMetasets=e.slice(0).sort(Bg("order","index"))}_removeUnreferencedMetasets(){const{_metasets:e,data:{datasets:n}}=this;e.length>n.length&&delete this._stacks,e.forEach((s,r)=>{n.filter(i=>i===s._dataset).length===0&&this._destroyDatasetMeta(r)})}buildOrUpdateControllers(){const e=[],n=this.data.datasets;let s,r;for(this._removeUnreferencedMetasets(),s=0,r=n.length;s<r;s++){const i=n[s];let o=this.getDatasetMeta(s);const a=i.type||this.config.type;if(o.type&&o.type!==a&&(this._destroyDatasetMeta(s),o=this.getDatasetMeta(s)),o.type=a,o.indexAxis=i.indexAxis||Ad(a,this.options),o.order=i.order||0,o.index=s,o.label=""+i.label,o.visible=this.isDatasetVisible(s),o.controller)o.controller.updateIndex(s),o.controller.linkScales();else{const l=un.getController(a),{datasetElementType:c,dataElementType:d}=Ee.datasets[a];Object.assign(l,{dataElementType:un.getElement(d),datasetElementType:c&&un.getElement(c)}),o.controller=new l(this,s),e.push(o.controller)}}return this._updateMetasets(),e}_resetElements(){ae(this.data.datasets,(e,n)=>{this.getDatasetMeta(n).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(e){const n=this.config;n.update();const s=this._options=n.createResolver(n.chartOptionScopes(),this.getContext()),r=this._animationsDisabled=!s.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:e,cancelable:!0})===!1)return;const i=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let c=0,d=this.data.datasets.length;c<d;c++){const{controller:f}=this.getDatasetMeta(c),h=!r&&i.indexOf(f)===-1;f.buildOrUpdateElements(h),o=Math.max(+f.getMaxOverflow(),o)}o=this._minPadding=s.layout.autoPadding?o:0,this._updateLayout(o),r||ae(i,c=>{c.reset()}),this._updateDatasets(e),this.notifyPlugins("afterUpdate",{mode:e}),this._layers.sort(Bg("z","_idx"));const{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){ae(this.scales,e=>{us.removeBox(this,e)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const e=this.options,n=new Set(Object.keys(this._listeners)),s=new Set(e.events);(!eg(n,s)||!!this._responsiveListeners!==e.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:e}=this,n=this._getUniformDataChanges()||[];for(const{method:s,start:r,count:i}of n){const o=s==="_removeElements"?-i:i;kj(e,r,o)}}_getUniformDataChanges(){const e=this._dataChanges;if(!e||!e.length)return;this._dataChanges=[];const n=this.data.datasets.length,s=i=>new Set(e.filter(o=>o[0]===i).map((o,a)=>a+","+o.splice(1).join(","))),r=s(0);for(let i=1;i<n;i++)if(!eg(r,s(i)))return;return Array.from(r).map(i=>i.split(",")).map(i=>({method:i[1],start:+i[2],count:+i[3]}))}_updateLayout(e){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;us.update(this,this.width,this.height,e);const n=this.chartArea,s=n.width<=0||n.height<=0;this._layers=[],ae(this.boxes,r=>{s&&r.position==="chartArea"||(r.configure&&r.configure(),this._layers.push(...r._layers()))},this),this._layers.forEach((r,i)=>{r._idx=i}),this.notifyPlugins("afterLayout")}_updateDatasets(e){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:e,cancelable:!0})!==!1){for(let n=0,s=this.data.datasets.length;n<s;++n)this.getDatasetMeta(n).controller.configure();for(let n=0,s=this.data.datasets.length;n<s;++n)this._updateDataset(n,Cs(e)?e({datasetIndex:n}):e);this.notifyPlugins("afterDatasetsUpdate",{mode:e})}}_updateDataset(e,n){const s=this.getDatasetMeta(e),r={meta:s,index:e,mode:n,cancelable:!0};this.notifyPlugins("beforeDatasetUpdate",r)!==!1&&(s.controller._update(n),r.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",r))}render(){this.notifyPlugins("beforeRender",{cancelable:!0})!==!1&&(_n.has(this)?this.attached&&!_n.running(this)&&_n.start(this):(this.draw(),$g({chart:this})))}draw(){let e;if(this._resizeBeforeDraw){const{width:s,height:r}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(s,r)}if(this.clear(),this.width<=0||this.height<=0||this.notifyPlugins("beforeDraw",{cancelable:!0})===!1)return;const n=this._layers;for(e=0;e<n.length&&n[e].z<=0;++e)n[e].draw(this.chartArea);for(this._drawDatasets();e<n.length;++e)n[e].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(e){const n=this._sortedMetasets,s=[];let r,i;for(r=0,i=n.length;r<i;++r){const o=n[r];(!e||o.visible)&&s.push(o)}return s}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0})===!1)return;const e=this.getSortedVisibleDatasetMetas();for(let n=e.length-1;n>=0;--n)this._drawDataset(e[n]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(e){const n=this.ctx,s={meta:e,index:e.index,cancelable:!0},r=Vk(this,e);this.notifyPlugins("beforeDatasetDraw",s)!==!1&&(r&&Gf(n,r),e.controller.draw(),r&&Jf(n),s.cancelable=!1,this.notifyPlugins("afterDatasetDraw",s))}isPointInArea(e){return Oy(e,this.chartArea,this._minPadding)}getElementsAtEventForMode(e,n,s,r){const i=SC.modes[n];return typeof i=="function"?i(this,e,s,r):[]}getDatasetMeta(e){const n=this.data.datasets[e],s=this._metasets;let r=s.filter(i=>i&&i._dataset===n).pop();return r||(r={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:n&&n.order||0,index:e,_dataset:n,_parsed:[],_sorted:!1},s.push(r)),r}getContext(){return this.$context||(this.$context=wi(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(e){const n=this.data.datasets[e];if(!n)return!1;const s=this.getDatasetMeta(e);return typeof s.hidden=="boolean"?!s.hidden:!n.hidden}setDatasetVisibility(e,n){const s=this.getDatasetMeta(e);s.hidden=!n}toggleDataVisibility(e){this._hiddenIndices[e]=!this._hiddenIndices[e]}getDataVisibility(e){return!this._hiddenIndices[e]}_updateVisibility(e,n,s){const r=s?"show":"hide",i=this.getDatasetMeta(e),o=i.controller._resolveAnimations(void 0,r);Bo(n)?(i.data[n].hidden=!s,this.update()):(this.setDatasetVisibility(e,s),o.update(i,{visible:s}),this.update(a=>a.datasetIndex===e?r:void 0))}hide(e,n){this._updateVisibility(e,n,!1)}show(e,n){this._updateVisibility(e,n,!0)}_destroyDatasetMeta(e){const n=this._metasets[e];n&&n.controller&&n.controller._destroy(),delete this._metasets[e]}_stop(){let e,n;for(this.stop(),_n.remove(this),e=0,n=this.data.datasets.length;e<n;++e)this._destroyDatasetMeta(e)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:e,ctx:n}=this;this._stop(),this.config.clearCache(),e&&(this.unbindEvents(),ug(e,n),this.platform.releaseContext(n),this.canvas=null,this.ctx=null),delete al[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...e){return this.canvas.toDataURL(...e)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const e=this._listeners,n=this.platform,s=(i,o)=>{n.addEventListener(this,i,o),e[i]=o},r=(i,o,a)=>{i.offsetX=o,i.offsetY=a,this._eventHandler(i)};ae(this.options.events,i=>s(i,r))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const e=this._responsiveListeners,n=this.platform,s=(l,c)=>{n.addEventListener(this,l,c),e[l]=c},r=(l,c)=>{e[l]&&(n.removeEventListener(this,l,c),delete e[l])},i=(l,c)=>{this.canvas&&this.resize(l,c)};let o;const a=()=>{r("attach",a),this.attached=!0,this.resize(),s("resize",i),s("detach",o)};o=()=>{this.attached=!1,r("resize",i),this._stop(),this._resize(0,0),s("attach",a)},n.isAttached(this.canvas)?a():o()}unbindEvents(){ae(this._listeners,(e,n)=>{this.platform.removeEventListener(this,n,e)}),this._listeners={},ae(this._responsiveListeners,(e,n)=>{this.platform.removeEventListener(this,n,e)}),this._responsiveListeners=void 0}updateHoverStyle(e,n,s){const r=s?"set":"remove";let i,o,a,l;for(n==="dataset"&&(i=this.getDatasetMeta(e[0].datasetIndex),i.controller["_"+r+"DatasetHoverStyle"]()),a=0,l=e.length;a<l;++a){o=e[a];const c=o&&this.getDatasetMeta(o.datasetIndex).controller;c&&c[r+"HoverStyle"](o.element,o.datasetIndex,o.index)}}getActiveElements(){return this._active||[]}setActiveElements(e){const n=this._active||[],s=e.map(({datasetIndex:i,index:o})=>{const a=this.getDatasetMeta(i);if(!a)throw new Error("No dataset found at index "+i);return{datasetIndex:i,element:a.data[o],index:o}});!Fl(s,n)&&(this._active=s,this._lastEvent=null,this._updateHoverStyles(s,n))}notifyPlugins(e,n,s){return this._plugins.notify(this,e,n,s)}isPluginEnabled(e){return this._plugins._cache.filter(n=>n.plugin.id===e).length===1}_updateHoverStyles(e,n,s){const r=this.options.hover,i=(l,c)=>l.filter(d=>!c.some(f=>d.datasetIndex===f.datasetIndex&&d.index===f.index)),o=i(n,e),a=s?e:i(e,n);o.length&&this.updateHoverStyle(o,r.mode,!1),a.length&&r.mode&&this.updateHoverStyle(a,r.mode,!0)}_eventHandler(e,n){const s={event:e,replay:n,cancelable:!0,inChartArea:this.isPointInArea(e)},r=o=>(o.options.events||this.options.events).includes(e.native.type);if(this.notifyPlugins("beforeEvent",s,r)===!1)return;const i=this._handleEvent(e,n,s.inChartArea);return s.cancelable=!1,this.notifyPlugins("afterEvent",s,r),(i||s.changed)&&this.render(),this}_handleEvent(e,n,s){const{_active:r=[],options:i}=this,o=n,a=this._getActiveElements(e,r,s,o),l=Y_(e),c=Cj(e,this._lastEvent,s,l);s&&(this._lastEvent=null,he(i.onHover,[e,a,this],this),l&&he(i.onClick,[e,a,this],this));const d=!Fl(a,r);return(d||n)&&(this._active=a,this._updateHoverStyles(a,r,n)),this._lastEvent=c,d}_getActiveElements(e,n,s,r){if(e.type==="mouseout")return[];if(!s)return n;const i=this.options.hover;return this.getElementsAtEventForMode(e,i.mode,i,r)}},B(Hn,"defaults",Ee),B(Hn,"instances",al),B(Hn,"overrides",ur),B(Hn,"registry",un),B(Hn,"version",wj),B(Hn,"getChart",Ug),Hn);function Wg(){return ae(Sc.instances,t=>t._plugins.invalidate())}function jj(t,e,n){const{startAngle:s,x:r,y:i,outerRadius:o,innerRadius:a,options:l}=e,{borderWidth:c,borderJoinStyle:d}=l,f=Math.min(c/o,dn(s-n));if(t.beginPath(),t.arc(r,i,o-c/2,s+f/2,n-f/2),a>0){const h=Math.min(c/a,dn(s-n));t.arc(r,i,a+c/2,n-h/2,s+h/2,!0)}else{const h=Math.min(c/2,o*dn(s-n));if(d==="round")t.arc(r,i,h,n-ge/2,s+ge/2,!0);else if(d==="bevel"){const p=2*h*h,m=-p*Math.cos(n+ge/2)+r,g=-p*Math.sin(n+ge/2)+i,b=p*Math.cos(s+ge/2)+r,y=p*Math.sin(s+ge/2)+i;t.lineTo(m,g),t.lineTo(b,y)}}t.closePath(),t.moveTo(0,0),t.rect(0,0,t.canvas.width,t.canvas.height),t.clip("evenodd")}function Nj(t,e,n){const{startAngle:s,pixelMargin:r,x:i,y:o,outerRadius:a,innerRadius:l}=e;let c=r/a;t.beginPath(),t.arc(i,o,a,s-c,n+c),l>r?(c=r/l,t.arc(i,o,l,n+c,s-c,!0)):t.arc(i,o,r,n+Le,s-Le),t.closePath(),t.clip()}function Ej(t){return Zf(t,["outerStart","outerEnd","innerStart","innerEnd"])}function Mj(t,e,n,s){const r=Ej(t.options.borderRadius),i=(n-e)/2,o=Math.min(i,s*e/2),a=l=>{const c=(n-Math.min(i,l))*s/2;return ct(l,0,Math.min(i,c))};return{outerStart:a(r.outerStart),outerEnd:a(r.outerEnd),innerStart:ct(r.innerStart,0,o),innerEnd:ct(r.innerEnd,0,o)}}function Sr(t,e,n,s){return{x:n+t*Math.cos(e),y:s+t*Math.sin(e)}}function Pj(t,e,n,s){const{x:r,y:i,startAngle:o,pixelMargin:a,innerRadius:l}=e,c=Math.max(e.outerRadius+s+n-a,0),d=l>0?l+s+n+a:0;t.beginPath(),t.arc(r,i,c,o,o+ve),d>0&&(t.moveTo(r+Math.cos(o)*d,i+Math.sin(o)*d),t.arc(r,i,d,o+ve,o,!0)),t.closePath()}function Kl(t,e,n,s,r,i){const{x:o,y:a,startAngle:l,pixelMargin:c,innerRadius:d}=e,{spacingMode:f="angular"}=e.options,h=r-l;if(i&&e.options.selfJoin&&Math.abs(h)>=ve-1e-4){Pj(t,e,n,s);return}const p=Math.max(e.outerRadius+s+n-c,0);let m=d>0?d+s+n+c:0,g=0,b=0;const y=p>0?Math.max(.001,h*p-n/ge)/p:.001,x=(h-y)/2;if(s){const I=d>0?d-s:0,V=p>0?p-s:0,F=(I+V)/2,ce=(()=>{const gt=F!==0?h*F/(F+s):h;return(h-gt)/2})(),$=F>0?Math.asin(Math.min(1,s/F)):0,ke=Math.max(0,y/2-.001),J=Math.sin(ke);if(f==="parallel"){if(m===0&&J>0){const zt=s/J,ie=Math.max(0,p-.001);m=Math.min(zt,ie)}const gt=Math.min(p>0?p*J:Number.POSITIVE_INFINITY,m>0?m*J:Number.POSITIVE_INFINITY),Ft=Math.min(s,gt);g=p>0?Math.asin(Math.min(1,Ft/p)):Math.min(ke,$),b=m>0?Math.asin(Math.min(1,Ft/m)):g}else f==="proportional"?(g=Math.min(ke,ce),b=Math.min(ke,ce)):(g=Math.min(ke,$),b=Math.min(ke,$))}const v=l+x+g,_=r-x-g,w=l+x+b,k=r-x-b,C=Math.min(_-v,k-w),{outerStart:j,outerEnd:M,innerStart:E,innerEnd:P}=Mj(e,m,p,C),A=p-j,Q=p-M,ne=v+j/A,Y=_-M/Q,oe=m+E,G=m+P,O=w+E/oe,L=k-P/G;if(t.beginPath(),i){const I=(ne+Y)/2;if(t.arc(o,a,p,ne,I),t.arc(o,a,p,I,Y),M>0){const $=Sr(Q,Y,o,a);t.arc($.x,$.y,M,Y,_+Le)}const V=Sr(G,k,o,a);if(t.lineTo(V.x,V.y),P>0){const $=Sr(G,L,o,a);t.arc($.x,$.y,P,k+Le,L+Math.PI)}const F=(k-P/m+(w+E/m))/2;if(t.arc(o,a,m,k-P/m,F,!0),t.arc(o,a,m,F,w+E/m,!0),E>0){const $=Sr(oe,O,o,a);t.arc($.x,$.y,E,O+Math.PI,w-Le)}const ce=Sr(A,v,o,a);if(t.lineTo(ce.x,ce.y),j>0){const $=Sr(A,ne,o,a);t.arc($.x,$.y,j,v-Le,ne)}}else{t.moveTo(o,a);const I=Math.cos(ne)*p+o,V=Math.sin(ne)*p+a;t.lineTo(I,V);const F=Math.cos(Y)*p+o,ce=Math.sin(Y)*p+a;t.lineTo(F,ce)}t.closePath()}function Rj(t,e,n,s,r){const{fullCircles:i,startAngle:o,circumference:a}=e;let l=e.endAngle;if(i){Kl(t,e,n,s,l,r);for(let c=0;c<i;++c)t.fill();isNaN(a)||(l=o+(a%ve||ve))}return Kl(t,e,n,s,l,r),t.fill(),l}function Oj(t,e,n,s,r){const{fullCircles:i,startAngle:o,circumference:a,options:l}=e,{borderWidth:c,borderJoinStyle:d,borderDash:f,borderDashOffset:h,borderRadius:p}=l,m=l.borderAlign==="inner";if(!c)return;t.setLineDash(f||[]),t.lineDashOffset=h,m?(t.lineWidth=c*2,t.lineJoin=d||"round"):(t.lineWidth=c,t.lineJoin=d||"bevel");let g=e.endAngle;const b=Math.abs(g-o)>=ve-1e-4;if(i){Kl(t,e,n,s,g,r);for(let x=0;x<i;++x)t.stroke();isNaN(a)||(g=o+(a%ve||ve))}m&&Nj(t,e,g),!(b&&e.innerRadius>0)&&l.selfJoin&&g-o>=ge&&p===0&&d!=="miter"&&jj(t,e,g),i||(Kl(t,e,n,s,g,r),t.stroke())}class eo extends js{constructor(n){super();B(this,"circumference");B(this,"endAngle");B(this,"fullCircles");B(this,"innerRadius");B(this,"outerRadius");B(this,"pixelMargin");B(this,"startAngle");B(this,"circular");this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,this.circular=!1,n&&Object.assign(this,n)}inRange(n,s,r){const i=this.getProps(["x","y"],r),{angle:o,distance:a}=_y(i,{x:n,y:s}),{startAngle:l,endAngle:c,innerRadius:d,outerRadius:f,circumference:h}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],r),p=(this.options.spacing+this.options.borderWidth)/2,m=Z(h,c-l),g=Ul(o,l,c)&&l!==c,b=m>=ve||g,y=Hs(a,d+p,f+p);return b&&y}getCenterPoint(n){const{x:s,y:r,startAngle:i,endAngle:o,innerRadius:a,outerRadius:l}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],n),{offset:c,spacing:d}=this.options,f=(i+o)/2,h=(a+l+d+c)/2;return{x:s+Math.cos(f)*h,y:r+Math.sin(f)*h}}tooltipPosition(n){return this.getCenterPoint(n)}draw(n){const{options:s,circumference:r}=this,i=(s.offset||0)/4,o=(s.spacing||0)/2,a=s.circular;if(this.pixelMargin=s.borderAlign==="inner"?.33:0,this.fullCircles=r>ve?Math.floor(r/ve):0,r===0||this.innerRadius<0||this.outerRadius<0)return;n.save();const l=(this.startAngle+this.endAngle)/2;n.translate(Math.cos(l)*i,Math.sin(l)*i);const c=1-Math.sin(Math.min(ge,r||0)),d=i*c;n.fillStyle=s.backgroundColor,n.strokeStyle=s.borderColor,Rj(n,this,d,o,a),Oj(n,this,d,o,a),n.restore()}}B(eo,"id","arc"),B(eo,"defaults",{borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,spacingMode:"angular",angle:void 0,circular:!0,selfJoin:!1}),B(eo,"defaultRoutes",{backgroundColor:"backgroundColor"}),B(eo,"descriptors",{_scriptable:!0,_indexable:n=>n!=="borderDash"});function Jy(t,e){const{x:n,y:s,base:r,width:i,height:o}=t.getProps(["x","y","base","width","height"],e);let a,l,c,d,f;return t.horizontal?(f=o/2,a=Math.min(n,r),l=Math.max(n,r),c=s-f,d=s+f):(f=i/2,a=n-f,l=n+f,c=Math.min(s,r),d=Math.max(s,r)),{left:a,top:c,right:l,bottom:d}}function ds(t,e,n,s){return t?0:ct(e,n,s)}function Tj(t,e,n){const s=t.options.borderWidth,r=t.borderSkipped,i=Ty(s);return{t:ds(r.top,i.top,0,n),r:ds(r.right,i.right,0,e),b:ds(r.bottom,i.bottom,0,n),l:ds(r.left,i.left,0,e)}}function Dj(t,e,n){const{enableBorderRadius:s}=t.getProps(["enableBorderRadius"]),r=t.options.borderRadius,i=Wr(r),o=Math.min(e,n),a=t.borderSkipped,l=s||te(r);return{topLeft:ds(!l||a.top||a.left,i.topLeft,0,o),topRight:ds(!l||a.top||a.right,i.topRight,0,o),bottomLeft:ds(!l||a.bottom||a.left,i.bottomLeft,0,o),bottomRight:ds(!l||a.bottom||a.right,i.bottomRight,0,o)}}function Lj(t){const e=Jy(t),n=e.right-e.left,s=e.bottom-e.top,r=Tj(t,n/2,s/2),i=Dj(t,n/2,s/2);return{outer:{x:e.left,y:e.top,w:n,h:s,radius:i},inner:{x:e.left+r.l,y:e.top+r.t,w:n-r.l-r.r,h:s-r.t-r.b,radius:{topLeft:Math.max(0,i.topLeft-Math.max(r.t,r.l)),topRight:Math.max(0,i.topRight-Math.max(r.t,r.r)),bottomLeft:Math.max(0,i.bottomLeft-Math.max(r.b,r.l)),bottomRight:Math.max(0,i.bottomRight-Math.max(r.b,r.r))}}}}function xu(t,e,n,s){const r=e===null,i=n===null,a=t&&!(r&&i)&&Jy(t,s);return a&&(r||Hs(e,a.left,a.right))&&(i||Hs(n,a.top,a.bottom))}function Aj(t){return t.topLeft||t.topRight||t.bottomLeft||t.bottomRight}function Ij(t,e){t.rect(e.x,e.y,e.w,e.h)}function yu(t,e,n={}){const s=t.x!==n.x?-e:0,r=t.y!==n.y?-e:0,i=(t.x+t.w!==n.x+n.w?e:0)-s,o=(t.y+t.h!==n.y+n.h?e:0)-r;return{x:t.x+s,y:t.y+r,w:t.w+i,h:t.h+o,radius:t.radius}}class ll extends js{constructor(e){super(),this.options=void 0,this.horizontal=void 0,this.base=void 0,this.width=void 0,this.height=void 0,this.inflateAmount=void 0,e&&Object.assign(this,e)}draw(e){const{inflateAmount:n,options:{borderColor:s,backgroundColor:r}}=this,{inner:i,outer:o}=Lj(this),a=Aj(o.radius)?Hl:Ij;e.save(),(o.w!==i.w||o.h!==i.h)&&(e.beginPath(),a(e,yu(o,n,i)),e.clip(),a(e,yu(i,-n,o)),e.fillStyle=s,e.fill("evenodd")),e.beginPath(),a(e,yu(i,n)),e.fillStyle=r,e.fill(),e.restore()}inRange(e,n,s){return xu(this,e,n,s)}inXRange(e,n){return xu(this,e,null,n)}inYRange(e,n){return xu(this,null,e,n)}getCenterPoint(e){const{x:n,y:s,base:r,horizontal:i}=this.getProps(["x","y","base","horizontal"],e);return{x:i?(n+r)/2:n,y:i?s:(s+r)/2}}getRange(e){return e==="x"?this.width/2:this.height/2}}B(ll,"id","bar"),B(ll,"defaults",{borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0}),B(ll,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});const Hg=(t,e)=>{let{boxHeight:n=e,boxWidth:s=e}=t;return t.usePointStyle&&(n=Math.min(n,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:n,itemHeight:Math.max(e,n)}},Fj=(t,e)=>t!==null&&e!==null&&t.datasetIndex===e.datasetIndex&&t.index===e.index;class Vg extends js{constructor(e){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=e.chart,this.options=e.options,this.ctx=e.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(e,n,s){this.maxWidth=e,this.maxHeight=n,this._margins=s,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const e=this.options.labels||{};let n=he(e.generateLabels,[this.chart],this)||[];e.filter&&(n=n.filter(s=>e.filter(s,this.chart.data))),e.sort&&(n=n.sort((s,r)=>e.sort(s,r,this.chart.data))),this.options.reverse&&n.reverse(),this.legendItems=n}fit(){const{options:e,ctx:n}=this;if(!e.display){this.width=this.height=0;return}const s=e.labels,r=ut(s.font),i=r.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:l}=Hg(s,i);let c,d;n.font=r.string,this.isHorizontal()?(c=this.maxWidth,d=this._fitRows(o,i,a,l)+10):(d=this.maxHeight,c=this._fitCols(o,r,a,l)+10),this.width=Math.min(c,e.maxWidth||this.maxWidth),this.height=Math.min(d,e.maxHeight||this.maxHeight)}_fitRows(e,n,s,r){const{ctx:i,maxWidth:o,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],c=this.lineWidths=[0],d=r+a;let f=e;i.textAlign="left",i.textBaseline="middle";let h=-1,p=-d;return this.legendItems.forEach((m,g)=>{const b=s+n/2+i.measureText(m.text).width;(g===0||c[c.length-1]+b+2*a>o)&&(f+=d,c[c.length-(g>0?0:1)]=0,p+=d,h++),l[g]={left:0,top:p,row:h,width:b,height:r},c[c.length-1]+=b+a}),f}_fitCols(e,n,s,r){const{ctx:i,maxHeight:o,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],c=this.columnSizes=[],d=o-e;let f=a,h=0,p=0,m=0,g=0;return this.legendItems.forEach((b,y)=>{const{itemWidth:x,itemHeight:v}=zj(s,n,i,b,r);y>0&&p+v+2*a>d&&(f+=h+a,c.push({width:h,height:p}),m+=h+a,g++,h=p=0),l[y]={left:m,top:p,col:g,width:x,height:v},h=Math.max(h,x),p+=v+a}),f+=h,c.push({width:h,height:p}),f}adjustHitBoxes(){if(!this.options.display)return;const e=this._computeTitleHeight(),{legendHitBoxes:n,options:{align:s,labels:{padding:r},rtl:i}}=this,o=Hr(i,this.left,this.width);if(this.isHorizontal()){let a=0,l=bt(s,this.left+r,this.right-this.lineWidths[a]);for(const c of n)a!==c.row&&(a=c.row,l=bt(s,this.left+r,this.right-this.lineWidths[a])),c.top+=this.top+e+r,c.left=o.leftForLtr(o.x(l),c.width),l+=c.width+r}else{let a=0,l=bt(s,this.top+e+r,this.bottom-this.columnSizes[a].height);for(const c of n)c.col!==a&&(a=c.col,l=bt(s,this.top+e+r,this.bottom-this.columnSizes[a].height)),c.top=l,c.left+=this.left+r,c.left=o.leftForLtr(o.x(c.left),c.width),l+=c.height+r}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){const e=this.ctx;Gf(e,this),this._draw(),Jf(e)}}_draw(){const{options:e,columnSizes:n,lineWidths:s,ctx:r}=this,{align:i,labels:o}=e,a=Ee.color,l=Hr(e.rtl,this.left,this.width),c=ut(o.font),{padding:d}=o,f=c.size,h=f/2;let p;this.drawTitle(),r.textAlign=l.textAlign("left"),r.textBaseline="middle",r.lineWidth=.5,r.font=c.string;const{boxWidth:m,boxHeight:g,itemHeight:b}=Hg(o,f),y=function(k,C,j){if(isNaN(m)||m<=0||isNaN(g)||g<0)return;r.save();const M=Z(j.lineWidth,1);if(r.fillStyle=Z(j.fillStyle,a),r.lineCap=Z(j.lineCap,"butt"),r.lineDashOffset=Z(j.lineDashOffset,0),r.lineJoin=Z(j.lineJoin,"miter"),r.lineWidth=M,r.strokeStyle=Z(j.strokeStyle,a),r.setLineDash(Z(j.lineDash,[])),o.usePointStyle){const E={radius:g*Math.SQRT2/2,pointStyle:j.pointStyle,rotation:j.rotation,borderWidth:M},P=l.xPlus(k,m/2),A=C+h;Ry(r,E,P,A,o.pointStyleWidth&&m)}else{const E=C+Math.max((f-g)/2,0),P=l.leftForLtr(k,m),A=Wr(j.borderRadius);r.beginPath(),Object.values(A).some(Q=>Q!==0)?Hl(r,{x:P,y:E,w:m,h:g,radius:A}):r.rect(P,E,m,g),r.fill(),M!==0&&r.stroke()}r.restore()},x=function(k,C,j){Wl(r,j.text,k,C+b/2,c,{strikethrough:j.hidden,textAlign:l.textAlign(j.textAlign)})},v=this.isHorizontal(),_=this._computeTitleHeight();v?p={x:bt(i,this.left+d,this.right-s[0]),y:this.top+d+_,line:0}:p={x:this.left+d,y:bt(i,this.top+_+d,this.bottom-n[0].height),line:0},Fy(this.ctx,e.textDirection);const w=b+d;this.legendItems.forEach((k,C)=>{r.strokeStyle=k.fontColor,r.fillStyle=k.fontColor;const j=r.measureText(k.text).width,M=l.textAlign(k.textAlign||(k.textAlign=o.textAlign)),E=m+h+j;let P=p.x,A=p.y;l.setWidth(this.width),v?C>0&&P+E+d>this.right&&(A=p.y+=w,p.line++,P=p.x=bt(i,this.left+d,this.right-s[p.line])):C>0&&A+w>this.bottom&&(P=p.x=P+n[p.line].width+d,p.line++,A=p.y=bt(i,this.top+_+d,this.bottom-n[p.line].height));const Q=l.x(P);if(y(Q,A,k),P=ak(M,P+m+h,v?P+E:this.right,e.rtl),x(l.x(P),A,k),v)p.x+=E+d;else if(typeof k.text!="string"){const ne=c.lineHeight;p.y+=Zy(k,ne)+d}else p.y+=w}),zy(this.ctx,e.textDirection)}drawTitle(){const e=this.options,n=e.title,s=ut(n.font),r=Gt(n.padding);if(!n.display)return;const i=Hr(e.rtl,this.left,this.width),o=this.ctx,a=n.position,l=s.size/2,c=r.top+l;let d,f=this.left,h=this.width;if(this.isHorizontal())h=Math.max(...this.lineWidths),d=this.top+c,f=bt(e.align,f,this.right-h);else{const m=this.columnSizes.reduce((g,b)=>Math.max(g,b.height),0);d=c+bt(e.align,this.top,this.bottom-m-e.labels.padding-this._computeTitleHeight())}const p=bt(a,f,f+h);o.textAlign=i.textAlign(Ey(a)),o.textBaseline="middle",o.strokeStyle=n.color,o.fillStyle=n.color,o.font=s.string,Wl(o,n.text,p,d,s)}_computeTitleHeight(){const e=this.options.title,n=ut(e.font),s=Gt(e.padding);return e.display?n.lineHeight+s.height:0}_getLegendItemAt(e,n){let s,r,i;if(Hs(e,this.left,this.right)&&Hs(n,this.top,this.bottom)){for(i=this.legendHitBoxes,s=0;s<i.length;++s)if(r=i[s],Hs(e,r.left,r.left+r.width)&&Hs(n,r.top,r.top+r.height))return this.legendItems[s]}return null}handleEvent(e){const n=this.options;if(!Uj(e.type,n))return;const s=this._getLegendItemAt(e.x,e.y);if(e.type==="mousemove"||e.type==="mouseout"){const r=this._hoveredItem,i=Fj(r,s);r&&!i&&he(n.onLeave,[e,r,this],this),this._hoveredItem=s,s&&!i&&he(n.onHover,[e,s,this],this)}else s&&he(n.onClick,[e,s,this],this)}}function zj(t,e,n,s,r){const i=Bj(s,t,e,n),o=$j(r,s,e.lineHeight);return{itemWidth:i,itemHeight:o}}function Bj(t,e,n,s){let r=t.text;return r&&typeof r!="string"&&(r=r.reduce((i,o)=>i.length>o.length?i:o)),e+n.size/2+s.measureText(r).width}function $j(t,e,n){let s=t;return typeof e.text!="string"&&(s=Zy(e,n)),s}function Zy(t,e){const n=t.text?t.text.length:0;return e*n}function Uj(t,e){return!!((t==="mousemove"||t==="mouseout")&&(e.onHover||e.onLeave)||e.onClick&&(t==="click"||t==="mouseup"))}var Wj={id:"legend",_element:Vg,start(t,e,n){const s=t.legend=new Vg({ctx:t.ctx,options:n,chart:t});us.configure(t,s,n),us.addBox(t,s)},stop(t){us.removeBox(t,t.legend),delete t.legend},beforeUpdate(t,e,n){const s=t.legend;us.configure(t,s,n),s.options=n},afterUpdate(t){const e=t.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(t,e){e.replay||t.legend.handleEvent(e.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(t,e,n){const s=e.datasetIndex,r=n.chart;r.isDatasetVisible(s)?(r.hide(s),e.hidden=!0):(r.show(s),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:t=>t.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:n,pointStyle:s,textAlign:r,color:i,useBorderRadius:o,borderRadius:a}}=t.legend.options;return t._getSortedDatasetMetas().map(l=>{const c=l.controller.getStyle(n?0:void 0),d=Gt(c.borderWidth);return{text:e[l.index].label,fillStyle:c.backgroundColor,fontColor:i,hidden:!l.visible,lineCap:c.borderCapStyle,lineDash:c.borderDash,lineDashOffset:c.borderDashOffset,lineJoin:c.borderJoinStyle,lineWidth:(d.width+d.height)/4,strokeStyle:c.borderColor,pointStyle:s||c.pointStyle,rotation:c.rotation,textAlign:r||c.textAlign,borderRadius:o&&(a||c.borderRadius),datasetIndex:l.index}},this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};const to={average(t){if(!t.length)return!1;let e,n,s=new Set,r=0,i=0;for(e=0,n=t.length;e<n;++e){const a=t[e].element;if(a&&a.hasValue()){const l=a.tooltipPosition();s.add(l.x),r+=l.y,++i}}return i===0||s.size===0?!1:{x:[...s].reduce((a,l)=>a+l)/s.size,y:r/i}},nearest(t,e){if(!t.length)return!1;let n=e.x,s=e.y,r=Number.POSITIVE_INFINITY,i,o,a;for(i=0,o=t.length;i<o;++i){const l=t[i].element;if(l&&l.hasValue()){const c=l.getCenterPoint(),d=tk(e,c);d<r&&(r=d,a=l)}}if(a){const l=a.tooltipPosition();n=l.x,s=l.y}return{x:n,y:s}}};function ln(t,e){return e&&(Fe(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function kn(t){return(typeof t=="string"||t instanceof String)&&t.indexOf(`
83
83
  `)>-1?t.split(`
84
- `):t}function Hj(t,e){const{element:n,datasetIndex:s,index:r}=e,i=t.getDatasetMeta(s).controller,{label:o,value:a}=i.getLabelAndValue(r);return{chart:t,label:o,parsed:i.getParsed(r),raw:t.data.datasets[s].data[r],formattedValue:a,dataset:i.getDataset(),dataIndex:r,datasetIndex:s,element:n}}function Qg(t,e){const n=t.chart.ctx,{body:s,footer:r,title:i}=t,{boxWidth:o,boxHeight:a}=e,l=ut(e.bodyFont),c=ut(e.titleFont),d=ut(e.footerFont),f=i.length,h=r.length,p=s.length,m=Gt(e.padding);let g=m.height,b=0,y=s.reduce((_,w)=>_+w.before.length+w.lines.length+w.after.length,0);if(y+=t.beforeBody.length+t.afterBody.length,f&&(g+=f*c.lineHeight+(f-1)*e.titleSpacing+e.titleMarginBottom),y){const _=e.displayColors?Math.max(a,l.lineHeight):l.lineHeight;g+=p*_+(y-p)*l.lineHeight+(y-1)*e.bodySpacing}h&&(g+=e.footerMarginTop+h*d.lineHeight+(h-1)*e.footerSpacing);let x=0;const v=function(_){b=Math.max(b,n.measureText(_).width+x)};return n.save(),n.font=c.string,ae(t.title,v),n.font=l.string,ae(t.beforeBody.concat(t.afterBody),v),x=e.displayColors?o+2+e.boxPadding:0,ae(s,_=>{ae(_.before,v),ae(_.lines,v),ae(_.after,v)}),x=0,n.font=d.string,ae(t.footer,v),n.restore(),b+=m.width,{width:b,height:g}}function Vj(t,e){const{y:n,height:s}=e;return n<s/2?"top":n>t.height-s/2?"bottom":"center"}function Qj(t,e,n,s){const{x:r,width:i}=s,o=n.caretSize+n.caretPadding;if(t==="left"&&r+i+o>e.width||t==="right"&&r-i-o<0)return!0}function Kj(t,e,n,s){const{x:r,width:i}=n,{width:o,chartArea:{left:a,right:l}}=t;let c="center";return s==="center"?c=r<=(a+l)/2?"left":"right":r<=i/2?c="left":r>=o-i/2&&(c="right"),Qj(c,t,e,n)&&(c="center"),c}function Kg(t,e,n){const s=n.yAlign||e.yAlign||Vj(t,n);return{xAlign:n.xAlign||e.xAlign||Kj(t,e,n,s),yAlign:s}}function Yj(t,e){let{x:n,width:s}=t;return e==="right"?n-=s:e==="center"&&(n-=s/2),n}function Xj(t,e,n){let{y:s,height:r}=t;return e==="top"?s+=n:e==="bottom"?s-=r+n:s-=r/2,s}function Yg(t,e,n,s){const{caretSize:r,caretPadding:i,cornerRadius:o}=t,{xAlign:a,yAlign:l}=n,c=r+i,{topLeft:d,topRight:f,bottomLeft:h,bottomRight:p}=Wr(o);let m=Yj(e,a);const g=Xj(e,l,c);return l==="center"?a==="left"?m+=c:a==="right"&&(m-=c):a==="left"?m-=Math.max(d,h)+r:a==="right"&&(m+=Math.max(f,p)+r),{x:ct(m,0,s.width-e.width),y:ct(g,0,s.height-e.height)}}function $a(t,e,n){const s=Gt(n.padding);return e==="center"?t.x+t.width/2:e==="right"?t.x+t.width-s.right:t.x+s.left}function Xg(t){return ln([],kn(t))}function qj(t,e,n){return wi(t,{tooltip:e,tooltipItems:n,type:"tooltip"})}function qg(t,e){const n=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return n?t.override(n):t}const ev={beforeTitle:wn,title(t){if(t.length>0){const e=t[0],n=e.chart.data.labels,s=n?n.length:0;if(this&&this.options&&this.options.mode==="dataset")return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex<s)return n[e.dataIndex]}return""},afterTitle:wn,beforeBody:wn,beforeLabel:wn,label(t){if(this&&this.options&&this.options.mode==="dataset")return t.label+": "+t.formattedValue||t.formattedValue;let e=t.dataset.label||"";e&&(e+=": ");const n=t.formattedValue;return ue(n)||(e+=n),e},labelColor(t){const n=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:n.borderColor,backgroundColor:n.backgroundColor,borderWidth:n.borderWidth,borderDash:n.borderDash,borderDashOffset:n.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const n=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:n.pointStyle,rotation:n.rotation}},afterLabel:wn,afterBody:wn,beforeFooter:wn,footer:wn,afterFooter:wn};function rt(t,e,n,s){const r=t[e].call(n,s);return typeof r>"u"?ev[e].call(n,s):r}class Fd extends js{constructor(e){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=e.chart,this.options=e.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(e){this.options=e,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const e=this._cachedAnimations;if(e)return e;const n=this.chart,s=this.options.setContext(this.getContext()),r=s.enabled&&n.options.animation&&s.animations,i=new By(this.chart,r);return r._cacheable&&(this._cachedAnimations=Object.freeze(i)),i}getContext(){return this.$context||(this.$context=qj(this.chart.getContext(),this,this._tooltipItems))}getTitle(e,n){const{callbacks:s}=n,r=rt(s,"beforeTitle",this,e),i=rt(s,"title",this,e),o=rt(s,"afterTitle",this,e);let a=[];return a=ln(a,kn(r)),a=ln(a,kn(i)),a=ln(a,kn(o)),a}getBeforeBody(e,n){return Xg(rt(n.callbacks,"beforeBody",this,e))}getBody(e,n){const{callbacks:s}=n,r=[];return ae(e,i=>{const o={before:[],lines:[],after:[]},a=qg(s,i);ln(o.before,kn(rt(a,"beforeLabel",this,i))),ln(o.lines,rt(a,"label",this,i)),ln(o.after,kn(rt(a,"afterLabel",this,i))),r.push(o)}),r}getAfterBody(e,n){return Xg(rt(n.callbacks,"afterBody",this,e))}getFooter(e,n){const{callbacks:s}=n,r=rt(s,"beforeFooter",this,e),i=rt(s,"footer",this,e),o=rt(s,"afterFooter",this,e);let a=[];return a=ln(a,kn(r)),a=ln(a,kn(i)),a=ln(a,kn(o)),a}_createItems(e){const n=this._active,s=this.chart.data,r=[],i=[],o=[];let a=[],l,c;for(l=0,c=n.length;l<c;++l)a.push(Hj(this.chart,n[l]));return e.filter&&(a=a.filter((d,f,h)=>e.filter(d,f,h,s))),e.itemSort&&(a=a.sort((d,f)=>e.itemSort(d,f,s))),ae(a,d=>{const f=qg(e.callbacks,d);r.push(rt(f,"labelColor",this,d)),i.push(rt(f,"labelPointStyle",this,d)),o.push(rt(f,"labelTextColor",this,d))}),this.labelColors=r,this.labelPointStyles=i,this.labelTextColors=o,this.dataPoints=a,a}update(e,n){const s=this.options.setContext(this.getContext()),r=this._active;let i,o=[];if(!r.length)this.opacity!==0&&(i={opacity:0});else{const a=to[s.position].call(this,r,this._eventPosition);o=this._createItems(s),this.title=this.getTitle(o,s),this.beforeBody=this.getBeforeBody(o,s),this.body=this.getBody(o,s),this.afterBody=this.getAfterBody(o,s),this.footer=this.getFooter(o,s);const l=this._size=Qg(this,s),c=Object.assign({},a,l),d=Kg(this.chart,s,c),f=Yg(s,c,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,i={opacity:1,x:f.x,y:f.y,width:l.width,height:l.height,caretX:a.x,caretY:a.y}}this._tooltipItems=o,this.$context=void 0,i&&this._resolveAnimations().update(this,i),e&&s.external&&s.external.call(this,{chart:this.chart,tooltip:this,replay:n})}drawCaret(e,n,s,r){const i=this.getCaretPosition(e,s,r);n.lineTo(i.x1,i.y1),n.lineTo(i.x2,i.y2),n.lineTo(i.x3,i.y3)}getCaretPosition(e,n,s){const{xAlign:r,yAlign:i}=this,{caretSize:o,cornerRadius:a}=s,{topLeft:l,topRight:c,bottomLeft:d,bottomRight:f}=Wr(a),{x:h,y:p}=e,{width:m,height:g}=n;let b,y,x,v,_,w;return i==="center"?(_=p+g/2,r==="left"?(b=h,y=b-o,v=_+o,w=_-o):(b=h+m,y=b+o,v=_-o,w=_+o),x=b):(r==="left"?y=h+Math.max(l,d)+o:r==="right"?y=h+m-Math.max(c,f)-o:y=this.caretX,i==="top"?(v=p,_=v-o,b=y-o,x=y+o):(v=p+g,_=v+o,b=y+o,x=y-o),w=v),{x1:b,x2:y,x3:x,y1:v,y2:_,y3:w}}drawTitle(e,n,s){const r=this.title,i=r.length;let o,a,l;if(i){const c=Hr(s.rtl,this.x,this.width);for(e.x=$a(this,s.titleAlign,s),n.textAlign=c.textAlign(s.titleAlign),n.textBaseline="middle",o=ut(s.titleFont),a=s.titleSpacing,n.fillStyle=s.titleColor,n.font=o.string,l=0;l<i;++l)n.fillText(r[l],c.x(e.x),e.y+o.lineHeight/2),e.y+=o.lineHeight+a,l+1===i&&(e.y+=s.titleMarginBottom-a)}}_drawColorBox(e,n,s,r,i){const o=this.labelColors[s],a=this.labelPointStyles[s],{boxHeight:l,boxWidth:c}=i,d=ut(i.bodyFont),f=$a(this,"left",i),h=r.x(f),p=l<d.lineHeight?(d.lineHeight-l)/2:0,m=n.y+p;if(i.usePointStyle){const g={radius:Math.min(c,l)/2,pointStyle:a.pointStyle,rotation:a.rotation,borderWidth:1},b=r.leftForLtr(h,c)+c/2,y=m+l/2;e.strokeStyle=i.multiKeyBackground,e.fillStyle=i.multiKeyBackground,dg(e,g,b,y),e.strokeStyle=o.borderColor,e.fillStyle=o.backgroundColor,dg(e,g,b,y)}else{e.lineWidth=te(o.borderWidth)?Math.max(...Object.values(o.borderWidth)):o.borderWidth||1,e.strokeStyle=o.borderColor,e.setLineDash(o.borderDash||[]),e.lineDashOffset=o.borderDashOffset||0;const g=r.leftForLtr(h,c),b=r.leftForLtr(r.xPlus(h,1),c-2),y=Wr(o.borderRadius);Object.values(y).some(x=>x!==0)?(e.beginPath(),e.fillStyle=i.multiKeyBackground,Hl(e,{x:g,y:m,w:c,h:l,radius:y}),e.fill(),e.stroke(),e.fillStyle=o.backgroundColor,e.beginPath(),Hl(e,{x:b,y:m+1,w:c-2,h:l-2,radius:y}),e.fill()):(e.fillStyle=i.multiKeyBackground,e.fillRect(g,m,c,l),e.strokeRect(g,m,c,l),e.fillStyle=o.backgroundColor,e.fillRect(b,m+1,c-2,l-2))}e.fillStyle=this.labelTextColors[s]}drawBody(e,n,s){const{body:r}=this,{bodySpacing:i,bodyAlign:o,displayColors:a,boxHeight:l,boxWidth:c,boxPadding:d}=s,f=ut(s.bodyFont);let h=f.lineHeight,p=0;const m=Hr(s.rtl,this.x,this.width),g=function(j){n.fillText(j,m.x(e.x+p),e.y+h/2),e.y+=h+i},b=m.textAlign(o);let y,x,v,_,w,k,C;for(n.textAlign=o,n.textBaseline="middle",n.font=f.string,e.x=$a(this,b,s),n.fillStyle=s.bodyColor,ae(this.beforeBody,g),p=a&&b!=="right"?o==="center"?c/2+d:c+2+d:0,_=0,k=r.length;_<k;++_){for(y=r[_],x=this.labelTextColors[_],n.fillStyle=x,ae(y.before,g),v=y.lines,a&&v.length&&(this._drawColorBox(n,e,_,m,s),h=Math.max(f.lineHeight,l)),w=0,C=v.length;w<C;++w)g(v[w]),h=f.lineHeight;ae(y.after,g)}p=0,h=f.lineHeight,ae(this.afterBody,g),e.y-=i}drawFooter(e,n,s){const r=this.footer,i=r.length;let o,a;if(i){const l=Hr(s.rtl,this.x,this.width);for(e.x=$a(this,s.footerAlign,s),e.y+=s.footerMarginTop,n.textAlign=l.textAlign(s.footerAlign),n.textBaseline="middle",o=ut(s.footerFont),n.fillStyle=s.footerColor,n.font=o.string,a=0;a<i;++a)n.fillText(r[a],l.x(e.x),e.y+o.lineHeight/2),e.y+=o.lineHeight+s.footerSpacing}}drawBackground(e,n,s,r){const{xAlign:i,yAlign:o}=this,{x:a,y:l}=e,{width:c,height:d}=s,{topLeft:f,topRight:h,bottomLeft:p,bottomRight:m}=Wr(r.cornerRadius);n.fillStyle=r.backgroundColor,n.strokeStyle=r.borderColor,n.lineWidth=r.borderWidth,n.beginPath(),n.moveTo(a+f,l),o==="top"&&this.drawCaret(e,n,s,r),n.lineTo(a+c-h,l),n.quadraticCurveTo(a+c,l,a+c,l+h),o==="center"&&i==="right"&&this.drawCaret(e,n,s,r),n.lineTo(a+c,l+d-m),n.quadraticCurveTo(a+c,l+d,a+c-m,l+d),o==="bottom"&&this.drawCaret(e,n,s,r),n.lineTo(a+p,l+d),n.quadraticCurveTo(a,l+d,a,l+d-p),o==="center"&&i==="left"&&this.drawCaret(e,n,s,r),n.lineTo(a,l+f),n.quadraticCurveTo(a,l,a+f,l),n.closePath(),n.fill(),r.borderWidth>0&&n.stroke()}_updateAnimationTarget(e){const n=this.chart,s=this.$animations,r=s&&s.x,i=s&&s.y;if(r||i){const o=to[e.position].call(this,this._active,this._eventPosition);if(!o)return;const a=this._size=Qg(this,e),l=Object.assign({},o,this._size),c=Kg(n,e,l),d=Yg(e,l,c,n);(r._to!==d.x||i._to!==d.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=a.width,this.height=a.height,this.caretX=o.x,this.caretY=o.y,this._resolveAnimations().update(this,d))}}_willRender(){return!!this.opacity}draw(e){const n=this.options.setContext(this.getContext());let s=this.opacity;if(!s)return;this._updateAnimationTarget(n);const r={width:this.width,height:this.height},i={x:this.x,y:this.y};s=Math.abs(s)<.001?0:s;const o=Gt(n.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;n.enabled&&a&&(e.save(),e.globalAlpha=s,this.drawBackground(i,e,r,n),Fy(e,n.textDirection),i.y+=o.top,this.drawTitle(i,e,n),this.drawBody(i,e,n),this.drawFooter(i,e,n),zy(e,n.textDirection),e.restore())}getActiveElements(){return this._active||[]}setActiveElements(e,n){const s=this._active,r=e.map(({datasetIndex:a,index:l})=>{const c=this.chart.getDatasetMeta(a);if(!c)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:c.data[l],index:l}}),i=!Fl(s,r),o=this._positionChanged(r,n);(i||o)&&(this._active=r,this._eventPosition=n,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(e,n,s=!0){if(n&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const r=this.options,i=this._active||[],o=this._getActiveElements(e,i,n,s),a=this._positionChanged(o,e),l=n||!Fl(o,i)||a;return l&&(this._active=o,(r.enabled||r.external)&&(this._eventPosition={x:e.x,y:e.y},this.update(!0,n))),l}_getActiveElements(e,n,s,r){const i=this.options;if(e.type==="mouseout")return[];if(!r)return n.filter(a=>this.chart.data.datasets[a.datasetIndex]&&this.chart.getDatasetMeta(a.datasetIndex).controller.getParsed(a.index)!==void 0);const o=this.chart.getElementsAtEventForMode(e,i.mode,i,s);return i.reverse&&o.reverse(),o}_positionChanged(e,n){const{caretX:s,caretY:r,options:i}=this,o=to[i.position].call(this,e,n);return o!==!1&&(s!==o.x||r!==o.y)}}B(Fd,"positioners",to);var Gj={id:"tooltip",_element:Fd,positioners:to,afterInit(t,e,n){n&&(t.tooltip=new Fd({chart:t,options:n}))},beforeUpdate(t,e,n){t.tooltip&&t.tooltip.initialize(n)},reset(t,e,n){t.tooltip&&t.tooltip.initialize(n)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const n={tooltip:e};if(t.notifyPlugins("beforeTooltipDraw",{...n,cancelable:!0})===!1)return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",n)}},afterEvent(t,e){if(t.tooltip){const n=e.replay;t.tooltip.handleEvent(e.event,n,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:ev},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>t!=="filter"&&t!=="itemSort"&&t!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};const Jj=(t,e,n,s)=>(typeof e=="string"?(n=t.push(e)-1,s.unshift({index:n,label:e})):isNaN(e)&&(n=null),n);function Zj(t,e,n,s){const r=t.indexOf(e);if(r===-1)return Jj(t,e,n,s);const i=t.lastIndexOf(e);return r!==i?n:r}const eN=(t,e)=>t===null?null:ct(Math.round(t),0,e);function Gg(t){const e=this.getLabels();return t>=0&&t<e.length?e[t]:t}class zd extends Si{constructor(e){super(e),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(e){const n=this._addedLabels;if(n.length){const s=this.getLabels();for(const{index:r,label:i}of n)s[r]===i&&s.splice(r,1);this._addedLabels=[]}super.init(e)}parse(e,n){if(ue(e))return null;const s=this.getLabels();return n=isFinite(n)&&s[n]===e?n:Zj(s,e,Z(n,e),this._addedLabels),eN(n,s.length-1)}determineDataLimits(){const{minDefined:e,maxDefined:n}=this.getUserBounds();let{min:s,max:r}=this.getMinMax(!0);this.options.bounds==="ticks"&&(e||(s=0),n||(r=this.getLabels().length-1)),this.min=s,this.max=r}buildTicks(){const e=this.min,n=this.max,s=this.options.offset,r=[];let i=this.getLabels();i=e===0&&n===i.length-1?i:i.slice(e,n+1),this._valueRange=Math.max(i.length-(s?0:1),1),this._startValue=this.min-(s?.5:0);for(let o=e;o<=n;o++)r.push({value:o});return r}getLabelForValue(e){return Gg.call(this,e)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(e){return typeof e!="number"&&(e=this.parse(e)),e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getPixelForTick(e){const n=this.ticks;return e<0||e>n.length-1?null:this.getPixelForValue(n[e].value)}getValueForPixel(e){return Math.round(this._startValue+this.getDecimalForPixel(e)*this._valueRange)}getBasePixel(){return this.bottom}}B(zd,"id","category"),B(zd,"defaults",{ticks:{callback:Gg}});function tN(t,e){const n=[],{bounds:r,step:i,min:o,max:a,precision:l,count:c,maxTicks:d,maxDigits:f,includeBounds:h}=t,p=i||1,m=d-1,{min:g,max:b}=e,y=!ue(o),x=!ue(a),v=!ue(c),_=(b-g)/(f+1);let w=ng((b-g)/m/p)*p,k,C,j,M;if(w<1e-14&&!y&&!x)return[{value:g},{value:b}];M=Math.ceil(b/w)-Math.floor(g/w),M>m&&(w=ng(M*w/m/p)*p),ue(l)||(k=Math.pow(10,l),w=Math.ceil(w*k)/k),r==="ticks"?(C=Math.floor(g/w)*w,j=Math.ceil(b/w)*w):(C=g,j=b),y&&x&&i&&J_((a-o)/i,w/1e3)?(M=Math.round(Math.min((a-o)/w,d)),w=(a-o)/M,C=o,j=a):v?(C=y?o:C,j=x?a:j,M=c-1,w=(j-C)/M):(M=(j-C)/w,rl(M,Math.round(M),w/1e3)?M=Math.round(M):M=Math.ceil(M));const E=Math.max(sg(w),sg(C));k=Math.pow(10,ue(l)?E:l),C=Math.round(C*k)/k,j=Math.round(j*k)/k;let P=0;for(y&&(h&&C!==o?(n.push({value:o}),C<o&&P++,rl(Math.round((C+P*w)*k)/k,o,Jg(o,_,t))&&P++):C<o&&P++);P<M;++P){const A=Math.round((C+P*w)*k)/k;if(x&&A>a)break;n.push({value:A})}return x&&h&&j!==a?n.length&&rl(n[n.length-1].value,a,Jg(a,_,t))?n[n.length-1].value=a:n.push({value:a}):(!x||j===a)&&n.push({value:j}),n}function Jg(t,e,{horizontal:n,minRotation:s}){const r=Rn(s),i=(n?Math.sin(r):Math.cos(r))||.001,o=.75*e*(""+t).length;return Math.min(e/i,o)}class nN extends Si{constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(e,n){return ue(e)||(typeof e=="number"||e instanceof Number)&&!isFinite(+e)?null:+e}handleTickRangeOptions(){const{beginAtZero:e}=this.options,{minDefined:n,maxDefined:s}=this.getUserBounds();let{min:r,max:i}=this;const o=l=>r=n?r:l,a=l=>i=s?i:l;if(e){const l=Ss(r),c=Ss(i);l<0&&c<0?a(0):l>0&&c>0&&o(0)}if(r===i){let l=i===0?1:Math.abs(i*.05);a(i+l),e||o(r-l)}this.min=r,this.max=i}getTickLimit(){const e=this.options.ticks;let{maxTicksLimit:n,stepSize:s}=e,r;return s?(r=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,r>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${r} ticks. Limiting to 1000.`),r=1e3)):(r=this.computeTickLimit(),n=n||11),n&&(r=Math.min(n,r)),r}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const e=this.options,n=e.ticks;let s=this.getTickLimit();s=Math.max(2,s);const r={maxTicks:s,bounds:e.bounds,min:e.min,max:e.max,precision:n.precision,step:n.stepSize,count:n.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:n.minRotation||0,includeBounds:n.includeBounds!==!1},i=this._range||this,o=tN(r,i);return e.bounds==="ticks"&&Z_(o,this,"value"),e.reverse?(o.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),o}configure(){const e=this.ticks;let n=this.min,s=this.max;if(super.configure(),this.options.offset&&e.length){const r=(s-n)/Math.max(e.length-1,1)/2;n-=r,s+=r}this._startValue=n,this._endValue=s,this._valueRange=s-n}getLabelForValue(e){return qf(e,this.chart.options.locale,this.options.ticks.format)}}class Bd extends nN{determineDataLimits(){const{min:e,max:n}=this.getMinMax(!0);this.min=It(e)?e:0,this.max=It(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const e=this.isHorizontal(),n=e?this.width:this.height,s=Rn(this.options.ticks.minRotation),r=(e?Math.sin(s):Math.cos(s))||.001,i=this._resolveTickFontOptions(0);return Math.ceil(n/Math.min(40,i.lineHeight/r))}getPixelForValue(e){return e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getValueForPixel(e){return this._startValue+this.getDecimalForPixel(e)*this._valueRange}}B(Bd,"id","linear"),B(Bd,"defaults",{ticks:{callback:Py.formatters.numeric}});const _c={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},at=Object.keys(_c);function Zg(t,e){return t-e}function em(t,e){if(ue(e))return null;const n=t._adapter,{parser:s,round:r,isoWeekday:i}=t._parseOpts;let o=e;return typeof s=="function"&&(o=s(o)),It(o)||(o=typeof s=="string"?n.parse(o,s):n.parse(o)),o===null?null:(r&&(o=r==="week"&&($l(i)||i===!0)?n.startOf(o,"isoWeek",i):n.startOf(o,r)),+o)}function tm(t,e,n,s){const r=at.length;for(let i=at.indexOf(t);i<r-1;++i){const o=_c[at[i]],a=o.steps?o.steps:Number.MAX_SAFE_INTEGER;if(o.common&&Math.ceil((n-e)/(a*o.size))<=s)return at[i]}return at[r-1]}function sN(t,e,n,s,r){for(let i=at.length-1;i>=at.indexOf(n);i--){const o=at[i];if(_c[o].common&&t._adapter.diff(r,s,o)>=e-1)return o}return at[n?at.indexOf(n):0]}function rN(t){for(let e=at.indexOf(t)+1,n=at.length;e<n;++e)if(_c[at[e]].common)return at[e]}function nm(t,e,n){if(!n)t[e]=!0;else if(n.length){const{lo:s,hi:r}=Xf(n,e),i=n[s]>=e?n[s]:n[r];t[i]=!0}}function iN(t,e,n,s){const r=t._adapter,i=+r.startOf(e[0].value,s),o=e[e.length-1].value;let a,l;for(a=i;a<=o;a=+r.add(a,1,s))l=n[a],l>=0&&(e[l].major=!0);return e}function sm(t,e,n){const s=[],r={},i=e.length;let o,a;for(o=0;o<i;++o)a=e[o],r[a]=o,s.push({value:a,major:!1});return i===0||!n?s:iN(t,s,r,n)}class Yl extends Si{constructor(e){super(e),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(e,n={}){const s=e.time||(e.time={}),r=this._adapter=new xC._date(e.adapters.date);r.init(n),fo(s.displayFormats,r.formats()),this._parseOpts={parser:s.parser,round:s.round,isoWeekday:s.isoWeekday},super.init(e),this._normalized=n.normalized}parse(e,n){return e===void 0?null:em(this,e)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const e=this.options,n=this._adapter,s=e.time.unit||"day";let{min:r,max:i,minDefined:o,maxDefined:a}=this.getUserBounds();function l(c){!o&&!isNaN(c.min)&&(r=Math.min(r,c.min)),!a&&!isNaN(c.max)&&(i=Math.max(i,c.max))}(!o||!a)&&(l(this._getLabelBounds()),(e.bounds!=="ticks"||e.ticks.source!=="labels")&&l(this.getMinMax(!1))),r=It(r)&&!isNaN(r)?r:+n.startOf(Date.now(),s),i=It(i)&&!isNaN(i)?i:+n.endOf(Date.now(),s)+1,this.min=Math.min(r,i-1),this.max=Math.max(r+1,i)}_getLabelBounds(){const e=this.getLabelTimestamps();let n=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;return e.length&&(n=e[0],s=e[e.length-1]),{min:n,max:s}}buildTicks(){const e=this.options,n=e.time,s=e.ticks,r=s.source==="labels"?this.getLabelTimestamps():this._generate();e.bounds==="ticks"&&r.length&&(this.min=this._userMin||r[0],this.max=this._userMax||r[r.length-1]);const i=this.min,o=this.max,a=rk(r,i,o);return this._unit=n.unit||(s.autoSkip?tm(n.minUnit,this.min,this.max,this._getLabelCapacity(i)):sN(this,a.length,n.minUnit,this.min,this.max)),this._majorUnit=!s.major.enabled||this._unit==="year"?void 0:rN(this._unit),this.initOffsets(r),e.reverse&&a.reverse(),sm(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(e=>+e.value))}initOffsets(e=[]){let n=0,s=0,r,i;this.options.offset&&e.length&&(r=this.getDecimalForValue(e[0]),e.length===1?n=1-r:n=(this.getDecimalForValue(e[1])-r)/2,i=this.getDecimalForValue(e[e.length-1]),e.length===1?s=i:s=(i-this.getDecimalForValue(e[e.length-2]))/2);const o=e.length<3?.5:.25;n=ct(n,0,o),s=ct(s,0,o),this._offsets={start:n,end:s,factor:1/(n+1+s)}}_generate(){const e=this._adapter,n=this.min,s=this.max,r=this.options,i=r.time,o=i.unit||tm(i.minUnit,n,s,this._getLabelCapacity(n)),a=Z(r.ticks.stepSize,1),l=o==="week"?i.isoWeekday:!1,c=$l(l)||l===!0,d={};let f=n,h,p;if(c&&(f=+e.startOf(f,"isoWeek",l)),f=+e.startOf(f,c?"day":o),e.diff(s,n,o)>1e5*a)throw new Error(n+" and "+s+" are too far apart with stepSize of "+a+" "+o);const m=r.ticks.source==="data"&&this.getDataTimestamps();for(h=f,p=0;h<s;h=+e.add(h,a,o),p++)nm(d,h,m);return(h===s||r.bounds==="ticks"||p===1)&&nm(d,h,m),Object.keys(d).sort(Zg).map(g=>+g)}getLabelForValue(e){const n=this._adapter,s=this.options.time;return s.tooltipFormat?n.format(e,s.tooltipFormat):n.format(e,s.displayFormats.datetime)}format(e,n){const r=this.options.time.displayFormats,i=this._unit,o=n||r[i];return this._adapter.format(e,o)}_tickFormatFunction(e,n,s,r){const i=this.options,o=i.ticks.callback;if(o)return he(o,[e,n,s],this);const a=i.time.displayFormats,l=this._unit,c=this._majorUnit,d=l&&a[l],f=c&&a[c],h=s[n],p=c&&f&&h&&h.major;return this._adapter.format(e,r||(p?f:d))}generateTickLabels(e){let n,s,r;for(n=0,s=e.length;n<s;++n)r=e[n],r.label=this._tickFormatFunction(r.value,n,e)}getDecimalForValue(e){return e===null?NaN:(e-this.min)/(this.max-this.min)}getPixelForValue(e){const n=this._offsets,s=this.getDecimalForValue(e);return this.getPixelForDecimal((n.start+s)*n.factor)}getValueForPixel(e){const n=this._offsets,s=this.getDecimalForPixel(e)/n.factor-n.end;return this.min+s*(this.max-this.min)}_getLabelSize(e){const n=this.options.ticks,s=this.ctx.measureText(e).width,r=Rn(this.isHorizontal()?n.maxRotation:n.minRotation),i=Math.cos(r),o=Math.sin(r),a=this._resolveTickFontOptions(0).size;return{w:s*i+a*o,h:s*o+a*i}}_getLabelCapacity(e){const n=this.options.time,s=n.displayFormats,r=s[n.unit]||s.millisecond,i=this._tickFormatFunction(e,0,sm(this,[e],this._majorUnit),r),o=this._getLabelSize(i),a=Math.floor(this.isHorizontal()?this.width/o.w:this.height/o.h)-1;return a>0?a:1}getDataTimestamps(){let e=this._cache.data||[],n,s;if(e.length)return e;const r=this.getMatchingVisibleMetas();if(this._normalized&&r.length)return this._cache.data=r[0].controller.getAllParsedValues(this);for(n=0,s=r.length;n<s;++n)e=e.concat(r[n].controller.getAllParsedValues(this));return this._cache.data=this.normalize(e)}getLabelTimestamps(){const e=this._cache.labels||[];let n,s;if(e.length)return e;const r=this.getLabels();for(n=0,s=r.length;n<s;++n)e.push(em(this,r[n]));return this._cache.labels=this._normalized?e:this.normalize(e)}normalize(e){return Cy(e.sort(Zg))}}B(Yl,"id","time"),B(Yl,"defaults",{bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}});function Ua(t,e,n){let s=0,r=t.length-1,i,o,a,l;n?(e>=t[s].pos&&e<=t[r].pos&&({lo:s,hi:r}=Dd(t,"pos",e)),{pos:i,time:a}=t[s],{pos:o,time:l}=t[r]):(e>=t[s].time&&e<=t[r].time&&({lo:s,hi:r}=Dd(t,"time",e)),{time:i,pos:a}=t[s],{time:o,pos:l}=t[r]);const c=o-i;return c?a+(l-a)*(e-i)/c:a}class rm extends Yl{constructor(e){super(e),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const e=this._getTimestampsForTable(),n=this._table=this.buildLookupTable(e);this._minPos=Ua(n,this.min),this._tableRange=Ua(n,this.max)-this._minPos,super.initOffsets(e)}buildLookupTable(e){const{min:n,max:s}=this,r=[],i=[];let o,a,l,c,d;for(o=0,a=e.length;o<a;++o)c=e[o],c>=n&&c<=s&&r.push(c);if(r.length<2)return[{time:n,pos:0},{time:s,pos:1}];for(o=0,a=r.length;o<a;++o)d=r[o+1],l=r[o-1],c=r[o],Math.round((d+l)/2)!==c&&i.push({time:c,pos:o/(a-1)});return i}_generate(){const e=this.min,n=this.max;let s=super.getDataTimestamps();return(!s.includes(e)||!s.length)&&s.splice(0,0,e),(!s.includes(n)||s.length===1)&&s.push(n),s.sort((r,i)=>r-i)}_getTimestampsForTable(){let e=this._cache.all||[];if(e.length)return e;const n=this.getDataTimestamps(),s=this.getLabelTimestamps();return n.length&&s.length?e=this.normalize(n.concat(s)):e=n.length?n:s,e=this._cache.all=e,e}getDecimalForValue(e){return(Ua(this._table,e)-this._minPos)/this._tableRange}getValueForPixel(e){const n=this._offsets,s=this.getDecimalForPixel(e)/n.factor-n.end;return Ua(this._table,s*this._tableRange+this._minPos,!0)}}B(rm,"id","timeseries"),B(rm,"defaults",Yl.defaults);const tv="label";function im(t,e){typeof t=="function"?t(e):t&&(t.current=e)}function oN(t,e){const n=t.options;n&&e&&Object.assign(n,e)}function nv(t,e){t.labels=e}function sv(t,e,n=tv){const s=[];t.datasets=e.map(r=>{const i=t.datasets.find(o=>o[n]===r[n]);return!i||!r.data||s.includes(i)?{...r}:(s.push(i),Object.assign(i,r),i)})}function aN(t,e=tv){const n={labels:[],datasets:[]};return nv(n,t.labels),sv(n,t.datasets,e),n}function lN(t,e){const{height:n=150,width:s=300,redraw:r=!1,datasetIdKey:i,type:o,data:a,options:l,plugins:c=[],fallbackContent:d,updateMode:f,...h}=t,p=S.useRef(null),m=S.useRef(null),g=()=>{p.current&&(m.current=new Sc(p.current,{type:o,data:aN(a,i),options:l&&{...l},plugins:c}),im(e,m.current))},b=()=>{im(e,null),m.current&&(m.current.destroy(),m.current=null)};return S.useEffect(()=>{!r&&m.current&&l&&oN(m.current,l)},[r,l]),S.useEffect(()=>{!r&&m.current&&nv(m.current.config.data,a.labels)},[r,a.labels]),S.useEffect(()=>{!r&&m.current&&a.datasets&&sv(m.current.config.data,a.datasets,i)},[r,a.datasets]),S.useEffect(()=>{m.current&&(r?(b(),setTimeout(g)):m.current.update(f))},[r,l,a.labels,a.datasets,f]),S.useEffect(()=>{m.current&&(b(),setTimeout(g))},[o]),S.useEffect(()=>(g(),()=>b()),[]),u.jsx("canvas",{ref:p,role:"img",height:n,width:s,...h,children:d})}const cN=S.forwardRef(lN);function rv(t,e){return Sc.register(e),S.forwardRef((n,s)=>u.jsx(cN,{...n,ref:s,type:t}))}const uN=rv("bar",il),dN=rv("doughnut",Ji),pt=["leads","em_contato","proposta","fechado"],mn={leads:"Novos Leads",em_contato:"Em Contato",proposta:"Proposta",fechado:"Fechado"};Sc.register(eo,ll,zd,Bd,Wj,Gj);function fN({porEtapa:t}){const e=pt.map(s=>t[s]??0),n=Math.max(20,Math.ceil((Math.max(...e)+1)/20)*20);return u.jsx("div",{className:"mt-4 h-64",children:u.jsx(uN,{data:{labels:pt.map(s=>mn[s]),datasets:[{label:"Quantidade",data:e,backgroundColor:["rgba(59, 130, 246, 0.8)","rgba(59, 130, 246, 0.6)","rgba(59, 130, 246, 0.4)","rgba(59, 130, 246, 0.3)"],borderRadius:4,barThickness:24}]},options:{indexAxis:"y",responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1}},scales:{x:{beginAtZero:!0,max:n,grid:{color:"#f3f4f6"},ticks:{stepSize:20}},y:{grid:{display:!1}}}}})})}function hN({enviadas:t,erros:e}){return u.jsx("div",{className:"mt-4 h-64 flex items-center justify-center",children:u.jsx(dN,{data:{labels:["Enviadas","Erros"],datasets:[{data:[t,e],backgroundColor:["#3b82f6","#ef4444"],borderWidth:0}]},options:{responsive:!0,maintainAspectRatio:!1,cutout:"70%",plugins:{legend:{display:!1},tooltip:{callbacks:{label:n=>`${n.label}: ${n.parsed}`}}}}})})}const pN=1e4;function gN({nomeUsuario:t}){const{data:e,isPending:n,isError:s,error:r,refetch:i}=ey({queryKey:["metrics"],queryFn:()=>W.metricas(),refetchInterval:pN,refetchIntervalInBackground:!1}),o=n,a=s?r instanceof Error?r.message:"Falha ao carregar métricas.":"",l=e==null?void 0:e.perfil,c=l==null?void 0:l.licenca.restam_dias;return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{children:[u.jsxs("h1",{className:"text-2xl font-bold text-gray-800",children:["Olá, ",t," 👋 bem-vindo ao seu painel"]}),u.jsxs("div",{className:"mt-2 flex items-center justify-between text-sm text-gray-500",children:[u.jsxs("span",{children:[l!=null&&l.licenca.ativa?"Licença ativa":"Sem licença"," •"," ",l!=null&&l.licenca.expira_em?`expira em ${l.licenca.expira_em}`:"—"," • dados 100% locais"]}),c!=null&&u.jsxs("span",{children:["Restam ",u.jsx("strong",{className:"text-gray-700",children:c===null?"∞":`${c} dias`})]})]})]}),a&&u.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 rounded-xl px-4 py-3 text-sm",children:[u.jsx("i",{className:"fas fa-exclamation-triangle mr-2"}),a]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[u.jsxs(Pa,{rotulo:"Status da Conexão",icone:"fas fa-plug",children:[u.jsx("div",{className:"mt-2 flex items-center",children:u.jsxs("span",{className:H("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",e!=null&&e.conexao.geral?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:[u.jsx("span",{className:H("w-2 h-2 mr-1.5 rounded-full",e!=null&&e.conexao.geral?"bg-green-500":"bg-red-500")}),e!=null&&e.conexao.geral?"Conectado":"Desconectado"]})}),u.jsxs("p",{className:"text-[11px] text-gray-400 mt-2",children:[u.jsx("i",{className:"fas fa-brain mr-1"}),e!=null&&e.conexao.llm?"LLM ✓":"LLM não configurado"," ·"," ",u.jsx("i",{className:"fas fa-paper-plane mr-1"}),e!=null&&e.conexao.openoutreach?"OpenOutreach ✓":"OpenOutreach não configurado"]})]}),u.jsx(Pa,{rotulo:"Taxa de entrega",valor:o?"—":`${(e==null?void 0:e.taxa_entrega)??0}%`,subtitulo:`${(e==null?void 0:e.total_enviadas)??0} enviadas • total`,icone:"fas fa-paper-plane"}),u.jsx(Pa,{rotulo:"Taxa de erro",valor:o?"—":`${(e==null?void 0:e.taxa_erro)??0}%`,subtitulo:`${(e==null?void 0:e.total_erros)??0} erros • total`,icone:"fas fa-triangle-exclamation"}),u.jsx(Pa,{rotulo:"Leads cadastrados",valor:o?"—":(e==null?void 0:e.leads_total)??0,subtitulo:"Total na base",icone:"fas fa-users"})]}),u.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm p-6 border border-gray-100",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"text-base font-semibold text-gray-800",children:"Leads por etapa (CRM)"}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Quantidade de leads em cada coluna do Kanban"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("span",{className:"text-[11px] text-gray-300 hidden sm:inline",title:"O painel atualiza sozinho",children:[u.jsx("i",{className:"fas fa-rotate mr-1"}),"a cada 10s"]}),u.jsx("button",{onClick:()=>i(),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Atualizar"})]})]}),e?u.jsx(fN,{porEtapa:e.leads_por_etapa}):u.jsx(mN,{})]}),u.jsxs("div",{className:"bg-white rounded-xl shadow-sm p-6 border border-gray-100",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"text-base font-semibold text-gray-800",children:"Desempenho das campanhas"}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Agregação de todas as campanhas (Enviadas × Erros)"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("span",{className:"text-[11px] text-gray-300 hidden sm:inline",title:"O painel atualiza sozinho",children:[u.jsx("i",{className:"fas fa-rotate mr-1"}),"a cada 10s"]}),u.jsx("button",{onClick:()=>i(),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Atualizar"})]})]}),u.jsx(hN,{enviadas:(e==null?void 0:e.campanhas.enviadas)??0,erros:(e==null?void 0:e.campanhas.erros)??0}),u.jsxs("div",{className:"mt-4 flex items-center justify-center space-x-6 text-xs",children:[u.jsxs("span",{className:"flex items-center",children:[u.jsx("span",{className:"w-3 h-3 bg-blue-500 rounded-full mr-1.5"})," Enviadas (",(e==null?void 0:e.campanhas.enviadas)??0,")"]}),u.jsxs("span",{className:"flex items-center",children:[u.jsx("span",{className:"w-3 h-3 bg-red-500 rounded-full mr-1.5"})," Erros (",(e==null?void 0:e.campanhas.erros)??0,")"]})]})]})]})]})}function mN(){return u.jsx("div",{className:"mt-4 h-64 flex items-center justify-center text-gray-300",children:u.jsx("i",{className:"fas fa-spinner fa-spin text-2xl"})})}function Qt({titulo:t,icone:e="fas fa-sliders",children:n,abertoInicial:s=!1}){const[r,i]=S.useState(s);return u.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[u.jsxs("button",{type:"button",onClick:()=>i(o=>!o),className:"w-full flex items-center justify-between px-4 py-3 text-sm font-medium text-gray-600 bg-gray-50 hover:bg-gray-100 transition",children:[u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx("i",{className:H(e,"text-gray-400")})," ",t]}),u.jsx("i",{className:H("fas fa-chevron-down text-xs text-gray-400 transition-transform",r&&"rotate-180")})]}),r&&u.jsx("div",{className:"px-4 py-4 bg-white space-y-3",children:n})]})}function ra({valor:t,altura:e="md",mostrarLabel:n=!1,className:s}){const r=Math.max(0,Math.min(100,Math.round(t))),i={sm:"h-1.5",md:"h-2.5"};return u.jsxs("div",{className:H("w-full",s),children:[n&&u.jsxs("div",{className:"flex justify-between text-xs text-gray-500 mb-1",children:[u.jsx("span",{children:"Progresso"}),u.jsxs("span",{className:"font-semibold text-gray-700",children:[r,"%"]})]}),u.jsx("div",{className:H("w-full bg-gray-200 rounded-full overflow-hidden",i[e]),children:u.jsx("div",{className:H("h-full rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 transition-all duration-500"),style:{width:`${r}%`}})})]})}const xN={leads:"bg-blue-100 text-blue-800",em_contato:"bg-amber-100 text-amber-800",proposta:"bg-violet-100 text-violet-800",fechado:"bg-green-100 text-green-800",rascunho:"bg-gray-100 text-gray-600",em_andamento:"bg-blue-100 text-blue-800",pausado:"bg-amber-100 text-amber-800",pausada:"bg-amber-100 text-amber-800",concluido:"bg-green-100 text-green-800",cancelado:"bg-gray-100 text-gray-600",erro:"bg-red-100 text-red-800",concluida:"bg-green-100 text-green-800",pendente:"bg-gray-100 text-gray-600",pulada:"bg-gray-100 text-gray-500",enviada:"bg-green-100 text-green-800",ativo:"bg-green-100 text-green-800",inativo:"bg-gray-100 text-gray-600"},yN={leads:"Leads",em_contato:"Em contato",proposta:"Proposta",fechado:"Fechado",rascunho:"Rascunho",em_andamento:"Ativa",pausado:"Pausado",pausada:"Pausada",concluido:"Concluído",concluida:"Concluída",cancelado:"Cancelado",erro:"Erro",pendente:"Pendente",pulada:"Pulada",enviada:"Enviada",ativo:"Ativo",inativo:"Inativo",texto:"Texto",audio:"Áudio"};function sr({status:t,rotulo:e,className:n}){const s=xN[t]||"bg-gray-100 text-gray-600";return u.jsx("span",{className:H("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",s,n),children:e||yN[t]||t})}const vN={nome:"",telefone:"",email:"",fonte:"Manual",etapa:"leads"};function bN(){const{toast:t}=en(),[e,n]=S.useState([]),[s,r]=S.useState(""),[i,o]=S.useState("todas"),[a,l]=S.useState(!1),[c,d]=S.useState(null),[f,h]=S.useState(null),[p,m]=S.useState(null),g=S.useCallback(async()=>{n(await W.leads.listar())},[]);S.useEffect(()=>{g().catch(k=>t("erro",k.message))},[g,t]);const b=S.useMemo(()=>{const k=s.trim().toLowerCase();return e.filter(C=>{const j=!k||C.nome.toLowerCase().includes(k)||C.telefone.includes(k)||C.email.toLowerCase().includes(k),M=i==="todas"||C.etapa===i;return j&&M})},[e,s,i]),y=()=>{d({...vN}),l(!0)},x=k=>{d({...k}),l(!0)},v=async()=>{var k;if(!((k=c==null?void 0:c.nome)!=null&&k.trim())){t("erro","O nome do lead é obrigatório.");return}try{if(c.id){const{id:C,criado_em:j,atualizado_em:M,...E}=c;await W.leads.atualizar(C,E),t("sucesso","Lead atualizado.")}else await W.leads.criar(c),t("sucesso","Lead criado com sucesso.");l(!1),d(null),await g()}catch(C){t("erro",C instanceof Error?C.message:"Falha ao salvar lead.")}},_=async()=>{if(f)try{await W.leads.remover(f.id),t("sucesso",`Lead "${f.nome}" removido.`),h(null),await g()}catch(k){t("erro",k instanceof Error?k.message:"Falha ao remover.")}},w=async k=>{m(k.id);try{(await W.leads.enriquecer(k.id)).notas.forEach(j=>t("info",j)),t("sucesso","Lead enriquecido."),await g()}catch(C){t("erro",C instanceof Error?C.message:"Falha ao enriquecer.")}finally{m(null)}};return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[u.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-[280px]",children:[u.jsxs("div",{className:"relative flex-1 max-w-md",children:[u.jsx("i",{className:"fas fa-search absolute left-3 top-2.5 text-gray-400 text-sm"}),u.jsx("input",{value:s,onChange:k=>r(k.target.value),placeholder:"Buscar por nome, telefone ou e-mail...",className:"w-full pl-9 pr-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 focus:border-indigo-400 outline-none"})]}),u.jsxs("select",{value:i,onChange:k=>o(k.target.value),className:"text-sm border border-gray-200 rounded-lg px-3 py-2 bg-white focus:ring-2 focus:ring-indigo-400 outline-none",children:[u.jsx("option",{value:"todas",children:"Todas as etapas"}),pt.map(k=>u.jsx("option",{value:k,children:mn[k]},k))]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("button",{onClick:()=>d_(e,"leadmaster-leads.json"),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition",children:[u.jsx("i",{className:"fas fa-download mr-2"})," Exportar"]}),u.jsxs("button",{onClick:y,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition shadow-sm",children:[u.jsx("i",{className:"fas fa-plus mr-2"})," Novo Lead"]})]})]}),u.jsx("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100 bg-gray-50/50",children:[u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Lead"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Contato"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Etapa"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Completude"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Atualizado"}),u.jsx("th",{className:"px-5 py-3 font-semibold text-right",children:"Ações"})]})}),u.jsxs("tbody",{children:[b.map(k=>{const C=l_(k),j=c_(k);return u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40 transition",children:[u.jsxs("td",{className:"px-5 py-3",children:[u.jsx("p",{className:"font-medium text-gray-800",children:k.nome}),u.jsxs("p",{className:"text-xs text-gray-400",children:[k.fonte,k.empresa?` · ${k.empresa}`:""]})]}),u.jsxs("td",{className:"px-5 py-3 text-gray-600",children:[u.jsx("p",{children:k.telefone||"—"}),u.jsx("p",{className:"text-xs text-gray-400",children:k.email||"sem e-mail"})]}),u.jsx("td",{className:"px-5 py-3",children:u.jsx(sr,{status:k.etapa})}),u.jsxs("td",{className:"px-5 py-3 w-52",children:[u.jsx(ra,{valor:C,altura:"sm"}),u.jsx("p",{className:"text-[11px] text-gray-400 mt-1",children:u_(C,j)})]}),u.jsx("td",{className:"px-5 py-3 text-xs text-gray-400",children:Il(k.atualizado_em)}),u.jsxs("td",{className:"px-5 py-3 text-right whitespace-nowrap",children:[u.jsx("button",{onClick:()=>w(k),disabled:p===k.id,title:" Enriquecer com IA / BrasilAPI",className:"text-gray-400 hover:text-indigo-600 px-1.5 disabled:opacity-40",children:u.jsx("i",{className:H("fas fa-wand-magic-sparkles",p===k.id&&"fa-spin")})}),u.jsx("button",{onClick:()=>x(k),title:"Editar",className:"text-gray-400 hover:text-indigo-600 px-1.5",children:u.jsx("i",{className:"fas fa-pen"})}),u.jsx("button",{onClick:()=>h(k),title:"Excluir",className:"text-gray-400 hover:text-red-600 px-1.5",children:u.jsx("i",{className:"fas fa-trash"})})]})]},k.id)}),b.length===0&&u.jsx("tr",{children:u.jsxs("td",{colSpan:6,className:"px-5 py-16 text-center text-gray-400",children:[u.jsx("i",{className:"fas fa-users text-3xl text-gray-200 block mb-3"}),"Nenhum lead encontrado. Crie um novo ou importe pelos Extratores."]})})]})]})})}),u.jsx(Xt,{aberto:a,onFechar:()=>l(!1),titulo:c!=null&&c.id?"Editar lead":"Novo lead",icone:"fas fa-user-plus",children:c&&u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(As,{rotulo:"Nome *",valor:c.nome||"",onChange:k=>d({...c,nome:k})}),u.jsx(As,{rotulo:"Telefone",valor:c.telefone||"",onChange:k=>d({...c,telefone:k}),placeholder:"(11) 99999-9999"}),u.jsx(As,{rotulo:"E-mail",tipo:"email",valor:c.email||"",onChange:k=>d({...c,email:k}),placeholder:"contato@empresa.com.br"}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Etapa"}),u.jsx("select",{value:c.etapa||"leads",onChange:k=>d({...c,etapa:k.target.value}),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",children:pt.map(k=>u.jsx("option",{value:k,children:mn[k]},k))})]})]}),u.jsxs(Qt,{titulo:"Campos avançados",icone:"fas fa-sliders",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(As,{rotulo:"Empresa",valor:c.empresa||"",onChange:k=>d({...c,empresa:k})}),u.jsx(As,{rotulo:"CNPJ",valor:c.cnpj||"",onChange:k=>d({...c,cnpj:k}),placeholder:"00.000.000/0000-00"}),u.jsx(As,{rotulo:"Cidade",valor:c.cidade||"",onChange:k=>d({...c,cidade:k}),placeholder:"São Paulo/SP"}),u.jsx(As,{rotulo:"Fonte",valor:c.fonte||"",onChange:k=>d({...c,fonte:k}),placeholder:"Google Maps, Instagram, CNPJ..."})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Observações"}),u.jsx("textarea",{value:c.observacoes||"",onChange:k=>d({...c,observacoes:k.target.value}),rows:3,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",placeholder:"Histórico de conversas, próximos passos..."})]})]}),u.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[u.jsx("button",{onClick:()=>l(!1),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:v,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar"]})]})]})}),u.jsxs(Xt,{aberto:!!f,onFechar:()=>h(null),titulo:"Excluir lead",icone:"fas fa-trash",children:[u.jsxs("p",{className:"text-sm text-gray-600",children:["Tem certeza que deseja excluir ",u.jsx("strong",{children:f==null?void 0:f.nome}),"? Essa ação não pode ser desfeita."]}),u.jsxs("div",{className:"flex justify-end gap-3 mt-6",children:[u.jsx("button",{onClick:()=>h(null),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsx("button",{onClick:_,className:"px-6 py-2.5 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700",children:"Excluir"})]})]})]})}function As({rotulo:t,valor:e,onChange:n,tipo:s="text",placeholder:r}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("input",{type:s,value:e,onChange:i=>n(i.target.value),placeholder:r,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function wN(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return S.useMemo(()=>s=>{e.forEach(r=>r(s))},e)}const kc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function _i(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function oh(t){return"nodeType"in t}function st(t){var e,n;return t?_i(t)?t:oh(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function ah(t){const{Document:e}=st(t);return t instanceof e}function ia(t){return _i(t)?!1:t instanceof st(t).HTMLElement}function iv(t){return t instanceof st(t).SVGElement}function ki(t){return t?_i(t)?t.document:oh(t)?ah(t)?t:ia(t)||iv(t)?t.ownerDocument:document:document:document}const Jt=kc?S.useLayoutEffect:S.useEffect;function Cc(t){const e=S.useRef(t);return Jt(()=>{e.current=t}),S.useCallback(function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];return e.current==null?void 0:e.current(...s)},[])}function SN(){const t=S.useRef(null),e=S.useCallback((s,r)=>{t.current=setInterval(s,r)},[]),n=S.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function Uo(t,e){e===void 0&&(e=[t]);const n=S.useRef(t);return Jt(()=>{n.current!==t&&(n.current=t)},e),n}function oa(t,e){const n=S.useRef();return S.useMemo(()=>{const s=t(n.current);return n.current=s,s},[...e])}function Xl(t){const e=Cc(t),n=S.useRef(null),s=S.useCallback(r=>{r!==n.current&&(e==null||e(r,n.current)),n.current=r},[]);return[n,s]}function ql(t){const e=S.useRef();return S.useEffect(()=>{e.current=t},[t]),e.current}let vu={};function aa(t,e){return S.useMemo(()=>{if(e)return e;const n=vu[t]==null?0:vu[t]+1;return vu[t]=n,t+"-"+n},[t,e])}function ov(t){return function(e){for(var n=arguments.length,s=new Array(n>1?n-1:0),r=1;r<n;r++)s[r-1]=arguments[r];return s.reduce((i,o)=>{const a=Object.entries(o);for(const[l,c]of a){const d=i[l];d!=null&&(i[l]=d+t*c)}return i},{...e})}}const Qr=ov(1),Gl=ov(-1);function _N(t){return"clientX"in t&&"clientY"in t}function jc(t){if(!t)return!1;const{KeyboardEvent:e}=st(t.target);return e&&t instanceof e}function kN(t){if(!t)return!1;const{TouchEvent:e}=st(t.target);return e&&t instanceof e}function Jl(t){if(kN(t)){if(t.touches&&t.touches.length){const{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){const{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return _N(t)?{x:t.clientX,y:t.clientY}:null}const Ns=Object.freeze({Translate:{toString(t){if(!t)return;const{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;const{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[Ns.Translate.toString(t),Ns.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:s}=t;return e+" "+n+"ms "+s}}}),om="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function CN(t){return t.matches(om)?t:t.querySelector(om)}const jN={display:"none"};function NN(t){let{id:e,value:n}=t;return pe.createElement("div",{id:e,style:jN},n)}function EN(t){let{id:e,announcement:n,ariaLiveType:s="assertive"}=t;const r={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return pe.createElement("div",{id:e,style:r,role:"status","aria-live":s,"aria-atomic":!0},n)}function MN(){const[t,e]=S.useState("");return{announce:S.useCallback(s=>{s!=null&&e(s)},[]),announcement:t}}const av=S.createContext(null);function PN(t){const e=S.useContext(av);S.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(t)},[t,e])}function RN(){const[t]=S.useState(()=>new Set),e=S.useCallback(s=>(t.add(s),()=>t.delete(s)),[t]);return[S.useCallback(s=>{let{type:r,event:i}=s;t.forEach(o=>{var a;return(a=o[r])==null?void 0:a.call(o,i)})},[t]),e]}const ON={draggable:`
84
+ `):t}function Hj(t,e){const{element:n,datasetIndex:s,index:r}=e,i=t.getDatasetMeta(s).controller,{label:o,value:a}=i.getLabelAndValue(r);return{chart:t,label:o,parsed:i.getParsed(r),raw:t.data.datasets[s].data[r],formattedValue:a,dataset:i.getDataset(),dataIndex:r,datasetIndex:s,element:n}}function Qg(t,e){const n=t.chart.ctx,{body:s,footer:r,title:i}=t,{boxWidth:o,boxHeight:a}=e,l=ut(e.bodyFont),c=ut(e.titleFont),d=ut(e.footerFont),f=i.length,h=r.length,p=s.length,m=Gt(e.padding);let g=m.height,b=0,y=s.reduce((_,w)=>_+w.before.length+w.lines.length+w.after.length,0);if(y+=t.beforeBody.length+t.afterBody.length,f&&(g+=f*c.lineHeight+(f-1)*e.titleSpacing+e.titleMarginBottom),y){const _=e.displayColors?Math.max(a,l.lineHeight):l.lineHeight;g+=p*_+(y-p)*l.lineHeight+(y-1)*e.bodySpacing}h&&(g+=e.footerMarginTop+h*d.lineHeight+(h-1)*e.footerSpacing);let x=0;const v=function(_){b=Math.max(b,n.measureText(_).width+x)};return n.save(),n.font=c.string,ae(t.title,v),n.font=l.string,ae(t.beforeBody.concat(t.afterBody),v),x=e.displayColors?o+2+e.boxPadding:0,ae(s,_=>{ae(_.before,v),ae(_.lines,v),ae(_.after,v)}),x=0,n.font=d.string,ae(t.footer,v),n.restore(),b+=m.width,{width:b,height:g}}function Vj(t,e){const{y:n,height:s}=e;return n<s/2?"top":n>t.height-s/2?"bottom":"center"}function Qj(t,e,n,s){const{x:r,width:i}=s,o=n.caretSize+n.caretPadding;if(t==="left"&&r+i+o>e.width||t==="right"&&r-i-o<0)return!0}function Kj(t,e,n,s){const{x:r,width:i}=n,{width:o,chartArea:{left:a,right:l}}=t;let c="center";return s==="center"?c=r<=(a+l)/2?"left":"right":r<=i/2?c="left":r>=o-i/2&&(c="right"),Qj(c,t,e,n)&&(c="center"),c}function Kg(t,e,n){const s=n.yAlign||e.yAlign||Vj(t,n);return{xAlign:n.xAlign||e.xAlign||Kj(t,e,n,s),yAlign:s}}function Yj(t,e){let{x:n,width:s}=t;return e==="right"?n-=s:e==="center"&&(n-=s/2),n}function Xj(t,e,n){let{y:s,height:r}=t;return e==="top"?s+=n:e==="bottom"?s-=r+n:s-=r/2,s}function Yg(t,e,n,s){const{caretSize:r,caretPadding:i,cornerRadius:o}=t,{xAlign:a,yAlign:l}=n,c=r+i,{topLeft:d,topRight:f,bottomLeft:h,bottomRight:p}=Wr(o);let m=Yj(e,a);const g=Xj(e,l,c);return l==="center"?a==="left"?m+=c:a==="right"&&(m-=c):a==="left"?m-=Math.max(d,h)+r:a==="right"&&(m+=Math.max(f,p)+r),{x:ct(m,0,s.width-e.width),y:ct(g,0,s.height-e.height)}}function $a(t,e,n){const s=Gt(n.padding);return e==="center"?t.x+t.width/2:e==="right"?t.x+t.width-s.right:t.x+s.left}function Xg(t){return ln([],kn(t))}function qj(t,e,n){return wi(t,{tooltip:e,tooltipItems:n,type:"tooltip"})}function qg(t,e){const n=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return n?t.override(n):t}const ev={beforeTitle:wn,title(t){if(t.length>0){const e=t[0],n=e.chart.data.labels,s=n?n.length:0;if(this&&this.options&&this.options.mode==="dataset")return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex<s)return n[e.dataIndex]}return""},afterTitle:wn,beforeBody:wn,beforeLabel:wn,label(t){if(this&&this.options&&this.options.mode==="dataset")return t.label+": "+t.formattedValue||t.formattedValue;let e=t.dataset.label||"";e&&(e+=": ");const n=t.formattedValue;return ue(n)||(e+=n),e},labelColor(t){const n=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:n.borderColor,backgroundColor:n.backgroundColor,borderWidth:n.borderWidth,borderDash:n.borderDash,borderDashOffset:n.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const n=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:n.pointStyle,rotation:n.rotation}},afterLabel:wn,afterBody:wn,beforeFooter:wn,footer:wn,afterFooter:wn};function rt(t,e,n,s){const r=t[e].call(n,s);return typeof r>"u"?ev[e].call(n,s):r}class Fd extends js{constructor(e){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=e.chart,this.options=e.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(e){this.options=e,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const e=this._cachedAnimations;if(e)return e;const n=this.chart,s=this.options.setContext(this.getContext()),r=s.enabled&&n.options.animation&&s.animations,i=new By(this.chart,r);return r._cacheable&&(this._cachedAnimations=Object.freeze(i)),i}getContext(){return this.$context||(this.$context=qj(this.chart.getContext(),this,this._tooltipItems))}getTitle(e,n){const{callbacks:s}=n,r=rt(s,"beforeTitle",this,e),i=rt(s,"title",this,e),o=rt(s,"afterTitle",this,e);let a=[];return a=ln(a,kn(r)),a=ln(a,kn(i)),a=ln(a,kn(o)),a}getBeforeBody(e,n){return Xg(rt(n.callbacks,"beforeBody",this,e))}getBody(e,n){const{callbacks:s}=n,r=[];return ae(e,i=>{const o={before:[],lines:[],after:[]},a=qg(s,i);ln(o.before,kn(rt(a,"beforeLabel",this,i))),ln(o.lines,rt(a,"label",this,i)),ln(o.after,kn(rt(a,"afterLabel",this,i))),r.push(o)}),r}getAfterBody(e,n){return Xg(rt(n.callbacks,"afterBody",this,e))}getFooter(e,n){const{callbacks:s}=n,r=rt(s,"beforeFooter",this,e),i=rt(s,"footer",this,e),o=rt(s,"afterFooter",this,e);let a=[];return a=ln(a,kn(r)),a=ln(a,kn(i)),a=ln(a,kn(o)),a}_createItems(e){const n=this._active,s=this.chart.data,r=[],i=[],o=[];let a=[],l,c;for(l=0,c=n.length;l<c;++l)a.push(Hj(this.chart,n[l]));return e.filter&&(a=a.filter((d,f,h)=>e.filter(d,f,h,s))),e.itemSort&&(a=a.sort((d,f)=>e.itemSort(d,f,s))),ae(a,d=>{const f=qg(e.callbacks,d);r.push(rt(f,"labelColor",this,d)),i.push(rt(f,"labelPointStyle",this,d)),o.push(rt(f,"labelTextColor",this,d))}),this.labelColors=r,this.labelPointStyles=i,this.labelTextColors=o,this.dataPoints=a,a}update(e,n){const s=this.options.setContext(this.getContext()),r=this._active;let i,o=[];if(!r.length)this.opacity!==0&&(i={opacity:0});else{const a=to[s.position].call(this,r,this._eventPosition);o=this._createItems(s),this.title=this.getTitle(o,s),this.beforeBody=this.getBeforeBody(o,s),this.body=this.getBody(o,s),this.afterBody=this.getAfterBody(o,s),this.footer=this.getFooter(o,s);const l=this._size=Qg(this,s),c=Object.assign({},a,l),d=Kg(this.chart,s,c),f=Yg(s,c,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,i={opacity:1,x:f.x,y:f.y,width:l.width,height:l.height,caretX:a.x,caretY:a.y}}this._tooltipItems=o,this.$context=void 0,i&&this._resolveAnimations().update(this,i),e&&s.external&&s.external.call(this,{chart:this.chart,tooltip:this,replay:n})}drawCaret(e,n,s,r){const i=this.getCaretPosition(e,s,r);n.lineTo(i.x1,i.y1),n.lineTo(i.x2,i.y2),n.lineTo(i.x3,i.y3)}getCaretPosition(e,n,s){const{xAlign:r,yAlign:i}=this,{caretSize:o,cornerRadius:a}=s,{topLeft:l,topRight:c,bottomLeft:d,bottomRight:f}=Wr(a),{x:h,y:p}=e,{width:m,height:g}=n;let b,y,x,v,_,w;return i==="center"?(_=p+g/2,r==="left"?(b=h,y=b-o,v=_+o,w=_-o):(b=h+m,y=b+o,v=_-o,w=_+o),x=b):(r==="left"?y=h+Math.max(l,d)+o:r==="right"?y=h+m-Math.max(c,f)-o:y=this.caretX,i==="top"?(v=p,_=v-o,b=y-o,x=y+o):(v=p+g,_=v+o,b=y+o,x=y-o),w=v),{x1:b,x2:y,x3:x,y1:v,y2:_,y3:w}}drawTitle(e,n,s){const r=this.title,i=r.length;let o,a,l;if(i){const c=Hr(s.rtl,this.x,this.width);for(e.x=$a(this,s.titleAlign,s),n.textAlign=c.textAlign(s.titleAlign),n.textBaseline="middle",o=ut(s.titleFont),a=s.titleSpacing,n.fillStyle=s.titleColor,n.font=o.string,l=0;l<i;++l)n.fillText(r[l],c.x(e.x),e.y+o.lineHeight/2),e.y+=o.lineHeight+a,l+1===i&&(e.y+=s.titleMarginBottom-a)}}_drawColorBox(e,n,s,r,i){const o=this.labelColors[s],a=this.labelPointStyles[s],{boxHeight:l,boxWidth:c}=i,d=ut(i.bodyFont),f=$a(this,"left",i),h=r.x(f),p=l<d.lineHeight?(d.lineHeight-l)/2:0,m=n.y+p;if(i.usePointStyle){const g={radius:Math.min(c,l)/2,pointStyle:a.pointStyle,rotation:a.rotation,borderWidth:1},b=r.leftForLtr(h,c)+c/2,y=m+l/2;e.strokeStyle=i.multiKeyBackground,e.fillStyle=i.multiKeyBackground,dg(e,g,b,y),e.strokeStyle=o.borderColor,e.fillStyle=o.backgroundColor,dg(e,g,b,y)}else{e.lineWidth=te(o.borderWidth)?Math.max(...Object.values(o.borderWidth)):o.borderWidth||1,e.strokeStyle=o.borderColor,e.setLineDash(o.borderDash||[]),e.lineDashOffset=o.borderDashOffset||0;const g=r.leftForLtr(h,c),b=r.leftForLtr(r.xPlus(h,1),c-2),y=Wr(o.borderRadius);Object.values(y).some(x=>x!==0)?(e.beginPath(),e.fillStyle=i.multiKeyBackground,Hl(e,{x:g,y:m,w:c,h:l,radius:y}),e.fill(),e.stroke(),e.fillStyle=o.backgroundColor,e.beginPath(),Hl(e,{x:b,y:m+1,w:c-2,h:l-2,radius:y}),e.fill()):(e.fillStyle=i.multiKeyBackground,e.fillRect(g,m,c,l),e.strokeRect(g,m,c,l),e.fillStyle=o.backgroundColor,e.fillRect(b,m+1,c-2,l-2))}e.fillStyle=this.labelTextColors[s]}drawBody(e,n,s){const{body:r}=this,{bodySpacing:i,bodyAlign:o,displayColors:a,boxHeight:l,boxWidth:c,boxPadding:d}=s,f=ut(s.bodyFont);let h=f.lineHeight,p=0;const m=Hr(s.rtl,this.x,this.width),g=function(j){n.fillText(j,m.x(e.x+p),e.y+h/2),e.y+=h+i},b=m.textAlign(o);let y,x,v,_,w,k,C;for(n.textAlign=o,n.textBaseline="middle",n.font=f.string,e.x=$a(this,b,s),n.fillStyle=s.bodyColor,ae(this.beforeBody,g),p=a&&b!=="right"?o==="center"?c/2+d:c+2+d:0,_=0,k=r.length;_<k;++_){for(y=r[_],x=this.labelTextColors[_],n.fillStyle=x,ae(y.before,g),v=y.lines,a&&v.length&&(this._drawColorBox(n,e,_,m,s),h=Math.max(f.lineHeight,l)),w=0,C=v.length;w<C;++w)g(v[w]),h=f.lineHeight;ae(y.after,g)}p=0,h=f.lineHeight,ae(this.afterBody,g),e.y-=i}drawFooter(e,n,s){const r=this.footer,i=r.length;let o,a;if(i){const l=Hr(s.rtl,this.x,this.width);for(e.x=$a(this,s.footerAlign,s),e.y+=s.footerMarginTop,n.textAlign=l.textAlign(s.footerAlign),n.textBaseline="middle",o=ut(s.footerFont),n.fillStyle=s.footerColor,n.font=o.string,a=0;a<i;++a)n.fillText(r[a],l.x(e.x),e.y+o.lineHeight/2),e.y+=o.lineHeight+s.footerSpacing}}drawBackground(e,n,s,r){const{xAlign:i,yAlign:o}=this,{x:a,y:l}=e,{width:c,height:d}=s,{topLeft:f,topRight:h,bottomLeft:p,bottomRight:m}=Wr(r.cornerRadius);n.fillStyle=r.backgroundColor,n.strokeStyle=r.borderColor,n.lineWidth=r.borderWidth,n.beginPath(),n.moveTo(a+f,l),o==="top"&&this.drawCaret(e,n,s,r),n.lineTo(a+c-h,l),n.quadraticCurveTo(a+c,l,a+c,l+h),o==="center"&&i==="right"&&this.drawCaret(e,n,s,r),n.lineTo(a+c,l+d-m),n.quadraticCurveTo(a+c,l+d,a+c-m,l+d),o==="bottom"&&this.drawCaret(e,n,s,r),n.lineTo(a+p,l+d),n.quadraticCurveTo(a,l+d,a,l+d-p),o==="center"&&i==="left"&&this.drawCaret(e,n,s,r),n.lineTo(a,l+f),n.quadraticCurveTo(a,l,a+f,l),n.closePath(),n.fill(),r.borderWidth>0&&n.stroke()}_updateAnimationTarget(e){const n=this.chart,s=this.$animations,r=s&&s.x,i=s&&s.y;if(r||i){const o=to[e.position].call(this,this._active,this._eventPosition);if(!o)return;const a=this._size=Qg(this,e),l=Object.assign({},o,this._size),c=Kg(n,e,l),d=Yg(e,l,c,n);(r._to!==d.x||i._to!==d.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=a.width,this.height=a.height,this.caretX=o.x,this.caretY=o.y,this._resolveAnimations().update(this,d))}}_willRender(){return!!this.opacity}draw(e){const n=this.options.setContext(this.getContext());let s=this.opacity;if(!s)return;this._updateAnimationTarget(n);const r={width:this.width,height:this.height},i={x:this.x,y:this.y};s=Math.abs(s)<.001?0:s;const o=Gt(n.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;n.enabled&&a&&(e.save(),e.globalAlpha=s,this.drawBackground(i,e,r,n),Fy(e,n.textDirection),i.y+=o.top,this.drawTitle(i,e,n),this.drawBody(i,e,n),this.drawFooter(i,e,n),zy(e,n.textDirection),e.restore())}getActiveElements(){return this._active||[]}setActiveElements(e,n){const s=this._active,r=e.map(({datasetIndex:a,index:l})=>{const c=this.chart.getDatasetMeta(a);if(!c)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:c.data[l],index:l}}),i=!Fl(s,r),o=this._positionChanged(r,n);(i||o)&&(this._active=r,this._eventPosition=n,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(e,n,s=!0){if(n&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const r=this.options,i=this._active||[],o=this._getActiveElements(e,i,n,s),a=this._positionChanged(o,e),l=n||!Fl(o,i)||a;return l&&(this._active=o,(r.enabled||r.external)&&(this._eventPosition={x:e.x,y:e.y},this.update(!0,n))),l}_getActiveElements(e,n,s,r){const i=this.options;if(e.type==="mouseout")return[];if(!r)return n.filter(a=>this.chart.data.datasets[a.datasetIndex]&&this.chart.getDatasetMeta(a.datasetIndex).controller.getParsed(a.index)!==void 0);const o=this.chart.getElementsAtEventForMode(e,i.mode,i,s);return i.reverse&&o.reverse(),o}_positionChanged(e,n){const{caretX:s,caretY:r,options:i}=this,o=to[i.position].call(this,e,n);return o!==!1&&(s!==o.x||r!==o.y)}}B(Fd,"positioners",to);var Gj={id:"tooltip",_element:Fd,positioners:to,afterInit(t,e,n){n&&(t.tooltip=new Fd({chart:t,options:n}))},beforeUpdate(t,e,n){t.tooltip&&t.tooltip.initialize(n)},reset(t,e,n){t.tooltip&&t.tooltip.initialize(n)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const n={tooltip:e};if(t.notifyPlugins("beforeTooltipDraw",{...n,cancelable:!0})===!1)return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",n)}},afterEvent(t,e){if(t.tooltip){const n=e.replay;t.tooltip.handleEvent(e.event,n,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:ev},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>t!=="filter"&&t!=="itemSort"&&t!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};const Jj=(t,e,n,s)=>(typeof e=="string"?(n=t.push(e)-1,s.unshift({index:n,label:e})):isNaN(e)&&(n=null),n);function Zj(t,e,n,s){const r=t.indexOf(e);if(r===-1)return Jj(t,e,n,s);const i=t.lastIndexOf(e);return r!==i?n:r}const eN=(t,e)=>t===null?null:ct(Math.round(t),0,e);function Gg(t){const e=this.getLabels();return t>=0&&t<e.length?e[t]:t}class zd extends Si{constructor(e){super(e),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(e){const n=this._addedLabels;if(n.length){const s=this.getLabels();for(const{index:r,label:i}of n)s[r]===i&&s.splice(r,1);this._addedLabels=[]}super.init(e)}parse(e,n){if(ue(e))return null;const s=this.getLabels();return n=isFinite(n)&&s[n]===e?n:Zj(s,e,Z(n,e),this._addedLabels),eN(n,s.length-1)}determineDataLimits(){const{minDefined:e,maxDefined:n}=this.getUserBounds();let{min:s,max:r}=this.getMinMax(!0);this.options.bounds==="ticks"&&(e||(s=0),n||(r=this.getLabels().length-1)),this.min=s,this.max=r}buildTicks(){const e=this.min,n=this.max,s=this.options.offset,r=[];let i=this.getLabels();i=e===0&&n===i.length-1?i:i.slice(e,n+1),this._valueRange=Math.max(i.length-(s?0:1),1),this._startValue=this.min-(s?.5:0);for(let o=e;o<=n;o++)r.push({value:o});return r}getLabelForValue(e){return Gg.call(this,e)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(e){return typeof e!="number"&&(e=this.parse(e)),e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getPixelForTick(e){const n=this.ticks;return e<0||e>n.length-1?null:this.getPixelForValue(n[e].value)}getValueForPixel(e){return Math.round(this._startValue+this.getDecimalForPixel(e)*this._valueRange)}getBasePixel(){return this.bottom}}B(zd,"id","category"),B(zd,"defaults",{ticks:{callback:Gg}});function tN(t,e){const n=[],{bounds:r,step:i,min:o,max:a,precision:l,count:c,maxTicks:d,maxDigits:f,includeBounds:h}=t,p=i||1,m=d-1,{min:g,max:b}=e,y=!ue(o),x=!ue(a),v=!ue(c),_=(b-g)/(f+1);let w=ng((b-g)/m/p)*p,k,C,j,M;if(w<1e-14&&!y&&!x)return[{value:g},{value:b}];M=Math.ceil(b/w)-Math.floor(g/w),M>m&&(w=ng(M*w/m/p)*p),ue(l)||(k=Math.pow(10,l),w=Math.ceil(w*k)/k),r==="ticks"?(C=Math.floor(g/w)*w,j=Math.ceil(b/w)*w):(C=g,j=b),y&&x&&i&&J_((a-o)/i,w/1e3)?(M=Math.round(Math.min((a-o)/w,d)),w=(a-o)/M,C=o,j=a):v?(C=y?o:C,j=x?a:j,M=c-1,w=(j-C)/M):(M=(j-C)/w,rl(M,Math.round(M),w/1e3)?M=Math.round(M):M=Math.ceil(M));const E=Math.max(sg(w),sg(C));k=Math.pow(10,ue(l)?E:l),C=Math.round(C*k)/k,j=Math.round(j*k)/k;let P=0;for(y&&(h&&C!==o?(n.push({value:o}),C<o&&P++,rl(Math.round((C+P*w)*k)/k,o,Jg(o,_,t))&&P++):C<o&&P++);P<M;++P){const A=Math.round((C+P*w)*k)/k;if(x&&A>a)break;n.push({value:A})}return x&&h&&j!==a?n.length&&rl(n[n.length-1].value,a,Jg(a,_,t))?n[n.length-1].value=a:n.push({value:a}):(!x||j===a)&&n.push({value:j}),n}function Jg(t,e,{horizontal:n,minRotation:s}){const r=Rn(s),i=(n?Math.sin(r):Math.cos(r))||.001,o=.75*e*(""+t).length;return Math.min(e/i,o)}class nN extends Si{constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(e,n){return ue(e)||(typeof e=="number"||e instanceof Number)&&!isFinite(+e)?null:+e}handleTickRangeOptions(){const{beginAtZero:e}=this.options,{minDefined:n,maxDefined:s}=this.getUserBounds();let{min:r,max:i}=this;const o=l=>r=n?r:l,a=l=>i=s?i:l;if(e){const l=Ss(r),c=Ss(i);l<0&&c<0?a(0):l>0&&c>0&&o(0)}if(r===i){let l=i===0?1:Math.abs(i*.05);a(i+l),e||o(r-l)}this.min=r,this.max=i}getTickLimit(){const e=this.options.ticks;let{maxTicksLimit:n,stepSize:s}=e,r;return s?(r=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,r>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${r} ticks. Limiting to 1000.`),r=1e3)):(r=this.computeTickLimit(),n=n||11),n&&(r=Math.min(n,r)),r}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const e=this.options,n=e.ticks;let s=this.getTickLimit();s=Math.max(2,s);const r={maxTicks:s,bounds:e.bounds,min:e.min,max:e.max,precision:n.precision,step:n.stepSize,count:n.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:n.minRotation||0,includeBounds:n.includeBounds!==!1},i=this._range||this,o=tN(r,i);return e.bounds==="ticks"&&Z_(o,this,"value"),e.reverse?(o.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),o}configure(){const e=this.ticks;let n=this.min,s=this.max;if(super.configure(),this.options.offset&&e.length){const r=(s-n)/Math.max(e.length-1,1)/2;n-=r,s+=r}this._startValue=n,this._endValue=s,this._valueRange=s-n}getLabelForValue(e){return qf(e,this.chart.options.locale,this.options.ticks.format)}}class Bd extends nN{determineDataLimits(){const{min:e,max:n}=this.getMinMax(!0);this.min=It(e)?e:0,this.max=It(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const e=this.isHorizontal(),n=e?this.width:this.height,s=Rn(this.options.ticks.minRotation),r=(e?Math.sin(s):Math.cos(s))||.001,i=this._resolveTickFontOptions(0);return Math.ceil(n/Math.min(40,i.lineHeight/r))}getPixelForValue(e){return e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getValueForPixel(e){return this._startValue+this.getDecimalForPixel(e)*this._valueRange}}B(Bd,"id","linear"),B(Bd,"defaults",{ticks:{callback:Py.formatters.numeric}});const _c={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},at=Object.keys(_c);function Zg(t,e){return t-e}function em(t,e){if(ue(e))return null;const n=t._adapter,{parser:s,round:r,isoWeekday:i}=t._parseOpts;let o=e;return typeof s=="function"&&(o=s(o)),It(o)||(o=typeof s=="string"?n.parse(o,s):n.parse(o)),o===null?null:(r&&(o=r==="week"&&($l(i)||i===!0)?n.startOf(o,"isoWeek",i):n.startOf(o,r)),+o)}function tm(t,e,n,s){const r=at.length;for(let i=at.indexOf(t);i<r-1;++i){const o=_c[at[i]],a=o.steps?o.steps:Number.MAX_SAFE_INTEGER;if(o.common&&Math.ceil((n-e)/(a*o.size))<=s)return at[i]}return at[r-1]}function sN(t,e,n,s,r){for(let i=at.length-1;i>=at.indexOf(n);i--){const o=at[i];if(_c[o].common&&t._adapter.diff(r,s,o)>=e-1)return o}return at[n?at.indexOf(n):0]}function rN(t){for(let e=at.indexOf(t)+1,n=at.length;e<n;++e)if(_c[at[e]].common)return at[e]}function nm(t,e,n){if(!n)t[e]=!0;else if(n.length){const{lo:s,hi:r}=Xf(n,e),i=n[s]>=e?n[s]:n[r];t[i]=!0}}function iN(t,e,n,s){const r=t._adapter,i=+r.startOf(e[0].value,s),o=e[e.length-1].value;let a,l;for(a=i;a<=o;a=+r.add(a,1,s))l=n[a],l>=0&&(e[l].major=!0);return e}function sm(t,e,n){const s=[],r={},i=e.length;let o,a;for(o=0;o<i;++o)a=e[o],r[a]=o,s.push({value:a,major:!1});return i===0||!n?s:iN(t,s,r,n)}class Yl extends Si{constructor(e){super(e),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(e,n={}){const s=e.time||(e.time={}),r=this._adapter=new xC._date(e.adapters.date);r.init(n),fo(s.displayFormats,r.formats()),this._parseOpts={parser:s.parser,round:s.round,isoWeekday:s.isoWeekday},super.init(e),this._normalized=n.normalized}parse(e,n){return e===void 0?null:em(this,e)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const e=this.options,n=this._adapter,s=e.time.unit||"day";let{min:r,max:i,minDefined:o,maxDefined:a}=this.getUserBounds();function l(c){!o&&!isNaN(c.min)&&(r=Math.min(r,c.min)),!a&&!isNaN(c.max)&&(i=Math.max(i,c.max))}(!o||!a)&&(l(this._getLabelBounds()),(e.bounds!=="ticks"||e.ticks.source!=="labels")&&l(this.getMinMax(!1))),r=It(r)&&!isNaN(r)?r:+n.startOf(Date.now(),s),i=It(i)&&!isNaN(i)?i:+n.endOf(Date.now(),s)+1,this.min=Math.min(r,i-1),this.max=Math.max(r+1,i)}_getLabelBounds(){const e=this.getLabelTimestamps();let n=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;return e.length&&(n=e[0],s=e[e.length-1]),{min:n,max:s}}buildTicks(){const e=this.options,n=e.time,s=e.ticks,r=s.source==="labels"?this.getLabelTimestamps():this._generate();e.bounds==="ticks"&&r.length&&(this.min=this._userMin||r[0],this.max=this._userMax||r[r.length-1]);const i=this.min,o=this.max,a=rk(r,i,o);return this._unit=n.unit||(s.autoSkip?tm(n.minUnit,this.min,this.max,this._getLabelCapacity(i)):sN(this,a.length,n.minUnit,this.min,this.max)),this._majorUnit=!s.major.enabled||this._unit==="year"?void 0:rN(this._unit),this.initOffsets(r),e.reverse&&a.reverse(),sm(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(e=>+e.value))}initOffsets(e=[]){let n=0,s=0,r,i;this.options.offset&&e.length&&(r=this.getDecimalForValue(e[0]),e.length===1?n=1-r:n=(this.getDecimalForValue(e[1])-r)/2,i=this.getDecimalForValue(e[e.length-1]),e.length===1?s=i:s=(i-this.getDecimalForValue(e[e.length-2]))/2);const o=e.length<3?.5:.25;n=ct(n,0,o),s=ct(s,0,o),this._offsets={start:n,end:s,factor:1/(n+1+s)}}_generate(){const e=this._adapter,n=this.min,s=this.max,r=this.options,i=r.time,o=i.unit||tm(i.minUnit,n,s,this._getLabelCapacity(n)),a=Z(r.ticks.stepSize,1),l=o==="week"?i.isoWeekday:!1,c=$l(l)||l===!0,d={};let f=n,h,p;if(c&&(f=+e.startOf(f,"isoWeek",l)),f=+e.startOf(f,c?"day":o),e.diff(s,n,o)>1e5*a)throw new Error(n+" and "+s+" are too far apart with stepSize of "+a+" "+o);const m=r.ticks.source==="data"&&this.getDataTimestamps();for(h=f,p=0;h<s;h=+e.add(h,a,o),p++)nm(d,h,m);return(h===s||r.bounds==="ticks"||p===1)&&nm(d,h,m),Object.keys(d).sort(Zg).map(g=>+g)}getLabelForValue(e){const n=this._adapter,s=this.options.time;return s.tooltipFormat?n.format(e,s.tooltipFormat):n.format(e,s.displayFormats.datetime)}format(e,n){const r=this.options.time.displayFormats,i=this._unit,o=n||r[i];return this._adapter.format(e,o)}_tickFormatFunction(e,n,s,r){const i=this.options,o=i.ticks.callback;if(o)return he(o,[e,n,s],this);const a=i.time.displayFormats,l=this._unit,c=this._majorUnit,d=l&&a[l],f=c&&a[c],h=s[n],p=c&&f&&h&&h.major;return this._adapter.format(e,r||(p?f:d))}generateTickLabels(e){let n,s,r;for(n=0,s=e.length;n<s;++n)r=e[n],r.label=this._tickFormatFunction(r.value,n,e)}getDecimalForValue(e){return e===null?NaN:(e-this.min)/(this.max-this.min)}getPixelForValue(e){const n=this._offsets,s=this.getDecimalForValue(e);return this.getPixelForDecimal((n.start+s)*n.factor)}getValueForPixel(e){const n=this._offsets,s=this.getDecimalForPixel(e)/n.factor-n.end;return this.min+s*(this.max-this.min)}_getLabelSize(e){const n=this.options.ticks,s=this.ctx.measureText(e).width,r=Rn(this.isHorizontal()?n.maxRotation:n.minRotation),i=Math.cos(r),o=Math.sin(r),a=this._resolveTickFontOptions(0).size;return{w:s*i+a*o,h:s*o+a*i}}_getLabelCapacity(e){const n=this.options.time,s=n.displayFormats,r=s[n.unit]||s.millisecond,i=this._tickFormatFunction(e,0,sm(this,[e],this._majorUnit),r),o=this._getLabelSize(i),a=Math.floor(this.isHorizontal()?this.width/o.w:this.height/o.h)-1;return a>0?a:1}getDataTimestamps(){let e=this._cache.data||[],n,s;if(e.length)return e;const r=this.getMatchingVisibleMetas();if(this._normalized&&r.length)return this._cache.data=r[0].controller.getAllParsedValues(this);for(n=0,s=r.length;n<s;++n)e=e.concat(r[n].controller.getAllParsedValues(this));return this._cache.data=this.normalize(e)}getLabelTimestamps(){const e=this._cache.labels||[];let n,s;if(e.length)return e;const r=this.getLabels();for(n=0,s=r.length;n<s;++n)e.push(em(this,r[n]));return this._cache.labels=this._normalized?e:this.normalize(e)}normalize(e){return Cy(e.sort(Zg))}}B(Yl,"id","time"),B(Yl,"defaults",{bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}});function Ua(t,e,n){let s=0,r=t.length-1,i,o,a,l;n?(e>=t[s].pos&&e<=t[r].pos&&({lo:s,hi:r}=Dd(t,"pos",e)),{pos:i,time:a}=t[s],{pos:o,time:l}=t[r]):(e>=t[s].time&&e<=t[r].time&&({lo:s,hi:r}=Dd(t,"time",e)),{time:i,pos:a}=t[s],{time:o,pos:l}=t[r]);const c=o-i;return c?a+(l-a)*(e-i)/c:a}class rm extends Yl{constructor(e){super(e),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const e=this._getTimestampsForTable(),n=this._table=this.buildLookupTable(e);this._minPos=Ua(n,this.min),this._tableRange=Ua(n,this.max)-this._minPos,super.initOffsets(e)}buildLookupTable(e){const{min:n,max:s}=this,r=[],i=[];let o,a,l,c,d;for(o=0,a=e.length;o<a;++o)c=e[o],c>=n&&c<=s&&r.push(c);if(r.length<2)return[{time:n,pos:0},{time:s,pos:1}];for(o=0,a=r.length;o<a;++o)d=r[o+1],l=r[o-1],c=r[o],Math.round((d+l)/2)!==c&&i.push({time:c,pos:o/(a-1)});return i}_generate(){const e=this.min,n=this.max;let s=super.getDataTimestamps();return(!s.includes(e)||!s.length)&&s.splice(0,0,e),(!s.includes(n)||s.length===1)&&s.push(n),s.sort((r,i)=>r-i)}_getTimestampsForTable(){let e=this._cache.all||[];if(e.length)return e;const n=this.getDataTimestamps(),s=this.getLabelTimestamps();return n.length&&s.length?e=this.normalize(n.concat(s)):e=n.length?n:s,e=this._cache.all=e,e}getDecimalForValue(e){return(Ua(this._table,e)-this._minPos)/this._tableRange}getValueForPixel(e){const n=this._offsets,s=this.getDecimalForPixel(e)/n.factor-n.end;return Ua(this._table,s*this._tableRange+this._minPos,!0)}}B(rm,"id","timeseries"),B(rm,"defaults",Yl.defaults);const tv="label";function im(t,e){typeof t=="function"?t(e):t&&(t.current=e)}function oN(t,e){const n=t.options;n&&e&&Object.assign(n,e)}function nv(t,e){t.labels=e}function sv(t,e,n=tv){const s=[];t.datasets=e.map(r=>{const i=t.datasets.find(o=>o[n]===r[n]);return!i||!r.data||s.includes(i)?{...r}:(s.push(i),Object.assign(i,r),i)})}function aN(t,e=tv){const n={labels:[],datasets:[]};return nv(n,t.labels),sv(n,t.datasets,e),n}function lN(t,e){const{height:n=150,width:s=300,redraw:r=!1,datasetIdKey:i,type:o,data:a,options:l,plugins:c=[],fallbackContent:d,updateMode:f,...h}=t,p=S.useRef(null),m=S.useRef(null),g=()=>{p.current&&(m.current=new Sc(p.current,{type:o,data:aN(a,i),options:l&&{...l},plugins:c}),im(e,m.current))},b=()=>{im(e,null),m.current&&(m.current.destroy(),m.current=null)};return S.useEffect(()=>{!r&&m.current&&l&&oN(m.current,l)},[r,l]),S.useEffect(()=>{!r&&m.current&&nv(m.current.config.data,a.labels)},[r,a.labels]),S.useEffect(()=>{!r&&m.current&&a.datasets&&sv(m.current.config.data,a.datasets,i)},[r,a.datasets]),S.useEffect(()=>{m.current&&(r?(b(),setTimeout(g)):m.current.update(f))},[r,l,a.labels,a.datasets,f]),S.useEffect(()=>{m.current&&(b(),setTimeout(g))},[o]),S.useEffect(()=>(g(),()=>b()),[]),u.jsx("canvas",{ref:p,role:"img",height:n,width:s,...h,children:d})}const cN=S.forwardRef(lN);function rv(t,e){return Sc.register(e),S.forwardRef((n,s)=>u.jsx(cN,{...n,ref:s,type:t}))}const uN=rv("bar",il),dN=rv("doughnut",Ji),pt=["leads","em_contato","proposta","fechado"],mn={leads:"Novos Leads",em_contato:"Em Contato",proposta:"Proposta",fechado:"Fechado"};Sc.register(eo,ll,zd,Bd,Wj,Gj);function fN({porEtapa:t}){const e=pt.map(r=>t[r]??0),n=e.reduce((r,i)=>r+i,0),s=Math.max(20,Math.ceil((Math.max(...e)+1)/20)*20);return n===0?u.jsxs("div",{className:"mt-4 h-64 flex flex-col items-center justify-center text-center gap-2 border-2 border-dashed border-gray-100 rounded-lg px-4",children:[u.jsx("i",{className:"fas fa-inbox text-2xl text-gray-300"}),u.jsx("p",{className:"text-sm text-gray-400",children:"Nenhum dado ainda. Comece extraindo leads!"}),u.jsx("p",{className:"text-xs text-gray-300",children:"Use os extratores (Maps, Instagram ou CNPJ) para popular o CRM."})]}):u.jsx("div",{className:"mt-4 h-64",children:u.jsx(uN,{data:{labels:pt.map(r=>mn[r]),datasets:[{label:"Quantidade",data:e,backgroundColor:["rgba(59, 130, 246, 0.8)","rgba(59, 130, 246, 0.6)","rgba(59, 130, 246, 0.4)","rgba(59, 130, 246, 0.3)"],borderRadius:4,barThickness:24}]},options:{indexAxis:"y",responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1}},scales:{x:{beginAtZero:!0,max:s,grid:{color:"#f3f4f6"},ticks:{stepSize:20}},y:{grid:{display:!1}}}}})})}function hN({enviadas:t,erros:e}){return t+e===0?u.jsxs("div",{className:"mt-4 h-64 flex flex-col items-center justify-center text-center gap-2 border-2 border-dashed border-gray-100 rounded-lg px-4",children:[u.jsx("i",{className:"fas fa-paper-plane text-2xl text-gray-300"}),u.jsx("p",{className:"text-sm text-gray-400",children:"Nenhuma campanha disparada ainda."}),u.jsx("p",{className:"text-xs text-gray-300",children:"Crie uma campanha em Disparos para ver o desempenho aqui."})]}):u.jsx("div",{className:"mt-4 h-64 flex items-center justify-center",children:u.jsx(dN,{data:{labels:["Enviadas","Erros"],datasets:[{data:[t,e],backgroundColor:["#3b82f6","#ef4444"],borderWidth:0}]},options:{responsive:!0,maintainAspectRatio:!1,cutout:"70%",plugins:{legend:{display:!1},tooltip:{callbacks:{label:n=>`${n.label}: ${n.parsed}`}}}}})})}const pN=1e4;function gN({nomeUsuario:t}){const{data:e,isPending:n,isError:s,error:r,refetch:i}=ey({queryKey:["metrics"],queryFn:()=>W.metricas(),refetchInterval:pN,refetchIntervalInBackground:!1}),o=n,a=s?r instanceof Error?r.message:"Falha ao carregar métricas.":"",l=e==null?void 0:e.perfil,c=l==null?void 0:l.licenca.restam_dias;return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{children:[u.jsxs("h1",{className:"text-2xl font-bold text-gray-800",children:["Olá, ",t," 👋 bem-vindo ao seu painel"]}),u.jsxs("div",{className:"mt-2 flex items-center justify-between text-sm text-gray-500",children:[u.jsxs("span",{children:[l!=null&&l.licenca.ativa?"Licença ativa":"Sem licença"," •"," ",l!=null&&l.licenca.expira_em?`expira em ${l.licenca.expira_em}`:"—"," • dados 100% locais"]}),c!=null&&u.jsxs("span",{children:["Restam ",u.jsx("strong",{className:"text-gray-700",children:c===null?"∞":`${c} dias`})]})]})]}),a&&u.jsxs("div",{className:"bg-red-50 border border-red-200 text-red-700 rounded-xl px-4 py-3 text-sm",children:[u.jsx("i",{className:"fas fa-exclamation-triangle mr-2"}),a]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[u.jsxs(Pa,{rotulo:"Status da Conexão",icone:"fas fa-plug",children:[u.jsx("div",{className:"mt-2 flex items-center",children:u.jsxs("span",{className:H("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",e!=null&&e.conexao.geral?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:[u.jsx("span",{className:H("w-2 h-2 mr-1.5 rounded-full",e!=null&&e.conexao.geral?"bg-green-500":"bg-red-500")}),e!=null&&e.conexao.geral?"Conectado":"Desconectado"]})}),u.jsxs("p",{className:"text-[11px] text-gray-400 mt-2",children:[u.jsx("i",{className:"fas fa-brain mr-1"}),e!=null&&e.conexao.llm?"LLM ✓":"LLM não configurado"," ·"," ",u.jsx("i",{className:"fas fa-paper-plane mr-1"}),e!=null&&e.conexao.openoutreach?"OpenOutreach ✓":"OpenOutreach não configurado"]})]}),u.jsx(Pa,{rotulo:"Taxa de entrega",valor:o?"—":`${(e==null?void 0:e.taxa_entrega)??0}%`,subtitulo:`${(e==null?void 0:e.total_enviadas)??0} enviadas • total`,icone:"fas fa-paper-plane"}),u.jsx(Pa,{rotulo:"Taxa de erro",valor:o?"—":`${(e==null?void 0:e.taxa_erro)??0}%`,subtitulo:`${(e==null?void 0:e.total_erros)??0} erros • total`,icone:"fas fa-triangle-exclamation"}),u.jsx(Pa,{rotulo:"Leads cadastrados",valor:o?"—":(e==null?void 0:e.leads_total)??0,subtitulo:"Total na base",icone:"fas fa-users"})]}),u.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm p-6 border border-gray-100",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"text-base font-semibold text-gray-800",children:"Leads por etapa (CRM)"}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Quantidade de leads em cada coluna do Kanban"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("span",{className:"text-[11px] text-gray-300 hidden sm:inline",title:"O painel atualiza sozinho",children:[u.jsx("i",{className:"fas fa-rotate mr-1"}),"a cada 10s"]}),u.jsx("button",{onClick:()=>i(),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Atualizar"})]})]}),e?u.jsx(fN,{porEtapa:e.leads_por_etapa}):u.jsx(mN,{})]}),u.jsxs("div",{className:"bg-white rounded-xl shadow-sm p-6 border border-gray-100",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"text-base font-semibold text-gray-800",children:"Desempenho das campanhas"}),u.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Agregação de todas as campanhas (Enviadas × Erros)"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("span",{className:"text-[11px] text-gray-300 hidden sm:inline",title:"O painel atualiza sozinho",children:[u.jsx("i",{className:"fas fa-rotate mr-1"}),"a cada 10s"]}),u.jsx("button",{onClick:()=>i(),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Atualizar"})]})]}),u.jsx(hN,{enviadas:(e==null?void 0:e.campanhas.enviadas)??0,erros:(e==null?void 0:e.campanhas.erros)??0}),u.jsxs("div",{className:"mt-4 flex items-center justify-center space-x-6 text-xs",children:[u.jsxs("span",{className:"flex items-center",children:[u.jsx("span",{className:"w-3 h-3 bg-blue-500 rounded-full mr-1.5"})," Enviadas (",(e==null?void 0:e.campanhas.enviadas)??0,")"]}),u.jsxs("span",{className:"flex items-center",children:[u.jsx("span",{className:"w-3 h-3 bg-red-500 rounded-full mr-1.5"})," Erros (",(e==null?void 0:e.campanhas.erros)??0,")"]})]})]})]})]})}function mN(){return u.jsx("div",{className:"mt-4 h-64 flex items-center justify-center text-gray-300",children:u.jsx("i",{className:"fas fa-spinner fa-spin text-2xl"})})}function Qt({titulo:t,icone:e="fas fa-sliders",children:n,abertoInicial:s=!1}){const[r,i]=S.useState(s);return u.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[u.jsxs("button",{type:"button",onClick:()=>i(o=>!o),className:"w-full flex items-center justify-between px-4 py-3 text-sm font-medium text-gray-600 bg-gray-50 hover:bg-gray-100 transition",children:[u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx("i",{className:H(e,"text-gray-400")})," ",t]}),u.jsx("i",{className:H("fas fa-chevron-down text-xs text-gray-400 transition-transform",r&&"rotate-180")})]}),r&&u.jsx("div",{className:"px-4 py-4 bg-white space-y-3",children:n})]})}function ra({valor:t,altura:e="md",mostrarLabel:n=!1,className:s}){const r=Math.max(0,Math.min(100,Math.round(t))),i={sm:"h-1.5",md:"h-2.5"};return u.jsxs("div",{className:H("w-full",s),children:[n&&u.jsxs("div",{className:"flex justify-between text-xs text-gray-500 mb-1",children:[u.jsx("span",{children:"Progresso"}),u.jsxs("span",{className:"font-semibold text-gray-700",children:[r,"%"]})]}),u.jsx("div",{className:H("w-full bg-gray-200 rounded-full overflow-hidden",i[e]),children:u.jsx("div",{className:H("h-full rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 transition-all duration-500"),style:{width:`${r}%`}})})]})}const xN={leads:"bg-blue-100 text-blue-800",em_contato:"bg-amber-100 text-amber-800",proposta:"bg-violet-100 text-violet-800",fechado:"bg-green-100 text-green-800",rascunho:"bg-gray-100 text-gray-600",em_andamento:"bg-blue-100 text-blue-800",pausado:"bg-amber-100 text-amber-800",pausada:"bg-amber-100 text-amber-800",concluido:"bg-green-100 text-green-800",cancelado:"bg-gray-100 text-gray-600",erro:"bg-red-100 text-red-800",concluida:"bg-green-100 text-green-800",pendente:"bg-gray-100 text-gray-600",pulada:"bg-gray-100 text-gray-500",enviada:"bg-green-100 text-green-800",ativo:"bg-green-100 text-green-800",inativo:"bg-gray-100 text-gray-600"},yN={leads:"Leads",em_contato:"Em contato",proposta:"Proposta",fechado:"Fechado",rascunho:"Rascunho",em_andamento:"Ativa",pausado:"Pausado",pausada:"Pausada",concluido:"Concluído",concluida:"Concluída",cancelado:"Cancelado",erro:"Erro",pendente:"Pendente",pulada:"Pulada",enviada:"Enviada",ativo:"Ativo",inativo:"Inativo",texto:"Texto",audio:"Áudio"};function sr({status:t,rotulo:e,className:n}){const s=xN[t]||"bg-gray-100 text-gray-600";return u.jsx("span",{className:H("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",s,n),children:e||yN[t]||t})}const vN={nome:"",telefone:"",email:"",fonte:"Manual",etapa:"leads"};function bN(){const{toast:t}=en(),[e,n]=S.useState([]),[s,r]=S.useState(""),[i,o]=S.useState("todas"),[a,l]=S.useState(!1),[c,d]=S.useState(null),[f,h]=S.useState(null),[p,m]=S.useState(null),g=S.useCallback(async()=>{n(await W.leads.listar())},[]);S.useEffect(()=>{g().catch(k=>t("erro",k.message))},[g,t]);const b=S.useMemo(()=>{const k=s.trim().toLowerCase();return e.filter(C=>{const j=!k||C.nome.toLowerCase().includes(k)||C.telefone.includes(k)||C.email.toLowerCase().includes(k),M=i==="todas"||C.etapa===i;return j&&M})},[e,s,i]),y=()=>{d({...vN}),l(!0)},x=k=>{d({...k}),l(!0)},v=async()=>{var k;if(!((k=c==null?void 0:c.nome)!=null&&k.trim())){t("erro","O nome do lead é obrigatório.");return}try{if(c.id){const{id:C,criado_em:j,atualizado_em:M,...E}=c;await W.leads.atualizar(C,E),t("sucesso","Lead atualizado.")}else await W.leads.criar(c),t("sucesso","Lead criado com sucesso.");l(!1),d(null),await g()}catch(C){t("erro",C instanceof Error?C.message:"Falha ao salvar lead.")}},_=async()=>{if(f)try{await W.leads.remover(f.id),t("sucesso",`Lead "${f.nome}" removido.`),h(null),await g()}catch(k){t("erro",k instanceof Error?k.message:"Falha ao remover.")}},w=async k=>{m(k.id);try{(await W.leads.enriquecer(k.id)).notas.forEach(j=>t("info",j)),t("sucesso","Lead enriquecido."),await g()}catch(C){t("erro",C instanceof Error?C.message:"Falha ao enriquecer.")}finally{m(null)}};return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[u.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-[280px]",children:[u.jsxs("div",{className:"relative flex-1 max-w-md",children:[u.jsx("i",{className:"fas fa-search absolute left-3 top-2.5 text-gray-400 text-sm"}),u.jsx("input",{value:s,onChange:k=>r(k.target.value),placeholder:"Buscar por nome, telefone ou e-mail...",className:"w-full pl-9 pr-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 focus:border-indigo-400 outline-none"})]}),u.jsxs("select",{value:i,onChange:k=>o(k.target.value),className:"text-sm border border-gray-200 rounded-lg px-3 py-2 bg-white focus:ring-2 focus:ring-indigo-400 outline-none",children:[u.jsx("option",{value:"todas",children:"Todas as etapas"}),pt.map(k=>u.jsx("option",{value:k,children:mn[k]},k))]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("button",{onClick:()=>d_(e,"leadmaster-leads.json"),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition",children:[u.jsx("i",{className:"fas fa-download mr-2"})," Exportar"]}),u.jsxs("button",{onClick:y,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition shadow-sm",children:[u.jsx("i",{className:"fas fa-plus mr-2"})," Novo Lead"]})]})]}),u.jsx("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100 bg-gray-50/50",children:[u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Lead"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Contato"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Etapa"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Completude"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Atualizado"}),u.jsx("th",{className:"px-5 py-3 font-semibold text-right",children:"Ações"})]})}),u.jsxs("tbody",{children:[b.map(k=>{const C=l_(k),j=c_(k);return u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40 transition",children:[u.jsxs("td",{className:"px-5 py-3",children:[u.jsx("p",{className:"font-medium text-gray-800",children:k.nome}),u.jsxs("p",{className:"text-xs text-gray-400",children:[k.fonte,k.empresa?` · ${k.empresa}`:""]})]}),u.jsxs("td",{className:"px-5 py-3 text-gray-600",children:[u.jsx("p",{children:k.telefone||"—"}),u.jsx("p",{className:"text-xs text-gray-400",children:k.email||"sem e-mail"})]}),u.jsx("td",{className:"px-5 py-3",children:u.jsx(sr,{status:k.etapa})}),u.jsxs("td",{className:"px-5 py-3 w-52",children:[u.jsx(ra,{valor:C,altura:"sm"}),u.jsx("p",{className:"text-[11px] text-gray-400 mt-1",children:u_(C,j)})]}),u.jsx("td",{className:"px-5 py-3 text-xs text-gray-400",children:Il(k.atualizado_em)}),u.jsxs("td",{className:"px-5 py-3 text-right whitespace-nowrap",children:[u.jsx("button",{onClick:()=>w(k),disabled:p===k.id,title:" Enriquecer com IA / BrasilAPI",className:"text-gray-400 hover:text-indigo-600 px-1.5 disabled:opacity-40",children:u.jsx("i",{className:H("fas fa-wand-magic-sparkles",p===k.id&&"fa-spin")})}),u.jsx("button",{onClick:()=>x(k),title:"Editar",className:"text-gray-400 hover:text-indigo-600 px-1.5",children:u.jsx("i",{className:"fas fa-pen"})}),u.jsx("button",{onClick:()=>h(k),title:"Excluir",className:"text-gray-400 hover:text-red-600 px-1.5",children:u.jsx("i",{className:"fas fa-trash"})})]})]},k.id)}),b.length===0&&u.jsx("tr",{children:u.jsxs("td",{colSpan:6,className:"px-5 py-16 text-center text-gray-400",children:[u.jsx("i",{className:"fas fa-users text-3xl text-gray-200 block mb-3"}),"Nenhum lead encontrado. Crie um novo ou importe pelos Extratores."]})})]})]})})}),u.jsx(Xt,{aberto:a,onFechar:()=>l(!1),titulo:c!=null&&c.id?"Editar lead":"Novo lead",icone:"fas fa-user-plus",children:c&&u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(As,{rotulo:"Nome *",valor:c.nome||"",onChange:k=>d({...c,nome:k})}),u.jsx(As,{rotulo:"Telefone",valor:c.telefone||"",onChange:k=>d({...c,telefone:k}),placeholder:"(11) 99999-9999"}),u.jsx(As,{rotulo:"E-mail",tipo:"email",valor:c.email||"",onChange:k=>d({...c,email:k}),placeholder:"contato@empresa.com.br"}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Etapa"}),u.jsx("select",{value:c.etapa||"leads",onChange:k=>d({...c,etapa:k.target.value}),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",children:pt.map(k=>u.jsx("option",{value:k,children:mn[k]},k))})]})]}),u.jsxs(Qt,{titulo:"Campos avançados",icone:"fas fa-sliders",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(As,{rotulo:"Empresa",valor:c.empresa||"",onChange:k=>d({...c,empresa:k})}),u.jsx(As,{rotulo:"CNPJ",valor:c.cnpj||"",onChange:k=>d({...c,cnpj:k}),placeholder:"00.000.000/0000-00"}),u.jsx(As,{rotulo:"Cidade",valor:c.cidade||"",onChange:k=>d({...c,cidade:k}),placeholder:"São Paulo/SP"}),u.jsx(As,{rotulo:"Fonte",valor:c.fonte||"",onChange:k=>d({...c,fonte:k}),placeholder:"Google Maps, Instagram, CNPJ..."})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Observações"}),u.jsx("textarea",{value:c.observacoes||"",onChange:k=>d({...c,observacoes:k.target.value}),rows:3,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",placeholder:"Histórico de conversas, próximos passos..."})]})]}),u.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[u.jsx("button",{onClick:()=>l(!1),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:v,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar"]})]})]})}),u.jsxs(Xt,{aberto:!!f,onFechar:()=>h(null),titulo:"Excluir lead",icone:"fas fa-trash",children:[u.jsxs("p",{className:"text-sm text-gray-600",children:["Tem certeza que deseja excluir ",u.jsx("strong",{children:f==null?void 0:f.nome}),"? Essa ação não pode ser desfeita."]}),u.jsxs("div",{className:"flex justify-end gap-3 mt-6",children:[u.jsx("button",{onClick:()=>h(null),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsx("button",{onClick:_,className:"px-6 py-2.5 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700",children:"Excluir"})]})]})]})}function As({rotulo:t,valor:e,onChange:n,tipo:s="text",placeholder:r}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("input",{type:s,value:e,onChange:i=>n(i.target.value),placeholder:r,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function wN(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return S.useMemo(()=>s=>{e.forEach(r=>r(s))},e)}const kc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function _i(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function oh(t){return"nodeType"in t}function st(t){var e,n;return t?_i(t)?t:oh(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function ah(t){const{Document:e}=st(t);return t instanceof e}function ia(t){return _i(t)?!1:t instanceof st(t).HTMLElement}function iv(t){return t instanceof st(t).SVGElement}function ki(t){return t?_i(t)?t.document:oh(t)?ah(t)?t:ia(t)||iv(t)?t.ownerDocument:document:document:document}const Jt=kc?S.useLayoutEffect:S.useEffect;function Cc(t){const e=S.useRef(t);return Jt(()=>{e.current=t}),S.useCallback(function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];return e.current==null?void 0:e.current(...s)},[])}function SN(){const t=S.useRef(null),e=S.useCallback((s,r)=>{t.current=setInterval(s,r)},[]),n=S.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function Uo(t,e){e===void 0&&(e=[t]);const n=S.useRef(t);return Jt(()=>{n.current!==t&&(n.current=t)},e),n}function oa(t,e){const n=S.useRef();return S.useMemo(()=>{const s=t(n.current);return n.current=s,s},[...e])}function Xl(t){const e=Cc(t),n=S.useRef(null),s=S.useCallback(r=>{r!==n.current&&(e==null||e(r,n.current)),n.current=r},[]);return[n,s]}function ql(t){const e=S.useRef();return S.useEffect(()=>{e.current=t},[t]),e.current}let vu={};function aa(t,e){return S.useMemo(()=>{if(e)return e;const n=vu[t]==null?0:vu[t]+1;return vu[t]=n,t+"-"+n},[t,e])}function ov(t){return function(e){for(var n=arguments.length,s=new Array(n>1?n-1:0),r=1;r<n;r++)s[r-1]=arguments[r];return s.reduce((i,o)=>{const a=Object.entries(o);for(const[l,c]of a){const d=i[l];d!=null&&(i[l]=d+t*c)}return i},{...e})}}const Qr=ov(1),Gl=ov(-1);function _N(t){return"clientX"in t&&"clientY"in t}function jc(t){if(!t)return!1;const{KeyboardEvent:e}=st(t.target);return e&&t instanceof e}function kN(t){if(!t)return!1;const{TouchEvent:e}=st(t.target);return e&&t instanceof e}function Jl(t){if(kN(t)){if(t.touches&&t.touches.length){const{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){const{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return _N(t)?{x:t.clientX,y:t.clientY}:null}const Ns=Object.freeze({Translate:{toString(t){if(!t)return;const{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;const{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[Ns.Translate.toString(t),Ns.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:s}=t;return e+" "+n+"ms "+s}}}),om="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function CN(t){return t.matches(om)?t:t.querySelector(om)}const jN={display:"none"};function NN(t){let{id:e,value:n}=t;return pe.createElement("div",{id:e,style:jN},n)}function EN(t){let{id:e,announcement:n,ariaLiveType:s="assertive"}=t;const r={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return pe.createElement("div",{id:e,style:r,role:"status","aria-live":s,"aria-atomic":!0},n)}function MN(){const[t,e]=S.useState("");return{announce:S.useCallback(s=>{s!=null&&e(s)},[]),announcement:t}}const av=S.createContext(null);function PN(t){const e=S.useContext(av);S.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(t)},[t,e])}function RN(){const[t]=S.useState(()=>new Set),e=S.useCallback(s=>(t.add(s),()=>t.delete(s)),[t]);return[S.useCallback(s=>{let{type:r,event:i}=s;t.forEach(o=>{var a;return(a=o[r])==null?void 0:a.call(o,i)})},[t]),e]}const ON={draggable:`
85
85
  To pick up a draggable item, press the space bar.
86
86
  While dragging, use the arrow keys to move the item.
87
87
  Press space again to drop the item in its new position, or press escape to cancel.
88
- `},TN={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function DN(t){let{announcements:e=TN,container:n,hiddenTextDescribedById:s,screenReaderInstructions:r=ON}=t;const{announce:i,announcement:o}=MN(),a=aa("DndLiveRegion"),[l,c]=S.useState(!1);if(S.useEffect(()=>{c(!0)},[]),PN(S.useMemo(()=>({onDragStart(f){let{active:h}=f;i(e.onDragStart({active:h}))},onDragMove(f){let{active:h,over:p}=f;e.onDragMove&&i(e.onDragMove({active:h,over:p}))},onDragOver(f){let{active:h,over:p}=f;i(e.onDragOver({active:h,over:p}))},onDragEnd(f){let{active:h,over:p}=f;i(e.onDragEnd({active:h,over:p}))},onDragCancel(f){let{active:h,over:p}=f;i(e.onDragCancel({active:h,over:p}))}}),[i,e])),!l)return null;const d=pe.createElement(pe.Fragment,null,pe.createElement(NN,{id:s,value:r.draggable}),pe.createElement(EN,{id:a,announcement:o}));return n?Ar.createPortal(d,n):d}var Te;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Te||(Te={}));function Zl(){}function LN(t,e){return S.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function AN(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return S.useMemo(()=>[...e].filter(s=>s!=null),[...e])}const Zt=Object.freeze({x:0,y:0});function IN(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function FN(t,e){const n=Jl(t);if(!n)return"0 0";const s={x:(n.x-e.left)/e.width*100,y:(n.y-e.top)/e.height*100};return s.x+"% "+s.y+"%"}function zN(t,e){let{data:{value:n}}=t,{data:{value:s}}=e;return n-s}function BN(t,e){let{data:{value:n}}=t,{data:{value:s}}=e;return s-n}function am(t){let{left:e,top:n,height:s,width:r}=t;return[{x:e,y:n},{x:e+r,y:n},{x:e,y:n+s},{x:e+r,y:n+s}]}function $N(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}const UN=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:s}=t;const r=am(e),i=[];for(const o of s){const{id:a}=o,l=n.get(a);if(l){const c=am(l),d=r.reduce((h,p,m)=>h+IN(c[m],p),0),f=Number((d/4).toFixed(4));i.push({id:a,data:{droppableContainer:o,value:f}})}}return i.sort(zN)};function WN(t,e){const n=Math.max(e.top,t.top),s=Math.max(e.left,t.left),r=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),o=r-s,a=i-n;if(s<r&&n<i){const l=e.width*e.height,c=t.width*t.height,d=o*a,f=d/(l+c-d);return Number(f.toFixed(4))}return 0}const HN=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:s}=t;const r=[];for(const i of s){const{id:o}=i,a=n.get(o);if(a){const l=WN(a,e);l>0&&r.push({id:o,data:{droppableContainer:i,value:l}})}}return r.sort(BN)};function VN(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function lv(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:Zt}function QN(t){return function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),i=1;i<s;i++)r[i-1]=arguments[i];return r.reduce((o,a)=>({...o,top:o.top+t*a.y,bottom:o.bottom+t*a.y,left:o.left+t*a.x,right:o.right+t*a.x}),{...n})}}const KN=QN(1);function cv(t){if(t.startsWith("matrix3d(")){const e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){const e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function YN(t,e,n){const s=cv(e);if(!s)return t;const{scaleX:r,scaleY:i,x:o,y:a}=s,l=t.left-o-(1-r)*parseFloat(n),c=t.top-a-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),d=r?t.width/r:t.width,f=i?t.height/i:t.height;return{width:d,height:f,top:c,right:l+d,bottom:c+f,left:l}}const XN={ignoreTransform:!1};function Ci(t,e){e===void 0&&(e=XN);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:c,transformOrigin:d}=st(t).getComputedStyle(t);c&&(n=YN(n,c,d))}const{top:s,left:r,width:i,height:o,bottom:a,right:l}=n;return{top:s,left:r,width:i,height:o,bottom:a,right:l}}function lm(t){return Ci(t,{ignoreTransform:!0})}function qN(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function GN(t,e){return e===void 0&&(e=st(t).getComputedStyle(t)),e.position==="fixed"}function JN(t,e){e===void 0&&(e=st(t).getComputedStyle(t));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(r=>{const i=e[r];return typeof i=="string"?n.test(i):!1})}function lh(t,e){const n=[];function s(r){if(e!=null&&n.length>=e||!r)return n;if(ah(r)&&r.scrollingElement!=null&&!n.includes(r.scrollingElement))return n.push(r.scrollingElement),n;if(!ia(r)||iv(r)||n.includes(r))return n;const i=st(t).getComputedStyle(r);return r!==t&&JN(r,i)&&n.push(r),GN(r,i)?n:s(r.parentNode)}return t?s(t):n}function uv(t){const[e]=lh(t,1);return e??null}function bu(t){return!kc||!t?null:_i(t)?t:oh(t)?ah(t)||t===ki(t).scrollingElement?window:ia(t)?t:null:null}function dv(t){return _i(t)?t.scrollX:t.scrollLeft}function fv(t){return _i(t)?t.scrollY:t.scrollTop}function $d(t){return{x:dv(t),y:fv(t)}}var Ie;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(Ie||(Ie={}));function hv(t){return!kc||!t?!1:t===document.scrollingElement}function pv(t){const e={x:0,y:0},n=hv(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},s={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},r=t.scrollTop<=e.y,i=t.scrollLeft<=e.x,o=t.scrollTop>=s.y,a=t.scrollLeft>=s.x;return{isTop:r,isLeft:i,isBottom:o,isRight:a,maxScroll:s,minScroll:e}}const ZN={x:.2,y:.2};function eE(t,e,n,s,r){let{top:i,left:o,right:a,bottom:l}=n;s===void 0&&(s=10),r===void 0&&(r=ZN);const{isTop:c,isBottom:d,isLeft:f,isRight:h}=pv(t),p={x:0,y:0},m={x:0,y:0},g={height:e.height*r.y,width:e.width*r.x};return!c&&i<=e.top+g.height?(p.y=Ie.Backward,m.y=s*Math.abs((e.top+g.height-i)/g.height)):!d&&l>=e.bottom-g.height&&(p.y=Ie.Forward,m.y=s*Math.abs((e.bottom-g.height-l)/g.height)),!h&&a>=e.right-g.width?(p.x=Ie.Forward,m.x=s*Math.abs((e.right-g.width-a)/g.width)):!f&&o<=e.left+g.width&&(p.x=Ie.Backward,m.x=s*Math.abs((e.left+g.width-o)/g.width)),{direction:p,speed:m}}function tE(t){if(t===document.scrollingElement){const{innerWidth:i,innerHeight:o}=window;return{top:0,left:0,right:i,bottom:o,width:i,height:o}}const{top:e,left:n,right:s,bottom:r}=t.getBoundingClientRect();return{top:e,left:n,right:s,bottom:r,width:t.clientWidth,height:t.clientHeight}}function gv(t){return t.reduce((e,n)=>Qr(e,$d(n)),Zt)}function nE(t){return t.reduce((e,n)=>e+dv(n),0)}function sE(t){return t.reduce((e,n)=>e+fv(n),0)}function mv(t,e){if(e===void 0&&(e=Ci),!t)return;const{top:n,left:s,bottom:r,right:i}=e(t);uv(t)&&(r<=0||i<=0||n>=window.innerHeight||s>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const rE=[["x",["left","right"],nE],["y",["top","bottom"],sE]];class ch{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=lh(n),r=gv(s);this.rect={...e},this.width=e.width,this.height=e.height;for(const[i,o,a]of rE)for(const l of o)Object.defineProperty(this,l,{get:()=>{const c=a(s),d=r[i]-c;return this.rect[l]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class go{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...n)})},this.target=e}add(e,n,s){var r;(r=this.target)==null||r.addEventListener(e,n,s),this.listeners.push([e,n,s])}}function iE(t){const{EventTarget:e}=st(t);return t instanceof e?t:ki(t)}function wu(t,e){const n=Math.abs(t.x),s=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+s**2)>e:"x"in e&&"y"in e?n>e.x&&s>e.y:"x"in e?n>e.x:"y"in e?s>e.y:!1}var Pt;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(Pt||(Pt={}));function cm(t){t.preventDefault()}function oE(t){t.stopPropagation()}var se;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(se||(se={}));const xv={start:[se.Space,se.Enter],cancel:[se.Esc],end:[se.Space,se.Enter,se.Tab]},aE=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case se.Right:return{...n,x:n.x+25};case se.Left:return{...n,x:n.x-25};case se.Down:return{...n,y:n.y+25};case se.Up:return{...n,y:n.y-25}}};class yv{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new go(ki(n)),this.windowListeners=new go(st(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Pt.Resize,this.handleCancel),this.windowListeners.add(Pt.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Pt.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,s=e.node.current;s&&mv(s),n(Zt)}handleKeyDown(e){if(jc(e)){const{active:n,context:s,options:r}=this.props,{keyboardCodes:i=xv,coordinateGetter:o=aE,scrollBehavior:a="smooth"}=r,{code:l}=e;if(i.end.includes(l)){this.handleEnd(e);return}if(i.cancel.includes(l)){this.handleCancel(e);return}const{collisionRect:c}=s.current,d=c?{x:c.left,y:c.top}:Zt;this.referenceCoordinates||(this.referenceCoordinates=d);const f=o(e,{active:n,context:s.current,currentCoordinates:d});if(f){const h=Gl(f,d),p={x:0,y:0},{scrollableAncestors:m}=s.current;for(const g of m){const b=e.code,{isTop:y,isRight:x,isLeft:v,isBottom:_,maxScroll:w,minScroll:k}=pv(g),C=tE(g),j={x:Math.min(b===se.Right?C.right-C.width/2:C.right,Math.max(b===se.Right?C.left:C.left+C.width/2,f.x)),y:Math.min(b===se.Down?C.bottom-C.height/2:C.bottom,Math.max(b===se.Down?C.top:C.top+C.height/2,f.y))},M=b===se.Right&&!x||b===se.Left&&!v,E=b===se.Down&&!_||b===se.Up&&!y;if(M&&j.x!==f.x){const P=g.scrollLeft+h.x,A=b===se.Right&&P<=w.x||b===se.Left&&P>=k.x;if(A&&!h.y){g.scrollTo({left:P,behavior:a});return}A?p.x=g.scrollLeft-P:p.x=b===se.Right?g.scrollLeft-w.x:g.scrollLeft-k.x,p.x&&g.scrollBy({left:-p.x,behavior:a});break}else if(E&&j.y!==f.y){const P=g.scrollTop+h.y,A=b===se.Down&&P<=w.y||b===se.Up&&P>=k.y;if(A&&!h.x){g.scrollTo({top:P,behavior:a});return}A?p.y=g.scrollTop-P:p.y=b===se.Down?g.scrollTop-w.y:g.scrollTop-k.y,p.y&&g.scrollBy({top:-p.y,behavior:a});break}}this.handleMove(e,Qr(Gl(f,this.referenceCoordinates),p))}}}handleMove(e,n){const{onMove:s}=this.props;e.preventDefault(),s(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}yv.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:s=xv,onActivation:r}=e,{active:i}=n;const{code:o}=t.nativeEvent;if(s.start.includes(o)){const a=i.activatorNode.current;return a&&t.target!==a?!1:(t.preventDefault(),r==null||r({event:t.nativeEvent}),!0)}return!1}}];function um(t){return!!(t&&"distance"in t)}function dm(t){return!!(t&&"delay"in t)}class uh{constructor(e,n,s){var r;s===void 0&&(s=iE(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:i}=e,{target:o}=i;this.props=e,this.events=n,this.document=ki(o),this.documentListeners=new go(this.document),this.listeners=new go(s),this.windowListeners=new go(st(o)),this.initialCoordinates=(r=Jl(i))!=null?r:Zt,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:s}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Pt.Resize,this.handleCancel),this.windowListeners.add(Pt.DragStart,cm),this.windowListeners.add(Pt.VisibilityChange,this.handleCancel),this.windowListeners.add(Pt.ContextMenu,cm),this.documentListeners.add(Pt.Keydown,this.handleKeydown),n){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(dm(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(um(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:s,onPending:r}=this.props;r(s,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(Pt.Click,oE,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Pt.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:s,initialCoordinates:r,props:i}=this,{onMove:o,options:{activationConstraint:a}}=i;if(!r)return;const l=(n=Jl(e))!=null?n:Zt,c=Gl(r,l);if(!s&&a){if(um(a)){if(a.tolerance!=null&&wu(c,a.tolerance))return this.handleCancel();if(wu(c,a.distance))return this.handleStart()}if(dm(a)&&wu(c,a.tolerance))return this.handleCancel();this.handlePending(a,c);return}e.cancelable&&e.preventDefault(),o(l)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===se.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const lE={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class dh extends uh{constructor(e){const{event:n}=e,s=ki(n.target);super(e,lE,s)}}dh.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:s}=e;return!n.isPrimary||n.button!==0?!1:(s==null||s({event:n}),!0)}}];const cE={move:{name:"mousemove"},end:{name:"mouseup"}};var Ud;(function(t){t[t.RightClick=2]="RightClick"})(Ud||(Ud={}));class uE extends uh{constructor(e){super(e,cE,ki(e.event.target))}}uE.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:s}=e;return n.button===Ud.RightClick?!1:(s==null||s({event:n}),!0)}}];const Su={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class dE extends uh{constructor(e){super(e,Su)}static setup(){return window.addEventListener(Su.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(Su.move.name,e)};function e(){}}}dE.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:s}=e;const{touches:r}=n;return r.length>1?!1:(s==null||s({event:n}),!0)}}];var mo;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(mo||(mo={}));var ec;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(ec||(ec={}));function fE(t){let{acceleration:e,activator:n=mo.Pointer,canScroll:s,draggingRect:r,enabled:i,interval:o=5,order:a=ec.TreeOrder,pointerCoordinates:l,scrollableAncestors:c,scrollableAncestorRects:d,delta:f,threshold:h}=t;const p=pE({delta:f,disabled:!i}),[m,g]=SN(),b=S.useRef({x:0,y:0}),y=S.useRef({x:0,y:0}),x=S.useMemo(()=>{switch(n){case mo.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case mo.DraggableRect:return r}},[n,r,l]),v=S.useRef(null),_=S.useCallback(()=>{const k=v.current;if(!k)return;const C=b.current.x*y.current.x,j=b.current.y*y.current.y;k.scrollBy(C,j)},[]),w=S.useMemo(()=>a===ec.TreeOrder?[...c].reverse():c,[a,c]);S.useEffect(()=>{if(!i||!c.length||!x){g();return}for(const k of w){if((s==null?void 0:s(k))===!1)continue;const C=c.indexOf(k),j=d[C];if(!j)continue;const{direction:M,speed:E}=eE(k,j,x,e,h);for(const P of["x","y"])p[P][M[P]]||(E[P]=0,M[P]=0);if(E.x>0||E.y>0){g(),v.current=k,m(_,o),b.current=E,y.current=M;return}}b.current={x:0,y:0},y.current={x:0,y:0},g()},[e,_,s,g,i,o,JSON.stringify(x),JSON.stringify(p),m,c,w,d,JSON.stringify(h)])}const hE={x:{[Ie.Backward]:!1,[Ie.Forward]:!1},y:{[Ie.Backward]:!1,[Ie.Forward]:!1}};function pE(t){let{delta:e,disabled:n}=t;const s=ql(e);return oa(r=>{if(n||!s||!r)return hE;const i={x:Math.sign(e.x-s.x),y:Math.sign(e.y-s.y)};return{x:{[Ie.Backward]:r.x[Ie.Backward]||i.x===-1,[Ie.Forward]:r.x[Ie.Forward]||i.x===1},y:{[Ie.Backward]:r.y[Ie.Backward]||i.y===-1,[Ie.Forward]:r.y[Ie.Forward]||i.y===1}}},[n,e,s])}function gE(t,e){const n=e!=null?t.get(e):void 0,s=n?n.node.current:null;return oa(r=>{var i;return e==null?null:(i=s??r)!=null?i:null},[s,e])}function mE(t,e){return S.useMemo(()=>t.reduce((n,s)=>{const{sensor:r}=s,i=r.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,s)}));return[...n,...i]},[]),[t,e])}var Wo;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(Wo||(Wo={}));var Wd;(function(t){t.Optimized="optimized"})(Wd||(Wd={}));const fm=new Map;function xE(t,e){let{dragging:n,dependencies:s,config:r}=e;const[i,o]=S.useState(null),{frequency:a,measure:l,strategy:c}=r,d=S.useRef(t),f=b(),h=Uo(f),p=S.useCallback(function(y){y===void 0&&(y=[]),!h.current&&o(x=>x===null?y:x.concat(y.filter(v=>!x.includes(v))))},[h]),m=S.useRef(null),g=oa(y=>{if(f&&!n)return fm;if(!y||y===fm||d.current!==t||i!=null){const x=new Map;for(let v of t){if(!v)continue;if(i&&i.length>0&&!i.includes(v.id)&&v.rect.current){x.set(v.id,v.rect.current);continue}const _=v.node.current,w=_?new ch(l(_),_):null;v.rect.current=w,w&&x.set(v.id,w)}return x}return y},[t,i,n,f,l]);return S.useEffect(()=>{d.current=t},[t]),S.useEffect(()=>{f||p()},[n,f]),S.useEffect(()=>{i&&i.length>0&&o(null)},[JSON.stringify(i)]),S.useEffect(()=>{f||typeof a!="number"||m.current!==null||(m.current=setTimeout(()=>{p(),m.current=null},a))},[a,f,p,...s]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:i!=null};function b(){switch(c){case Wo.Always:return!1;case Wo.BeforeDragging:return n;default:return!n}}}function fh(t,e){return oa(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function yE(t,e){return fh(t,e)}function vE(t){let{callback:e,disabled:n}=t;const s=Cc(e),r=S.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(s)},[s,n]);return S.useEffect(()=>()=>r==null?void 0:r.disconnect(),[r]),r}function Nc(t){let{callback:e,disabled:n}=t;const s=Cc(e),r=S.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(s)},[n]);return S.useEffect(()=>()=>r==null?void 0:r.disconnect(),[r]),r}function bE(t){return new ch(Ci(t),t)}function hm(t,e,n){e===void 0&&(e=bE);const[s,r]=S.useState(null);function i(){r(l=>{if(!t)return null;if(t.isConnected===!1){var c;return(c=l??n)!=null?c:null}const d=e(t);return JSON.stringify(l)===JSON.stringify(d)?l:d})}const o=vE({callback(l){if(t)for(const c of l){const{type:d,target:f}=c;if(d==="childList"&&f instanceof HTMLElement&&f.contains(t)){i();break}}}}),a=Nc({callback:i});return Jt(()=>{i(),t?(a==null||a.observe(t),o==null||o.observe(document.body,{childList:!0,subtree:!0})):(a==null||a.disconnect(),o==null||o.disconnect())},[t]),s}function wE(t){const e=fh(t);return lv(t,e)}const pm=[];function SE(t){const e=S.useRef(t),n=oa(s=>t?s&&s!==pm&&t&&e.current&&t.parentNode===e.current.parentNode?s:lh(t):pm,[t]);return S.useEffect(()=>{e.current=t},[t]),n}function _E(t){const[e,n]=S.useState(null),s=S.useRef(t),r=S.useCallback(i=>{const o=bu(i.target);o&&n(a=>a?(a.set(o,$d(o)),new Map(a)):null)},[]);return S.useEffect(()=>{const i=s.current;if(t!==i){o(i);const a=t.map(l=>{const c=bu(l);return c?(c.addEventListener("scroll",r,{passive:!0}),[c,$d(c)]):null}).filter(l=>l!=null);n(a.length?new Map(a):null),s.current=t}return()=>{o(t),o(i)};function o(a){a.forEach(l=>{const c=bu(l);c==null||c.removeEventListener("scroll",r)})}},[r,t]),S.useMemo(()=>t.length?e?Array.from(e.values()).reduce((i,o)=>Qr(i,o),Zt):gv(t):Zt,[t,e])}function gm(t,e){e===void 0&&(e=[]);const n=S.useRef(null);return S.useEffect(()=>{n.current=null},e),S.useEffect(()=>{const s=t!==Zt;s&&!n.current&&(n.current=t),!s&&n.current&&(n.current=null)},[t]),n.current?Gl(t,n.current):Zt}function kE(t){S.useEffect(()=>{if(!kc)return;const e=t.map(n=>{let{sensor:s}=n;return s.setup==null?void 0:s.setup()});return()=>{for(const n of e)n==null||n()}},t.map(e=>{let{sensor:n}=e;return n}))}function CE(t,e){return S.useMemo(()=>t.reduce((n,s)=>{let{eventName:r,handler:i}=s;return n[r]=o=>{i(o,e)},n},{}),[t,e])}function vv(t){return S.useMemo(()=>t?qN(t):null,[t])}const mm=[];function jE(t,e){e===void 0&&(e=Ci);const[n]=t,s=vv(n?st(n):null),[r,i]=S.useState(mm);function o(){i(()=>t.length?t.map(l=>hv(l)?s:new ch(e(l),l)):mm)}const a=Nc({callback:o});return Jt(()=>{a==null||a.disconnect(),o(),t.forEach(l=>a==null?void 0:a.observe(l))},[t]),r}function bv(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return ia(e)?e:t}function NE(t){let{measure:e}=t;const[n,s]=S.useState(null),r=S.useCallback(c=>{for(const{target:d}of c)if(ia(d)){s(f=>{const h=e(d);return f?{...f,width:h.width,height:h.height}:h});break}},[e]),i=Nc({callback:r}),o=S.useCallback(c=>{const d=bv(c);i==null||i.disconnect(),d&&(i==null||i.observe(d)),s(d?e(d):null)},[e,i]),[a,l]=Xl(o);return S.useMemo(()=>({nodeRef:a,rect:n,setRef:l}),[n,a,l])}const EE=[{sensor:dh,options:{}},{sensor:yv,options:{}}],ME={current:{}},cl={draggable:{measure:lm},droppable:{measure:lm,strategy:Wo.WhileDragging,frequency:Wd.Optimized},dragOverlay:{measure:Ci}};class xo extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,s;return(n=(s=this.get(e))==null?void 0:s.node.current)!=null?n:void 0}}const PE={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new xo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Zl},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:cl,measureDroppableContainers:Zl,windowRect:null,measuringScheduled:!1},wv={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Zl,draggableNodes:new Map,over:null,measureDroppableContainers:Zl},la=S.createContext(wv),Sv=S.createContext(PE);function RE(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new xo}}}function OE(t,e){switch(e.type){case Te.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case Te.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case Te.DragEnd:case Te.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Te.RegisterDroppable:{const{element:n}=e,{id:s}=n,r=new xo(t.droppable.containers);return r.set(s,n),{...t,droppable:{...t.droppable,containers:r}}}case Te.SetDroppableDisabled:{const{id:n,key:s,disabled:r}=e,i=t.droppable.containers.get(n);if(!i||s!==i.key)return t;const o=new xo(t.droppable.containers);return o.set(n,{...i,disabled:r}),{...t,droppable:{...t.droppable,containers:o}}}case Te.UnregisterDroppable:{const{id:n,key:s}=e,r=t.droppable.containers.get(n);if(!r||s!==r.key)return t;const i=new xo(t.droppable.containers);return i.delete(n),{...t,droppable:{...t.droppable,containers:i}}}default:return t}}function TE(t){let{disabled:e}=t;const{active:n,activatorEvent:s,draggableNodes:r}=S.useContext(la),i=ql(s),o=ql(n==null?void 0:n.id);return S.useEffect(()=>{if(!e&&!s&&i&&o!=null){if(!jc(i)||document.activeElement===i.target)return;const a=r.get(o);if(!a)return;const{activatorNode:l,node:c}=a;if(!l.current&&!c.current)return;requestAnimationFrame(()=>{for(const d of[l.current,c.current]){if(!d)continue;const f=CN(d);if(f){f.focus();break}}})}},[s,e,r,o,i]),null}function _v(t,e){let{transform:n,...s}=e;return t!=null&&t.length?t.reduce((r,i)=>i({transform:r,...s}),n):n}function DE(t){return S.useMemo(()=>({draggable:{...cl.draggable,...t==null?void 0:t.draggable},droppable:{...cl.droppable,...t==null?void 0:t.droppable},dragOverlay:{...cl.dragOverlay,...t==null?void 0:t.dragOverlay}}),[t==null?void 0:t.draggable,t==null?void 0:t.droppable,t==null?void 0:t.dragOverlay])}function LE(t){let{activeNode:e,measure:n,initialRect:s,config:r=!0}=t;const i=S.useRef(!1),{x:o,y:a}=typeof r=="boolean"?{x:r,y:r}:r;Jt(()=>{if(!o&&!a||!e){i.current=!1;return}if(i.current||!s)return;const c=e==null?void 0:e.node.current;if(!c||c.isConnected===!1)return;const d=n(c),f=lv(d,s);if(o||(f.x=0),a||(f.y=0),i.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const h=uv(c);h&&h.scrollBy({top:f.y,left:f.x})}},[e,o,a,s,n])}const Ec=S.createContext({...Zt,scaleX:1,scaleY:1});var Yn;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(Yn||(Yn={}));const AE=S.memo(function(e){var n,s,r,i;let{id:o,accessibility:a,autoScroll:l=!0,children:c,sensors:d=EE,collisionDetection:f=HN,measuring:h,modifiers:p,...m}=e;const g=S.useReducer(OE,void 0,RE),[b,y]=g,[x,v]=RN(),[_,w]=S.useState(Yn.Uninitialized),k=_===Yn.Initialized,{draggable:{active:C,nodes:j,translate:M},droppable:{containers:E}}=b,P=C!=null?j.get(C):null,A=S.useRef({initial:null,translated:null}),Q=S.useMemo(()=>{var Ve;return C!=null?{id:C,data:(Ve=P==null?void 0:P.data)!=null?Ve:ME,rect:A}:null},[C,P]),ne=S.useRef(null),[Y,oe]=S.useState(null),[G,O]=S.useState(null),L=Uo(m,Object.values(m)),I=aa("DndDescribedBy",o),V=S.useMemo(()=>E.getEnabled(),[E]),F=DE(h),{droppableRects:ce,measureDroppableContainers:$,measuringScheduled:ke}=xE(V,{dragging:k,dependencies:[M.x,M.y],config:F.droppable}),J=gE(j,C),gt=S.useMemo(()=>G?Jl(G):null,[G]),Ft=zv(),zt=yE(J,F.draggable.measure);LE({activeNode:C!=null?j.get(C):null,config:Ft.layoutShiftCompensation,initialRect:zt,measure:F.draggable.measure});const ie=hm(J,F.draggable.measure,zt),ji=hm(J?J.parentElement:null),tn=S.useRef({activatorEvent:null,active:null,activeNode:J,collisionRect:null,collisions:null,droppableRects:ce,draggableNodes:j,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),pr=E.getNodeFor((n=tn.current.over)==null?void 0:n.id),vn=NE({measure:F.dragOverlay.measure}),gr=(s=vn.nodeRef.current)!=null?s:J,mr=k?(r=vn.rect)!=null?r:ie:null,hh=!!(vn.nodeRef.current&&vn.rect),ph=wE(hh?null:ie),Mc=vv(gr?st(gr):null),Fn=SE(k?pr??J:null),ca=jE(Fn),ua=_v(p,{transform:{x:M.x-ph.x,y:M.y-ph.y,scaleX:1,scaleY:1},activatorEvent:G,active:Q,activeNodeRect:ie,containerNodeRect:ji,draggingNodeRect:mr,over:tn.current.over,overlayNodeRect:vn.rect,scrollableAncestors:Fn,scrollableAncestorRects:ca,windowRect:Mc}),gh=gt?Qr(gt,M):null,mh=_E(Fn),Ov=gm(mh),Tv=gm(mh,[ie]),xr=Qr(ua,Ov),yr=mr?KN(mr,ua):null,Ni=Q&&yr?f({active:Q,collisionRect:yr,droppableRects:ce,droppableContainers:V,pointerCoordinates:gh}):null,xh=$N(Ni,"id"),[zn,yh]=S.useState(null),Dv=hh?ua:Qr(ua,Tv),Lv=VN(Dv,(i=zn==null?void 0:zn.rect)!=null?i:null,ie),Pc=S.useRef(null),vh=S.useCallback((Ve,mt)=>{let{sensor:xt,options:Bn}=mt;if(ne.current==null)return;const Nt=j.get(ne.current);if(!Nt)return;const yt=Ve.nativeEvent,nn=new xt({active:ne.current,activeNode:Nt,event:yt,options:Bn,context:tn,onAbort(Be){if(!j.get(Be))return;const{onDragAbort:sn}=L.current,bn={id:Be};sn==null||sn(bn),x({type:"onDragAbort",event:bn})},onPending(Be,$n,sn,bn){if(!j.get(Be))return;const{onDragPending:Mi}=L.current,Un={id:Be,constraint:$n,initialCoordinates:sn,offset:bn};Mi==null||Mi(Un),x({type:"onDragPending",event:Un})},onStart(Be){const $n=ne.current;if($n==null)return;const sn=j.get($n);if(!sn)return;const{onDragStart:bn}=L.current,Ei={activatorEvent:yt,active:{id:$n,data:sn.data,rect:A}};Ar.unstable_batchedUpdates(()=>{bn==null||bn(Ei),w(Yn.Initializing),y({type:Te.DragStart,initialCoordinates:Be,active:$n}),x({type:"onDragStart",event:Ei}),oe(Pc.current),O(yt)})},onMove(Be){y({type:Te.DragMove,coordinates:Be})},onEnd:vr(Te.DragEnd),onCancel:vr(Te.DragCancel)});Pc.current=nn;function vr(Be){return async function(){const{active:sn,collisions:bn,over:Ei,scrollAdjustedTranslate:Mi}=tn.current;let Un=null;if(sn&&Mi){const{cancelDrop:Pi}=L.current;Un={activatorEvent:yt,active:sn,collisions:bn,delta:Mi,over:Ei},Be===Te.DragEnd&&typeof Pi=="function"&&await Promise.resolve(Pi(Un))&&(Be=Te.DragCancel)}ne.current=null,Ar.unstable_batchedUpdates(()=>{y({type:Be}),w(Yn.Uninitialized),yh(null),oe(null),O(null),Pc.current=null;const Pi=Be===Te.DragEnd?"onDragEnd":"onDragCancel";if(Un){const Rc=L.current[Pi];Rc==null||Rc(Un),x({type:Pi,event:Un})}})}}},[j]),Av=S.useCallback((Ve,mt)=>(xt,Bn)=>{const Nt=xt.nativeEvent,yt=j.get(Bn);if(ne.current!==null||!yt||Nt.dndKit||Nt.defaultPrevented)return;const nn={active:yt};Ve(xt,mt.options,nn)===!0&&(Nt.dndKit={capturedBy:mt.sensor},ne.current=Bn,vh(xt,mt))},[j,vh]),bh=mE(d,Av);kE(d),Jt(()=>{ie&&_===Yn.Initializing&&w(Yn.Initialized)},[ie,_]),S.useEffect(()=>{const{onDragMove:Ve}=L.current,{active:mt,activatorEvent:xt,collisions:Bn,over:Nt}=tn.current;if(!mt||!xt)return;const yt={active:mt,activatorEvent:xt,collisions:Bn,delta:{x:xr.x,y:xr.y},over:Nt};Ar.unstable_batchedUpdates(()=>{Ve==null||Ve(yt),x({type:"onDragMove",event:yt})})},[xr.x,xr.y]),S.useEffect(()=>{const{active:Ve,activatorEvent:mt,collisions:xt,droppableContainers:Bn,scrollAdjustedTranslate:Nt}=tn.current;if(!Ve||ne.current==null||!mt||!Nt)return;const{onDragOver:yt}=L.current,nn=Bn.get(xh),vr=nn&&nn.rect.current?{id:nn.id,rect:nn.rect.current,data:nn.data,disabled:nn.disabled}:null,Be={active:Ve,activatorEvent:mt,collisions:xt,delta:{x:Nt.x,y:Nt.y},over:vr};Ar.unstable_batchedUpdates(()=>{yh(vr),yt==null||yt(Be),x({type:"onDragOver",event:Be})})},[xh]),Jt(()=>{tn.current={activatorEvent:G,active:Q,activeNode:J,collisionRect:yr,collisions:Ni,droppableRects:ce,draggableNodes:j,draggingNode:gr,draggingNodeRect:mr,droppableContainers:E,over:zn,scrollableAncestors:Fn,scrollAdjustedTranslate:xr},A.current={initial:mr,translated:yr}},[Q,J,Ni,yr,j,gr,mr,ce,E,zn,Fn,xr]),fE({...Ft,delta:M,draggingRect:yr,pointerCoordinates:gh,scrollableAncestors:Fn,scrollableAncestorRects:ca});const Iv=S.useMemo(()=>({active:Q,activeNode:J,activeNodeRect:ie,activatorEvent:G,collisions:Ni,containerNodeRect:ji,dragOverlay:vn,draggableNodes:j,droppableContainers:E,droppableRects:ce,over:zn,measureDroppableContainers:$,scrollableAncestors:Fn,scrollableAncestorRects:ca,measuringConfiguration:F,measuringScheduled:ke,windowRect:Mc}),[Q,J,ie,G,Ni,ji,vn,j,E,ce,zn,$,Fn,ca,F,ke,Mc]),Fv=S.useMemo(()=>({activatorEvent:G,activators:bh,active:Q,activeNodeRect:ie,ariaDescribedById:{draggable:I},dispatch:y,draggableNodes:j,over:zn,measureDroppableContainers:$}),[G,bh,Q,ie,y,I,j,zn,$]);return pe.createElement(av.Provider,{value:v},pe.createElement(la.Provider,{value:Fv},pe.createElement(Sv.Provider,{value:Iv},pe.createElement(Ec.Provider,{value:Lv},c)),pe.createElement(TE,{disabled:(a==null?void 0:a.restoreFocus)===!1})),pe.createElement(DN,{...a,hiddenTextDescribedById:I}));function zv(){const Ve=(Y==null?void 0:Y.autoScrollEnabled)===!1,mt=typeof l=="object"?l.enabled===!1:l===!1,xt=k&&!Ve&&!mt;return typeof l=="object"?{...l,enabled:xt}:{enabled:xt}}}),IE=S.createContext(null),xm="button",FE="Draggable";function zE(t){let{id:e,data:n,disabled:s=!1,attributes:r}=t;const i=aa(FE),{activators:o,activatorEvent:a,active:l,activeNodeRect:c,ariaDescribedById:d,draggableNodes:f,over:h}=S.useContext(la),{role:p=xm,roleDescription:m="draggable",tabIndex:g=0}=r??{},b=(l==null?void 0:l.id)===e,y=S.useContext(b?Ec:IE),[x,v]=Xl(),[_,w]=Xl(),k=CE(o,e),C=Uo(n);Jt(()=>(f.set(e,{id:e,key:i,node:x,activatorNode:_,data:C}),()=>{const M=f.get(e);M&&M.key===i&&f.delete(e)}),[f,e]);const j=S.useMemo(()=>({role:p,tabIndex:g,"aria-disabled":s,"aria-pressed":b&&p===xm?!0:void 0,"aria-roledescription":m,"aria-describedby":d.draggable}),[s,p,g,b,m,d.draggable]);return{active:l,activatorEvent:a,activeNodeRect:c,attributes:j,isDragging:b,listeners:s?void 0:k,node:x,over:h,setNodeRef:v,setActivatorNodeRef:w,transform:y}}function kv(){return S.useContext(Sv)}const BE="Droppable",$E={timeout:25};function Cv(t){let{data:e,disabled:n=!1,id:s,resizeObserverConfig:r}=t;const i=aa(BE),{active:o,dispatch:a,over:l,measureDroppableContainers:c}=S.useContext(la),d=S.useRef({disabled:n}),f=S.useRef(!1),h=S.useRef(null),p=S.useRef(null),{disabled:m,updateMeasurementsFor:g,timeout:b}={...$E,...r},y=Uo(g??s),x=S.useCallback(()=>{if(!f.current){f.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{c(Array.isArray(y.current)?y.current:[y.current]),p.current=null},b)},[b]),v=Nc({callback:x,disabled:m||!o}),_=S.useCallback((j,M)=>{v&&(M&&(v.unobserve(M),f.current=!1),j&&v.observe(j))},[v]),[w,k]=Xl(_),C=Uo(e);return S.useEffect(()=>{!v||!w.current||(v.disconnect(),f.current=!1,v.observe(w.current))},[w,v]),S.useEffect(()=>(a({type:Te.RegisterDroppable,element:{id:s,key:i,disabled:n,node:w,rect:h,data:C}}),()=>a({type:Te.UnregisterDroppable,key:i,id:s})),[s]),S.useEffect(()=>{n!==d.current.disabled&&(a({type:Te.SetDroppableDisabled,id:s,key:i,disabled:n}),d.current.disabled=n)},[s,i,n,a]),{active:o,rect:h,isOver:(l==null?void 0:l.id)===s,node:w,over:l,setNodeRef:k}}function UE(t){let{animation:e,children:n}=t;const[s,r]=S.useState(null),[i,o]=S.useState(null),a=ql(n);return!n&&!s&&a&&r(a),Jt(()=>{if(!i)return;const l=s==null?void 0:s.key,c=s==null?void 0:s.props.id;if(l==null||c==null){r(null);return}Promise.resolve(e(c,i)).then(()=>{r(null)})},[e,s,i]),pe.createElement(pe.Fragment,null,n,s?S.cloneElement(s,{ref:o}):null)}const WE={x:0,y:0,scaleX:1,scaleY:1};function HE(t){let{children:e}=t;return pe.createElement(la.Provider,{value:wv},pe.createElement(Ec.Provider,{value:WE},e))}const VE={position:"fixed",touchAction:"none"},QE=t=>jc(t)?"transform 250ms ease":void 0,KE=S.forwardRef((t,e)=>{let{as:n,activatorEvent:s,adjustScale:r,children:i,className:o,rect:a,style:l,transform:c,transition:d=QE}=t;if(!a)return null;const f=r?c:{...c,scaleX:1,scaleY:1},h={...VE,width:a.width,height:a.height,top:a.top,left:a.left,transform:Ns.Transform.toString(f),transformOrigin:r&&s?FN(s,a):void 0,transition:typeof d=="function"?d(s):d,...l};return pe.createElement(n,{className:o,style:h,ref:e},i)}),YE=t=>e=>{let{active:n,dragOverlay:s}=e;const r={},{styles:i,className:o}=t;if(i!=null&&i.active)for(const[a,l]of Object.entries(i.active))l!==void 0&&(r[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,l));if(i!=null&&i.dragOverlay)for(const[a,l]of Object.entries(i.dragOverlay))l!==void 0&&s.node.style.setProperty(a,l);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&s.node.classList.add(o.dragOverlay),function(){for(const[l,c]of Object.entries(r))n.node.style.setProperty(l,c);o!=null&&o.active&&n.node.classList.remove(o.active)}},XE=t=>{let{transform:{initial:e,final:n}}=t;return[{transform:Ns.Transform.toString(e)},{transform:Ns.Transform.toString(n)}]},qE={duration:250,easing:"ease",keyframes:XE,sideEffects:YE({styles:{active:{opacity:"0"}}})};function GE(t){let{config:e,draggableNodes:n,droppableContainers:s,measuringConfiguration:r}=t;return Cc((i,o)=>{if(e===null)return;const a=n.get(i);if(!a)return;const l=a.node.current;if(!l)return;const c=bv(o);if(!c)return;const{transform:d}=st(o).getComputedStyle(o),f=cv(d);if(!f)return;const h=typeof e=="function"?e:JE(e);return mv(l,r.draggable.measure),h({active:{id:i,data:a.data,node:l,rect:r.draggable.measure(l)},draggableNodes:n,dragOverlay:{node:o,rect:r.dragOverlay.measure(c)},droppableContainers:s,measuringConfiguration:r,transform:f})})}function JE(t){const{duration:e,easing:n,sideEffects:s,keyframes:r}={...qE,...t};return i=>{let{active:o,dragOverlay:a,transform:l,...c}=i;if(!e)return;const d={x:a.rect.left-o.rect.left,y:a.rect.top-o.rect.top},f={scaleX:l.scaleX!==1?o.rect.width*l.scaleX/a.rect.width:1,scaleY:l.scaleY!==1?o.rect.height*l.scaleY/a.rect.height:1},h={x:l.x-d.x,y:l.y-d.y,...f},p=r({...c,active:o,dragOverlay:a,transform:{initial:l,final:h}}),[m]=p,g=p[p.length-1];if(JSON.stringify(m)===JSON.stringify(g))return;const b=s==null?void 0:s({active:o,dragOverlay:a,...c}),y=a.node.animate(p,{duration:e,easing:n,fill:"forwards"});return new Promise(x=>{y.onfinish=()=>{b==null||b(),x()}})}}let ym=0;function ZE(t){return S.useMemo(()=>{if(t!=null)return ym++,ym},[t])}const e2=pe.memo(t=>{let{adjustScale:e=!1,children:n,dropAnimation:s,style:r,transition:i,modifiers:o,wrapperElement:a="div",className:l,zIndex:c=999}=t;const{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:p,draggableNodes:m,droppableContainers:g,dragOverlay:b,over:y,measuringConfiguration:x,scrollableAncestors:v,scrollableAncestorRects:_,windowRect:w}=kv(),k=S.useContext(Ec),C=ZE(f==null?void 0:f.id),j=_v(o,{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:p,draggingNodeRect:b.rect,over:y,overlayNodeRect:b.rect,scrollableAncestors:v,scrollableAncestorRects:_,transform:k,windowRect:w}),M=fh(h),E=GE({config:s,draggableNodes:m,droppableContainers:g,measuringConfiguration:x}),P=M?b.setRef:void 0;return pe.createElement(HE,null,pe.createElement(UE,{animation:E},f&&C?pe.createElement(KE,{key:C,id:f.id,ref:P,as:a,activatorEvent:d,adjustScale:e,className:l,transition:i,rect:M,style:{zIndex:c,...r},transform:j},n):null))});function jv(t,e,n){const s=t.slice();return s.splice(n<0?s.length+n:n,0,s.splice(e,1)[0]),s}function t2(t,e){return t.reduce((n,s,r)=>{const i=e.get(s);return i&&(n[r]=i),n},Array(t.length))}function Wa(t){return t!==null&&t>=0}function n2(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function s2(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}const Nv=t=>{let{rects:e,activeIndex:n,overIndex:s,index:r}=t;const i=jv(e,s,n),o=e[r],a=i[r];return!a||!o?null:{x:a.left-o.left,y:a.top-o.top,scaleX:a.width/o.width,scaleY:a.height/o.height}},Ha={scaleX:1,scaleY:1},r2=t=>{var e;let{activeIndex:n,activeNodeRect:s,index:r,rects:i,overIndex:o}=t;const a=(e=i[n])!=null?e:s;if(!a)return null;if(r===n){const c=i[o];return c?{x:0,y:n<o?c.top+c.height-(a.top+a.height):c.top-a.top,...Ha}:null}const l=i2(i,r,n);return r>n&&r<=o?{x:0,y:-a.height-l,...Ha}:r<n&&r>=o?{x:0,y:a.height+l,...Ha}:{x:0,y:0,...Ha}};function i2(t,e,n){const s=t[e],r=t[e-1],i=t[e+1];return s?n<e?r?s.top-(r.top+r.height):i?i.top-(s.top+s.height):0:i?i.top-(s.top+s.height):r?s.top-(r.top+r.height):0:0}const Ev="Sortable",Mv=pe.createContext({activeIndex:-1,containerId:Ev,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:Nv,disabled:{draggable:!1,droppable:!1}});function o2(t){let{children:e,id:n,items:s,strategy:r=Nv,disabled:i=!1}=t;const{active:o,dragOverlay:a,droppableRects:l,over:c,measureDroppableContainers:d}=kv(),f=aa(Ev,n),h=a.rect!==null,p=S.useMemo(()=>s.map(k=>typeof k=="object"&&"id"in k?k.id:k),[s]),m=o!=null,g=o?p.indexOf(o.id):-1,b=c?p.indexOf(c.id):-1,y=S.useRef(p),x=!n2(p,y.current),v=b!==-1&&g===-1||x,_=s2(i);Jt(()=>{x&&m&&d(p)},[x,p,m,d]),S.useEffect(()=>{y.current=p},[p]);const w=S.useMemo(()=>({activeIndex:g,containerId:f,disabled:_,disableTransforms:v,items:p,overIndex:b,useDragOverlay:h,sortedRects:t2(p,l),strategy:r}),[g,f,_.draggable,_.droppable,v,p,b,l,h,r]);return pe.createElement(Mv.Provider,{value:w},e)}const a2=t=>{let{id:e,items:n,activeIndex:s,overIndex:r}=t;return jv(n,s,r).indexOf(e)},l2=t=>{let{containerId:e,isSorting:n,wasDragging:s,index:r,items:i,newIndex:o,previousItems:a,previousContainerId:l,transition:c}=t;return!c||!s||a!==i&&r===o?!1:n?!0:o!==r&&e===l},c2={duration:200,easing:"ease"},Pv="transform",u2=Ns.Transition.toString({property:Pv,duration:0,easing:"linear"}),d2={roleDescription:"sortable"};function f2(t){let{disabled:e,index:n,node:s,rect:r}=t;const[i,o]=S.useState(null),a=S.useRef(n);return Jt(()=>{if(!e&&n!==a.current&&s.current){const l=r.current;if(l){const c=Ci(s.current,{ignoreTransform:!0}),d={x:l.left-c.left,y:l.top-c.top,scaleX:l.width/c.width,scaleY:l.height/c.height};(d.x||d.y)&&o(d)}}n!==a.current&&(a.current=n)},[e,n,s,r]),S.useEffect(()=>{i&&o(null)},[i]),i}function h2(t){let{animateLayoutChanges:e=l2,attributes:n,disabled:s,data:r,getNewIndex:i=a2,id:o,strategy:a,resizeObserverConfig:l,transition:c=c2}=t;const{items:d,containerId:f,activeIndex:h,disabled:p,disableTransforms:m,sortedRects:g,overIndex:b,useDragOverlay:y,strategy:x}=S.useContext(Mv),v=p2(s,p),_=d.indexOf(o),w=S.useMemo(()=>({sortable:{containerId:f,index:_,items:d},...r}),[f,r,_,d]),k=S.useMemo(()=>d.slice(d.indexOf(o)),[d,o]),{rect:C,node:j,isOver:M,setNodeRef:E}=Cv({id:o,data:w,disabled:v.droppable,resizeObserverConfig:{updateMeasurementsFor:k,...l}}),{active:P,activatorEvent:A,activeNodeRect:Q,attributes:ne,setNodeRef:Y,listeners:oe,isDragging:G,over:O,setActivatorNodeRef:L,transform:I}=zE({id:o,data:w,attributes:{...d2,...n},disabled:v.draggable}),V=wN(E,Y),F=!!P,ce=F&&!m&&Wa(h)&&Wa(b),$=!y&&G,ke=$&&ce?I:null,gt=ce?ke??(a??x)({rects:g,activeNodeRect:Q,activeIndex:h,overIndex:b,index:_}):null,Ft=Wa(h)&&Wa(b)?i({id:o,items:d,activeIndex:h,overIndex:b}):_,zt=P==null?void 0:P.id,ie=S.useRef({activeId:zt,items:d,newIndex:Ft,containerId:f}),ji=d!==ie.current.items,tn=e({active:P,containerId:f,isDragging:G,isSorting:F,id:o,index:_,items:d,newIndex:ie.current.newIndex,previousItems:ie.current.items,previousContainerId:ie.current.containerId,transition:c,wasDragging:ie.current.activeId!=null}),pr=f2({disabled:!tn,index:_,node:j,rect:C});return S.useEffect(()=>{F&&ie.current.newIndex!==Ft&&(ie.current.newIndex=Ft),f!==ie.current.containerId&&(ie.current.containerId=f),d!==ie.current.items&&(ie.current.items=d)},[F,Ft,f,d]),S.useEffect(()=>{if(zt===ie.current.activeId)return;if(zt!=null&&ie.current.activeId==null){ie.current.activeId=zt;return}const gr=setTimeout(()=>{ie.current.activeId=zt},50);return()=>clearTimeout(gr)},[zt]),{active:P,activeIndex:h,attributes:ne,data:w,rect:C,index:_,newIndex:Ft,items:d,isOver:M,isSorting:F,isDragging:G,listeners:oe,node:j,overIndex:b,over:O,setNodeRef:V,setActivatorNodeRef:L,setDroppableNodeRef:E,setDraggableNodeRef:Y,transform:pr??gt,transition:vn()};function vn(){if(pr||ji&&ie.current.newIndex===_)return u2;if(!($&&!jc(A)||!c)&&(F||tn))return Ns.Transition.toString({...c,property:Pv})}}function p2(t,e){var n,s;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t==null?void 0:t.draggable)!=null?n:e.draggable,droppable:(s=t==null?void 0:t.droppable)!=null?s:e.droppable}}se.Down,se.Right,se.Up,se.Left;function Rv({lead:t,onAbrir:e,emOverlay:n=!1}){const{attributes:s,listeners:r,setNodeRef:i,transform:o,transition:a,isDragging:l}=h2({id:t.id});return u.jsxs("div",{ref:i,...r,...s,style:{transform:Ns.Transform.toString(o),transition:a,opacity:l?.5:1},className:H("bg-white rounded-lg shadow-sm border border-gray-100 p-3 cursor-grab active:cursor-grabbing select-none touch-none",n&&"shadow-xl rotate-2 cursor-grabbing"),onDoubleClick:()=>e==null?void 0:e(t),title:"Arraste para mudar de coluna · duplo clique para editar",children:[u.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",children:t.nome}),u.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:na(t.telefone)}),u.jsxs("div",{className:"flex items-center justify-between mt-2",children:[u.jsx("span",{className:"text-[10px] uppercase tracking-wide bg-indigo-50 text-indigo-700 px-1.5 py-0.5 rounded font-medium",children:t.fonte}),u.jsx("span",{className:"text-[10px] text-gray-400",title:"Data de criação",children:new Date(t.criado_em).toLocaleDateString("pt-BR")})]})]})}function g2({etapa:t,leads:e,cor:n,onAbrirLead:s}){const{setNodeRef:r,isOver:i}=Cv({id:t});return u.jsxs("div",{className:"w-72 shrink-0",children:[u.jsxs("div",{className:"flex items-center justify-between px-1 pb-2",children:[u.jsxs("span",{className:"flex items-center gap-2 text-sm font-semibold text-gray-700",children:[u.jsx("span",{className:H("w-2.5 h-2.5 rounded-full",n)}),mn[t]]}),u.jsx("span",{className:"text-xs font-medium text-gray-500 bg-white border border-gray-200 rounded-full px-2 py-0.5 shadow-sm",children:e.length})]}),u.jsx("div",{ref:r,className:H("bg-white rounded-xl p-3 min-h-[420px] transition-colors","shadow-sm border",i?"border-2 border-dashed border-indigo-400 bg-indigo-50":"border-gray-100"),children:u.jsx(o2,{items:e.map(o=>o.id),strategy:r2,children:u.jsxs("div",{className:"space-y-2 max-h-[calc(100vh-320px)] overflow-y-auto pr-0.5",children:[e.length===0&&u.jsxs("div",{className:"text-center text-xs text-gray-400 border-2 border-dashed border-gray-200 rounded-lg py-10 mt-8",children:[u.jsx("i",{className:"fas fa-inbox text-2xl text-gray-300 mb-2 block"}),"Arraste leads para cá"]}),e.map(o=>u.jsx(Rv,{lead:o,onAbrir:s},o.id))]})})})]})}const m2={leads:"bg-blue-500",em_contato:"bg-amber-500",proposta:"bg-violet-500",fechado:"bg-green-500"};function Hi(t,e){if(pt.includes(e))return e;for(const n of pt)if((t[n]||[]).includes(e))return n;return null}function x2({leads:t,onMover:e,onAbrirLead:n}){const[s,r]=S.useState(()=>y2(t)),[i,o]=S.useState(null),a=S.useRef(s),l=AN(LN(dh,{activationConstraint:{distance:6}}));S.useEffect(()=>{r(m=>{const g=new Set(t.map(v=>v.id)),b={};for(const v of pt)b[v]=(m[v]||[]).filter(_=>g.has(_));let y=!1;for(const v of t){const _=Hi(b,v.id);_===null?(b[v.etapa]=[...b[v.etapa]||[],v.id],y=!0):_!==v.etapa&&(b[_]=b[_].filter(w=>w!==v.id),b[v.etapa]=[...b[v.etapa]||[],v.id],y=!0)}const x=pt.every(v=>(b[v]||[]).length===(m[v]||[]).length);return y||!x?b:m})},[t]);const c=S.useCallback(m=>m&&t.find(g=>g.id===m)||null,[t]),d=S.useMemo(()=>c(i),[c,i]),f=m=>{a.current=s,o(String(m.active.id))},h=S.useCallback(m=>{const{active:g,over:b}=m;if(!b)return;const y=String(g.id),x=String(b.id);r(v=>{const _=Hi(v,y),w=Hi(v,x);return!_||!w||_===w?v:{...v,[_]:v[_].filter(k=>k!==y),[w]:[...v[w],y]}})},[]),p=async m=>{o(null);const g=String(m.active.id);if(!m.over){r(a.current);return}const b=Hi(s,String(m.over.id)),y=Hi(a.current,g);!b||!y||b===y||await e(g,b)};return u.jsxs(AE,{sensors:l,collisionDetection:UN,onDragStart:f,onDragOver:h,onDragEnd:p,children:[u.jsx("div",{className:"flex gap-4 overflow-x-auto pb-2",children:pt.map(m=>u.jsx(g2,{etapa:m,cor:m2[m],leads:t.filter(g=>{var b;return(b=s[m])==null?void 0:b.includes(g.id)}),onAbrirLead:n},m))}),u.jsx(e2,{children:d?u.jsx(Rv,{lead:d,emOverlay:!0}):null})]})}function y2(t){const e={leads:[],em_contato:[],proposta:[],fechado:[]};for(const n of t)e[n.etapa]&&e[n.etapa].push(n.id);return e}const vm={nome:"",telefone:"",email:"",fonte:"Manual",etapa:"leads"};function v2(){const{toast:t}=en(),[e,n]=S.useState([]),[s,r]=S.useState(null),[i,o]=S.useState(!1),[a,l]=S.useState(!1),[c,d]=S.useState(null),[f,h]=S.useState({...vm}),[p,m]=S.useState(""),g=S.useCallback(async()=>{n(await W.crm.leadsListar())},[]);S.useEffect(()=>{g().catch(C=>t("erro",C.message))},[g,t]);const b=async(C,j)=>{const M=e;n(E=>E.map(P=>P.id===C?{...P,etapa:j}:P));try{await W.crm.moverLead(C,j),t("sucesso",`Lead movido para "${mn[j]}".`)}catch(E){n(M),t("erro",E instanceof Error?E.message:"Falha ao mover lead.")}},y=async()=>{var C;if(!((C=f.nome)!=null&&C.trim())){t("erro","O nome do lead é obrigatório.");return}try{await W.crm.criarLead({...f,etapa:f.etapa||"leads"}),t("sucesso","Lead criado com sucesso."),l(!1),h({...vm}),await g()}catch(j){t("erro",j instanceof Error?j.message:"Falha ao criar lead.")}},x=async()=>{o(!0);try{const C=await W.crm.sugestoes();r(C.sugestoes)}catch(C){t("erro",C instanceof Error?C.message:"Falha ao pedir sugestões.")}finally{o(!1)}},v=async C=>{try{await W.crm.aplicar(C.lead_id,C.para),r(j=>(j==null?void 0:j.filter(M=>M!==C))??null),await g(),t("sucesso",`Sugestão aplicada: ${C.lead_nome} → ${mn[C.para]}.`)}catch(j){t("erro",j instanceof Error?j.message:"Falha ao aplicar sugestão.")}},_=async C=>{try{(await W.leads.enriquecer(C.id)).notas.forEach(M=>t("info",M)),await g()}catch(j){t("erro",j instanceof Error?j.message:"Falha ao enriquecer.")}},w=async()=>{if(c)try{await W.leads.atualizar(c.id,{observacoes:p}),d(null),await g(),t("sucesso","Observações salvas.")}catch(C){t("erro",C instanceof Error?C.message:"Falha ao salvar.")}},k=S.useMemo(()=>Object.fromEntries(pt.map(C=>[C,e.filter(j=>j.etapa===C).length])),[e]);return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[u.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-500 flex-wrap",children:[u.jsxs("span",{children:[u.jsx("strong",{className:"text-gray-800",children:e.length})," leads no funil"]}),pt.map(C=>u.jsxs("span",{className:"hidden md:inline",children:[mn[C],": ",u.jsx("strong",{className:"text-gray-700",children:k[C]})]},C))]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("button",{onClick:x,disabled:i,className:"px-5 py-2.5 text-sm font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fas fa-wand-magic-sparkles mr-2",i&&"fa-spin")}),"Sugestões da IA"]}),u.jsxs("button",{onClick:()=>l(!0),className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition shadow-sm",children:[u.jsx("i",{className:"fas fa-plus mr-2"})," Adicionar Lead"]})]})]}),u.jsx(x2,{leads:e,onMover:b,onAbrirLead:C=>{d(C),m(C.observacoes||"")}}),u.jsxs(Xt,{aberto:s!==null,onFechar:()=>r(null),titulo:"Sugestões de movimentação (Agente de CRM)",icone:"fas fa-robot",largura:"lg",children:[s&&s.length===0&&u.jsxs("p",{className:"text-sm text-gray-500 text-center py-8",children:[u.jsx("i",{className:"fas fa-circle-check text-green-500 text-2xl block mb-3"}),"Nenhuma sugestão no momento — o funil está equilibrado. 🎯"]}),u.jsx("div",{className:"space-y-3",children:s==null?void 0:s.map((C,j)=>u.jsxs("div",{className:"border border-gray-100 rounded-xl p-4 flex items-start justify-between gap-4 hover:border-indigo-200 transition",children:[u.jsxs("div",{className:"min-w-0",children:[u.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",children:C.lead_nome}),u.jsxs("p",{className:"text-xs text-gray-500 mt-1 flex items-center gap-2",children:[u.jsx(sr,{status:C.de})," ",u.jsx("i",{className:"fas fa-arrow-right text-gray-300"})," ",u.jsx(sr,{status:C.para}),u.jsxs("span",{className:"text-gray-400",children:["confiança ",Math.round(C.confianca*100),"%"]})]}),u.jsx("p",{className:"text-xs text-gray-600 mt-2",children:C.motivo})]}),u.jsx("button",{onClick:()=>v(C),className:"shrink-0 px-4 py-2 text-xs font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:"Aplicar"})]},j))})]}),u.jsx(Xt,{aberto:a,onFechar:()=>l(!1),titulo:"Adicionar Lead",icone:"fas fa-user-plus",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(_r,{rotulo:"Nome *",valor:f.nome||"",onChange:C=>h({...f,nome:C})}),u.jsx(_r,{rotulo:"Telefone",valor:f.telefone||"",onChange:C=>h({...f,telefone:C}),placeholder:"(11) 99999-9999"}),u.jsx(_r,{rotulo:"E-mail",tipo:"email",valor:f.email||"",onChange:C=>h({...f,email:C}),placeholder:"contato@empresa.com.br"}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Coluna inicial"}),u.jsx("select",{value:f.etapa||"leads",onChange:C=>h({...f,etapa:C.target.value}),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",children:pt.map(C=>u.jsx("option",{value:C,children:mn[C]},C))})]})]}),u.jsx(_r,{rotulo:"Fonte",valor:f.fonte||"",onChange:C=>h({...f,fonte:C}),placeholder:"Manual, Google Maps, Instagram, CNPJ..."}),u.jsxs(Qt,{titulo:"Campos avançados",icone:"fas fa-sliders",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(_r,{rotulo:"Empresa",valor:f.empresa||"",onChange:C=>h({...f,empresa:C})}),u.jsx(_r,{rotulo:"Cidade",valor:f.cidade||"",onChange:C=>h({...f,cidade:C}),placeholder:"São Paulo/SP"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Observações"}),u.jsx("textarea",{value:f.observacoes||"",onChange:C=>h({...f,observacoes:C.target.value}),rows:3,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})]}),u.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[u.jsx("button",{onClick:()=>l(!1),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:y,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar"]})]})]})}),u.jsx(Xt,{aberto:!!c,onFechar:()=>d(null),titulo:"Lead",icone:"fas fa-address-card",children:c&&u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-base font-semibold text-gray-800",children:c.nome}),u.jsxs("p",{className:"text-xs text-gray-500 mt-0.5",children:[na(c.telefone)," · ",c.fonte," · criado em ",Il(c.criado_em)]})]}),u.jsx(sr,{status:c.etapa})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Observações"}),u.jsx("textarea",{value:p,onChange:C=>m(C.target.value),rows:4,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",placeholder:"Ex.: ligou pedindo proposta, retorna na sexta..."})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("button",{onClick:()=>_(c),className:"text-sm text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-wand-magic-sparkles mr-1"})," Enriquecer com IA"]}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx("button",{onClick:()=>d(null),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:w,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar"]})]})]})]})})]})}function _r({rotulo:t,valor:e,onChange:n,tipo:s="text",placeholder:r}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("input",{type:s,value:e,onChange:i=>n(i.target.value),placeholder:r,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function b2(){const{toast:t}=en(),[e,n]=S.useState([]),[s,r]=S.useState(!1),[i,o]=S.useState(null),[a,l]=S.useState(""),[c,d]=S.useState(""),[f,h]=S.useState("texto"),[p,m]=S.useState("leads"),g=S.useCallback(async()=>{n(await W.leads.listar())},[]);S.useEffect(()=>{g().catch(w=>t("erro",w.message))},[g,t]);const{data:b=[],refetch:y}=ey({queryKey:["campanhas"],queryFn:()=>W.campanhas.listar(),refetchInterval:w=>{var k;return(k=w.state.data)!=null&&k.some(C=>C.status==="em_andamento")?4e3:!1},refetchIntervalInBackground:!1}),x=S.useMemo(()=>Object.fromEntries(pt.map(w=>[w,e.filter(k=>k.etapa===w).length])),[e]),v=async()=>{if(!a.trim()){t("erro","Dê um nome para a campanha.");return}if(!c.trim()){t("erro","Escreva o template da mensagem.");return}try{await W.campanhas.criar({nome:a.trim(),canal:f,template:f,mensagem:c.trim(),lead_ids:[],filtro_etapa:p});const w=mn[p]??p;t("sucesso",`Campanha criada — ${x[p]??0} leads de "${w}" serão disparados.`),r(!1),l(""),d(""),await y(),await g()}catch(w){t("erro",w instanceof Error?w.message:"Falha ao criar campanha.")}},_=async(w,k)=>{try{await W.campanhas.status(w.id,k),t("sucesso",`Campanha "${w.nome}" → ${k==="ativa"?"Ativa":k==="pausada"?"Pausada":"Rascunho"}.`),await y()}catch(C){t("erro",C instanceof Error?C.message:"Falha ao alterar status.")}};return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:[u.jsx("strong",{className:"text-gray-800",children:b.length})," campanhas · templates em Agentes"]}),u.jsxs("button",{onClick:()=>r(!0),className:"px-6 py-3 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition shadow-sm",children:[u.jsx("i",{className:"fas fa-plus mr-2"})," Nova Campanha"]})]}),u.jsx("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100 bg-gray-50/50",children:[u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Nome"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Status"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Total de Leads"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Data de Criação"}),u.jsx("th",{className:"px-5 py-3 font-semibold text-right",children:"Ações"})]})}),u.jsxs("tbody",{children:[b.map(w=>{const k=w.status==="em_andamento",C=Math.max(w.total,w.enviadas+w.erros);return u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40",children:[u.jsxs("td",{className:"px-5 py-3",children:[u.jsx("p",{className:"font-medium text-gray-800 truncate max-w-[220px]",children:w.nome}),u.jsxs("p",{className:"text-xs text-gray-400",children:[w.canal==="audio"?"Áudio":"Texto",' · template "',w.template,'"']})]}),u.jsx("td",{className:"px-5 py-3",children:u.jsx(sr,{status:w.status})}),u.jsx("td",{className:"px-5 py-3 text-gray-600",children:C}),u.jsx("td",{className:"px-5 py-3 text-xs text-gray-400",children:Il(w.criado_em)}),u.jsxs("td",{className:"px-5 py-3 text-right whitespace-nowrap",children:[u.jsxs("button",{onClick:()=>o(w),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium mr-3",children:[u.jsx("i",{className:"fas fa-list mr-1"})," Ver"]}),k?u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>_(w,"pausada"),className:"px-4 py-2 text-xs font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded-lg hover:bg-amber-100 mr-2",children:[u.jsx("i",{className:"fas fa-pause mr-1"})," Pausar"]}),u.jsxs("button",{onClick:()=>_(w,"rascunho"),className:"px-4 py-2 text-xs font-medium text-red-700 bg-red-50 border border-red-200 rounded-lg hover:bg-red-100",children:[u.jsx("i",{className:"fas fa-stop mr-1"})," Parar"]})]}):u.jsxs("button",{onClick:()=>_(w,"ativa"),className:"px-5 py-2 text-xs font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-play mr-1"})," Iniciar"]})]})]},w.id)}),b.length===0&&u.jsx("tr",{children:u.jsxs("td",{colSpan:5,className:"px-5 py-16 text-center text-gray-400",children:[u.jsx("i",{className:"fas fa-bullhorn text-3xl text-gray-200 block mb-3"}),"Nenhuma campanha ainda. Clique em ",u.jsx("strong",{className:"text-indigo-500",children:"Nova Campanha"})," para começar."]})})]})]})})}),b.filter(w=>w.status==="em_andamento").length>0&&u.jsx("div",{className:"space-y-3",children:b.filter(w=>w.status==="em_andamento").map(w=>{const k=Math.max(w.total,w.enviadas+w.erros),C=k?Math.round((w.enviadas+w.erros)/k*100):0;return u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-indigo-100 p-4 space-y-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("p",{className:"text-sm font-medium text-gray-700 flex items-center gap-2",children:[u.jsx("i",{className:"fas fa-spinner fa-spin text-indigo-500"})," ",w.nome]}),u.jsxs("span",{className:"text-xs text-gray-500",children:[w.enviadas," enviadas · ",w.erros," erros"]})]}),u.jsx(ra,{valor:C,mostrarLabel:!0})]},w.id)})}),u.jsx(Xt,{aberto:s,onFechar:()=>r(!1),titulo:"Nova Campanha",icone:"fas fa-bullhorn",largura:"lg",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Nome da Campanha *"}),u.jsx("input",{value:a,onChange:w=>l(w.target.value),placeholder:"Ex.: Reativação de novos leads",className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Template da Mensagem *"}),u.jsx("textarea",{value:c,onChange:w=>d(w.target.value),rows:4,placeholder:"Use variáveis: {{nome}}, {{primeiro_nome}}, {{empresa}}, {{cidade}}...",className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none font-mono"}),u.jsxs("p",{className:"text-[11px] text-gray-400 mt-1",children:["Variáveis: ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{nome}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{primeiro_nome}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{empresa}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{cidade}}"})]})]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Canal"}),u.jsxs("select",{value:f,onChange:w=>h(w.target.value),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",children:[u.jsx("option",{value:"texto",children:"Texto"}),u.jsx("option",{value:"audio",children:"Áudio"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Filtrar Leads por Etapa do CRM"}),u.jsx("select",{value:p,onChange:w=>m(w.target.value),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",children:pt.map(w=>u.jsxs("option",{value:w,children:[mn[w]," (",x[w]??0," leads)"]},w))})]})]}),u.jsxs("p",{className:"text-xs text-gray-400 bg-gray-50 border border-gray-100 rounded-lg px-3 py-2",children:[u.jsx("i",{className:"fas fa-circle-info mr-1"})," O envio simulado altera o status no JSON. A integração real (OpenOutreach) é validada na hora de iniciar — configure em Ferramentas."]}),u.jsxs("div",{className:"flex justify-end gap-3 pt-1",children:[u.jsx("button",{onClick:()=>r(!1),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:v,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-plus mr-2"})," Criar Campanha"]})]})]})}),u.jsx(Xt,{aberto:!!i,onFechar:()=>o(null),titulo:`Eventos — ${(i==null?void 0:i.nome)??""}`,icone:"fas fa-list",largura:"lg",children:i&&u.jsxs("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:[i.eventos.length===0&&u.jsx("p",{className:"text-sm text-gray-400 text-center py-8",children:"Nenhum evento ainda — a execução do disparo é simulada nesta fase."}),i.eventos.slice().reverse().map((w,k)=>{var C;return u.jsxs("div",{className:"flex items-start gap-3 text-sm border-b border-gray-50 pb-2",children:[u.jsx("i",{className:H("mt-1 text-xs",w.status==="enviado"?"fas fa-circle-check text-green-500":"fas fa-circle-xmark text-red-500")}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("p",{className:"text-gray-700 truncate",children:((C=e.find(j=>j.id===w.lead_id))==null?void 0:C.nome)??w.lead_id}),w.mensagem&&u.jsx("p",{className:"text-xs text-gray-400 truncate",children:w.mensagem})]}),u.jsx("span",{className:"text-xs text-gray-300 shrink-0",children:Il(w.momento)})]},k)})]})})]})}const w2=[{para:"/extrator-maps",icone:"fas fa-map-marked-alt",titulo:"Google Maps",descricao:"Empresas por palavra-chave e localização. Sem scraper configurado, gera mock de 5–10 leads."},{para:"/extrator-instagram",icone:"fab fa-instagram",titulo:"Instagram",descricao:"Seguidores de um perfil público. Sem igmapper configurado, gera mock de 5–10 leads."},{para:"/extrator-cnpj",icone:"fas fa-building",titulo:"CNPJ (B2B)",descricao:"Empresas por CNAE + UF. Sem provedor configurado, gera mock de 5–10 empresas."}];function S2(){const t=bi();return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:["Selecione uma fonte de leads. Todas salvam diretamente em ",u.jsx("strong",{children:"leads.json"}),", na coluna"," ",u.jsx("strong",{children:'"Novos Leads"'})," do CRM — dados 100% locais."]}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:w2.map(e=>u.jsxs("button",{onClick:()=>t(e.para),className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 text-left space-y-3 hover:border-indigo-200 hover:shadow-md transition group",children:[u.jsx("span",{className:"w-11 h-11 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center text-lg group-hover:bg-indigo-100",children:u.jsx("i",{className:e.icone})}),u.jsx("p",{className:"text-sm font-semibold text-gray-800",children:e.titulo}),u.jsx("p",{className:"text-xs text-gray-500 leading-relaxed",children:e.descricao}),u.jsxs("span",{className:"text-xs font-medium text-indigo-600 group-hover:text-indigo-800",children:["Abrir extrator ",u.jsx("i",{className:"fas fa-arrow-right ml-1"})]})]},e.para))})]})}function _2(){const{toast:t}=en(),e=bi(),[n,s]=S.useState(""),[r,i]=S.useState(""),[o,a]=S.useState(10),[l,c]=S.useState(5),[d,f]=S.useState(!1),[h,p]=S.useState(!1),[m,g]=S.useState(0),[b,y]=S.useState(null),[x,v]=S.useState(""),_=async()=>{if(n.trim().length<2||r.trim().length<2){t("erro",'Preencha a palavra-chave e a localização (ex.: "Dentista", "Rio de Janeiro").');return}p(!0),y(null),g(8);const w=setInterval(()=>{g(k=>k<85?k+Math.ceil((90-k)/6):85)},90);try{const k=await W.extrair.maps({keyword:n.trim(),location:r.trim(),limit:o});clearInterval(w),g(100),y(k.importados),v(k.origem==="cli"?"scraper real":"mock de teste");const C=k.duplicados>0?` · ${k.duplicados} duplicados ignorados`:"",j=k.aviso?` · ${k.aviso}`:"";t("sucesso",`${k.importados.length} leads extraídos (${k.origem==="cli"?"scraper real":"mock"})${C}${j}`)}catch(k){clearInterval(w),g(0),t("erro",k instanceof Error?k.message:"Falha na extração.")}finally{p(!1)}};return u.jsxs("div",{className:"space-y-6 max-w-4xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-5",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:["Busque empresas por palavra-chave e localização. Sem scraper configurado, o LeadMaster gera",u.jsx("strong",{children:" dados mockados (5–10 leads)"})," para teste — sem risco de bloqueio de IP."]}),u.jsxs("span",{className:"text-xs shrink-0 text-gray-400",children:[u.jsx("i",{className:"fas fa-shield-halved mr-1"})," dados públicos"]})]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Palavra-chave *"}),u.jsx("input",{value:n,onChange:w=>s(w.target.value),placeholder:"Ex.: Dentista, pizzaria, academia...",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Localização *"}),u.jsx("input",{value:r,onChange:w=>i(w.target.value),placeholder:"Ex.: Rio de Janeiro, RJ",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Quantidade: ",o]}),u.jsx("input",{type:"range",min:5,max:10,value:o,onChange:w=>a(Number(w.target.value)),className:"w-full accent-indigo-500 mt-2"})]})]}),u.jsxs("button",{onClick:_,disabled:h,className:"w-full md:w-auto px-8 py-3.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fas fa-magnifying-glass mr-2",h&&"fa-spin")}),h?"Buscando leads...":"Iniciar Extração"]}),(h||m>0)&&u.jsxs("div",{className:"space-y-1",children:[u.jsx(ra,{valor:m}),u.jsx("p",{className:"text-xs text-indigo-600 font-medium",children:m<100?"Buscando leads no Google Maps...":"Extração concluída ✓"})]}),u.jsxs(Qt,{titulo:"Configurações avançadas",icone:"fas fa-sliders",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Raio de busca: ",l," km"]}),u.jsx("input",{type:"range",min:1,max:50,value:l,onChange:w=>c(Number(w.target.value)),className:"w-full accent-indigo-500"})]}),u.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-600 bg-gray-50 border border-gray-100 rounded-lg px-3 py-2.5 cursor-pointer h-fit",children:[u.jsx("input",{type:"checkbox",checked:d,onChange:w=>f(w.target.checked),className:"w-4 h-4 accent-indigo-500"}),"Apenas com nota ≥ 4,5"]})]}),u.jsx("p",{className:"text-[11px] text-gray-400",children:"As opções avançadas aplicam-se ao scraper real (gosom/google-maps-scraper), quando configurado em Ferramentas → Extratores. No modo mock elas são ignoradas."})]})]}),b&&u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:[u.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-gray-100 bg-gray-50/50",children:[u.jsxs("p",{className:"text-sm font-medium text-gray-700",children:[b.length," lead(s) extraído(s) · origem: ",u.jsx("span",{className:"text-indigo-600",children:x})]}),u.jsxs("button",{onClick:()=>e("/crm"),className:"px-5 py-2 text-xs font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50",children:[u.jsx("i",{className:"fas fa-columns mr-1"})," Ir para o CRM"]})]}),u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100",children:[u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Nome"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Telefone"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Localização"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Avaliação"})]})}),u.jsx("tbody",{children:b.map((w,k)=>{var j;const C=(j=w.extras)==null?void 0:j.avaliacao;return u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40",children:[u.jsx("td",{className:"px-5 py-2.5 text-gray-800",children:w.nome}),u.jsx("td",{className:"px-5 py-2.5 text-gray-600",children:na(w.telefone)}),u.jsxs("td",{className:"px-5 py-2.5 text-gray-500 text-xs",children:[w.cidade||"—",w.endereco?` · ${w.endereco}`:""]}),u.jsx("td",{className:"px-5 py-2.5 text-xs text-gray-400",children:C!==void 0?u.jsxs(u.Fragment,{children:[u.jsx("i",{className:"fas fa-star text-amber-400 mr-1"}),C]}):"—"})]},w.id||k)})})]})}),u.jsx("div",{className:"px-5 py-3 border-t border-gray-100 bg-gray-50/50",children:u.jsxs("button",{onClick:()=>e("/crm"),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-arrow-right mr-1"})," Ver todos os leads no CRM Kanban"]})})]})]})}function k2(){const{toast:t}=en(),e=bi(),[n,s]=S.useState(""),[r,i]=S.useState(10),[o,a]=S.useState(!1),[l,c]=S.useState(500),[d,f]=S.useState(!1),[h,p]=S.useState(0),[m,g]=S.useState(null),[b,y]=S.useState(""),x=async()=>{if(!n.includes("instagram.com")){t("erro","Informe a URL do perfil (ex.: https://instagram.com/perfil).");return}f(!0),g(null),p(8);const v=setInterval(()=>{p(_=>_<85?_+Math.ceil((90-_)/6):85)},90);try{const _=await W.extrair.instagram(n.trim(),r);clearInterval(v),p(100),g(_.importados),y(_.origem==="cli"?"igmapper real":"mock de teste");const w=_.duplicados>0?` · ${_.duplicados} duplicados ignorados`:"",k=_.aviso?` · ${_.aviso}`:"";t("sucesso",`${_.importados.length} leads extraídos (${_.origem==="cli"?"igmapper real":"mock"})${w}${k}`)}catch(_){clearInterval(v),p(0),t("erro",_ instanceof Error?_.message:"Falha na extração.")}finally{f(!1)}};return u.jsxs("div",{className:"space-y-6 max-w-4xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-5",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:["Extraia seguidores de um perfil público do Instagram. Sem igmapper configurado, o LeadMaster gera",u.jsx("strong",{children:" dados mockados (5–10 leads)"})," para teste — sem risco de bloqueio de conta."]}),u.jsxs("span",{className:"text-xs shrink-0 text-gray-400",children:[u.jsx("i",{className:"fas fa-shield-halved mr-1"})," perfis públicos"]})]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsxs("div",{className:"md:col-span-2",children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"URL do perfil *"}),u.jsx("input",{value:n,onChange:v=>s(v.target.value),placeholder:"https://instagram.com/perfil_do_concorrente/",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Quantidade de seguidores: ",r]}),u.jsx("input",{type:"range",min:5,max:10,value:r,onChange:v=>i(Number(v.target.value)),className:"w-full accent-indigo-500 mt-2"})]})]}),u.jsxs("button",{onClick:x,disabled:d,className:"w-full md:w-auto px-8 py-3.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fab fa-instagram mr-2",d&&"fa-spin")}),d?"Buscando seguidores...":"Iniciar Extração"]}),(d||h>0)&&u.jsxs("div",{className:"space-y-1",children:[u.jsx(ra,{valor:h}),u.jsx("p",{className:"text-xs text-indigo-600 font-medium",children:h<100?"Buscando seguidores no Instagram...":"Extração concluída ✓"})]}),u.jsxs(Qt,{titulo:"Configurações avançadas",icone:"fas fa-sliders",children:[u.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-600 bg-gray-50 border border-gray-100 rounded-lg px-3 py-2.5 cursor-pointer",children:[u.jsx("input",{type:"checkbox",checked:o,onChange:v=>a(v.target.checked),className:"w-4 h-4 accent-indigo-500"}),"Extrair apenas contas comerciais"]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Mínimo de seguidores: ",l]}),u.jsx("input",{type:"range",min:100,max:5e3,step:100,value:l,onChange:v=>c(Number(v.target.value)),className:"w-full accent-indigo-500"})]}),u.jsx("p",{className:"text-[11px] text-gray-400",children:"As opções avançadas aplicam-se ao igmapper real (lucasoal/igmapper), quando configurado em Ferramentas → Extratores. No modo mock elas são ignoradas."})]})]}),m&&u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:[u.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-gray-100 bg-gray-50/50",children:[u.jsxs("p",{className:"text-sm font-medium text-gray-700",children:[m.length," lead(s) extraído(s) · origem: ",u.jsx("span",{className:"text-indigo-600",children:b})]}),u.jsxs("button",{onClick:()=>e("/crm"),className:"px-5 py-2 text-xs font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50",children:[u.jsx("i",{className:"fas fa-columns mr-1"})," Ir para o CRM"]})]}),u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100",children:[u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Nome / Username"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Telefone"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Fonte"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Seguidores"})]})}),u.jsx("tbody",{children:m.map((v,_)=>{var C,j;const w=((C=v.extras)==null?void 0:C.username)||"",k=(j=v.extras)==null?void 0:j.seguidores;return u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40",children:[u.jsxs("td",{className:"px-5 py-2.5 text-gray-800",children:[v.nome,w&&u.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:["@",w]})]}),u.jsx("td",{className:"px-5 py-2.5 text-gray-600",children:na(v.telefone)}),u.jsx("td",{className:"px-5 py-2.5",children:u.jsx("span",{className:"text-[10px] uppercase tracking-wide bg-pink-50 text-pink-700 px-1.5 py-0.5 rounded font-medium",children:v.fonte})}),u.jsx("td",{className:"px-5 py-2.5 text-xs text-gray-400",children:k!==void 0?k.toLocaleString("pt-BR"):"—"})]},v.id||_)})})]})}),u.jsx("div",{className:"px-5 py-3 border-t border-gray-100 bg-gray-50/50",children:u.jsxs("button",{onClick:()=>e("/crm"),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-arrow-right mr-1"})," Ver todos os leads no CRM Kanban"]})})]})]})}const C2=["AC","AL","AP","AM","BA","CE","DF","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RJ","RN","RS","RO","RR","SC","SP","SE","TO"];function j2(){const{toast:t}=en(),e=bi(),[n,s]=S.useState(""),[r,i]=S.useState("SP"),[o,a]=S.useState(10),[l,c]=S.useState(""),[d,f]=S.useState(0),[h,p]=S.useState(!1),[m,g]=S.useState(0),[b,y]=S.useState(null),[x,v]=S.useState(""),[_,w]=S.useState(""),[k,C]=S.useState(!1),j=async()=>{if(n.trim().length<2){t("erro","Informe o CNAE (ex.: 6201-5/01 — desenvolvimento de software).");return}p(!0),y(null),g(8);const E=setInterval(()=>{g(P=>P<85?P+Math.ceil((90-P)/6):85)},90);try{const P=await W.extrair.cnpjExtract({cnae:n.trim(),uf:r,limit:o});clearInterval(E),g(100),y(P.importados),v(P.origem==="provedor"?"provedor real":"mock de teste");const A=P.duplicados>0?` · ${P.duplicados} duplicados ignorados`:"",Q=P.aviso?` · ${P.aviso}`:"";t("sucesso",`${P.importados.length} empresas extraídas (${P.origem==="provedor"?"provedor real":"mock"})${A}${Q}`)}catch(P){clearInterval(E),g(0),t("erro",P instanceof Error?P.message:"Falha na extração.")}finally{p(!1)}},M=async()=>{const E=_.trim();if(E.length<8){t("erro","Informe um CNPJ completo (14 dígitos, com ou sem pontuação).");return}C(!0);try{const P=await W.extrair.cnpj(E),A=await W.leads.importar([P]);t("sucesso",`${A.importados.length} lead(s) importado(s) para "Novos Leads"${A.duplicados.length?` · ${A.duplicados.length} duplicado(s)`:""}.`),w("")}catch(P){t("erro",P instanceof Error?P.message:"Falha ao consultar o CNPJ.")}finally{C(!1)}};return u.jsxs("div",{className:"space-y-6 max-w-4xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-5",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:["Busque empresas por CNAE e estado. Sem provedor configurado, o LeadMaster gera",u.jsx("strong",{children:" dados mockados (5–10 empresas)"})," para teste — sem risco de bloqueio."]}),u.jsxs("span",{className:"text-xs shrink-0 text-gray-400",children:[u.jsx("i",{className:"fas fa-shield-halved mr-1"})," dados B2B"]})]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"CNAE *"}),u.jsx("input",{value:n,onChange:E=>s(E.target.value),placeholder:"Ex.: 6201-5/01 (desenvolvimento de software)",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"UF *"}),u.jsx("select",{value:r,onChange:E=>i(E.target.value),className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none bg-white",children:C2.map(E=>u.jsx("option",{value:E,children:E},E))})]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Quantidade: ",o]}),u.jsx("input",{type:"range",min:5,max:10,value:o,onChange:E=>a(Number(E.target.value)),className:"w-full accent-indigo-500 mt-2"})]})]}),u.jsxs("button",{onClick:j,disabled:h,className:"w-full md:w-auto px-8 py-3.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fas fa-building mr-2",h&&"fa-spin")}),h?"Buscando empresas...":"Iniciar Extração"]}),(h||m>0)&&u.jsxs("div",{className:"space-y-1",children:[u.jsx(ra,{valor:m}),u.jsx("p",{className:"text-xs text-indigo-600 font-medium",children:m<100?"Buscando empresas por CNAE...":"Extração concluída ✓"})]}),u.jsxs(Qt,{titulo:"Configurações avançadas",icone:"fas fa-sliders",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Porte da empresa"}),u.jsxs("select",{value:l,onChange:E=>c(E.target.value),className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none bg-white",children:[u.jsx("option",{value:"",children:"Todos"}),u.jsx("option",{value:"ME",children:"ME (Microempresa)"}),u.jsx("option",{value:"EPP",children:"EPP (Pequeno porte)"}),u.jsx("option",{value:"medio",children:"Médio porte"}),u.jsx("option",{value:"grande",children:"Grande porte"})]})]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Capital social mínimo: ",d.toLocaleString("pt-BR",{style:"currency",currency:"BRL",maximumFractionDigits:0})]}),u.jsx("input",{type:"range",min:0,max:5e6,step:1e5,value:d,onChange:E=>f(Number(E.target.value)),className:"w-full accent-indigo-500"})]})]}),u.jsx("p",{className:"text-[11px] text-gray-400",children:"Os filtros de porte e capital social aplicam-se ao provedor real de busca, quando configurado em Ferramentas → Extratores. No modo mock eles são ignorados."})]}),u.jsxs("div",{className:"pt-1 border-t border-gray-100",children:[u.jsxs("p",{className:"text-xs font-medium text-gray-500 mb-2",children:[u.jsx("i",{className:"fas fa-magnifying-glass mr-1"})," Consulta avulsa por CNPJ (BrasilAPI) — importa uma empresa específica"]}),u.jsxs("div",{className:"flex flex-wrap gap-3",children:[u.jsx("input",{value:_,onChange:E=>w(E.target.value),placeholder:"00.000.000/0000-00",className:"flex-1 min-w-[220px] px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"}),u.jsxs("button",{onClick:M,disabled:k,className:"px-5 py-2.5 text-xs font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50 disabled:opacity-60",children:[u.jsx("i",{className:H("fas fa-file-import mr-1",k&&"fa-spin")}),k?"Importando...":"Consultar e importar"]})]})]})]}),b&&u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:[u.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-gray-100 bg-gray-50/50",children:[u.jsxs("p",{className:"text-sm font-medium text-gray-700",children:[b.length," lead(s) extraído(s) · origem: ",u.jsx("span",{className:"text-indigo-600",children:x})]}),u.jsxs("button",{onClick:()=>e("/crm"),className:"px-5 py-2 text-xs font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50",children:[u.jsx("i",{className:"fas fa-columns mr-1"})," Ir para o CRM"]})]}),u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100",children:[u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Nome Fantasia"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"CNPJ"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Cidade / UF"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Telefone"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Fonte"})]})}),u.jsx("tbody",{children:b.map((E,P)=>u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40",children:[u.jsx("td",{className:"px-5 py-2.5 text-gray-800",children:E.nome}),u.jsx("td",{className:"px-5 py-2.5 text-gray-600 font-mono text-xs",children:E.cnpj||"—"}),u.jsx("td",{className:"px-5 py-2.5 text-gray-500 text-xs",children:E.cidade||"—"}),u.jsx("td",{className:"px-5 py-2.5 text-gray-600",children:na(E.telefone)}),u.jsx("td",{className:"px-5 py-2.5",children:u.jsx("span",{className:"text-[10px] uppercase tracking-wide bg-indigo-50 text-indigo-700 px-1.5 py-0.5 rounded font-medium",children:E.fonte})})]},E.id||P))})]})}),u.jsx("div",{className:"px-5 py-3 border-t border-gray-100 bg-gray-50/50",children:u.jsxs("button",{onClick:()=>e("/crm"),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-arrow-right mr-1"})," Ver todos os leads no CRM Kanban"]})})]})]})}function N2(){const[t,e]=s_(),n=t.get("tab")||"disparo";return u.jsxs("div",{className:"space-y-6",children:[u.jsx("div",{className:"flex gap-2",children:[{id:"disparo",rotulo:"Agente de Disparo",icone:"fas fa-paper-plane"},{id:"atendimento",rotulo:"Agente de Atendimento",icone:"fas fa-headset"}].map(s=>u.jsxs("button",{onClick:()=>e({tab:s.id}),className:H("px-5 py-2.5 text-sm font-medium rounded-lg transition",n===s.id?"bg-[#1e1b4b] text-white shadow-sm":"bg-white text-gray-600 border border-gray-200 hover:bg-gray-50"),children:[u.jsx("i",{className:H(s.icone,"mr-2")}),s.rotulo]},s.id))}),n==="disparo"?u.jsx(E2,{}):u.jsx(M2,{})]})}function E2(){const{toast:t}=en(),[e,n]=S.useState({texto:"",audio:""}),[s,r]=S.useState("LeadMaster"),[i,o]=S.useState(""),[a,l]=S.useState(!1),[c,d]=S.useState(!1),[f,h]=S.useState(null),p=S.useCallback(async()=>{const[b,y]=await Promise.all([W.agentes.templates(),W.config.obter()]);n({texto:b.texto??"",audio:b.audio??""}),r(y.agentes.disparo.minha_empresa??"LeadMaster"),h(y.integracoes.openoutreach)},[]);S.useEffect(()=>{p().catch(b=>t("erro",b.message))},[p,t]);const m=async()=>{d(!0);try{await W.agentes.salvarTemplates(e),await W.config.salvar({agentes:{disparo:{templates:e,minha_empresa:s}}}),t("sucesso","Templates do agente de disparo salvos."),await p()}catch(b){t("erro",b instanceof Error?b.message:"Falha ao salvar templates.")}finally{d(!1)}},g=async()=>{try{const b=await W.agentes.testarTemplate(e.texto);o(b.renderizado),l(!0)}catch(b){t("erro",b instanceof Error?b.message:"Falha ao renderizar template.")}};return u.jsxs("div",{className:"space-y-5 max-w-3xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800",children:"Templates de mensagem"}),u.jsx(sr,{status:f!=null&&f.url&&f.enabled!==!1?"ativo":"inativo",rotulo:f!=null&&f.url&&f.enabled!==!1?"OpenOutreach configurado":"OpenOutreach não configurado"})]}),u.jsxs("p",{className:"text-xs text-gray-500",children:["Variáveis disponíveis: ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{nome}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{primeiro_nome}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{empresa}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{cidade}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{minha_empresa}}"}),"."]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Template — texto"}),u.jsx("textarea",{value:e.texto,onChange:b=>n({...e,texto:b.target.value}),rows:4,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Template — áudio (texto para gravação)"}),u.jsx("textarea",{value:e.audio,onChange:b=>n({...e,audio:b.target.value}),rows:4,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Nome da sua empresa"}),u.jsx("input",{value:s,onChange:b=>r(b.target.value),className:"w-full max-w-xs px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{onClick:m,disabled:c,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 disabled:opacity-60",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar templates"]}),u.jsxs("button",{onClick:g,className:"px-4 py-2.5 text-sm font-medium text-indigo-600 bg-indigo-50 border border-indigo-200 rounded-lg hover:bg-indigo-100",children:[u.jsx("i",{className:"fas fa-vial mr-2"})," Testar com lead de exemplo"]})]})]}),u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 text-sm text-gray-500 space-y-2",children:[u.jsx("p",{className:"font-medium text-gray-700 text-xs uppercase tracking-wide",children:"Como funciona"}),u.jsxs("p",{children:["O envio em massa é executado pelo ",u.jsx("strong",{children:"OpenOutreach"})," (eracle/OpenOutreach). As campanhas ficam na página ",u.jsx("strong",{children:"Disparos"}),"; a validação da integração acontece na hora de iniciar a campanha — sem travas de pré-registro."]})]}),u.jsx(Xt,{aberto:a,onFechar:()=>l(!1),titulo:"Pré-visualização do template",icone:"fas fa-comment-dots",children:u.jsx("div",{className:"bg-gray-50 border border-gray-100 rounded-lg p-4 text-sm text-gray-700 whitespace-pre-wrap",children:i})})]})}function M2(){const{toast:t}=en(),[e,n]=S.useState("texto"),[s,r]=S.useState(""),[i,o]=S.useState([{role:"assistant",content:"Olá! Sou o assistente de atendimento do LeadMaster. Como posso ajudar?"}]),[a,l]=S.useState(""),[c,d]=S.useState(!1),f=S.useCallback(async()=>{const m=await W.config.obter();n(m.agentes.atendimento.modo==="voz"?"voz":"texto"),r(m.integracoes.pipecat.url||"")},[]);S.useEffect(()=>{f().catch(m=>t("erro",m.message))},[f,t]);const h=async m=>{n(m);try{await W.config.salvar({agentes:{atendimento:{modo:m}},integracoes:{pipecat:{url:s}}}),t("sucesso",`Modo de atendimento: ${m==="voz"?"voz (pipecat)":"texto (LLM)"}.`)}catch(g){t("erro",g instanceof Error?g.message:"Falha ao salvar modo.")}},p=async()=>{const m=a.trim();if(!m)return;const g=[...i,{role:"user",content:m}];o(g),l(""),d(!0);try{const b=await W.agentes.chat(g.map(y=>({role:y.role==="assistant"?"assistant":"user",content:y.content})));b.ok&&b.resposta?o([...g,{role:"assistant",content:b.resposta}]):(o([...g,{role:"assistant",content:`⚠ ${b.mensagem??"Sem resposta."}`}]),t("erro",b.mensagem??"Sem resposta do agente."))}catch(b){t("erro",b instanceof Error?b.message:"Falha no chat.")}finally{d(!1)}};return u.jsxs("div",{className:"space-y-5 max-w-3xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800",children:"Modo do agente de atendimento"}),u.jsx("div",{className:"flex gap-3",children:[{id:"texto",rotulo:"Texto (LLM)",icone:"fas fa-keyboard",descricao:"Chat via LLM configurado"},{id:"voz",rotulo:"Voz (pipecat)",icone:"fas fa-microphone",descricao:"Atendimento por voz"}].map(m=>u.jsxs("button",{onClick:()=>h(m.id),className:H("flex-1 px-4 py-3 rounded-lg border text-left transition",e===m.id?"bg-indigo-50 border-indigo-400":"bg-white border-gray-200 hover:bg-gray-50"),children:[u.jsxs("p",{className:H("text-sm font-medium flex items-center gap-2",e===m.id?"text-indigo-700":"text-gray-600"),children:[u.jsx("i",{className:m.icone})," ",m.rotulo]}),u.jsx("p",{className:"text-xs text-gray-400 mt-1",children:m.descricao})]},m.id))}),e==="voz"&&u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"URL do serviço pipecat"}),u.jsx("input",{value:s,onChange:m=>r(m.target.value),onBlur:()=>h("voz"),placeholder:"http://localhost:5000",className:"w-full max-w-md px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})]}),u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800 mb-3",children:"Testar conversa"}),u.jsxs("div",{className:"space-y-3 max-h-80 overflow-y-auto mb-4",children:[i.map((m,g)=>u.jsx("div",{className:H("flex",m.role==="user"?"justify-end":"justify-start"),children:u.jsx("div",{className:H("max-w-[80%] px-4 py-2.5 rounded-2xl text-sm",m.role==="user"?"bg-indigo-500 text-white rounded-br-sm":"bg-gray-100 text-gray-700 rounded-bl-sm"),children:m.content})},g)),c&&u.jsxs("div",{className:"text-xs text-gray-400 flex items-center gap-2",children:[u.jsx("i",{className:"fas fa-spinner fa-spin"})," pensando..."]})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("input",{value:a,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&p(),placeholder:"Digite uma mensagem do cliente para testar...",className:"flex-1 px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"}),u.jsx("button",{onClick:p,disabled:c,className:"px-5 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 disabled:opacity-60",children:u.jsx("i",{className:"fas fa-paper-plane"})})]})]})]})}function P2({onConfigSalva:t}){const{toast:e}=en(),[n,s]=S.useState(null),[r,i]=S.useState(!1),[o,a]=S.useState(""),l=S.useCallback(async()=>{const h=await W.config.obter();s(h)},[]);if(S.useEffect(()=>{l().catch(h=>e("erro",h.message))},[l,e]),!n)return u.jsx("div",{className:"text-center text-gray-400 py-16",children:u.jsx("i",{className:"fas fa-spinner fa-spin text-2xl"})});const c=h=>{s(p=>{if(!p)return p;const m=JSON.parse(JSON.stringify(p));return h(m),m})},d=async()=>{i(!0);try{const h=await W.config.salvar(n);s(h),t==null||t(h),e("sucesso","Configurações salvas localmente (config.json).")}catch(h){e("erro",h instanceof Error?h.message:"Falha ao salvar configurações.")}finally{i(!1)}},f=async()=>{a("llm");try{const h=await W.config.testarLlm();e(h.ok?"sucesso":"erro",h.ok?`LLM respondeu: ${h.resposta}`:h.mensagem??"Falha no teste.")}finally{a("")}};return u.jsxs("div",{className:"space-y-6 max-w-4xl",children:[u.jsxs(Va,{titulo:"LLM (agentes de IA)",icone:"fas fa-brain",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsx(an,{rotulo:"Base URL",valor:n.llm.base_url,onChange:h=>c(p=>{p.llm.base_url=h}),placeholder:"https://api.openai.com/v1"}),u.jsx(an,{rotulo:"Modelo",valor:n.llm.modelo,onChange:h=>c(p=>{p.llm.modelo=h}),placeholder:"gpt-4o-mini"}),u.jsx(O2,{rotulo:"API Key",configurado:!!n.llm.api_key_configurado,onChange:h=>c(p=>{p.llm.api_key=h})})]}),u.jsx(T2,{rotulo:"Testar conexão LLM",carregando:o==="llm",onClick:f})]}),u.jsxs(Va,{titulo:"Extratores de leads",icone:"fas fa-magnifying-glass-location",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(an,{rotulo:"Google Maps Scraper — binário",valor:n.extratores.google_maps_cli,onChange:h=>c(p=>{p.extratores.google_maps_cli=h}),placeholder:"C:\\ferramentas\\google-maps-scraper.exe"}),u.jsx(an,{rotulo:"igmapper — binário",valor:n.extratores.igmapper_cli,onChange:h=>c(p=>{p.extratores.igmapper_cli=h}),placeholder:"Caminho do CLI igmapper"})]}),u.jsxs(Qt,{titulo:"Argumentos dos scrapers (templates)",icone:"fas fa-terminal",children:[u.jsx(bm,{rotulo:"Google Maps — template de argumentos",valor:n.extratores.google_maps_args,onChange:h=>c(p=>{p.extratores.google_maps_args=h}),linhas:2}),u.jsx(bm,{rotulo:"igmapper — template de argumentos",valor:n.extratores.igmapper_args,onChange:h=>c(p=>{p.extratores.igmapper_args=h}),linhas:2})]}),u.jsxs(Qt,{titulo:"CNPJ e Scrapling",icone:"fas fa-building",children:[u.jsx(an,{rotulo:"Provedor de busca CNAE/UF — URL",valor:n.extratores.cnpj_provedor_busca,onChange:h=>c(p=>{p.extratores.cnpj_provedor_busca=h}),placeholder:"https://api.opencnpj.org"}),u.jsx(an,{rotulo:"Scrapling — binário (scraping profundo)",valor:n.extratores.scrapling_cli,onChange:h=>c(p=>{p.extratores.scrapling_cli=h}),placeholder:"Caminho do CLI Scrapling"})]})]}),u.jsxs(Va,{titulo:"Agentes — integrações",icone:"fas fa-robot",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(an,{rotulo:"OpenOutreach — URL",valor:n.integracoes.openoutreach.url,onChange:h=>c(p=>{p.integracoes.openoutreach.url=h}),placeholder:"http://localhost:9090"}),u.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-600 bg-indigo-50 border border-indigo-100 rounded-lg px-3 py-2.5 cursor-pointer h-fit mt-5",children:[u.jsx("input",{type:"checkbox",checked:n.integracoes.openoutreach.enabled,onChange:h=>c(p=>{p.integracoes.openoutreach.enabled=h.target.checked}),className:"w-4 h-4 accent-indigo-500"}),"OpenOutreach ativo"]})]}),u.jsx(an,{rotulo:"pipecat — URL (atendimento por voz)",valor:n.integracoes.pipecat.url,onChange:h=>c(p=>{p.integracoes.pipecat.url=h}),placeholder:"http://localhost:5000"})]}),u.jsx(Va,{titulo:"Perfil e licença",icone:"fas fa-user",children:u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsx(an,{rotulo:"Seu nome",valor:n.perfil.nome,onChange:h=>c(p=>{p.perfil.nome=h})}),u.jsx(an,{rotulo:"Expira em",valor:n.perfil.licenca.expira_em,onChange:h=>c(p=>{p.perfil.licenca.expira_em=h})}),u.jsx(R2,{rotulo:"Dias restantes (vazio = infinito)",valor:n.perfil.licenca.restam_dias??0,onChange:h=>c(p=>{p.perfil.licenca.restam_dias=h>0?h:null})})]})}),u.jsx("div",{className:"flex justify-end",children:u.jsxs("button",{onClick:d,disabled:r,className:"px-8 py-3 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fas fa-save mr-2",r&&"fa-spin")}),r?"Salvando...":"Salvar configurações"]})})]})}function Va({titulo:t,icone:e,children:n}){return u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4",children:[u.jsxs("h3",{className:"text-sm font-semibold text-gray-800 flex items-center gap-2",children:[u.jsx("i",{className:H(e,"text-indigo-400")})," ",t]}),n]})}function an({rotulo:t,valor:e,onChange:n,placeholder:s,tipo:r="text"}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("input",{type:r,value:e,onChange:i=>n(i.target.value),placeholder:s,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function R2({rotulo:t,valor:e,onChange:n}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("input",{type:"number",value:e??0,onChange:s=>n(Number(s.target.value)||0),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function O2({rotulo:t,configurado:e,onChange:n}){return u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:[t," ",e&&u.jsx("span",{className:"text-green-600",children:"• configurado"})]}),u.jsx("input",{type:"password",onChange:s=>n(s.target.value),placeholder:e?"•••••••• (deixe vazio para manter)":"cole a chave aqui",className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function bm({rotulo:t,valor:e,onChange:n,linhas:s=3}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("textarea",{value:e,onChange:r=>n(r.target.value),rows:s,className:"w-full px-3 py-2 text-xs font-mono border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function T2({rotulo:t,onClick:e,carregando:n}){return u.jsxs("button",{onClick:e,disabled:n,className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium disabled:opacity-50",children:[u.jsx("i",{className:H("fas fa-vial-circle-check mr-1",n&&"fa-spin")})," ",t]})}const D2=[{id:"lead.criado",rotulo:"Lead criado"},{id:"lead.etapa",rotulo:"Lead mudou de etapa"},{id:"campanha.concluida",rotulo:"Campanha concluída"}];function L2(){const{toast:t}=en(),[e,n]=S.useState(""),[s,r]=S.useState(new Set),[i,o]=S.useState(""),[a,l]=S.useState(!1),[c,d]=S.useState(!1),f=S.useCallback(async()=>{const g=await W.webhook.obter();n(g.url),r(new Set(g.eventos))},[]);S.useEffect(()=>{f().catch(g=>t("erro",g.message))},[f,t]);const h=g=>r(b=>{const y=new Set(b);return y.has(g)?y.delete(g):y.add(g),y}),p=async()=>{d(!0);try{await W.webhook.salvar({url:e.trim(),eventos:[...s]}),t("sucesso","Webhook salvo.")}catch(g){t("erro",g instanceof Error?g.message:"Falha ao salvar webhook.")}finally{d(!1)}},m=async()=>{if(!e.trim()){t("erro","Informe a URL do webhook antes de testar.");return}try{const g=await W.webhook.testar(e.trim());g.ok?o(`✅ HTTP ${g.status_http} — o endpoint recebeu o evento de teste.
88
+ `},TN={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function DN(t){let{announcements:e=TN,container:n,hiddenTextDescribedById:s,screenReaderInstructions:r=ON}=t;const{announce:i,announcement:o}=MN(),a=aa("DndLiveRegion"),[l,c]=S.useState(!1);if(S.useEffect(()=>{c(!0)},[]),PN(S.useMemo(()=>({onDragStart(f){let{active:h}=f;i(e.onDragStart({active:h}))},onDragMove(f){let{active:h,over:p}=f;e.onDragMove&&i(e.onDragMove({active:h,over:p}))},onDragOver(f){let{active:h,over:p}=f;i(e.onDragOver({active:h,over:p}))},onDragEnd(f){let{active:h,over:p}=f;i(e.onDragEnd({active:h,over:p}))},onDragCancel(f){let{active:h,over:p}=f;i(e.onDragCancel({active:h,over:p}))}}),[i,e])),!l)return null;const d=pe.createElement(pe.Fragment,null,pe.createElement(NN,{id:s,value:r.draggable}),pe.createElement(EN,{id:a,announcement:o}));return n?Ar.createPortal(d,n):d}var Te;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Te||(Te={}));function Zl(){}function LN(t,e){return S.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function AN(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return S.useMemo(()=>[...e].filter(s=>s!=null),[...e])}const Zt=Object.freeze({x:0,y:0});function IN(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function FN(t,e){const n=Jl(t);if(!n)return"0 0";const s={x:(n.x-e.left)/e.width*100,y:(n.y-e.top)/e.height*100};return s.x+"% "+s.y+"%"}function zN(t,e){let{data:{value:n}}=t,{data:{value:s}}=e;return n-s}function BN(t,e){let{data:{value:n}}=t,{data:{value:s}}=e;return s-n}function am(t){let{left:e,top:n,height:s,width:r}=t;return[{x:e,y:n},{x:e+r,y:n},{x:e,y:n+s},{x:e+r,y:n+s}]}function $N(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}const UN=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:s}=t;const r=am(e),i=[];for(const o of s){const{id:a}=o,l=n.get(a);if(l){const c=am(l),d=r.reduce((h,p,m)=>h+IN(c[m],p),0),f=Number((d/4).toFixed(4));i.push({id:a,data:{droppableContainer:o,value:f}})}}return i.sort(zN)};function WN(t,e){const n=Math.max(e.top,t.top),s=Math.max(e.left,t.left),r=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),o=r-s,a=i-n;if(s<r&&n<i){const l=e.width*e.height,c=t.width*t.height,d=o*a,f=d/(l+c-d);return Number(f.toFixed(4))}return 0}const HN=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:s}=t;const r=[];for(const i of s){const{id:o}=i,a=n.get(o);if(a){const l=WN(a,e);l>0&&r.push({id:o,data:{droppableContainer:i,value:l}})}}return r.sort(BN)};function VN(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function lv(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:Zt}function QN(t){return function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),i=1;i<s;i++)r[i-1]=arguments[i];return r.reduce((o,a)=>({...o,top:o.top+t*a.y,bottom:o.bottom+t*a.y,left:o.left+t*a.x,right:o.right+t*a.x}),{...n})}}const KN=QN(1);function cv(t){if(t.startsWith("matrix3d(")){const e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){const e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function YN(t,e,n){const s=cv(e);if(!s)return t;const{scaleX:r,scaleY:i,x:o,y:a}=s,l=t.left-o-(1-r)*parseFloat(n),c=t.top-a-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),d=r?t.width/r:t.width,f=i?t.height/i:t.height;return{width:d,height:f,top:c,right:l+d,bottom:c+f,left:l}}const XN={ignoreTransform:!1};function Ci(t,e){e===void 0&&(e=XN);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:c,transformOrigin:d}=st(t).getComputedStyle(t);c&&(n=YN(n,c,d))}const{top:s,left:r,width:i,height:o,bottom:a,right:l}=n;return{top:s,left:r,width:i,height:o,bottom:a,right:l}}function lm(t){return Ci(t,{ignoreTransform:!0})}function qN(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function GN(t,e){return e===void 0&&(e=st(t).getComputedStyle(t)),e.position==="fixed"}function JN(t,e){e===void 0&&(e=st(t).getComputedStyle(t));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(r=>{const i=e[r];return typeof i=="string"?n.test(i):!1})}function lh(t,e){const n=[];function s(r){if(e!=null&&n.length>=e||!r)return n;if(ah(r)&&r.scrollingElement!=null&&!n.includes(r.scrollingElement))return n.push(r.scrollingElement),n;if(!ia(r)||iv(r)||n.includes(r))return n;const i=st(t).getComputedStyle(r);return r!==t&&JN(r,i)&&n.push(r),GN(r,i)?n:s(r.parentNode)}return t?s(t):n}function uv(t){const[e]=lh(t,1);return e??null}function bu(t){return!kc||!t?null:_i(t)?t:oh(t)?ah(t)||t===ki(t).scrollingElement?window:ia(t)?t:null:null}function dv(t){return _i(t)?t.scrollX:t.scrollLeft}function fv(t){return _i(t)?t.scrollY:t.scrollTop}function $d(t){return{x:dv(t),y:fv(t)}}var Ie;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(Ie||(Ie={}));function hv(t){return!kc||!t?!1:t===document.scrollingElement}function pv(t){const e={x:0,y:0},n=hv(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},s={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},r=t.scrollTop<=e.y,i=t.scrollLeft<=e.x,o=t.scrollTop>=s.y,a=t.scrollLeft>=s.x;return{isTop:r,isLeft:i,isBottom:o,isRight:a,maxScroll:s,minScroll:e}}const ZN={x:.2,y:.2};function e2(t,e,n,s,r){let{top:i,left:o,right:a,bottom:l}=n;s===void 0&&(s=10),r===void 0&&(r=ZN);const{isTop:c,isBottom:d,isLeft:f,isRight:h}=pv(t),p={x:0,y:0},m={x:0,y:0},g={height:e.height*r.y,width:e.width*r.x};return!c&&i<=e.top+g.height?(p.y=Ie.Backward,m.y=s*Math.abs((e.top+g.height-i)/g.height)):!d&&l>=e.bottom-g.height&&(p.y=Ie.Forward,m.y=s*Math.abs((e.bottom-g.height-l)/g.height)),!h&&a>=e.right-g.width?(p.x=Ie.Forward,m.x=s*Math.abs((e.right-g.width-a)/g.width)):!f&&o<=e.left+g.width&&(p.x=Ie.Backward,m.x=s*Math.abs((e.left+g.width-o)/g.width)),{direction:p,speed:m}}function t2(t){if(t===document.scrollingElement){const{innerWidth:i,innerHeight:o}=window;return{top:0,left:0,right:i,bottom:o,width:i,height:o}}const{top:e,left:n,right:s,bottom:r}=t.getBoundingClientRect();return{top:e,left:n,right:s,bottom:r,width:t.clientWidth,height:t.clientHeight}}function gv(t){return t.reduce((e,n)=>Qr(e,$d(n)),Zt)}function n2(t){return t.reduce((e,n)=>e+dv(n),0)}function s2(t){return t.reduce((e,n)=>e+fv(n),0)}function mv(t,e){if(e===void 0&&(e=Ci),!t)return;const{top:n,left:s,bottom:r,right:i}=e(t);uv(t)&&(r<=0||i<=0||n>=window.innerHeight||s>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const r2=[["x",["left","right"],n2],["y",["top","bottom"],s2]];class ch{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=lh(n),r=gv(s);this.rect={...e},this.width=e.width,this.height=e.height;for(const[i,o,a]of r2)for(const l of o)Object.defineProperty(this,l,{get:()=>{const c=a(s),d=r[i]-c;return this.rect[l]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class go{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...n)})},this.target=e}add(e,n,s){var r;(r=this.target)==null||r.addEventListener(e,n,s),this.listeners.push([e,n,s])}}function i2(t){const{EventTarget:e}=st(t);return t instanceof e?t:ki(t)}function wu(t,e){const n=Math.abs(t.x),s=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+s**2)>e:"x"in e&&"y"in e?n>e.x&&s>e.y:"x"in e?n>e.x:"y"in e?s>e.y:!1}var Pt;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(Pt||(Pt={}));function cm(t){t.preventDefault()}function o2(t){t.stopPropagation()}var se;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(se||(se={}));const xv={start:[se.Space,se.Enter],cancel:[se.Esc],end:[se.Space,se.Enter,se.Tab]},a2=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case se.Right:return{...n,x:n.x+25};case se.Left:return{...n,x:n.x-25};case se.Down:return{...n,y:n.y+25};case se.Up:return{...n,y:n.y-25}}};class yv{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new go(ki(n)),this.windowListeners=new go(st(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Pt.Resize,this.handleCancel),this.windowListeners.add(Pt.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Pt.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,s=e.node.current;s&&mv(s),n(Zt)}handleKeyDown(e){if(jc(e)){const{active:n,context:s,options:r}=this.props,{keyboardCodes:i=xv,coordinateGetter:o=a2,scrollBehavior:a="smooth"}=r,{code:l}=e;if(i.end.includes(l)){this.handleEnd(e);return}if(i.cancel.includes(l)){this.handleCancel(e);return}const{collisionRect:c}=s.current,d=c?{x:c.left,y:c.top}:Zt;this.referenceCoordinates||(this.referenceCoordinates=d);const f=o(e,{active:n,context:s.current,currentCoordinates:d});if(f){const h=Gl(f,d),p={x:0,y:0},{scrollableAncestors:m}=s.current;for(const g of m){const b=e.code,{isTop:y,isRight:x,isLeft:v,isBottom:_,maxScroll:w,minScroll:k}=pv(g),C=t2(g),j={x:Math.min(b===se.Right?C.right-C.width/2:C.right,Math.max(b===se.Right?C.left:C.left+C.width/2,f.x)),y:Math.min(b===se.Down?C.bottom-C.height/2:C.bottom,Math.max(b===se.Down?C.top:C.top+C.height/2,f.y))},M=b===se.Right&&!x||b===se.Left&&!v,E=b===se.Down&&!_||b===se.Up&&!y;if(M&&j.x!==f.x){const P=g.scrollLeft+h.x,A=b===se.Right&&P<=w.x||b===se.Left&&P>=k.x;if(A&&!h.y){g.scrollTo({left:P,behavior:a});return}A?p.x=g.scrollLeft-P:p.x=b===se.Right?g.scrollLeft-w.x:g.scrollLeft-k.x,p.x&&g.scrollBy({left:-p.x,behavior:a});break}else if(E&&j.y!==f.y){const P=g.scrollTop+h.y,A=b===se.Down&&P<=w.y||b===se.Up&&P>=k.y;if(A&&!h.x){g.scrollTo({top:P,behavior:a});return}A?p.y=g.scrollTop-P:p.y=b===se.Down?g.scrollTop-w.y:g.scrollTop-k.y,p.y&&g.scrollBy({top:-p.y,behavior:a});break}}this.handleMove(e,Qr(Gl(f,this.referenceCoordinates),p))}}}handleMove(e,n){const{onMove:s}=this.props;e.preventDefault(),s(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}yv.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:s=xv,onActivation:r}=e,{active:i}=n;const{code:o}=t.nativeEvent;if(s.start.includes(o)){const a=i.activatorNode.current;return a&&t.target!==a?!1:(t.preventDefault(),r==null||r({event:t.nativeEvent}),!0)}return!1}}];function um(t){return!!(t&&"distance"in t)}function dm(t){return!!(t&&"delay"in t)}class uh{constructor(e,n,s){var r;s===void 0&&(s=i2(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:i}=e,{target:o}=i;this.props=e,this.events=n,this.document=ki(o),this.documentListeners=new go(this.document),this.listeners=new go(s),this.windowListeners=new go(st(o)),this.initialCoordinates=(r=Jl(i))!=null?r:Zt,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:s}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Pt.Resize,this.handleCancel),this.windowListeners.add(Pt.DragStart,cm),this.windowListeners.add(Pt.VisibilityChange,this.handleCancel),this.windowListeners.add(Pt.ContextMenu,cm),this.documentListeners.add(Pt.Keydown,this.handleKeydown),n){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(dm(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(um(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:s,onPending:r}=this.props;r(s,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(Pt.Click,o2,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Pt.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:s,initialCoordinates:r,props:i}=this,{onMove:o,options:{activationConstraint:a}}=i;if(!r)return;const l=(n=Jl(e))!=null?n:Zt,c=Gl(r,l);if(!s&&a){if(um(a)){if(a.tolerance!=null&&wu(c,a.tolerance))return this.handleCancel();if(wu(c,a.distance))return this.handleStart()}if(dm(a)&&wu(c,a.tolerance))return this.handleCancel();this.handlePending(a,c);return}e.cancelable&&e.preventDefault(),o(l)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===se.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const l2={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class dh extends uh{constructor(e){const{event:n}=e,s=ki(n.target);super(e,l2,s)}}dh.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:s}=e;return!n.isPrimary||n.button!==0?!1:(s==null||s({event:n}),!0)}}];const c2={move:{name:"mousemove"},end:{name:"mouseup"}};var Ud;(function(t){t[t.RightClick=2]="RightClick"})(Ud||(Ud={}));class u2 extends uh{constructor(e){super(e,c2,ki(e.event.target))}}u2.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:s}=e;return n.button===Ud.RightClick?!1:(s==null||s({event:n}),!0)}}];const Su={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class d2 extends uh{constructor(e){super(e,Su)}static setup(){return window.addEventListener(Su.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(Su.move.name,e)};function e(){}}}d2.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:s}=e;const{touches:r}=n;return r.length>1?!1:(s==null||s({event:n}),!0)}}];var mo;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(mo||(mo={}));var ec;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(ec||(ec={}));function f2(t){let{acceleration:e,activator:n=mo.Pointer,canScroll:s,draggingRect:r,enabled:i,interval:o=5,order:a=ec.TreeOrder,pointerCoordinates:l,scrollableAncestors:c,scrollableAncestorRects:d,delta:f,threshold:h}=t;const p=p2({delta:f,disabled:!i}),[m,g]=SN(),b=S.useRef({x:0,y:0}),y=S.useRef({x:0,y:0}),x=S.useMemo(()=>{switch(n){case mo.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case mo.DraggableRect:return r}},[n,r,l]),v=S.useRef(null),_=S.useCallback(()=>{const k=v.current;if(!k)return;const C=b.current.x*y.current.x,j=b.current.y*y.current.y;k.scrollBy(C,j)},[]),w=S.useMemo(()=>a===ec.TreeOrder?[...c].reverse():c,[a,c]);S.useEffect(()=>{if(!i||!c.length||!x){g();return}for(const k of w){if((s==null?void 0:s(k))===!1)continue;const C=c.indexOf(k),j=d[C];if(!j)continue;const{direction:M,speed:E}=e2(k,j,x,e,h);for(const P of["x","y"])p[P][M[P]]||(E[P]=0,M[P]=0);if(E.x>0||E.y>0){g(),v.current=k,m(_,o),b.current=E,y.current=M;return}}b.current={x:0,y:0},y.current={x:0,y:0},g()},[e,_,s,g,i,o,JSON.stringify(x),JSON.stringify(p),m,c,w,d,JSON.stringify(h)])}const h2={x:{[Ie.Backward]:!1,[Ie.Forward]:!1},y:{[Ie.Backward]:!1,[Ie.Forward]:!1}};function p2(t){let{delta:e,disabled:n}=t;const s=ql(e);return oa(r=>{if(n||!s||!r)return h2;const i={x:Math.sign(e.x-s.x),y:Math.sign(e.y-s.y)};return{x:{[Ie.Backward]:r.x[Ie.Backward]||i.x===-1,[Ie.Forward]:r.x[Ie.Forward]||i.x===1},y:{[Ie.Backward]:r.y[Ie.Backward]||i.y===-1,[Ie.Forward]:r.y[Ie.Forward]||i.y===1}}},[n,e,s])}function g2(t,e){const n=e!=null?t.get(e):void 0,s=n?n.node.current:null;return oa(r=>{var i;return e==null?null:(i=s??r)!=null?i:null},[s,e])}function m2(t,e){return S.useMemo(()=>t.reduce((n,s)=>{const{sensor:r}=s,i=r.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,s)}));return[...n,...i]},[]),[t,e])}var Wo;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(Wo||(Wo={}));var Wd;(function(t){t.Optimized="optimized"})(Wd||(Wd={}));const fm=new Map;function x2(t,e){let{dragging:n,dependencies:s,config:r}=e;const[i,o]=S.useState(null),{frequency:a,measure:l,strategy:c}=r,d=S.useRef(t),f=b(),h=Uo(f),p=S.useCallback(function(y){y===void 0&&(y=[]),!h.current&&o(x=>x===null?y:x.concat(y.filter(v=>!x.includes(v))))},[h]),m=S.useRef(null),g=oa(y=>{if(f&&!n)return fm;if(!y||y===fm||d.current!==t||i!=null){const x=new Map;for(let v of t){if(!v)continue;if(i&&i.length>0&&!i.includes(v.id)&&v.rect.current){x.set(v.id,v.rect.current);continue}const _=v.node.current,w=_?new ch(l(_),_):null;v.rect.current=w,w&&x.set(v.id,w)}return x}return y},[t,i,n,f,l]);return S.useEffect(()=>{d.current=t},[t]),S.useEffect(()=>{f||p()},[n,f]),S.useEffect(()=>{i&&i.length>0&&o(null)},[JSON.stringify(i)]),S.useEffect(()=>{f||typeof a!="number"||m.current!==null||(m.current=setTimeout(()=>{p(),m.current=null},a))},[a,f,p,...s]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:i!=null};function b(){switch(c){case Wo.Always:return!1;case Wo.BeforeDragging:return n;default:return!n}}}function fh(t,e){return oa(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function y2(t,e){return fh(t,e)}function v2(t){let{callback:e,disabled:n}=t;const s=Cc(e),r=S.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(s)},[s,n]);return S.useEffect(()=>()=>r==null?void 0:r.disconnect(),[r]),r}function Nc(t){let{callback:e,disabled:n}=t;const s=Cc(e),r=S.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(s)},[n]);return S.useEffect(()=>()=>r==null?void 0:r.disconnect(),[r]),r}function b2(t){return new ch(Ci(t),t)}function hm(t,e,n){e===void 0&&(e=b2);const[s,r]=S.useState(null);function i(){r(l=>{if(!t)return null;if(t.isConnected===!1){var c;return(c=l??n)!=null?c:null}const d=e(t);return JSON.stringify(l)===JSON.stringify(d)?l:d})}const o=v2({callback(l){if(t)for(const c of l){const{type:d,target:f}=c;if(d==="childList"&&f instanceof HTMLElement&&f.contains(t)){i();break}}}}),a=Nc({callback:i});return Jt(()=>{i(),t?(a==null||a.observe(t),o==null||o.observe(document.body,{childList:!0,subtree:!0})):(a==null||a.disconnect(),o==null||o.disconnect())},[t]),s}function w2(t){const e=fh(t);return lv(t,e)}const pm=[];function S2(t){const e=S.useRef(t),n=oa(s=>t?s&&s!==pm&&t&&e.current&&t.parentNode===e.current.parentNode?s:lh(t):pm,[t]);return S.useEffect(()=>{e.current=t},[t]),n}function _2(t){const[e,n]=S.useState(null),s=S.useRef(t),r=S.useCallback(i=>{const o=bu(i.target);o&&n(a=>a?(a.set(o,$d(o)),new Map(a)):null)},[]);return S.useEffect(()=>{const i=s.current;if(t!==i){o(i);const a=t.map(l=>{const c=bu(l);return c?(c.addEventListener("scroll",r,{passive:!0}),[c,$d(c)]):null}).filter(l=>l!=null);n(a.length?new Map(a):null),s.current=t}return()=>{o(t),o(i)};function o(a){a.forEach(l=>{const c=bu(l);c==null||c.removeEventListener("scroll",r)})}},[r,t]),S.useMemo(()=>t.length?e?Array.from(e.values()).reduce((i,o)=>Qr(i,o),Zt):gv(t):Zt,[t,e])}function gm(t,e){e===void 0&&(e=[]);const n=S.useRef(null);return S.useEffect(()=>{n.current=null},e),S.useEffect(()=>{const s=t!==Zt;s&&!n.current&&(n.current=t),!s&&n.current&&(n.current=null)},[t]),n.current?Gl(t,n.current):Zt}function k2(t){S.useEffect(()=>{if(!kc)return;const e=t.map(n=>{let{sensor:s}=n;return s.setup==null?void 0:s.setup()});return()=>{for(const n of e)n==null||n()}},t.map(e=>{let{sensor:n}=e;return n}))}function C2(t,e){return S.useMemo(()=>t.reduce((n,s)=>{let{eventName:r,handler:i}=s;return n[r]=o=>{i(o,e)},n},{}),[t,e])}function vv(t){return S.useMemo(()=>t?qN(t):null,[t])}const mm=[];function j2(t,e){e===void 0&&(e=Ci);const[n]=t,s=vv(n?st(n):null),[r,i]=S.useState(mm);function o(){i(()=>t.length?t.map(l=>hv(l)?s:new ch(e(l),l)):mm)}const a=Nc({callback:o});return Jt(()=>{a==null||a.disconnect(),o(),t.forEach(l=>a==null?void 0:a.observe(l))},[t]),r}function bv(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return ia(e)?e:t}function N2(t){let{measure:e}=t;const[n,s]=S.useState(null),r=S.useCallback(c=>{for(const{target:d}of c)if(ia(d)){s(f=>{const h=e(d);return f?{...f,width:h.width,height:h.height}:h});break}},[e]),i=Nc({callback:r}),o=S.useCallback(c=>{const d=bv(c);i==null||i.disconnect(),d&&(i==null||i.observe(d)),s(d?e(d):null)},[e,i]),[a,l]=Xl(o);return S.useMemo(()=>({nodeRef:a,rect:n,setRef:l}),[n,a,l])}const E2=[{sensor:dh,options:{}},{sensor:yv,options:{}}],M2={current:{}},cl={draggable:{measure:lm},droppable:{measure:lm,strategy:Wo.WhileDragging,frequency:Wd.Optimized},dragOverlay:{measure:Ci}};class xo extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,s;return(n=(s=this.get(e))==null?void 0:s.node.current)!=null?n:void 0}}const P2={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new xo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Zl},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:cl,measureDroppableContainers:Zl,windowRect:null,measuringScheduled:!1},wv={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Zl,draggableNodes:new Map,over:null,measureDroppableContainers:Zl},la=S.createContext(wv),Sv=S.createContext(P2);function R2(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new xo}}}function O2(t,e){switch(e.type){case Te.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case Te.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case Te.DragEnd:case Te.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Te.RegisterDroppable:{const{element:n}=e,{id:s}=n,r=new xo(t.droppable.containers);return r.set(s,n),{...t,droppable:{...t.droppable,containers:r}}}case Te.SetDroppableDisabled:{const{id:n,key:s,disabled:r}=e,i=t.droppable.containers.get(n);if(!i||s!==i.key)return t;const o=new xo(t.droppable.containers);return o.set(n,{...i,disabled:r}),{...t,droppable:{...t.droppable,containers:o}}}case Te.UnregisterDroppable:{const{id:n,key:s}=e,r=t.droppable.containers.get(n);if(!r||s!==r.key)return t;const i=new xo(t.droppable.containers);return i.delete(n),{...t,droppable:{...t.droppable,containers:i}}}default:return t}}function T2(t){let{disabled:e}=t;const{active:n,activatorEvent:s,draggableNodes:r}=S.useContext(la),i=ql(s),o=ql(n==null?void 0:n.id);return S.useEffect(()=>{if(!e&&!s&&i&&o!=null){if(!jc(i)||document.activeElement===i.target)return;const a=r.get(o);if(!a)return;const{activatorNode:l,node:c}=a;if(!l.current&&!c.current)return;requestAnimationFrame(()=>{for(const d of[l.current,c.current]){if(!d)continue;const f=CN(d);if(f){f.focus();break}}})}},[s,e,r,o,i]),null}function _v(t,e){let{transform:n,...s}=e;return t!=null&&t.length?t.reduce((r,i)=>i({transform:r,...s}),n):n}function D2(t){return S.useMemo(()=>({draggable:{...cl.draggable,...t==null?void 0:t.draggable},droppable:{...cl.droppable,...t==null?void 0:t.droppable},dragOverlay:{...cl.dragOverlay,...t==null?void 0:t.dragOverlay}}),[t==null?void 0:t.draggable,t==null?void 0:t.droppable,t==null?void 0:t.dragOverlay])}function L2(t){let{activeNode:e,measure:n,initialRect:s,config:r=!0}=t;const i=S.useRef(!1),{x:o,y:a}=typeof r=="boolean"?{x:r,y:r}:r;Jt(()=>{if(!o&&!a||!e){i.current=!1;return}if(i.current||!s)return;const c=e==null?void 0:e.node.current;if(!c||c.isConnected===!1)return;const d=n(c),f=lv(d,s);if(o||(f.x=0),a||(f.y=0),i.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const h=uv(c);h&&h.scrollBy({top:f.y,left:f.x})}},[e,o,a,s,n])}const Ec=S.createContext({...Zt,scaleX:1,scaleY:1});var Yn;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(Yn||(Yn={}));const A2=S.memo(function(e){var n,s,r,i;let{id:o,accessibility:a,autoScroll:l=!0,children:c,sensors:d=E2,collisionDetection:f=HN,measuring:h,modifiers:p,...m}=e;const g=S.useReducer(O2,void 0,R2),[b,y]=g,[x,v]=RN(),[_,w]=S.useState(Yn.Uninitialized),k=_===Yn.Initialized,{draggable:{active:C,nodes:j,translate:M},droppable:{containers:E}}=b,P=C!=null?j.get(C):null,A=S.useRef({initial:null,translated:null}),Q=S.useMemo(()=>{var Ve;return C!=null?{id:C,data:(Ve=P==null?void 0:P.data)!=null?Ve:M2,rect:A}:null},[C,P]),ne=S.useRef(null),[Y,oe]=S.useState(null),[G,O]=S.useState(null),L=Uo(m,Object.values(m)),I=aa("DndDescribedBy",o),V=S.useMemo(()=>E.getEnabled(),[E]),F=D2(h),{droppableRects:ce,measureDroppableContainers:$,measuringScheduled:ke}=x2(V,{dragging:k,dependencies:[M.x,M.y],config:F.droppable}),J=g2(j,C),gt=S.useMemo(()=>G?Jl(G):null,[G]),Ft=zv(),zt=y2(J,F.draggable.measure);L2({activeNode:C!=null?j.get(C):null,config:Ft.layoutShiftCompensation,initialRect:zt,measure:F.draggable.measure});const ie=hm(J,F.draggable.measure,zt),ji=hm(J?J.parentElement:null),tn=S.useRef({activatorEvent:null,active:null,activeNode:J,collisionRect:null,collisions:null,droppableRects:ce,draggableNodes:j,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),pr=E.getNodeFor((n=tn.current.over)==null?void 0:n.id),vn=N2({measure:F.dragOverlay.measure}),gr=(s=vn.nodeRef.current)!=null?s:J,mr=k?(r=vn.rect)!=null?r:ie:null,hh=!!(vn.nodeRef.current&&vn.rect),ph=w2(hh?null:ie),Mc=vv(gr?st(gr):null),Fn=S2(k?pr??J:null),ca=j2(Fn),ua=_v(p,{transform:{x:M.x-ph.x,y:M.y-ph.y,scaleX:1,scaleY:1},activatorEvent:G,active:Q,activeNodeRect:ie,containerNodeRect:ji,draggingNodeRect:mr,over:tn.current.over,overlayNodeRect:vn.rect,scrollableAncestors:Fn,scrollableAncestorRects:ca,windowRect:Mc}),gh=gt?Qr(gt,M):null,mh=_2(Fn),Ov=gm(mh),Tv=gm(mh,[ie]),xr=Qr(ua,Ov),yr=mr?KN(mr,ua):null,Ni=Q&&yr?f({active:Q,collisionRect:yr,droppableRects:ce,droppableContainers:V,pointerCoordinates:gh}):null,xh=$N(Ni,"id"),[zn,yh]=S.useState(null),Dv=hh?ua:Qr(ua,Tv),Lv=VN(Dv,(i=zn==null?void 0:zn.rect)!=null?i:null,ie),Pc=S.useRef(null),vh=S.useCallback((Ve,mt)=>{let{sensor:xt,options:Bn}=mt;if(ne.current==null)return;const Nt=j.get(ne.current);if(!Nt)return;const yt=Ve.nativeEvent,nn=new xt({active:ne.current,activeNode:Nt,event:yt,options:Bn,context:tn,onAbort(Be){if(!j.get(Be))return;const{onDragAbort:sn}=L.current,bn={id:Be};sn==null||sn(bn),x({type:"onDragAbort",event:bn})},onPending(Be,$n,sn,bn){if(!j.get(Be))return;const{onDragPending:Mi}=L.current,Un={id:Be,constraint:$n,initialCoordinates:sn,offset:bn};Mi==null||Mi(Un),x({type:"onDragPending",event:Un})},onStart(Be){const $n=ne.current;if($n==null)return;const sn=j.get($n);if(!sn)return;const{onDragStart:bn}=L.current,Ei={activatorEvent:yt,active:{id:$n,data:sn.data,rect:A}};Ar.unstable_batchedUpdates(()=>{bn==null||bn(Ei),w(Yn.Initializing),y({type:Te.DragStart,initialCoordinates:Be,active:$n}),x({type:"onDragStart",event:Ei}),oe(Pc.current),O(yt)})},onMove(Be){y({type:Te.DragMove,coordinates:Be})},onEnd:vr(Te.DragEnd),onCancel:vr(Te.DragCancel)});Pc.current=nn;function vr(Be){return async function(){const{active:sn,collisions:bn,over:Ei,scrollAdjustedTranslate:Mi}=tn.current;let Un=null;if(sn&&Mi){const{cancelDrop:Pi}=L.current;Un={activatorEvent:yt,active:sn,collisions:bn,delta:Mi,over:Ei},Be===Te.DragEnd&&typeof Pi=="function"&&await Promise.resolve(Pi(Un))&&(Be=Te.DragCancel)}ne.current=null,Ar.unstable_batchedUpdates(()=>{y({type:Be}),w(Yn.Uninitialized),yh(null),oe(null),O(null),Pc.current=null;const Pi=Be===Te.DragEnd?"onDragEnd":"onDragCancel";if(Un){const Rc=L.current[Pi];Rc==null||Rc(Un),x({type:Pi,event:Un})}})}}},[j]),Av=S.useCallback((Ve,mt)=>(xt,Bn)=>{const Nt=xt.nativeEvent,yt=j.get(Bn);if(ne.current!==null||!yt||Nt.dndKit||Nt.defaultPrevented)return;const nn={active:yt};Ve(xt,mt.options,nn)===!0&&(Nt.dndKit={capturedBy:mt.sensor},ne.current=Bn,vh(xt,mt))},[j,vh]),bh=m2(d,Av);k2(d),Jt(()=>{ie&&_===Yn.Initializing&&w(Yn.Initialized)},[ie,_]),S.useEffect(()=>{const{onDragMove:Ve}=L.current,{active:mt,activatorEvent:xt,collisions:Bn,over:Nt}=tn.current;if(!mt||!xt)return;const yt={active:mt,activatorEvent:xt,collisions:Bn,delta:{x:xr.x,y:xr.y},over:Nt};Ar.unstable_batchedUpdates(()=>{Ve==null||Ve(yt),x({type:"onDragMove",event:yt})})},[xr.x,xr.y]),S.useEffect(()=>{const{active:Ve,activatorEvent:mt,collisions:xt,droppableContainers:Bn,scrollAdjustedTranslate:Nt}=tn.current;if(!Ve||ne.current==null||!mt||!Nt)return;const{onDragOver:yt}=L.current,nn=Bn.get(xh),vr=nn&&nn.rect.current?{id:nn.id,rect:nn.rect.current,data:nn.data,disabled:nn.disabled}:null,Be={active:Ve,activatorEvent:mt,collisions:xt,delta:{x:Nt.x,y:Nt.y},over:vr};Ar.unstable_batchedUpdates(()=>{yh(vr),yt==null||yt(Be),x({type:"onDragOver",event:Be})})},[xh]),Jt(()=>{tn.current={activatorEvent:G,active:Q,activeNode:J,collisionRect:yr,collisions:Ni,droppableRects:ce,draggableNodes:j,draggingNode:gr,draggingNodeRect:mr,droppableContainers:E,over:zn,scrollableAncestors:Fn,scrollAdjustedTranslate:xr},A.current={initial:mr,translated:yr}},[Q,J,Ni,yr,j,gr,mr,ce,E,zn,Fn,xr]),f2({...Ft,delta:M,draggingRect:yr,pointerCoordinates:gh,scrollableAncestors:Fn,scrollableAncestorRects:ca});const Iv=S.useMemo(()=>({active:Q,activeNode:J,activeNodeRect:ie,activatorEvent:G,collisions:Ni,containerNodeRect:ji,dragOverlay:vn,draggableNodes:j,droppableContainers:E,droppableRects:ce,over:zn,measureDroppableContainers:$,scrollableAncestors:Fn,scrollableAncestorRects:ca,measuringConfiguration:F,measuringScheduled:ke,windowRect:Mc}),[Q,J,ie,G,Ni,ji,vn,j,E,ce,zn,$,Fn,ca,F,ke,Mc]),Fv=S.useMemo(()=>({activatorEvent:G,activators:bh,active:Q,activeNodeRect:ie,ariaDescribedById:{draggable:I},dispatch:y,draggableNodes:j,over:zn,measureDroppableContainers:$}),[G,bh,Q,ie,y,I,j,zn,$]);return pe.createElement(av.Provider,{value:v},pe.createElement(la.Provider,{value:Fv},pe.createElement(Sv.Provider,{value:Iv},pe.createElement(Ec.Provider,{value:Lv},c)),pe.createElement(T2,{disabled:(a==null?void 0:a.restoreFocus)===!1})),pe.createElement(DN,{...a,hiddenTextDescribedById:I}));function zv(){const Ve=(Y==null?void 0:Y.autoScrollEnabled)===!1,mt=typeof l=="object"?l.enabled===!1:l===!1,xt=k&&!Ve&&!mt;return typeof l=="object"?{...l,enabled:xt}:{enabled:xt}}}),I2=S.createContext(null),xm="button",F2="Draggable";function z2(t){let{id:e,data:n,disabled:s=!1,attributes:r}=t;const i=aa(F2),{activators:o,activatorEvent:a,active:l,activeNodeRect:c,ariaDescribedById:d,draggableNodes:f,over:h}=S.useContext(la),{role:p=xm,roleDescription:m="draggable",tabIndex:g=0}=r??{},b=(l==null?void 0:l.id)===e,y=S.useContext(b?Ec:I2),[x,v]=Xl(),[_,w]=Xl(),k=C2(o,e),C=Uo(n);Jt(()=>(f.set(e,{id:e,key:i,node:x,activatorNode:_,data:C}),()=>{const M=f.get(e);M&&M.key===i&&f.delete(e)}),[f,e]);const j=S.useMemo(()=>({role:p,tabIndex:g,"aria-disabled":s,"aria-pressed":b&&p===xm?!0:void 0,"aria-roledescription":m,"aria-describedby":d.draggable}),[s,p,g,b,m,d.draggable]);return{active:l,activatorEvent:a,activeNodeRect:c,attributes:j,isDragging:b,listeners:s?void 0:k,node:x,over:h,setNodeRef:v,setActivatorNodeRef:w,transform:y}}function kv(){return S.useContext(Sv)}const B2="Droppable",$2={timeout:25};function Cv(t){let{data:e,disabled:n=!1,id:s,resizeObserverConfig:r}=t;const i=aa(B2),{active:o,dispatch:a,over:l,measureDroppableContainers:c}=S.useContext(la),d=S.useRef({disabled:n}),f=S.useRef(!1),h=S.useRef(null),p=S.useRef(null),{disabled:m,updateMeasurementsFor:g,timeout:b}={...$2,...r},y=Uo(g??s),x=S.useCallback(()=>{if(!f.current){f.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{c(Array.isArray(y.current)?y.current:[y.current]),p.current=null},b)},[b]),v=Nc({callback:x,disabled:m||!o}),_=S.useCallback((j,M)=>{v&&(M&&(v.unobserve(M),f.current=!1),j&&v.observe(j))},[v]),[w,k]=Xl(_),C=Uo(e);return S.useEffect(()=>{!v||!w.current||(v.disconnect(),f.current=!1,v.observe(w.current))},[w,v]),S.useEffect(()=>(a({type:Te.RegisterDroppable,element:{id:s,key:i,disabled:n,node:w,rect:h,data:C}}),()=>a({type:Te.UnregisterDroppable,key:i,id:s})),[s]),S.useEffect(()=>{n!==d.current.disabled&&(a({type:Te.SetDroppableDisabled,id:s,key:i,disabled:n}),d.current.disabled=n)},[s,i,n,a]),{active:o,rect:h,isOver:(l==null?void 0:l.id)===s,node:w,over:l,setNodeRef:k}}function U2(t){let{animation:e,children:n}=t;const[s,r]=S.useState(null),[i,o]=S.useState(null),a=ql(n);return!n&&!s&&a&&r(a),Jt(()=>{if(!i)return;const l=s==null?void 0:s.key,c=s==null?void 0:s.props.id;if(l==null||c==null){r(null);return}Promise.resolve(e(c,i)).then(()=>{r(null)})},[e,s,i]),pe.createElement(pe.Fragment,null,n,s?S.cloneElement(s,{ref:o}):null)}const W2={x:0,y:0,scaleX:1,scaleY:1};function H2(t){let{children:e}=t;return pe.createElement(la.Provider,{value:wv},pe.createElement(Ec.Provider,{value:W2},e))}const V2={position:"fixed",touchAction:"none"},Q2=t=>jc(t)?"transform 250ms ease":void 0,K2=S.forwardRef((t,e)=>{let{as:n,activatorEvent:s,adjustScale:r,children:i,className:o,rect:a,style:l,transform:c,transition:d=Q2}=t;if(!a)return null;const f=r?c:{...c,scaleX:1,scaleY:1},h={...V2,width:a.width,height:a.height,top:a.top,left:a.left,transform:Ns.Transform.toString(f),transformOrigin:r&&s?FN(s,a):void 0,transition:typeof d=="function"?d(s):d,...l};return pe.createElement(n,{className:o,style:h,ref:e},i)}),Y2=t=>e=>{let{active:n,dragOverlay:s}=e;const r={},{styles:i,className:o}=t;if(i!=null&&i.active)for(const[a,l]of Object.entries(i.active))l!==void 0&&(r[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,l));if(i!=null&&i.dragOverlay)for(const[a,l]of Object.entries(i.dragOverlay))l!==void 0&&s.node.style.setProperty(a,l);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&s.node.classList.add(o.dragOverlay),function(){for(const[l,c]of Object.entries(r))n.node.style.setProperty(l,c);o!=null&&o.active&&n.node.classList.remove(o.active)}},X2=t=>{let{transform:{initial:e,final:n}}=t;return[{transform:Ns.Transform.toString(e)},{transform:Ns.Transform.toString(n)}]},q2={duration:250,easing:"ease",keyframes:X2,sideEffects:Y2({styles:{active:{opacity:"0"}}})};function G2(t){let{config:e,draggableNodes:n,droppableContainers:s,measuringConfiguration:r}=t;return Cc((i,o)=>{if(e===null)return;const a=n.get(i);if(!a)return;const l=a.node.current;if(!l)return;const c=bv(o);if(!c)return;const{transform:d}=st(o).getComputedStyle(o),f=cv(d);if(!f)return;const h=typeof e=="function"?e:J2(e);return mv(l,r.draggable.measure),h({active:{id:i,data:a.data,node:l,rect:r.draggable.measure(l)},draggableNodes:n,dragOverlay:{node:o,rect:r.dragOverlay.measure(c)},droppableContainers:s,measuringConfiguration:r,transform:f})})}function J2(t){const{duration:e,easing:n,sideEffects:s,keyframes:r}={...q2,...t};return i=>{let{active:o,dragOverlay:a,transform:l,...c}=i;if(!e)return;const d={x:a.rect.left-o.rect.left,y:a.rect.top-o.rect.top},f={scaleX:l.scaleX!==1?o.rect.width*l.scaleX/a.rect.width:1,scaleY:l.scaleY!==1?o.rect.height*l.scaleY/a.rect.height:1},h={x:l.x-d.x,y:l.y-d.y,...f},p=r({...c,active:o,dragOverlay:a,transform:{initial:l,final:h}}),[m]=p,g=p[p.length-1];if(JSON.stringify(m)===JSON.stringify(g))return;const b=s==null?void 0:s({active:o,dragOverlay:a,...c}),y=a.node.animate(p,{duration:e,easing:n,fill:"forwards"});return new Promise(x=>{y.onfinish=()=>{b==null||b(),x()}})}}let ym=0;function Z2(t){return S.useMemo(()=>{if(t!=null)return ym++,ym},[t])}const eE=pe.memo(t=>{let{adjustScale:e=!1,children:n,dropAnimation:s,style:r,transition:i,modifiers:o,wrapperElement:a="div",className:l,zIndex:c=999}=t;const{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:p,draggableNodes:m,droppableContainers:g,dragOverlay:b,over:y,measuringConfiguration:x,scrollableAncestors:v,scrollableAncestorRects:_,windowRect:w}=kv(),k=S.useContext(Ec),C=Z2(f==null?void 0:f.id),j=_v(o,{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:p,draggingNodeRect:b.rect,over:y,overlayNodeRect:b.rect,scrollableAncestors:v,scrollableAncestorRects:_,transform:k,windowRect:w}),M=fh(h),E=G2({config:s,draggableNodes:m,droppableContainers:g,measuringConfiguration:x}),P=M?b.setRef:void 0;return pe.createElement(H2,null,pe.createElement(U2,{animation:E},f&&C?pe.createElement(K2,{key:C,id:f.id,ref:P,as:a,activatorEvent:d,adjustScale:e,className:l,transition:i,rect:M,style:{zIndex:c,...r},transform:j},n):null))});function jv(t,e,n){const s=t.slice();return s.splice(n<0?s.length+n:n,0,s.splice(e,1)[0]),s}function tE(t,e){return t.reduce((n,s,r)=>{const i=e.get(s);return i&&(n[r]=i),n},Array(t.length))}function Wa(t){return t!==null&&t>=0}function nE(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function sE(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}const Nv=t=>{let{rects:e,activeIndex:n,overIndex:s,index:r}=t;const i=jv(e,s,n),o=e[r],a=i[r];return!a||!o?null:{x:a.left-o.left,y:a.top-o.top,scaleX:a.width/o.width,scaleY:a.height/o.height}},Ha={scaleX:1,scaleY:1},rE=t=>{var e;let{activeIndex:n,activeNodeRect:s,index:r,rects:i,overIndex:o}=t;const a=(e=i[n])!=null?e:s;if(!a)return null;if(r===n){const c=i[o];return c?{x:0,y:n<o?c.top+c.height-(a.top+a.height):c.top-a.top,...Ha}:null}const l=iE(i,r,n);return r>n&&r<=o?{x:0,y:-a.height-l,...Ha}:r<n&&r>=o?{x:0,y:a.height+l,...Ha}:{x:0,y:0,...Ha}};function iE(t,e,n){const s=t[e],r=t[e-1],i=t[e+1];return s?n<e?r?s.top-(r.top+r.height):i?i.top-(s.top+s.height):0:i?i.top-(s.top+s.height):r?s.top-(r.top+r.height):0:0}const Ev="Sortable",Mv=pe.createContext({activeIndex:-1,containerId:Ev,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:Nv,disabled:{draggable:!1,droppable:!1}});function oE(t){let{children:e,id:n,items:s,strategy:r=Nv,disabled:i=!1}=t;const{active:o,dragOverlay:a,droppableRects:l,over:c,measureDroppableContainers:d}=kv(),f=aa(Ev,n),h=a.rect!==null,p=S.useMemo(()=>s.map(k=>typeof k=="object"&&"id"in k?k.id:k),[s]),m=o!=null,g=o?p.indexOf(o.id):-1,b=c?p.indexOf(c.id):-1,y=S.useRef(p),x=!nE(p,y.current),v=b!==-1&&g===-1||x,_=sE(i);Jt(()=>{x&&m&&d(p)},[x,p,m,d]),S.useEffect(()=>{y.current=p},[p]);const w=S.useMemo(()=>({activeIndex:g,containerId:f,disabled:_,disableTransforms:v,items:p,overIndex:b,useDragOverlay:h,sortedRects:tE(p,l),strategy:r}),[g,f,_.draggable,_.droppable,v,p,b,l,h,r]);return pe.createElement(Mv.Provider,{value:w},e)}const aE=t=>{let{id:e,items:n,activeIndex:s,overIndex:r}=t;return jv(n,s,r).indexOf(e)},lE=t=>{let{containerId:e,isSorting:n,wasDragging:s,index:r,items:i,newIndex:o,previousItems:a,previousContainerId:l,transition:c}=t;return!c||!s||a!==i&&r===o?!1:n?!0:o!==r&&e===l},cE={duration:200,easing:"ease"},Pv="transform",uE=Ns.Transition.toString({property:Pv,duration:0,easing:"linear"}),dE={roleDescription:"sortable"};function fE(t){let{disabled:e,index:n,node:s,rect:r}=t;const[i,o]=S.useState(null),a=S.useRef(n);return Jt(()=>{if(!e&&n!==a.current&&s.current){const l=r.current;if(l){const c=Ci(s.current,{ignoreTransform:!0}),d={x:l.left-c.left,y:l.top-c.top,scaleX:l.width/c.width,scaleY:l.height/c.height};(d.x||d.y)&&o(d)}}n!==a.current&&(a.current=n)},[e,n,s,r]),S.useEffect(()=>{i&&o(null)},[i]),i}function hE(t){let{animateLayoutChanges:e=lE,attributes:n,disabled:s,data:r,getNewIndex:i=aE,id:o,strategy:a,resizeObserverConfig:l,transition:c=cE}=t;const{items:d,containerId:f,activeIndex:h,disabled:p,disableTransforms:m,sortedRects:g,overIndex:b,useDragOverlay:y,strategy:x}=S.useContext(Mv),v=pE(s,p),_=d.indexOf(o),w=S.useMemo(()=>({sortable:{containerId:f,index:_,items:d},...r}),[f,r,_,d]),k=S.useMemo(()=>d.slice(d.indexOf(o)),[d,o]),{rect:C,node:j,isOver:M,setNodeRef:E}=Cv({id:o,data:w,disabled:v.droppable,resizeObserverConfig:{updateMeasurementsFor:k,...l}}),{active:P,activatorEvent:A,activeNodeRect:Q,attributes:ne,setNodeRef:Y,listeners:oe,isDragging:G,over:O,setActivatorNodeRef:L,transform:I}=z2({id:o,data:w,attributes:{...dE,...n},disabled:v.draggable}),V=wN(E,Y),F=!!P,ce=F&&!m&&Wa(h)&&Wa(b),$=!y&&G,ke=$&&ce?I:null,gt=ce?ke??(a??x)({rects:g,activeNodeRect:Q,activeIndex:h,overIndex:b,index:_}):null,Ft=Wa(h)&&Wa(b)?i({id:o,items:d,activeIndex:h,overIndex:b}):_,zt=P==null?void 0:P.id,ie=S.useRef({activeId:zt,items:d,newIndex:Ft,containerId:f}),ji=d!==ie.current.items,tn=e({active:P,containerId:f,isDragging:G,isSorting:F,id:o,index:_,items:d,newIndex:ie.current.newIndex,previousItems:ie.current.items,previousContainerId:ie.current.containerId,transition:c,wasDragging:ie.current.activeId!=null}),pr=fE({disabled:!tn,index:_,node:j,rect:C});return S.useEffect(()=>{F&&ie.current.newIndex!==Ft&&(ie.current.newIndex=Ft),f!==ie.current.containerId&&(ie.current.containerId=f),d!==ie.current.items&&(ie.current.items=d)},[F,Ft,f,d]),S.useEffect(()=>{if(zt===ie.current.activeId)return;if(zt!=null&&ie.current.activeId==null){ie.current.activeId=zt;return}const gr=setTimeout(()=>{ie.current.activeId=zt},50);return()=>clearTimeout(gr)},[zt]),{active:P,activeIndex:h,attributes:ne,data:w,rect:C,index:_,newIndex:Ft,items:d,isOver:M,isSorting:F,isDragging:G,listeners:oe,node:j,overIndex:b,over:O,setNodeRef:V,setActivatorNodeRef:L,setDroppableNodeRef:E,setDraggableNodeRef:Y,transform:pr??gt,transition:vn()};function vn(){if(pr||ji&&ie.current.newIndex===_)return uE;if(!($&&!jc(A)||!c)&&(F||tn))return Ns.Transition.toString({...c,property:Pv})}}function pE(t,e){var n,s;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t==null?void 0:t.draggable)!=null?n:e.draggable,droppable:(s=t==null?void 0:t.droppable)!=null?s:e.droppable}}se.Down,se.Right,se.Up,se.Left;function Rv({lead:t,onAbrir:e,emOverlay:n=!1}){const{attributes:s,listeners:r,setNodeRef:i,transform:o,transition:a,isDragging:l}=hE({id:t.id});return u.jsxs("div",{ref:i,...r,...s,style:{transform:Ns.Transform.toString(o),transition:a,opacity:l?.5:1},className:H("bg-white rounded-lg shadow-sm border border-gray-100 p-3 cursor-grab active:cursor-grabbing select-none touch-none",n&&"shadow-xl rotate-2 cursor-grabbing"),onDoubleClick:()=>e==null?void 0:e(t),title:"Arraste para mudar de coluna · duplo clique para editar",children:[u.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",children:t.nome}),u.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:na(t.telefone)}),u.jsxs("div",{className:"flex items-center justify-between mt-2",children:[u.jsx("span",{className:"text-[10px] uppercase tracking-wide bg-indigo-50 text-indigo-700 px-1.5 py-0.5 rounded font-medium",children:t.fonte}),u.jsx("span",{className:"text-[10px] text-gray-400",title:"Data de criação",children:new Date(t.criado_em).toLocaleDateString("pt-BR")})]})]})}function gE({etapa:t,leads:e,cor:n,onAbrirLead:s}){const{setNodeRef:r,isOver:i}=Cv({id:t});return u.jsxs("div",{className:"w-72 shrink-0",children:[u.jsxs("div",{className:"flex items-center justify-between px-1 pb-2",children:[u.jsxs("span",{className:"flex items-center gap-2 text-sm font-semibold text-gray-700",children:[u.jsx("span",{className:H("w-2.5 h-2.5 rounded-full",n)}),mn[t]]}),u.jsx("span",{className:"text-xs font-medium text-gray-500 bg-white border border-gray-200 rounded-full px-2 py-0.5 shadow-sm",children:e.length})]}),u.jsx("div",{ref:r,className:H("bg-white rounded-xl p-3 min-h-[420px] transition-colors","shadow-sm border",i?"border-2 border-dashed border-indigo-400 bg-indigo-50":"border-gray-100"),children:u.jsx(oE,{items:e.map(o=>o.id),strategy:rE,children:u.jsxs("div",{className:"space-y-2 max-h-[calc(100vh-320px)] overflow-y-auto pr-0.5",children:[e.length===0&&u.jsxs("div",{className:"text-center text-xs text-gray-400 border-2 border-dashed border-gray-200 rounded-lg py-10 mt-8",children:[u.jsx("i",{className:"fas fa-inbox text-2xl text-gray-300 mb-2 block"}),"Arraste leads para cá"]}),e.map(o=>u.jsx(Rv,{lead:o,onAbrir:s},o.id))]})})})]})}const mE={leads:"bg-blue-500",em_contato:"bg-amber-500",proposta:"bg-violet-500",fechado:"bg-green-500"};function Hi(t,e){if(pt.includes(e))return e;for(const n of pt)if((t[n]||[]).includes(e))return n;return null}function xE({leads:t,onMover:e,onAbrirLead:n}){const[s,r]=S.useState(()=>yE(t)),[i,o]=S.useState(null),a=S.useRef(s),l=AN(LN(dh,{activationConstraint:{distance:6}}));S.useEffect(()=>{r(m=>{const g=new Set(t.map(v=>v.id)),b={};for(const v of pt)b[v]=(m[v]||[]).filter(_=>g.has(_));let y=!1;for(const v of t){const _=Hi(b,v.id);_===null?(b[v.etapa]=[...b[v.etapa]||[],v.id],y=!0):_!==v.etapa&&(b[_]=b[_].filter(w=>w!==v.id),b[v.etapa]=[...b[v.etapa]||[],v.id],y=!0)}const x=pt.every(v=>(b[v]||[]).length===(m[v]||[]).length);return y||!x?b:m})},[t]);const c=S.useCallback(m=>m&&t.find(g=>g.id===m)||null,[t]),d=S.useMemo(()=>c(i),[c,i]),f=m=>{a.current=s,o(String(m.active.id))},h=S.useCallback(m=>{const{active:g,over:b}=m;if(!b)return;const y=String(g.id),x=String(b.id);r(v=>{const _=Hi(v,y),w=Hi(v,x);return!_||!w||_===w?v:{...v,[_]:v[_].filter(k=>k!==y),[w]:[...v[w],y]}})},[]),p=async m=>{o(null);const g=String(m.active.id);if(!m.over){r(a.current);return}const b=Hi(s,String(m.over.id)),y=Hi(a.current,g);!b||!y||b===y||await e(g,b)};return u.jsxs(A2,{sensors:l,collisionDetection:UN,onDragStart:f,onDragOver:h,onDragEnd:p,children:[u.jsx("div",{className:"flex gap-4 overflow-x-auto pb-2",children:pt.map(m=>u.jsx(gE,{etapa:m,cor:mE[m],leads:t.filter(g=>{var b;return(b=s[m])==null?void 0:b.includes(g.id)}),onAbrirLead:n},m))}),u.jsx(eE,{children:d?u.jsx(Rv,{lead:d,emOverlay:!0}):null})]})}function yE(t){const e={leads:[],em_contato:[],proposta:[],fechado:[]};for(const n of t)e[n.etapa]&&e[n.etapa].push(n.id);return e}const vm={nome:"",telefone:"",email:"",fonte:"Manual",etapa:"leads"};function vE(){const{toast:t}=en(),[e,n]=S.useState([]),[s,r]=S.useState(null),[i,o]=S.useState(!1),[a,l]=S.useState(!1),[c,d]=S.useState(null),[f,h]=S.useState({...vm}),[p,m]=S.useState(""),g=S.useCallback(async()=>{n(await W.crm.leadsListar())},[]);S.useEffect(()=>{g().catch(C=>t("erro",C.message))},[g,t]);const b=async(C,j)=>{const M=e;n(E=>E.map(P=>P.id===C?{...P,etapa:j}:P));try{await W.crm.moverLead(C,j),t("sucesso",`Lead movido para "${mn[j]}".`)}catch(E){n(M),t("erro",E instanceof Error?E.message:"Falha ao mover lead.")}},y=async()=>{var C;if(!((C=f.nome)!=null&&C.trim())){t("erro","O nome do lead é obrigatório.");return}try{await W.crm.criarLead({...f,etapa:f.etapa||"leads"}),t("sucesso","Lead criado com sucesso."),l(!1),h({...vm}),await g()}catch(j){t("erro",j instanceof Error?j.message:"Falha ao criar lead.")}},x=async()=>{o(!0);try{const C=await W.crm.sugestoes();r(C.sugestoes)}catch(C){t("erro",C instanceof Error?C.message:"Falha ao pedir sugestões.")}finally{o(!1)}},v=async C=>{try{await W.crm.aplicar(C.lead_id,C.para),r(j=>(j==null?void 0:j.filter(M=>M!==C))??null),await g(),t("sucesso",`Sugestão aplicada: ${C.lead_nome} → ${mn[C.para]}.`)}catch(j){t("erro",j instanceof Error?j.message:"Falha ao aplicar sugestão.")}},_=async C=>{try{(await W.leads.enriquecer(C.id)).notas.forEach(M=>t("info",M)),await g()}catch(j){t("erro",j instanceof Error?j.message:"Falha ao enriquecer.")}},w=async()=>{if(c)try{await W.leads.atualizar(c.id,{observacoes:p}),d(null),await g(),t("sucesso","Observações salvas.")}catch(C){t("erro",C instanceof Error?C.message:"Falha ao salvar.")}},k=S.useMemo(()=>Object.fromEntries(pt.map(C=>[C,e.filter(j=>j.etapa===C).length])),[e]);return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[u.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-500 flex-wrap",children:[u.jsxs("span",{children:[u.jsx("strong",{className:"text-gray-800",children:e.length})," leads no funil"]}),pt.map(C=>u.jsxs("span",{className:"hidden md:inline",children:[mn[C],": ",u.jsx("strong",{className:"text-gray-700",children:k[C]})]},C))]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("button",{onClick:x,disabled:i,className:"px-5 py-2.5 text-sm font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fas fa-wand-magic-sparkles mr-2",i&&"fa-spin")}),"Sugestões da IA"]}),u.jsxs("button",{onClick:()=>l(!0),className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition shadow-sm",children:[u.jsx("i",{className:"fas fa-plus mr-2"})," Adicionar Lead"]})]})]}),u.jsx(xE,{leads:e,onMover:b,onAbrirLead:C=>{d(C),m(C.observacoes||"")}}),u.jsxs(Xt,{aberto:s!==null,onFechar:()=>r(null),titulo:"Sugestões de movimentação (Agente de CRM)",icone:"fas fa-robot",largura:"lg",children:[s&&s.length===0&&u.jsxs("p",{className:"text-sm text-gray-500 text-center py-8",children:[u.jsx("i",{className:"fas fa-circle-check text-green-500 text-2xl block mb-3"}),"Nenhuma sugestão no momento — o funil está equilibrado. 🎯"]}),u.jsx("div",{className:"space-y-3",children:s==null?void 0:s.map((C,j)=>u.jsxs("div",{className:"border border-gray-100 rounded-xl p-4 flex items-start justify-between gap-4 hover:border-indigo-200 transition",children:[u.jsxs("div",{className:"min-w-0",children:[u.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",children:C.lead_nome}),u.jsxs("p",{className:"text-xs text-gray-500 mt-1 flex items-center gap-2",children:[u.jsx(sr,{status:C.de})," ",u.jsx("i",{className:"fas fa-arrow-right text-gray-300"})," ",u.jsx(sr,{status:C.para}),u.jsxs("span",{className:"text-gray-400",children:["confiança ",Math.round(C.confianca*100),"%"]})]}),u.jsx("p",{className:"text-xs text-gray-600 mt-2",children:C.motivo})]}),u.jsx("button",{onClick:()=>v(C),className:"shrink-0 px-4 py-2 text-xs font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:"Aplicar"})]},j))})]}),u.jsx(Xt,{aberto:a,onFechar:()=>l(!1),titulo:"Adicionar Lead",icone:"fas fa-user-plus",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(_r,{rotulo:"Nome *",valor:f.nome||"",onChange:C=>h({...f,nome:C})}),u.jsx(_r,{rotulo:"Telefone",valor:f.telefone||"",onChange:C=>h({...f,telefone:C}),placeholder:"(11) 99999-9999"}),u.jsx(_r,{rotulo:"E-mail",tipo:"email",valor:f.email||"",onChange:C=>h({...f,email:C}),placeholder:"contato@empresa.com.br"}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Coluna inicial"}),u.jsx("select",{value:f.etapa||"leads",onChange:C=>h({...f,etapa:C.target.value}),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",children:pt.map(C=>u.jsx("option",{value:C,children:mn[C]},C))})]})]}),u.jsx(_r,{rotulo:"Fonte",valor:f.fonte||"",onChange:C=>h({...f,fonte:C}),placeholder:"Manual, Google Maps, Instagram, CNPJ..."}),u.jsxs(Qt,{titulo:"Campos avançados",icone:"fas fa-sliders",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(_r,{rotulo:"Empresa",valor:f.empresa||"",onChange:C=>h({...f,empresa:C})}),u.jsx(_r,{rotulo:"Cidade",valor:f.cidade||"",onChange:C=>h({...f,cidade:C}),placeholder:"São Paulo/SP"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Observações"}),u.jsx("textarea",{value:f.observacoes||"",onChange:C=>h({...f,observacoes:C.target.value}),rows:3,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})]}),u.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[u.jsx("button",{onClick:()=>l(!1),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:y,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar"]})]})]})}),u.jsx(Xt,{aberto:!!c,onFechar:()=>d(null),titulo:"Lead",icone:"fas fa-address-card",children:c&&u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-base font-semibold text-gray-800",children:c.nome}),u.jsxs("p",{className:"text-xs text-gray-500 mt-0.5",children:[na(c.telefone)," · ",c.fonte," · criado em ",Il(c.criado_em)]})]}),u.jsx(sr,{status:c.etapa})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Observações"}),u.jsx("textarea",{value:p,onChange:C=>m(C.target.value),rows:4,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",placeholder:"Ex.: ligou pedindo proposta, retorna na sexta..."})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("button",{onClick:()=>_(c),className:"text-sm text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-wand-magic-sparkles mr-1"})," Enriquecer com IA"]}),u.jsxs("div",{className:"flex gap-3",children:[u.jsx("button",{onClick:()=>d(null),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:w,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar"]})]})]})]})})]})}function _r({rotulo:t,valor:e,onChange:n,tipo:s="text",placeholder:r}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("input",{type:s,value:e,onChange:i=>n(i.target.value),placeholder:r,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function bE(){const{toast:t}=en(),[e,n]=S.useState([]),[s,r]=S.useState(!1),[i,o]=S.useState(null),[a,l]=S.useState(""),[c,d]=S.useState(""),[f,h]=S.useState("texto"),[p,m]=S.useState("leads"),g=S.useCallback(async()=>{n(await W.leads.listar())},[]);S.useEffect(()=>{g().catch(w=>t("erro",w.message))},[g,t]);const{data:b=[],refetch:y}=ey({queryKey:["campanhas"],queryFn:()=>W.campanhas.listar(),refetchInterval:w=>{var k;return(k=w.state.data)!=null&&k.some(C=>C.status==="em_andamento")?4e3:!1},refetchIntervalInBackground:!1}),x=S.useMemo(()=>Object.fromEntries(pt.map(w=>[w,e.filter(k=>k.etapa===w).length])),[e]),v=async()=>{if(!a.trim()){t("erro","Dê um nome para a campanha.");return}if(!c.trim()){t("erro","Escreva o template da mensagem.");return}try{await W.campanhas.criar({nome:a.trim(),canal:f,template:f,mensagem:c.trim(),lead_ids:[],filtro_etapa:p});const w=mn[p]??p;t("sucesso",`Campanha criada — ${x[p]??0} leads de "${w}" serão disparados.`),r(!1),l(""),d(""),await y(),await g()}catch(w){t("erro",w instanceof Error?w.message:"Falha ao criar campanha.")}},_=async(w,k)=>{try{await W.campanhas.status(w.id,k),t("sucesso",`Campanha "${w.nome}" → ${k==="ativa"?"Ativa":k==="pausada"?"Pausada":"Rascunho"}.`),await y()}catch(C){t("erro",C instanceof Error?C.message:"Falha ao alterar status.")}};return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:[u.jsx("strong",{className:"text-gray-800",children:b.length})," campanhas · templates em Agentes"]}),u.jsxs("button",{onClick:()=>r(!0),className:"px-6 py-3 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition shadow-sm",children:[u.jsx("i",{className:"fas fa-plus mr-2"})," Nova Campanha"]})]}),u.jsx("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100 bg-gray-50/50",children:[u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Nome"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Status"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Total de Leads"}),u.jsx("th",{className:"px-5 py-3 font-semibold",children:"Data de Criação"}),u.jsx("th",{className:"px-5 py-3 font-semibold text-right",children:"Ações"})]})}),u.jsxs("tbody",{children:[b.map(w=>{const k=w.status==="em_andamento",C=Math.max(w.total,w.enviadas+w.erros);return u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40",children:[u.jsxs("td",{className:"px-5 py-3",children:[u.jsx("p",{className:"font-medium text-gray-800 truncate max-w-[220px]",children:w.nome}),u.jsxs("p",{className:"text-xs text-gray-400",children:[w.canal==="audio"?"Áudio":"Texto",' · template "',w.template,'"']})]}),u.jsx("td",{className:"px-5 py-3",children:u.jsx(sr,{status:w.status})}),u.jsx("td",{className:"px-5 py-3 text-gray-600",children:C}),u.jsx("td",{className:"px-5 py-3 text-xs text-gray-400",children:Il(w.criado_em)}),u.jsxs("td",{className:"px-5 py-3 text-right whitespace-nowrap",children:[u.jsxs("button",{onClick:()=>o(w),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium mr-3",children:[u.jsx("i",{className:"fas fa-list mr-1"})," Ver"]}),k?u.jsxs(u.Fragment,{children:[u.jsxs("button",{onClick:()=>_(w,"pausada"),className:"px-4 py-2 text-xs font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded-lg hover:bg-amber-100 mr-2",children:[u.jsx("i",{className:"fas fa-pause mr-1"})," Pausar"]}),u.jsxs("button",{onClick:()=>_(w,"rascunho"),className:"px-4 py-2 text-xs font-medium text-red-700 bg-red-50 border border-red-200 rounded-lg hover:bg-red-100",children:[u.jsx("i",{className:"fas fa-stop mr-1"})," Parar"]})]}):u.jsxs("button",{onClick:()=>_(w,"ativa"),className:"px-5 py-2 text-xs font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-play mr-1"})," Iniciar"]})]})]},w.id)}),b.length===0&&u.jsx("tr",{children:u.jsxs("td",{colSpan:5,className:"px-5 py-16 text-center text-gray-400",children:[u.jsx("i",{className:"fas fa-bullhorn text-3xl text-gray-200 block mb-3"}),"Nenhuma campanha ainda. Clique em ",u.jsx("strong",{className:"text-indigo-500",children:"Nova Campanha"})," para começar."]})})]})]})})}),b.filter(w=>w.status==="em_andamento").length>0&&u.jsx("div",{className:"space-y-3",children:b.filter(w=>w.status==="em_andamento").map(w=>{const k=Math.max(w.total,w.enviadas+w.erros),C=k?Math.round((w.enviadas+w.erros)/k*100):0;return u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-indigo-100 p-4 space-y-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("p",{className:"text-sm font-medium text-gray-700 flex items-center gap-2",children:[u.jsx("i",{className:"fas fa-spinner fa-spin text-indigo-500"})," ",w.nome]}),u.jsxs("span",{className:"text-xs text-gray-500",children:[w.enviadas," enviadas · ",w.erros," erros"]})]}),u.jsx(ra,{valor:C,mostrarLabel:!0})]},w.id)})}),u.jsx(Xt,{aberto:s,onFechar:()=>r(!1),titulo:"Nova Campanha",icone:"fas fa-bullhorn",largura:"lg",children:u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Nome da Campanha *"}),u.jsx("input",{value:a,onChange:w=>l(w.target.value),placeholder:"Ex.: Reativação de novos leads",className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Template da Mensagem *"}),u.jsx("textarea",{value:c,onChange:w=>d(w.target.value),rows:4,placeholder:"Use variáveis: {{nome}}, {{primeiro_nome}}, {{empresa}}, {{cidade}}...",className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none font-mono"}),u.jsxs("p",{className:"text-[11px] text-gray-400 mt-1",children:["Variáveis: ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{nome}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{primeiro_nome}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{empresa}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{cidade}}"})]})]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Canal"}),u.jsxs("select",{value:f,onChange:w=>h(w.target.value),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",children:[u.jsx("option",{value:"texto",children:"Texto"}),u.jsx("option",{value:"audio",children:"Áudio"})]})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Filtrar Leads por Etapa do CRM"}),u.jsx("select",{value:p,onChange:w=>m(w.target.value),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none",children:pt.map(w=>u.jsxs("option",{value:w,children:[mn[w]," (",x[w]??0," leads)"]},w))})]})]}),u.jsxs("p",{className:"text-xs text-gray-400 bg-gray-50 border border-gray-100 rounded-lg px-3 py-2",children:[u.jsx("i",{className:"fas fa-circle-info mr-1"})," O envio simulado altera o status no JSON. A integração real (OpenOutreach) é validada na hora de iniciar — configure em Ferramentas."]}),u.jsxs("div",{className:"flex justify-end gap-3 pt-1",children:[u.jsx("button",{onClick:()=>r(!1),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:v,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-plus mr-2"})," Criar Campanha"]})]})]})}),u.jsx(Xt,{aberto:!!i,onFechar:()=>o(null),titulo:`Eventos — ${(i==null?void 0:i.nome)??""}`,icone:"fas fa-list",largura:"lg",children:i&&u.jsxs("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:[i.eventos.length===0&&u.jsx("p",{className:"text-sm text-gray-400 text-center py-8",children:"Nenhum evento ainda — a execução do disparo é simulada nesta fase."}),i.eventos.slice().reverse().map((w,k)=>{var C;return u.jsxs("div",{className:"flex items-start gap-3 text-sm border-b border-gray-50 pb-2",children:[u.jsx("i",{className:H("mt-1 text-xs",w.status==="enviado"?"fas fa-circle-check text-green-500":"fas fa-circle-xmark text-red-500")}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("p",{className:"text-gray-700 truncate",children:((C=e.find(j=>j.id===w.lead_id))==null?void 0:C.nome)??w.lead_id}),w.mensagem&&u.jsx("p",{className:"text-xs text-gray-400 truncate",children:w.mensagem})]}),u.jsx("span",{className:"text-xs text-gray-300 shrink-0",children:Il(w.momento)})]},k)})]})})]})}const wE=[{para:"/extrator-maps",icone:"fas fa-map-marked-alt",titulo:"Google Maps",descricao:"Empresas por palavra-chave e localização. Sem scraper configurado, gera mock de 5–10 leads."},{para:"/extrator-instagram",icone:"fab fa-instagram",titulo:"Instagram",descricao:"Seguidores de um perfil público. Sem igmapper configurado, gera mock de 5–10 leads."},{para:"/extrator-cnpj",icone:"fas fa-building",titulo:"CNPJ (B2B)",descricao:"Empresas por CNAE + UF. Sem provedor configurado, gera mock de 5–10 empresas."}];function SE(){const t=bi();return u.jsxs("div",{className:"space-y-6",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:["Selecione uma fonte de leads. Todas salvam diretamente em ",u.jsx("strong",{children:"leads.json"}),", na coluna"," ",u.jsx("strong",{children:'"Novos Leads"'})," do CRM — dados 100% locais."]}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:wE.map(e=>u.jsxs("button",{onClick:()=>t(e.para),className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 text-left space-y-3 hover:border-indigo-200 hover:shadow-md transition group",children:[u.jsx("span",{className:"w-11 h-11 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center text-lg group-hover:bg-indigo-100",children:u.jsx("i",{className:e.icone})}),u.jsx("p",{className:"text-sm font-semibold text-gray-800",children:e.titulo}),u.jsx("p",{className:"text-xs text-gray-500 leading-relaxed",children:e.descricao}),u.jsxs("span",{className:"text-xs font-medium text-indigo-600 group-hover:text-indigo-800",children:["Abrir extrator ",u.jsx("i",{className:"fas fa-arrow-right ml-1"})]})]},e.para))})]})}function _E(){const{toast:t}=en(),e=bi(),[n,s]=S.useState(""),[r,i]=S.useState(""),[o,a]=S.useState(10),[l,c]=S.useState(5),[d,f]=S.useState(!1),[h,p]=S.useState(!1),[m,g]=S.useState(0),[b,y]=S.useState(null),[x,v]=S.useState(""),_=async()=>{if(n.trim().length<2||r.trim().length<2){t("erro",'Preencha a palavra-chave e a localização (ex.: "Dentista", "Rio de Janeiro").');return}p(!0),y(null),g(8);const w=setInterval(()=>{g(k=>k<85?k+Math.ceil((90-k)/6):85)},90);try{const k=await W.extrair.maps({keyword:n.trim(),location:r.trim(),limit:o});clearInterval(w),g(100),y(k.importados),v(k.origem==="cli"?"scraper real":"mock de teste");const C=k.duplicados>0?` · ${k.duplicados} duplicados ignorados`:"",j=k.aviso?` · ${k.aviso}`:"";t("sucesso",`${k.importados.length} leads extraídos (${k.origem==="cli"?"scraper real":"mock"})${C}${j}`)}catch(k){clearInterval(w),g(0),t("erro",k instanceof Error?k.message:"Falha na extração.")}finally{p(!1)}};return u.jsxs("div",{className:"space-y-6 max-w-4xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-5",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:["Busque empresas por palavra-chave e localização. Sem scraper configurado, o LeadMaster gera",u.jsx("strong",{children:" dados mockados (5–10 leads)"})," para teste — sem risco de bloqueio de IP."]}),u.jsxs("span",{className:"text-xs shrink-0 text-gray-400",children:[u.jsx("i",{className:"fas fa-shield-halved mr-1"})," dados públicos"]})]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Palavra-chave *"}),u.jsx("input",{value:n,onChange:w=>s(w.target.value),placeholder:"Ex.: Dentista, pizzaria, academia...",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Localização *"}),u.jsx("input",{value:r,onChange:w=>i(w.target.value),placeholder:"Ex.: Rio de Janeiro, RJ",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Quantidade: ",o]}),u.jsx("input",{type:"range",min:5,max:10,value:o,onChange:w=>a(Number(w.target.value)),className:"w-full accent-indigo-500 mt-2"})]})]}),u.jsxs("button",{onClick:_,disabled:h,className:"w-full md:w-auto px-8 py-3.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fas fa-magnifying-glass mr-2",h&&"fa-spin")}),h?"Buscando leads...":"Iniciar Extração"]}),(h||m>0)&&u.jsxs("div",{className:"space-y-1",children:[u.jsx(ra,{valor:m}),u.jsx("p",{className:"text-xs text-indigo-600 font-medium",children:m<100?"Buscando leads no Google Maps...":"Extração concluída ✓"})]}),u.jsxs(Qt,{titulo:"Configurações avançadas",icone:"fas fa-sliders",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Raio de busca: ",l," km"]}),u.jsx("input",{type:"range",min:1,max:50,value:l,onChange:w=>c(Number(w.target.value)),className:"w-full accent-indigo-500"})]}),u.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-600 bg-gray-50 border border-gray-100 rounded-lg px-3 py-2.5 cursor-pointer h-fit",children:[u.jsx("input",{type:"checkbox",checked:d,onChange:w=>f(w.target.checked),className:"w-4 h-4 accent-indigo-500"}),"Apenas com nota ≥ 4,5"]})]}),u.jsx("p",{className:"text-[11px] text-gray-400",children:"As opções avançadas aplicam-se ao scraper real (gosom/google-maps-scraper), quando configurado em Ferramentas → Extratores. No modo mock elas são ignoradas."})]})]}),b&&u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:[u.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-gray-100 bg-gray-50/50",children:[u.jsxs("p",{className:"text-sm font-medium text-gray-700",children:[b.length," lead(s) extraído(s) · origem: ",u.jsx("span",{className:"text-indigo-600",children:x})]}),u.jsxs("button",{onClick:()=>e("/crm"),className:"px-5 py-2 text-xs font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50",children:[u.jsx("i",{className:"fas fa-columns mr-1"})," Ir para o CRM"]})]}),u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100",children:[u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Nome"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Telefone"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Localização"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Avaliação"})]})}),u.jsx("tbody",{children:b.map((w,k)=>{var j;const C=(j=w.extras)==null?void 0:j.avaliacao;return u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40",children:[u.jsx("td",{className:"px-5 py-2.5 text-gray-800",children:w.nome}),u.jsx("td",{className:"px-5 py-2.5 text-gray-600",children:na(w.telefone)}),u.jsxs("td",{className:"px-5 py-2.5 text-gray-500 text-xs",children:[w.cidade||"—",w.endereco?` · ${w.endereco}`:""]}),u.jsx("td",{className:"px-5 py-2.5 text-xs text-gray-400",children:C!==void 0?u.jsxs(u.Fragment,{children:[u.jsx("i",{className:"fas fa-star text-amber-400 mr-1"}),C]}):"—"})]},w.id||k)})})]})}),u.jsx("div",{className:"px-5 py-3 border-t border-gray-100 bg-gray-50/50",children:u.jsxs("button",{onClick:()=>e("/crm"),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-arrow-right mr-1"})," Ver todos os leads no CRM Kanban"]})})]})]})}function kE(){const{toast:t}=en(),e=bi(),[n,s]=S.useState(""),[r,i]=S.useState(10),[o,a]=S.useState(!1),[l,c]=S.useState(500),[d,f]=S.useState(!1),[h,p]=S.useState(0),[m,g]=S.useState(null),[b,y]=S.useState(""),x=async()=>{if(!n.includes("instagram.com")){t("erro","Informe a URL do perfil (ex.: https://instagram.com/perfil).");return}f(!0),g(null),p(8);const v=setInterval(()=>{p(_=>_<85?_+Math.ceil((90-_)/6):85)},90);try{const _=await W.extrair.instagram(n.trim(),r);clearInterval(v),p(100),g(_.importados),y(_.origem==="cli"?"igmapper real":"mock de teste");const w=_.duplicados>0?` · ${_.duplicados} duplicados ignorados`:"",k=_.aviso?` · ${_.aviso}`:"";t("sucesso",`${_.importados.length} leads extraídos (${_.origem==="cli"?"igmapper real":"mock"})${w}${k}`)}catch(_){clearInterval(v),p(0),t("erro",_ instanceof Error?_.message:"Falha na extração.")}finally{f(!1)}};return u.jsxs("div",{className:"space-y-6 max-w-4xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-5",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:["Extraia seguidores de um perfil público do Instagram. Sem igmapper configurado, o LeadMaster gera",u.jsx("strong",{children:" dados mockados (5–10 leads)"})," para teste — sem risco de bloqueio de conta."]}),u.jsxs("span",{className:"text-xs shrink-0 text-gray-400",children:[u.jsx("i",{className:"fas fa-shield-halved mr-1"})," perfis públicos"]})]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsxs("div",{className:"md:col-span-2",children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"URL do perfil *"}),u.jsx("input",{value:n,onChange:v=>s(v.target.value),placeholder:"https://instagram.com/perfil_do_concorrente/",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Quantidade de seguidores: ",r]}),u.jsx("input",{type:"range",min:5,max:10,value:r,onChange:v=>i(Number(v.target.value)),className:"w-full accent-indigo-500 mt-2"})]})]}),u.jsxs("button",{onClick:x,disabled:d,className:"w-full md:w-auto px-8 py-3.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fab fa-instagram mr-2",d&&"fa-spin")}),d?"Buscando seguidores...":"Iniciar Extração"]}),(d||h>0)&&u.jsxs("div",{className:"space-y-1",children:[u.jsx(ra,{valor:h}),u.jsx("p",{className:"text-xs text-indigo-600 font-medium",children:h<100?"Buscando seguidores no Instagram...":"Extração concluída ✓"})]}),u.jsxs(Qt,{titulo:"Configurações avançadas",icone:"fas fa-sliders",children:[u.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-600 bg-gray-50 border border-gray-100 rounded-lg px-3 py-2.5 cursor-pointer",children:[u.jsx("input",{type:"checkbox",checked:o,onChange:v=>a(v.target.checked),className:"w-4 h-4 accent-indigo-500"}),"Extrair apenas contas comerciais"]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Mínimo de seguidores: ",l]}),u.jsx("input",{type:"range",min:100,max:5e3,step:100,value:l,onChange:v=>c(Number(v.target.value)),className:"w-full accent-indigo-500"})]}),u.jsx("p",{className:"text-[11px] text-gray-400",children:"As opções avançadas aplicam-se ao igmapper real (lucasoal/igmapper), quando configurado em Ferramentas → Extratores. No modo mock elas são ignoradas."})]})]}),m&&u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:[u.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-gray-100 bg-gray-50/50",children:[u.jsxs("p",{className:"text-sm font-medium text-gray-700",children:[m.length," lead(s) extraído(s) · origem: ",u.jsx("span",{className:"text-indigo-600",children:b})]}),u.jsxs("button",{onClick:()=>e("/crm"),className:"px-5 py-2 text-xs font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50",children:[u.jsx("i",{className:"fas fa-columns mr-1"})," Ir para o CRM"]})]}),u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100",children:[u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Nome / Username"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Telefone"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Fonte"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Seguidores"})]})}),u.jsx("tbody",{children:m.map((v,_)=>{var C,j;const w=((C=v.extras)==null?void 0:C.username)||"",k=(j=v.extras)==null?void 0:j.seguidores;return u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40",children:[u.jsxs("td",{className:"px-5 py-2.5 text-gray-800",children:[v.nome,w&&u.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:["@",w]})]}),u.jsx("td",{className:"px-5 py-2.5 text-gray-600",children:na(v.telefone)}),u.jsx("td",{className:"px-5 py-2.5",children:u.jsx("span",{className:"text-[10px] uppercase tracking-wide bg-pink-50 text-pink-700 px-1.5 py-0.5 rounded font-medium",children:v.fonte})}),u.jsx("td",{className:"px-5 py-2.5 text-xs text-gray-400",children:k!==void 0?k.toLocaleString("pt-BR"):"—"})]},v.id||_)})})]})}),u.jsx("div",{className:"px-5 py-3 border-t border-gray-100 bg-gray-50/50",children:u.jsxs("button",{onClick:()=>e("/crm"),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-arrow-right mr-1"})," Ver todos os leads no CRM Kanban"]})})]})]})}const CE=["AC","AL","AP","AM","BA","CE","DF","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RJ","RN","RS","RO","RR","SC","SP","SE","TO"];function jE(){const{toast:t}=en(),e=bi(),[n,s]=S.useState(""),[r,i]=S.useState("SP"),[o,a]=S.useState(10),[l,c]=S.useState(""),[d,f]=S.useState(0),[h,p]=S.useState(!1),[m,g]=S.useState(0),[b,y]=S.useState(null),[x,v]=S.useState(""),[_,w]=S.useState(""),[k,C]=S.useState(!1),j=async()=>{if(n.trim().length<2){t("erro","Informe o CNAE (ex.: 6201-5/01 — desenvolvimento de software).");return}p(!0),y(null),g(8);const E=setInterval(()=>{g(P=>P<85?P+Math.ceil((90-P)/6):85)},90);try{const P=await W.extrair.cnpjExtract({cnae:n.trim(),uf:r,limit:o});clearInterval(E),g(100),y(P.importados),v(P.origem==="provedor"?"provedor real":"mock de teste");const A=P.duplicados>0?` · ${P.duplicados} duplicados ignorados`:"",Q=P.aviso?` · ${P.aviso}`:"";t("sucesso",`${P.importados.length} empresas extraídas (${P.origem==="provedor"?"provedor real":"mock"})${A}${Q}`)}catch(P){clearInterval(E),g(0),t("erro",P instanceof Error?P.message:"Falha na extração.")}finally{p(!1)}},M=async()=>{const E=_.trim();if(E.length<8){t("erro","Informe um CNPJ completo (14 dígitos, com ou sem pontuação).");return}C(!0);try{const P=await W.extrair.cnpj(E),A=await W.leads.importar([P]);t("sucesso",`${A.importados.length} lead(s) importado(s) para "Novos Leads"${A.duplicados.length?` · ${A.duplicados.length} duplicado(s)`:""}.`),w("")}catch(P){t("erro",P instanceof Error?P.message:"Falha ao consultar o CNPJ.")}finally{C(!1)}};return u.jsxs("div",{className:"space-y-6 max-w-4xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-5",children:[u.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[u.jsxs("p",{className:"text-sm text-gray-500",children:["Busque empresas por CNAE e estado. Sem provedor configurado, o LeadMaster gera",u.jsx("strong",{children:" dados mockados (5–10 empresas)"})," para teste — sem risco de bloqueio."]}),u.jsxs("span",{className:"text-xs shrink-0 text-gray-400",children:[u.jsx("i",{className:"fas fa-shield-halved mr-1"})," dados B2B"]})]}),u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"CNAE *"}),u.jsx("input",{value:n,onChange:E=>s(E.target.value),placeholder:"Ex.: 6201-5/01 (desenvolvimento de software)",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"UF *"}),u.jsx("select",{value:r,onChange:E=>i(E.target.value),className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none bg-white",children:CE.map(E=>u.jsx("option",{value:E,children:E},E))})]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Quantidade: ",o]}),u.jsx("input",{type:"range",min:5,max:10,value:o,onChange:E=>a(Number(E.target.value)),className:"w-full accent-indigo-500 mt-2"})]})]}),u.jsxs("button",{onClick:j,disabled:h,className:"w-full md:w-auto px-8 py-3.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fas fa-building mr-2",h&&"fa-spin")}),h?"Buscando empresas...":"Iniciar Extração"]}),(h||m>0)&&u.jsxs("div",{className:"space-y-1",children:[u.jsx(ra,{valor:m}),u.jsx("p",{className:"text-xs text-indigo-600 font-medium",children:m<100?"Buscando empresas por CNAE...":"Extração concluída ✓"})]}),u.jsxs(Qt,{titulo:"Configurações avançadas",icone:"fas fa-sliders",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Porte da empresa"}),u.jsxs("select",{value:l,onChange:E=>c(E.target.value),className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none bg-white",children:[u.jsx("option",{value:"",children:"Todos"}),u.jsx("option",{value:"ME",children:"ME (Microempresa)"}),u.jsx("option",{value:"EPP",children:"EPP (Pequeno porte)"}),u.jsx("option",{value:"medio",children:"Médio porte"}),u.jsx("option",{value:"grande",children:"Grande porte"})]})]}),u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:["Capital social mínimo: ",d.toLocaleString("pt-BR",{style:"currency",currency:"BRL",maximumFractionDigits:0})]}),u.jsx("input",{type:"range",min:0,max:5e6,step:1e5,value:d,onChange:E=>f(Number(E.target.value)),className:"w-full accent-indigo-500"})]})]}),u.jsx("p",{className:"text-[11px] text-gray-400",children:"Os filtros de porte e capital social aplicam-se ao provedor real de busca, quando configurado em Ferramentas → Extratores. No modo mock eles são ignorados."})]}),u.jsxs("div",{className:"pt-1 border-t border-gray-100",children:[u.jsxs("p",{className:"text-xs font-medium text-gray-500 mb-2",children:[u.jsx("i",{className:"fas fa-magnifying-glass mr-1"})," Consulta avulsa por CNPJ (BrasilAPI) — importa uma empresa específica"]}),u.jsxs("div",{className:"flex flex-wrap gap-3",children:[u.jsx("input",{value:_,onChange:E=>w(E.target.value),placeholder:"00.000.000/0000-00",className:"flex-1 min-w-[220px] px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"}),u.jsxs("button",{onClick:M,disabled:k,className:"px-5 py-2.5 text-xs font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50 disabled:opacity-60",children:[u.jsx("i",{className:H("fas fa-file-import mr-1",k&&"fa-spin")}),k?"Importando...":"Consultar e importar"]})]})]})]}),b&&u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",children:[u.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-gray-100 bg-gray-50/50",children:[u.jsxs("p",{className:"text-sm font-medium text-gray-700",children:[b.length," lead(s) extraído(s) · origem: ",u.jsx("span",{className:"text-indigo-600",children:x})]}),u.jsxs("button",{onClick:()=>e("/crm"),className:"px-5 py-2 text-xs font-medium text-indigo-600 bg-white border border-indigo-200 rounded-lg hover:bg-indigo-50",children:[u.jsx("i",{className:"fas fa-columns mr-1"})," Ir para o CRM"]})]}),u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"text-left text-xs text-gray-500 uppercase border-b border-gray-100",children:[u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Nome Fantasia"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"CNPJ"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Cidade / UF"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Telefone"}),u.jsx("th",{className:"px-5 py-2 font-semibold",children:"Fonte"})]})}),u.jsx("tbody",{children:b.map((E,P)=>u.jsxs("tr",{className:"border-b border-gray-50 hover:bg-indigo-50/40",children:[u.jsx("td",{className:"px-5 py-2.5 text-gray-800",children:E.nome}),u.jsx("td",{className:"px-5 py-2.5 text-gray-600 font-mono text-xs",children:E.cnpj||"—"}),u.jsx("td",{className:"px-5 py-2.5 text-gray-500 text-xs",children:E.cidade||"—"}),u.jsx("td",{className:"px-5 py-2.5 text-gray-600",children:na(E.telefone)}),u.jsx("td",{className:"px-5 py-2.5",children:u.jsx("span",{className:"text-[10px] uppercase tracking-wide bg-indigo-50 text-indigo-700 px-1.5 py-0.5 rounded font-medium",children:E.fonte})})]},E.id||P))})]})}),u.jsx("div",{className:"px-5 py-3 border-t border-gray-100 bg-gray-50/50",children:u.jsxs("button",{onClick:()=>e("/crm"),className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:[u.jsx("i",{className:"fas fa-arrow-right mr-1"})," Ver todos os leads no CRM Kanban"]})})]})]})}function NE(){const[t,e]=s_(),n=t.get("tab")||"disparo";return u.jsxs("div",{className:"space-y-6",children:[u.jsx("div",{className:"flex gap-2",children:[{id:"disparo",rotulo:"Agente de Disparo",icone:"fas fa-paper-plane"},{id:"atendimento",rotulo:"Agente de Atendimento",icone:"fas fa-headset"}].map(s=>u.jsxs("button",{onClick:()=>e({tab:s.id}),className:H("px-5 py-2.5 text-sm font-medium rounded-lg transition",n===s.id?"bg-[#1e1b4b] text-white shadow-sm":"bg-white text-gray-600 border border-gray-200 hover:bg-gray-50"),children:[u.jsx("i",{className:H(s.icone,"mr-2")}),s.rotulo]},s.id))}),n==="disparo"?u.jsx(EE,{}):u.jsx(ME,{})]})}function EE(){const{toast:t}=en(),[e,n]=S.useState({texto:"",audio:""}),[s,r]=S.useState("LeadMaster"),[i,o]=S.useState(""),[a,l]=S.useState(!1),[c,d]=S.useState(!1),[f,h]=S.useState(null),p=S.useCallback(async()=>{const[b,y]=await Promise.all([W.agentes.templates(),W.config.obter()]);n({texto:b.texto??"",audio:b.audio??""}),r(y.agentes.disparo.minha_empresa??"LeadMaster"),h(y.integracoes.openoutreach)},[]);S.useEffect(()=>{p().catch(b=>t("erro",b.message))},[p,t]);const m=async()=>{d(!0);try{await W.agentes.salvarTemplates(e),await W.config.salvar({agentes:{disparo:{templates:e,minha_empresa:s}}}),t("sucesso","Templates do agente de disparo salvos."),await p()}catch(b){t("erro",b instanceof Error?b.message:"Falha ao salvar templates.")}finally{d(!1)}},g=async()=>{try{const b=await W.agentes.testarTemplate(e.texto);o(b.renderizado),l(!0)}catch(b){t("erro",b instanceof Error?b.message:"Falha ao renderizar template.")}};return u.jsxs("div",{className:"space-y-5 max-w-3xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800",children:"Templates de mensagem"}),u.jsx(sr,{status:f!=null&&f.url&&f.enabled!==!1?"ativo":"inativo",rotulo:f!=null&&f.url&&f.enabled!==!1?"OpenOutreach configurado":"OpenOutreach não configurado"})]}),u.jsxs("p",{className:"text-xs text-gray-500",children:["Variáveis disponíveis: ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{nome}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{primeiro_nome}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{empresa}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{cidade}}"}),","," ",u.jsx("code",{className:"bg-gray-100 px-1 rounded",children:"{{minha_empresa}}"}),"."]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Template — texto"}),u.jsx("textarea",{value:e.texto,onChange:b=>n({...e,texto:b.target.value}),rows:4,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Template — áudio (texto para gravação)"}),u.jsx("textarea",{value:e.audio,onChange:b=>n({...e,audio:b.target.value}),rows:4,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"Nome da sua empresa"}),u.jsx("input",{value:s,onChange:b=>r(b.target.value),className:"w-full max-w-xs px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{onClick:m,disabled:c,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 disabled:opacity-60",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar templates"]}),u.jsxs("button",{onClick:g,className:"px-4 py-2.5 text-sm font-medium text-indigo-600 bg-indigo-50 border border-indigo-200 rounded-lg hover:bg-indigo-100",children:[u.jsx("i",{className:"fas fa-vial mr-2"})," Testar com lead de exemplo"]})]})]}),u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 text-sm text-gray-500 space-y-2",children:[u.jsx("p",{className:"font-medium text-gray-700 text-xs uppercase tracking-wide",children:"Como funciona"}),u.jsxs("p",{children:["O envio em massa é executado pelo ",u.jsx("strong",{children:"OpenOutreach"})," (eracle/OpenOutreach). As campanhas ficam na página ",u.jsx("strong",{children:"Disparos"}),"; a validação da integração acontece na hora de iniciar a campanha — sem travas de pré-registro."]})]}),u.jsx(Xt,{aberto:a,onFechar:()=>l(!1),titulo:"Pré-visualização do template",icone:"fas fa-comment-dots",children:u.jsx("div",{className:"bg-gray-50 border border-gray-100 rounded-lg p-4 text-sm text-gray-700 whitespace-pre-wrap",children:i})})]})}function ME(){const{toast:t}=en(),[e,n]=S.useState("texto"),[s,r]=S.useState(""),[i,o]=S.useState([{role:"assistant",content:"Olá! Sou o assistente de atendimento do LeadMaster. Como posso ajudar?"}]),[a,l]=S.useState(""),[c,d]=S.useState(!1),f=S.useCallback(async()=>{const m=await W.config.obter();n(m.agentes.atendimento.modo==="voz"?"voz":"texto"),r(m.integracoes.pipecat.url||"")},[]);S.useEffect(()=>{f().catch(m=>t("erro",m.message))},[f,t]);const h=async m=>{n(m);try{await W.config.salvar({agentes:{atendimento:{modo:m}},integracoes:{pipecat:{url:s}}}),t("sucesso",`Modo de atendimento: ${m==="voz"?"voz (pipecat)":"texto (LLM)"}.`)}catch(g){t("erro",g instanceof Error?g.message:"Falha ao salvar modo.")}},p=async()=>{const m=a.trim();if(!m)return;const g=[...i,{role:"user",content:m}];o(g),l(""),d(!0);try{const b=await W.agentes.chat(g.map(y=>({role:y.role==="assistant"?"assistant":"user",content:y.content})));b.ok&&b.resposta?o([...g,{role:"assistant",content:b.resposta}]):(o([...g,{role:"assistant",content:`⚠ ${b.mensagem??"Sem resposta."}`}]),t("erro",b.mensagem??"Sem resposta do agente."))}catch(b){t("erro",b instanceof Error?b.message:"Falha no chat.")}finally{d(!1)}};return u.jsxs("div",{className:"space-y-5 max-w-3xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800",children:"Modo do agente de atendimento"}),u.jsx("div",{className:"flex gap-3",children:[{id:"texto",rotulo:"Texto (LLM)",icone:"fas fa-keyboard",descricao:"Chat via LLM configurado"},{id:"voz",rotulo:"Voz (pipecat)",icone:"fas fa-microphone",descricao:"Atendimento por voz"}].map(m=>u.jsxs("button",{onClick:()=>h(m.id),className:H("flex-1 px-4 py-3 rounded-lg border text-left transition",e===m.id?"bg-indigo-50 border-indigo-400":"bg-white border-gray-200 hover:bg-gray-50"),children:[u.jsxs("p",{className:H("text-sm font-medium flex items-center gap-2",e===m.id?"text-indigo-700":"text-gray-600"),children:[u.jsx("i",{className:m.icone})," ",m.rotulo]}),u.jsx("p",{className:"text-xs text-gray-400 mt-1",children:m.descricao})]},m.id))}),e==="voz"&&u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"URL do serviço pipecat"}),u.jsx("input",{value:s,onChange:m=>r(m.target.value),onBlur:()=>h("voz"),placeholder:"http://localhost:5000",className:"w-full max-w-md px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})]}),u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6",children:[u.jsx("h3",{className:"text-sm font-semibold text-gray-800 mb-3",children:"Testar conversa"}),u.jsxs("div",{className:"space-y-3 max-h-80 overflow-y-auto mb-4",children:[i.map((m,g)=>u.jsx("div",{className:H("flex",m.role==="user"?"justify-end":"justify-start"),children:u.jsx("div",{className:H("max-w-[80%] px-4 py-2.5 rounded-2xl text-sm",m.role==="user"?"bg-indigo-500 text-white rounded-br-sm":"bg-gray-100 text-gray-700 rounded-bl-sm"),children:m.content})},g)),c&&u.jsxs("div",{className:"text-xs text-gray-400 flex items-center gap-2",children:[u.jsx("i",{className:"fas fa-spinner fa-spin"})," pensando..."]})]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx("input",{value:a,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&p(),placeholder:"Digite uma mensagem do cliente para testar...",className:"flex-1 px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"}),u.jsx("button",{onClick:p,disabled:c,className:"px-5 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 disabled:opacity-60",children:u.jsx("i",{className:"fas fa-paper-plane"})})]})]})]})}function PE({onConfigSalva:t}){const{toast:e}=en(),[n,s]=S.useState(null),[r,i]=S.useState(!1),[o,a]=S.useState(""),l=S.useCallback(async()=>{const h=await W.config.obter();s(h)},[]);if(S.useEffect(()=>{l().catch(h=>e("erro",h.message))},[l,e]),!n)return u.jsx("div",{className:"text-center text-gray-400 py-16",children:u.jsx("i",{className:"fas fa-spinner fa-spin text-2xl"})});const c=h=>{s(p=>{if(!p)return p;const m=JSON.parse(JSON.stringify(p));return h(m),m})},d=async()=>{i(!0);try{const h=await W.config.salvar(n);s(h),t==null||t(h),e("sucesso","Configurações salvas localmente (config.json).")}catch(h){e("erro",h instanceof Error?h.message:"Falha ao salvar configurações.")}finally{i(!1)}},f=async()=>{a("llm");try{const h=await W.config.testarLlm();e(h.ok?"sucesso":"erro",h.ok?`LLM respondeu: ${h.resposta}`:h.mensagem??"Falha no teste.")}finally{a("")}};return u.jsxs("div",{className:"space-y-6 max-w-4xl",children:[u.jsxs(Va,{titulo:"LLM (agentes de IA)",icone:"fas fa-brain",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsx(an,{rotulo:"Base URL",valor:n.llm.base_url,onChange:h=>c(p=>{p.llm.base_url=h}),placeholder:"https://api.openai.com/v1"}),u.jsx(an,{rotulo:"Modelo",valor:n.llm.modelo,onChange:h=>c(p=>{p.llm.modelo=h}),placeholder:"gpt-4o-mini"}),u.jsx(OE,{rotulo:"API Key",configurado:!!n.llm.api_key_configurado,onChange:h=>c(p=>{p.llm.api_key=h})})]}),u.jsx(TE,{rotulo:"Testar conexão LLM",carregando:o==="llm",onClick:f})]}),u.jsxs(Va,{titulo:"Extratores de leads",icone:"fas fa-magnifying-glass-location",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(an,{rotulo:"Google Maps Scraper — binário",valor:n.extratores.google_maps_cli,onChange:h=>c(p=>{p.extratores.google_maps_cli=h}),placeholder:"C:\\ferramentas\\google-maps-scraper.exe"}),u.jsx(an,{rotulo:"igmapper — binário",valor:n.extratores.igmapper_cli,onChange:h=>c(p=>{p.extratores.igmapper_cli=h}),placeholder:"Caminho do CLI igmapper"})]}),u.jsxs(Qt,{titulo:"Argumentos dos scrapers (templates)",icone:"fas fa-terminal",children:[u.jsx(bm,{rotulo:"Google Maps — template de argumentos",valor:n.extratores.google_maps_args,onChange:h=>c(p=>{p.extratores.google_maps_args=h}),linhas:2}),u.jsx(bm,{rotulo:"igmapper — template de argumentos",valor:n.extratores.igmapper_args,onChange:h=>c(p=>{p.extratores.igmapper_args=h}),linhas:2})]}),u.jsxs(Qt,{titulo:"CNPJ e Scrapling",icone:"fas fa-building",children:[u.jsx(an,{rotulo:"Provedor de busca CNAE/UF — URL",valor:n.extratores.cnpj_provedor_busca,onChange:h=>c(p=>{p.extratores.cnpj_provedor_busca=h}),placeholder:"https://api.opencnpj.org"}),u.jsx(an,{rotulo:"Scrapling — binário (scraping profundo)",valor:n.extratores.scrapling_cli,onChange:h=>c(p=>{p.extratores.scrapling_cli=h}),placeholder:"Caminho do CLI Scrapling"})]})]}),u.jsxs(Va,{titulo:"Agentes — integrações",icone:"fas fa-robot",children:[u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u.jsx(an,{rotulo:"OpenOutreach — URL",valor:n.integracoes.openoutreach.url,onChange:h=>c(p=>{p.integracoes.openoutreach.url=h}),placeholder:"http://localhost:9090"}),u.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-600 bg-indigo-50 border border-indigo-100 rounded-lg px-3 py-2.5 cursor-pointer h-fit mt-5",children:[u.jsx("input",{type:"checkbox",checked:n.integracoes.openoutreach.enabled,onChange:h=>c(p=>{p.integracoes.openoutreach.enabled=h.target.checked}),className:"w-4 h-4 accent-indigo-500"}),"OpenOutreach ativo"]})]}),u.jsx(an,{rotulo:"pipecat — URL (atendimento por voz)",valor:n.integracoes.pipecat.url,onChange:h=>c(p=>{p.integracoes.pipecat.url=h}),placeholder:"http://localhost:5000"})]}),u.jsx(Va,{titulo:"Perfil e licença",icone:"fas fa-user",children:u.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[u.jsx(an,{rotulo:"Seu nome",valor:n.perfil.nome,onChange:h=>c(p=>{p.perfil.nome=h})}),u.jsx(an,{rotulo:"Expira em",valor:n.perfil.licenca.expira_em,onChange:h=>c(p=>{p.perfil.licenca.expira_em=h})}),u.jsx(RE,{rotulo:"Dias restantes (vazio = infinito)",valor:n.perfil.licenca.restam_dias??0,onChange:h=>c(p=>{p.perfil.licenca.restam_dias=h>0?h:null})})]})}),u.jsx("div",{className:"flex justify-end",children:u.jsxs("button",{onClick:d,disabled:r,className:"px-8 py-3 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 transition disabled:opacity-60 shadow-sm",children:[u.jsx("i",{className:H("fas fa-save mr-2",r&&"fa-spin")}),r?"Salvando...":"Salvar configurações"]})})]})}function Va({titulo:t,icone:e,children:n}){return u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4",children:[u.jsxs("h3",{className:"text-sm font-semibold text-gray-800 flex items-center gap-2",children:[u.jsx("i",{className:H(e,"text-indigo-400")})," ",t]}),n]})}function an({rotulo:t,valor:e,onChange:n,placeholder:s,tipo:r="text"}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("input",{type:r,value:e,onChange:i=>n(i.target.value),placeholder:s,className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function RE({rotulo:t,valor:e,onChange:n}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("input",{type:"number",value:e??0,onChange:s=>n(Number(s.target.value)||0),className:"w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function OE({rotulo:t,configurado:e,onChange:n}){const[s,r]=S.useState(!1);return u.jsxs("div",{children:[u.jsxs("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:[t," ",e&&u.jsx("span",{className:"text-green-600",children:"• configurado"})]}),u.jsxs("div",{className:"relative",children:[u.jsx("input",{type:s?"text":"password",onChange:i=>n(i.target.value),placeholder:e?"•••••••• (deixe vazio para manter)":"cole a chave aqui",className:"w-full px-3 py-2 pr-10 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"}),u.jsx("button",{type:"button",onClick:()=>r(i=>!i),title:s?"Ocultar chave":"Mostrar chave","aria-label":s?"Ocultar chave":"Mostrar chave",className:"absolute inset-y-0 right-0 px-3 text-gray-400 hover:text-indigo-600 transition",children:u.jsx("i",{className:s?"fas fa-eye-slash":"fas fa-eye"})})]})]})}function bm({rotulo:t,valor:e,onChange:n,linhas:s=3}){return u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:t}),u.jsx("textarea",{value:e,onChange:r=>n(r.target.value),rows:s,className:"w-full px-3 py-2 text-xs font-mono border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]})}function TE({rotulo:t,onClick:e,carregando:n}){return u.jsxs("button",{onClick:e,disabled:n,className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium disabled:opacity-50",children:[u.jsx("i",{className:H("fas fa-vial-circle-check mr-1",n&&"fa-spin")})," ",t]})}const DE=[{id:"lead.criado",rotulo:"Lead criado"},{id:"lead.etapa",rotulo:"Lead mudou de etapa"},{id:"campanha.concluida",rotulo:"Campanha concluída"}];function LE(){const{toast:t}=en(),[e,n]=S.useState(""),[s,r]=S.useState(new Set),[i,o]=S.useState(""),[a,l]=S.useState(!1),[c,d]=S.useState(!1),f=S.useCallback(async()=>{const g=await W.webhook.obter();n(g.url),r(new Set(g.eventos))},[]);S.useEffect(()=>{f().catch(g=>t("erro",g.message))},[f,t]);const h=g=>r(b=>{const y=new Set(b);return y.has(g)?y.delete(g):y.add(g),y}),p=async()=>{d(!0);try{await W.webhook.salvar({url:e.trim(),eventos:[...s]}),t("sucesso","Webhook salvo.")}catch(g){t("erro",g instanceof Error?g.message:"Falha ao salvar webhook.")}finally{d(!1)}},m=async()=>{if(!e.trim()){t("erro","Informe a URL do webhook antes de testar.");return}try{const g=await W.webhook.testar(e.trim());g.ok?o(`✅ HTTP ${g.status_http} — o endpoint recebeu o evento de teste.
89
89
 
90
- ${g.resposta??""}`):o(`❌ ${g.mensagem??"Falha no teste."}`),l(!0)}catch(g){t("erro",g instanceof Error?g.message:"Falha no teste.")}};return u.jsxs("div",{className:"space-y-6 max-w-3xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-5",children:[u.jsx("p",{className:"text-sm text-gray-500",children:"Receba eventos do LeadMaster (lead criado, mudança de etapa, campanha concluída) em qualquer endpoint local ou externo — útil para integrar com automações (n8n, Make, Zapier etc.)."}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"URL do webhook"}),u.jsx("input",{value:e,onChange:g=>n(g.target.value),placeholder:"https://seu-endpoint.com/webhook",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-2",children:"Eventos enviados"}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:D2.map(g=>u.jsxs("label",{className:H("flex items-center gap-3 px-4 py-3 rounded-lg border text-sm cursor-pointer transition",s.has(g.id)?"bg-indigo-50 border-indigo-300 text-indigo-700":"bg-white border-gray-200 text-gray-500 hover:bg-gray-50"),children:[u.jsx("input",{type:"checkbox",checked:s.has(g.id),onChange:()=>h(g.id),className:"w-4 h-4 accent-indigo-500"}),g.rotulo,u.jsx("code",{className:"text-[10px] text-gray-400 ml-auto",children:g.id})]},g.id))})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{onClick:p,disabled:c,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 disabled:opacity-60",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar"]}),u.jsxs("button",{onClick:m,className:"px-4 py-2.5 text-sm font-medium text-indigo-600 bg-indigo-50 border border-indigo-200 rounded-lg hover:bg-indigo-100",children:[u.jsx("i",{className:"fas fa-paper-plane mr-2"})," Enviar evento de teste"]})]})]}),u.jsx(Xt,{aberto:a,onFechar:()=>l(!1),titulo:"Resultado do teste",icone:"fas fa-satellite-dish",children:u.jsx("pre",{className:"text-xs text-gray-600 bg-gray-50 rounded-lg p-4 whitespace-pre-wrap",children:i})})]})}function A2(){const{toast:t}=en(),[e,n]=S.useState(null),[s,r]=S.useState(!1),i=async()=>{r(!0);try{n(await W.doctor()),t("sucesso","Diagnóstico concluído.")}catch(o){t("erro",o instanceof Error?o.message:"Falha no diagnóstico.")}finally{r(!1)}};return S.useEffect(()=>{i()},[]),u.jsxs("div",{className:"space-y-6 max-w-3xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("h3",{className:"text-sm font-semibold text-gray-800 flex items-center gap-2",children:[u.jsx("i",{className:"fas fa-heart-pulse text-indigo-400"})," Diagnóstico do ambiente"]}),u.jsxs("button",{onClick:i,disabled:s,className:"px-4 py-2 text-xs font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 disabled:opacity-60",children:[u.jsx("i",{className:H("fas fa-rotate mr-1",s&&"fa-spin")})," Executar novamente"]})]}),e&&u.jsxs("div",{className:"mt-4 space-y-2 text-sm",children:[u.jsx(Vi,{rotulo:"Versão do LeadMaster",valor:e.versao}),u.jsx(Vi,{rotulo:"Python",valor:e.python}),u.jsx(Vi,{rotulo:"Sistema",valor:e.sistema}),u.jsx(Vi,{rotulo:"Interface construída (dist)",valor:e.dist_frontend?"presente":"ausente (modo dev)"}),u.jsx(Vi,{rotulo:"Pasta de dados",valor:e.storage}),u.jsx("div",{className:"pt-2 flex flex-wrap gap-2",children:Object.entries(e.integracoes).map(([o,a])=>u.jsx(sr,{status:a?"ativo":"inativo",rotulo:`${I2(o)}: ${a?"ativo":"inativo"}`},o))})]})]}),u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6",children:[u.jsxs("h3",{className:"text-sm font-semibold text-gray-800 mb-3",children:[u.jsx("i",{className:"fas fa-circle-question text-indigo-400 mr-2"})," Perguntas frequentes"]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(Qt,{titulo:"Meus dados ficam na nuvem?",icone:"fas fa-cloud",children:"Não. O LeadMaster é 100% local: todos os dados (leads, campanhas e configuração) ficam em arquivos JSON na sua pasta de dados."}),u.jsx(Qt,{titulo:"Como turbinar os agentes com IA?",icone:"fas fa-brain",children:"Em Ferramentas → LLM, informe base URL, modelo e API key de qualquer API OpenAI-compatível. O agente de CRM passa a enriquecer e sugerir com mais contexto, e o de atendimento conversa por texto. Sem LLM, as heurísticas locais continuam funcionando."}),u.jsx(Qt,{titulo:"Como funcionam os disparos?",icone:"fas fa-paper-plane",children:"As campanhas de Disparos usam o OpenOutreach (eracle/OpenOutreach). Configure a URL em Ferramentas → Agentes — a validação acontece só na hora de iniciar a campanha."}),u.jsx(Qt,{titulo:"Onde reporto problemas?",icone:"fas fa-bug",children:"Abra uma issue em github.com/DanHachuel/LeadMaster ou use a página de diagnóstico acima ao pedir ajuda — ela resume todo o ambiente."})]})]}),u.jsxs("div",{className:"bg-[#1e1b4b] text-white rounded-xl p-6 flex items-center justify-between flex-wrap gap-4",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-sm font-semibold",children:"LeadMaster — SaaS local de prospecção e automação de conteúdo"}),u.jsx("p",{className:"text-xs text-gray-300 mt-1",children:"Instalável via npx · dados 100% locais · sem mensalidade de nuvem"})]}),u.jsxs("a",{href:"https://github.com/DanHachuel/LeadMaster",target:"_blank",rel:"noreferrer",className:"px-4 py-2.5 text-sm font-medium bg-white/10 hover:bg-white/20 rounded-lg transition",children:[u.jsx("i",{className:"fab fa-github mr-2"})," Repositório"]})]})]})}function Vi({rotulo:t,valor:e}){return u.jsxs("div",{className:"flex items-center justify-between border-b border-gray-50 pb-2",children:[u.jsx("span",{className:"text-xs text-gray-500",children:t}),u.jsx("span",{className:"text-xs font-medium text-gray-700 text-right break-all max-w-[60%]",children:e})]})}function I2(t){return{llm_configurado:"LLM",openoutreach:"OpenOutreach",pipecat:"pipecat"}[t]??t}const F2={"/":"Painel","/leads":"Leads","/agentes":"Agentes","/ferramentas":"Ferramentas","/extratores":"Extratores de Leads","/extrator-maps":"Extrator de Leads — Google Maps","/extrator-instagram":"Extrator de Leads — Instagram","/extrator-cnpj":"Extrator de Leads — CNPJ","/disparos":"Disparos","/crm":"CRM — Kanban","/webhook":"Webhook","/suporte":"Suporte"};function z2(){const[t,e]=S.useState(null),[n,s]=S.useState(!1),[r,i]=S.useState(!1),o=S.useCallback(async()=>{try{e(await W.config.obter())}catch{}},[]);return S.useEffect(()=>{o()},[o]),r?u.jsx("div",{className:"min-h-screen bg-[#1e1b4b] text-white flex items-center justify-center p-8",children:u.jsxs("div",{className:"text-center max-w-md",children:[u.jsx("i",{className:"fas fa-power-off text-4xl text-indigo-300 mb-4 block"}),u.jsx("h1",{className:"text-xl font-bold",children:"LeadMaster encerrado"}),u.jsx("p",{className:"text-sm text-gray-300 mt-3",children:"O servidor local foi desligado com sucesso. Seus dados estão salvos na pasta de dados."}),u.jsxs("p",{className:"text-xs text-gray-400 mt-6",children:["Para voltar, execute: ",u.jsx("code",{className:"bg-white/10 px-2 py-1 rounded",children:"npx --yes @danhachuel/leadmaster"})]})]})}):u.jsx(v_,{children:u.jsxs(GS,{children:[u.jsx(B2,{nomeUsuario:(t==null?void 0:t.perfil.nome)??"...",onSair:()=>s(!0),onConfigSalva:a=>e(a)}),u.jsxs(Xt,{aberto:n,onFechar:()=>s(!1),titulo:"Encerrar o LeadMaster",icone:"fas fa-power-off",children:[u.jsx("p",{className:"text-sm text-gray-600",children:"Isso encerra o servidor local (os processos do terminal também fecham). Seus dados permanecem salvos nos arquivos JSON da pasta de dados. Deseja continuar?"}),u.jsxs("div",{className:"flex justify-end gap-3 mt-6",children:[u.jsx("button",{onClick:()=>s(!1),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:async()=>{s(!1);try{await W.shutdown()}catch{}setTimeout(()=>i(!0),400)},className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-power-off mr-2"})," Encerrar"]})]})]})]})})}function B2({nomeUsuario:t,onSair:e,onConfigSalva:n}){const s=Os(),r=F2[s.pathname]??"LeadMaster";return u.jsxs("div",{className:"bg-gray-100 min-h-screen flex",children:[u.jsx(m_,{onSair:e}),u.jsxs("main",{className:"flex-1 flex flex-col min-w-0",children:[u.jsx(p_,{titulo:r,nomeUsuario:t}),u.jsxs("div",{className:"p-8 space-y-6 overflow-y-auto flex-1",children:[u.jsxs(US,{children:[u.jsx(vt,{path:"/",element:u.jsx(gN,{nomeUsuario:t})}),u.jsx(vt,{path:"/leads",element:u.jsx(bN,{})}),u.jsx(vt,{path:"/crm",element:u.jsx(v2,{})}),u.jsx(vt,{path:"/disparos",element:u.jsx(b2,{})}),u.jsx(vt,{path:"/extratores",element:u.jsx(S2,{})}),u.jsx(vt,{path:"/extrator-maps",element:u.jsx(_2,{})}),u.jsx(vt,{path:"/extrator-instagram",element:u.jsx(k2,{})}),u.jsx(vt,{path:"/extrator-cnpj",element:u.jsx(j2,{})}),u.jsx(vt,{path:"/agentes",element:u.jsx(N2,{})}),u.jsx(vt,{path:"/ferramentas",element:u.jsx(P2,{onConfigSalva:n})}),u.jsx(vt,{path:"/webhook",element:u.jsx(L2,{})}),u.jsx(vt,{path:"/suporte",element:u.jsx(A2,{})})]}),u.jsxs("footer",{className:"flex items-center justify-between text-xs text-gray-400 pt-4 border-t border-gray-200",children:[u.jsx("span",{children:"© 2026 LeadMaster. Todos os direitos reservados."}),u.jsx("span",{children:"Dados 100% locais — sem nuvem"})]})]})]})]})}const $2=new W1({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!0}}});_u.createRoot(document.getElementById("root")).render(u.jsx(pe.StrictMode,{children:u.jsx(x1,{client:$2,children:u.jsx(z2,{})})}));
90
+ ${g.resposta??""}`):o(`❌ ${g.mensagem??"Falha no teste."}`),l(!0)}catch(g){t("erro",g instanceof Error?g.message:"Falha no teste.")}};return u.jsxs("div",{className:"space-y-6 max-w-3xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-5",children:[u.jsx("p",{className:"text-sm text-gray-500",children:"Receba eventos do LeadMaster (lead criado, mudança de etapa, campanha concluída) em qualquer endpoint local ou externo — útil para integrar com automações (n8n, Make, Zapier etc.)."}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-1",children:"URL do webhook"}),u.jsx("input",{value:e,onChange:g=>n(g.target.value),placeholder:"https://seu-endpoint.com/webhook",className:"w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-400 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-xs font-medium text-gray-500 mb-2",children:"Eventos enviados"}),u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:DE.map(g=>u.jsxs("label",{className:H("flex items-center gap-3 px-4 py-3 rounded-lg border text-sm cursor-pointer transition",s.has(g.id)?"bg-indigo-50 border-indigo-300 text-indigo-700":"bg-white border-gray-200 text-gray-500 hover:bg-gray-50"),children:[u.jsx("input",{type:"checkbox",checked:s.has(g.id),onChange:()=>h(g.id),className:"w-4 h-4 accent-indigo-500"}),g.rotulo,u.jsx("code",{className:"text-[10px] text-gray-400 ml-auto",children:g.id})]},g.id))})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsxs("button",{onClick:p,disabled:c,className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 disabled:opacity-60",children:[u.jsx("i",{className:"fas fa-save mr-2"})," Salvar"]}),u.jsxs("button",{onClick:m,className:"px-4 py-2.5 text-sm font-medium text-indigo-600 bg-indigo-50 border border-indigo-200 rounded-lg hover:bg-indigo-100",children:[u.jsx("i",{className:"fas fa-paper-plane mr-2"})," Enviar evento de teste"]})]})]}),u.jsx(Xt,{aberto:a,onFechar:()=>l(!1),titulo:"Resultado do teste",icone:"fas fa-satellite-dish",children:u.jsx("pre",{className:"text-xs text-gray-600 bg-gray-50 rounded-lg p-4 whitespace-pre-wrap",children:i})})]})}function AE(){const{toast:t}=en(),[e,n]=S.useState(null),[s,r]=S.useState(!1),i=async()=>{r(!0);try{n(await W.doctor()),t("sucesso","Diagnóstico concluído.")}catch(o){t("erro",o instanceof Error?o.message:"Falha no diagnóstico.")}finally{r(!1)}};return S.useEffect(()=>{i()},[]),u.jsxs("div",{className:"space-y-6 max-w-3xl",children:[u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("h3",{className:"text-sm font-semibold text-gray-800 flex items-center gap-2",children:[u.jsx("i",{className:"fas fa-heart-pulse text-indigo-400"})," Diagnóstico do ambiente"]}),u.jsxs("button",{onClick:i,disabled:s,className:"px-4 py-2 text-xs font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90 disabled:opacity-60",children:[u.jsx("i",{className:H("fas fa-rotate mr-1",s&&"fa-spin")})," Executar novamente"]})]}),e&&u.jsxs("div",{className:"mt-4 space-y-2 text-sm",children:[u.jsx(Vi,{rotulo:"Versão do LeadMaster",valor:e.versao}),u.jsx(Vi,{rotulo:"Python",valor:e.python}),u.jsx(Vi,{rotulo:"Sistema",valor:e.sistema}),u.jsx(Vi,{rotulo:"Interface construída (dist)",valor:e.dist_frontend?"presente":"ausente (modo dev)"}),u.jsx(Vi,{rotulo:"Pasta de dados",valor:e.storage}),u.jsx("div",{className:"pt-2 flex flex-wrap gap-2",children:Object.entries(e.integracoes).map(([o,a])=>u.jsx(sr,{status:a?"ativo":"inativo",rotulo:`${IE(o)}: ${a?"ativo":"inativo"}`},o))})]})]}),u.jsxs("div",{className:"bg-white rounded-xl shadow-sm border border-gray-100 p-6",children:[u.jsxs("h3",{className:"text-sm font-semibold text-gray-800 mb-3",children:[u.jsx("i",{className:"fas fa-circle-question text-indigo-400 mr-2"})," Perguntas frequentes"]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(Qt,{titulo:"Meus dados ficam na nuvem?",icone:"fas fa-cloud",children:"Não. O LeadMaster é 100% local: todos os dados (leads, campanhas e configuração) ficam em arquivos JSON na sua pasta de dados."}),u.jsx(Qt,{titulo:"Como turbinar os agentes com IA?",icone:"fas fa-brain",children:"Em Ferramentas → LLM, informe base URL, modelo e API key de qualquer API OpenAI-compatível. O agente de CRM passa a enriquecer e sugerir com mais contexto, e o de atendimento conversa por texto. Sem LLM, as heurísticas locais continuam funcionando."}),u.jsx(Qt,{titulo:"Como funcionam os disparos?",icone:"fas fa-paper-plane",children:"As campanhas de Disparos usam o OpenOutreach (eracle/OpenOutreach). Configure a URL em Ferramentas → Agentes — a validação acontece só na hora de iniciar a campanha."}),u.jsx(Qt,{titulo:"Onde reporto problemas?",icone:"fas fa-bug",children:"Abra uma issue em github.com/DanHachuel/LeadMaster ou use a página de diagnóstico acima ao pedir ajuda — ela resume todo o ambiente."})]})]}),u.jsxs("div",{className:"bg-[#1e1b4b] text-white rounded-xl p-6 flex items-center justify-between flex-wrap gap-4",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-sm font-semibold",children:"LeadMaster — SaaS local de prospecção e automação de conteúdo"}),u.jsx("p",{className:"text-xs text-gray-300 mt-1",children:"Instalável via npx · dados 100% locais · sem mensalidade de nuvem"})]}),u.jsxs("a",{href:"https://github.com/DanHachuel/LeadMaster",target:"_blank",rel:"noreferrer",className:"px-4 py-2.5 text-sm font-medium bg-white/10 hover:bg-white/20 rounded-lg transition",children:[u.jsx("i",{className:"fab fa-github mr-2"})," Repositório"]})]})]})}function Vi({rotulo:t,valor:e}){return u.jsxs("div",{className:"flex items-center justify-between border-b border-gray-50 pb-2",children:[u.jsx("span",{className:"text-xs text-gray-500",children:t}),u.jsx("span",{className:"text-xs font-medium text-gray-700 text-right break-all max-w-[60%]",children:e})]})}function IE(t){return{llm_configurado:"LLM",openoutreach:"OpenOutreach",pipecat:"pipecat"}[t]??t}const FE={"/":"Painel","/leads":"Leads","/agentes":"Agentes","/ferramentas":"Ferramentas","/extratores":"Extratores de Leads","/extrator-maps":"Extrator de Leads — Google Maps","/extrator-instagram":"Extrator de Leads — Instagram","/extrator-cnpj":"Extrator de Leads — CNPJ","/disparos":"Disparos","/crm":"CRM — Kanban","/webhook":"Webhook","/suporte":"Suporte"};function zE(){const[t,e]=S.useState(null),[n,s]=S.useState(!1),[r,i]=S.useState(!1),o=S.useCallback(async()=>{try{e(await W.config.obter())}catch{}},[]);return S.useEffect(()=>{o()},[o]),r?u.jsx("div",{className:"min-h-screen bg-[#1e1b4b] text-white flex items-center justify-center p-8",children:u.jsxs("div",{className:"text-center max-w-md",children:[u.jsx("i",{className:"fas fa-power-off text-4xl text-indigo-300 mb-4 block"}),u.jsx("h1",{className:"text-xl font-bold",children:"LeadMaster encerrado"}),u.jsx("p",{className:"text-sm text-gray-300 mt-3",children:"O servidor local foi desligado com sucesso. Seus dados estão salvos na pasta de dados."}),u.jsxs("p",{className:"text-xs text-gray-400 mt-6",children:["Para voltar, execute: ",u.jsx("code",{className:"bg-white/10 px-2 py-1 rounded",children:"npx --yes @danhachuel/leadmaster"})]})]})}):u.jsx(v_,{children:u.jsxs(GS,{children:[u.jsx(BE,{nomeUsuario:(t==null?void 0:t.perfil.nome)??"...",onSair:()=>s(!0),onConfigSalva:a=>e(a)}),u.jsxs(Xt,{aberto:n,onFechar:()=>s(!1),titulo:"Encerrar o LeadMaster",icone:"fas fa-power-off",children:[u.jsx("p",{className:"text-sm text-gray-600",children:"Isso encerra o servidor local (os processos do terminal também fecham). Seus dados permanecem salvos nos arquivos JSON da pasta de dados. Deseja continuar?"}),u.jsxs("div",{className:"flex justify-end gap-3 mt-6",children:[u.jsx("button",{onClick:()=>s(!1),className:"px-4 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50",children:"Cancelar"}),u.jsxs("button",{onClick:async()=>{s(!1);try{await W.shutdown()}catch{}setTimeout(()=>i(!0),400)},className:"px-6 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-lg hover:opacity-90",children:[u.jsx("i",{className:"fas fa-power-off mr-2"})," Encerrar"]})]})]})]})})}function BE({nomeUsuario:t,onSair:e,onConfigSalva:n}){const s=Os(),r=FE[s.pathname]??"LeadMaster";return u.jsxs("div",{className:"bg-gray-100 min-h-screen flex",children:[u.jsx(m_,{onSair:e}),u.jsxs("main",{className:"flex-1 flex flex-col min-w-0",children:[u.jsx(p_,{titulo:r,nomeUsuario:t}),u.jsxs("div",{className:"p-8 space-y-6 overflow-y-auto flex-1",children:[u.jsxs(US,{children:[u.jsx(vt,{path:"/",element:u.jsx(gN,{nomeUsuario:t})}),u.jsx(vt,{path:"/leads",element:u.jsx(bN,{})}),u.jsx(vt,{path:"/crm",element:u.jsx(vE,{})}),u.jsx(vt,{path:"/disparos",element:u.jsx(bE,{})}),u.jsx(vt,{path:"/extratores",element:u.jsx(SE,{})}),u.jsx(vt,{path:"/extrator-maps",element:u.jsx(_E,{})}),u.jsx(vt,{path:"/extrator-instagram",element:u.jsx(kE,{})}),u.jsx(vt,{path:"/extrator-cnpj",element:u.jsx(jE,{})}),u.jsx(vt,{path:"/agentes",element:u.jsx(NE,{})}),u.jsx(vt,{path:"/ferramentas",element:u.jsx(PE,{onConfigSalva:n})}),u.jsx(vt,{path:"/webhook",element:u.jsx(LE,{})}),u.jsx(vt,{path:"/suporte",element:u.jsx(AE,{})})]}),u.jsxs("footer",{className:"flex items-center justify-between text-xs text-gray-400 pt-4 border-t border-gray-200",children:[u.jsx("span",{children:"© 2026 LeadMaster. Todos os direitos reservados."}),u.jsx("span",{children:"Dados 100% locais — sem nuvem"})]})]})]})]})}const $E=new W1({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!0}}});_u.createRoot(document.getElementById("root")).render(u.jsx(pe.StrictMode,{children:u.jsx(x1,{client:$E,children:u.jsx(zE,{})})}));