1import{a as o,j as e}from"./trpc-vendor-Bta84Nsh.js";import{t as p,D as we,a as ye,b as ke,c as Se,L as ze,B as y,k as Qt,S as he,u as Ut,g as xe,C as ps,h as bs,l as fs,m as js,n as Ns,o as Ze,p as vs,I as ws,q as Te,r as ys,W as ks,s as Ht}from"./index-_3-B0itT.js";import{u as Ge}from"./react-vendor-DpXpH6G7.js";import{S as G,a as q,b as J,c as Y,d as k}from"./select-DqcHU93A.js";import{t as d,aV as Zt,w as Ss,b as De,af as Cs,au as Ls,as as be,n as Gt,g as As,q as mt,bt as qt,bk as $s,bu as Jt,bm as Is,a3 as _s,h as xt,a8 as Yt,A as dt,bv as Ms,bw as Xt,ap as Ce,aa as Es,a7 as ct,aj as zs,bx as Ts,I as Ds,aZ as Fs,K as qe,a9 as Rs,X as Ps,aY as es,aw as Os,by as Vs,bz as Dt,bA as Bs,aA as Ws,D as Ks,j as Qs,bl as Us,Z as Hs,o as Ft,bB as Rt,an as Zs}from"./ui-vendor-NEZNvIbV.js";import{L as Gs,a as qs}from"./LeadReasonDialog-Bc1fjbie.js";import{u as Js,a as Pt,D as Ys,b as Xs,T as er,M as tr,c as sr,d as rr}from"./core.esm-CoyFR6--.js";import{S as ut}from"./SourceIcon-mjrky-KW.js";const nr=[{value:"import",label:"Import"},{value:"promo",label:"Promo-Aktion"},{value:"studio_interessenten",label:"Studio-Interessenten"},{value:"former_member",label:"Ehem. Mitglied"},{value:"ads",label:"Werbeanzeigen"},{value:"flyer",label:"Flyer / Aktion"},{value:"referral",label:"Empfehlung"},{value:"walk_in",label:"Walk-in (Laufkunde)"},{value:"online",label:"Online-Formular"},{value:"call_center",label:"Call-Center"},{value:"other",label:"Sonstiges"}],ar=[{value:"lead",label:"Lead"},{value:"contacted",label:"Kontaktiert"},{value:"appointment",label:"Termin"},{value:"closed",label:"Abschluss"},{value:"referral",label:"Referral"},{value:"lost",label:"Verloren"},{value:"reactivation",label:"Reaktivierung"}];function Ot(s,l){const f=[];let n="",N=!1;for(let c=0;c<s.length;c++){const $=s[c];$==='"'?N&&s[c+1]==='"'?(n+='"',c++):N=!N:$===l&&!N?(f.push(n),n=""):n+=$}return f.push(n),f.map(c=>c.trim())}function Vt(s){const l=(s||"").replace(/^["']|["']$/g,"").replace(/\s+/g," ").trim();if(!l)return{firstName:"",lastName:""};if(l.includes(",")){const[n,N]=l.split(",");return{firstName:(N||"").trim(),lastName:(n||"").trim()}}const f=l.split(" ");return f.length===1?{firstName:f[0],lastName:""}:{firstName:f[0],lastName:f.slice(1).join(" ")}}function Bt(s){const l=s.trim().split(/\r?\n/);if(l.length<2)return[];const f=(l[0].match(/;/g)?.length??0)>(l[0].match(/,/g)?.length??0)?";":",",n=Ot(l[0],f).map(A=>A.toLowerCase().replace(/^["']|["']$/g,"").trim()),N=A=>{for(const u of A){const h=n.findIndex(M=>M.includes(u));if(h>=0)return h}return-1},c=N(["vorname","firstname","first_name","first name"]),$=N(["nachname","lastname","last_name","last name"]),b=N(["email","e-mail","mail"]),g=N(["telefon","phone","tel","handy","mobile"]),m=c<0&&$<0?N(["vollständiger name","voller name","full name","kundenname","kunde","name"]):-1,S=[];for(let A=1;A<l.length;A++){if(!l[A].trim())continue;const u=Ot(l[A],f);let h=(c>=0?u[c]:"")||"",M=($>=0?u[$]:"")||"";if(!h&&!M&&m>=0){const E=Vt(u[m]??"");h=E.firstName,M=E.lastName}if(!h.trim()&&M.trim().includes(" ")){const E=Vt(M);h=E.firstName,M=E.lastName}h||(h="Unbekannt");const x=(b>=0?u[b]:"")||void 0,w=(g>=0?u[g]:"")||void 0;
1h==="Unbekannt"&&!M&&!x&&!w||S.push({firstName:h,lastName:M,email:x,phone:w})}return S}function lr({open:s,onOpenChange:l,onSuccess:f}){const[n,N]=o.useState(""),[c,$]=o.useState([]),[b,g]=o.useState(""),[m,S]=o.useState(""),[A,u]=o.useState("import"),[h,M]=o.useState("lead"),[x,w]=o.useState(""),[E,D]=o.useState(!0),[K,fe]=o.useState("none"),re=o.useRef(null),{data:L=[]}=p.brands.list.useQuery(),{data:Q=[]}=p.weeklyFlows.list.useQuery(void 0,{enabled:s}),B=Q.filter(i=>{if(!i.isActive)return!1;const F=i.targetBrandIds??[];return F.length===0?!0:m?F.includes(Number(m)):!1}),[I,ne]=o.useState(null),de=p.leads.previewCsvImport.useMutation({onSuccess:i=>ne(i),onError:i=>d.error(`Vorab-Pruefung fehlgeschlagen: ${i.message}`)}),ce=p.leads.importLeads.useMutation({onSuccess:i=>{if(i.pendingApproval){d.success(`Zur Admin-Freigabe eingereicht (${i.count??0} Leads). Der Import läuft erst nach Freigabe.`,{duration:6e3}),X(),l(!1);return}const F=i.subscribedToFlow>0?`, ${i.subscribedToFlow} in Wochen-Mailing aktiviert`:"";d.success(`${i.imported} Leads importiert${i.skipped>0?`, ${i.skipped} übersprungen`:""}${F}`),X(),l(!1),f()},onError:i=>d.error(i.message)}),X=()=>{N(""),$([]),g(""),S(""),u("import"),M("lead"),w(""),fe("none"),ne(null)},Fe=i=>{const F=i.target.files?.[0];if(!F)return;g(F.name);const R=new FileReader;R.onload=P=>{const ae=P.target?.result;N(ae),$(Bt(ae))},R.readAsText(F,"utf-8")},W=i=>{i.preventDefault();const F=i.dataTransfer.files?.[0];if(!F)return;g(F.name);const R=new FileReader;R.onload=P=>{const ae=P.target?.result;N(ae),$(Bt(ae))},R.readAsText(F,"utf-8")},U=c.length>0&&m!==""&&!ce.isPending&&(I===null||I.newCount>0),V=p.leads.undoLastImport.useMutation({onSuccess:i=>{i.willDelete!==void 0?window.confirm(`${i.matched} Leads gefunden. ${i.willDelete} koennen rueckgaengig gemacht werden â ${i.protectedFromDelete} sind durch Termine/Vertraege geschuetzt. 2 3Wirklich loeschen?`)&&V.mutate({brandId:Number(m),source:A,status:h,sinceMinutes:60,previewOnly:!1}):(d.success(`${i.deleted} Leads zurueckgesetzt (${i.protectedFromDelete} wegen Termin/Vertrag geschuetzt)`),f())},onError:i=>d.error(i.message)}),Ne=()=>{if(!m){d.error("Bitte zuerst Marke + Quelle waehlen, deren Import du undoen willst.");return}V.mutate({brandId:Number(m),source:A,status:h,sinceMinutes:60,previewOnly:!0})};return e.jsx(we,{open:s,onOpenChange:i=>{i||X(),l(i)},children:e.jsxs(ye,{className:"bg-card border-border max-w-2xl max-h-[90vh] flex flex-col",children:[e.jsx(ke,{className:"shrink-0",children:e.jsx(Se,{children:"CSV-Import"})}),e.jsxs("div",{className:"space-y-4 overflow-y-auto flex-1 min-h-0 pr-1 -mr-1",children:[e.jsxs("div",{className:"text-xs text-muted-foreground bg-muted/50 rounded p-3 space-y-1",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Erwartetes CSV-Format:"}),e.jsx("code",{className:"block",children:"Vorname,Nachname,Email,Telefon"}),e.jsx("code",{className:"block",children:"Max,Mustermann,[email protected],+49123"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"Trennzeichen: Komma oder Semikolon. Quelle, Status und Marke werden unten ausgewählt."})]}),e.jsxs("div",{className:"border-2 border-dashed border-border rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>re.current?.click(),onDrop:W,onDragOver:i=>i.preventDefault(),children:[e.jsx(Zt,{className:"h-8 w-8 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b||"CSV-Datei auswählen oder hierher ziehen"}),e.jsx("input",{ref:re,type:"file",accept:".csv,.txt",className:"hidden",onChange:Fe})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ze,{className:"text-xs text-muted-foreground",children:"Marke *"}),e.jsxs(G,{value:m,onValueChange:S,children:[e.jsx(q,{className:"h-9",children:e.jsx(J,{placeholder:"Marke wählen..."})}),e.jsx(Y,{children:L.map(i=>e.jsx(k,{value:String(i.id),children:i.name},i.id))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ze,{className:"text-xs text-muted-foreground",children:"Quelle"}),e.jsxs(G,{value:A,onValueChange:u,children:[e.jsx(q,{className:"h-9",children:e.jsx(J,{})}),e.jsx(Y,{children:nr.map(i=>e.jsx(k,{value:i.value,children:i.label},i.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ze,{className:"text-xs text-muted-foreground",children:"Status"}),e.jsxs(G,{value:h,onValueChange:M,children:[e.jsx(q,{className:"h-9",children:e.jsx(J,{})}),e.jsx(Y,{children:ar.map(i=>e.jsx(k,{value:i.value,children:i.label},i.value))})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ze,{className:"text-xs text-muted-foreground",children:"Notiz für alle Leads (optional)"}),e.jsx("textarea",{value:x,onChange:i=>w(i.target.value),rows:2,placeholder:"z.B. Liste vom Messestand 06/2026 â vor Anruf kurz aufwärmen",className:"w-full text-sm px-2.5 py-1.5 rounded-md border border-border bg-background resize-y"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:'Wird bei jedem importierten Lead unter âNotizen" hinterlegt.'})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ze,{className:"text-xs text-muted-foreground",children:"Direkt in Wochen-Mailing einschreiben (optional)"}),e.jsxs(G,{value:K,onValueChange:fe,children:[e.jsx(q,{className:"h-9",children:e.jsx(J,{placeholder:"Kein Wochen-Mailing â nur importieren"})}),e.jsxs(Y,{children:[e.jsx(k,{value:"none",children:"â Kein Wochen-Mailing â"}),B.length===0&&m&&e.jsx(k,{value:"empty",disabled:!0,children:"Keine Flows fuer diese Marke aktiv"}),B.map(i=>
3e.jsxs(k,{value:String(i.id),children:[i.name," (",i.subscriberCount??0," aktiv)"]},i.id))]})]}),K!=="none"&&K!=="empty"&&e.jsx("p",{className:"text-[11px] text-blue-400 mt-1",children:"â Importierte Leads (mit Email) landen direkt im Verteiler. Sonntag-Kickoff enrollt sie automatisch."}),!m&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Erst Marke waehlen, dann erscheinen die passenden Flows."})]}),c.length>0&&e.jsxs("div",{className:"rounded border border-blue-500/30 bg-blue-500/5 p-3 flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"text-xs text-blue-200/90 flex items-center gap-2",children:[e.jsx(Ss,{className:"w-4 h-4 text-blue-300 shrink-0"}),e.jsx("span",{children:"Pruefen wer schon im System existiert (Email + Telefon-Abgleich) BEVOR der Import startet."})]}),e.jsx(y,{size:"sm",variant:"outline",disabled:!m||de.isPending,onClick:()=>{ne(null),de.mutate({brandId:Number(m),csvText:n})},className:"text-xs h-7 border-blue-500/40 text-blue-300 hover:bg-blue-500/10",children:de.isPending?"Pruefe...":"Duplikate pruefen"})]}),I&&e.jsxs("div",{className:"rounded border border-border bg-card/40 p-3 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{className:"rounded border border-emerald-500/30 bg-emerald-500/10 p-2 text-center",children:[e.jsx("div",{className:"text-emerald-300 text-[10px] uppercase",children:"Neu"}),e.jsx("div",{className:"text-2xl font-black text-emerald-400",children:I.newCount})]}),e.jsxs("div",{className:"rounded border border-orange-500/30 bg-
3orange-500/10 p-2 text-center",children:[e.jsx("div",{className:"text-orange-300 text-[10px] uppercase",children:"Duplikate"}),e.jsx("div",{className:"text-2xl font-black text-orange-400",children:I.duplicates}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"werden uebersprungen"})]}),e.jsxs("div",{className:"rounded border border-red-500/30 bg-red-500/10 p-2 text-center",children:[e.jsx("div",{className:"text-red-300 text-[10px] uppercase",children:"Ungueltig"}),e.jsx("div",{className:"text-2xl font-black text-red-400",children:I.invalid})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border border-border",children:e.jsxs("table",{className:"w-full text-[11px]",children:[e.jsx("thead",{className:"bg-muted/30 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-1",children:"Status"}),e.jsx("th",{className:"text-left px-2 py-1",children:"Name"}),e.jsx("th",{className:"text-left px-2 py-1",children:"Email"}),e.jsx("th",{className:"text-left px-2 py-1",children:"Telefon"})]})}),e.jsxs("tbody",{children:[I.rows.slice(0,100).map(i=>e.jsxs("tr",{className:`border-t border-border/40 ${i.isDuplicate?"opacity-50":""}`,children:[e.jsx("td",{className:"px-2 py-1",children:i.isInvalid?e.jsxs("span",{className:"text-red-300 inline-flex items-center gap-1",children:[e.jsx(De,{className:"w-3 h-3"})," leer"]}):i.isDuplicate?e.jsxs("span",{className:"text-orange-300",children:["â Duplikat (",i.duplicateReason,")"]}):e.jsx("span",{className:"text-emerald-300",children:"â neu"})}),e.jsxs("td",{className:"px-2 py-1",children:[i.firstName," ",i.lastName]}),e.jsx("td",{className:"px-2 py-1 text-muted-foreground",children:i.email||"â"}),e.jsx("td",{className:"px-2 py-1 text-muted-foreground font-mono",children:i.phone||"â"})]},i.rowIndex)),I.rows.length>100&&e.jsx("tr",{children:e.jsxs("td",{colSpan:4,className:"px-2 py-1 text-center text-muted-foreground",children:["... und ",I.rows.length-100," weitere"]})})]})]})}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Beim Klick auf ",e.jsx("strong",{children:"Importieren"})," werden nur die ",e.jsxs("strong",{className:"text-emerald-300",children:[I.newCount," neuen"]})," Eintraege angelegt. Duplikate werden automatisch uebersprungen."]})]}),c.length>0&&!I&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-400",children:[e.jsx(Cs,{className:"h-4 w-4"}),c.length," Leads erkannt"]}),e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border border-border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left px-3 py-2 text-muted-foreground",children:"Telefon"}),e.jsx("th",{className:"text-left px-3 py-2 text-muted-foreground",children:"E-Mail"})]})}),e.jsxs("tbody",{children:[c.slice(0,25).map((i,F)=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsxs("td",{className:"px-3 py-2",children:[i.firstName," ",i.lastName]}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:i.phone||"â"}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:i.email||"â"})]},F)),c.length>25&&e.jsx("tr",{className:"border-t border-border",children:e.jsxs("td",{colSpan:3,className:"px-3 py-2 text-center text-muted-foreground",children:["... und ",c.length-25," weitere"]})})]})]})})]}),e.jsxs("label",{className:"flex items-start gap-2 text-xs cursor-pointer rounded-md border border-border bg-muted/30 px-3 py-2",children:[e.jsx("input",{type:"checkbox",checked:E,onChange:i=>D(i.target.checked),className:"h-3.5 w-3.5 mt-0.5"}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"WhatsApp-/E-Mail-Flows auslösen"})," â die für die gewählte Quelle aktiven ",e.jsx("code",{children:"new_lead"}),"-Flows feuern für jeden importierten Lead.",e.jsx("span",{className:"block text-muted-foreground
3/70",children:"Bei groÃen Alt-Importen abwählen, um keinen Massen-Versand auszulösen."})]})]})]}),e.jsxs("div",{className:"border-t border-border pt-3 shrink-0 flex gap-2 justify-between items-center flex-wrap gap-y-2",children:[e.jsx(y,{variant:"ghost",size:"sm",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 text-xs",onClick:Ne,disabled:V.isPending||!m,title:"Soft-deletet Leads die in den letzten 60 Min mit dieser Marke + Quelle importiert wurden (Termine/Vertraege werden geschuetzt)",children:V.isPending?"...":"â¶ Letzten Import (60 Min) rückgängig"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{variant:"outline",onClick:()=>{X(),l(!1)},children:"Abbrechen"}),e.jsx(y,{disabled:!U,onClick:()=>ce.mutate({csvText:n,brandId:Number(m),source:A,status:h,weeklyFlowId:K!=="none"&&K!=="empty"?Number(K):null,triggerFlows:E,note:x.trim()||null}),children:ce.isPending?"Importiere...":I?`${I.newCount} neue Leads importieren`:`${c.length} Leads importieren`})]})]})]})})}const ir=["sonstige","blacklisted"],Wt=[{key:"lead",label:"Neu",icon:Ls,color:"text-blue-400",bg:"bg-blue-500/10 border-blue-500/20"},{key:"contacted",label:"Kontaktiert",icon:be,color:"text-yellow-400",bg:"bg-yellow-500/10 border-yellow-500/20"},{key:"appointment",label:"Termin",icon:Gt,color:"text-purple-400",bg:"bg-purple-500/10 border-purple-500/20"},{key:"closed",label:"Abschluss",icon:As,color:"text-green-400",bg:"bg-green-500/10 border-green-500/20"},{key:"reactivation",label:"Reaktivierung",icon:mt,color:"text-orange-400",bg:"bg-orange-500/10 border-orange-500/20"},{key:"not_interested",label:"Kein Interesse",icon:qt,color:"text-rose-400",bg:"bg-rose-500/10 border-rose-500/20"},{key:"sonstige",label:"Aussortiert",icon:$s,color:"text-slate-400",bg:"bg-slate-500/10 border-slate-500/20"},{key:"blacklisted",label:"Schwarze Liste",icon:Jt,color:"text-red-400",bg:"bg-red-500/10 border-red-500/20"}];function Le(s){const l=new Date(s),f=l.getDate().toString().padStart(2,"0"),n=(l.getMonth()+1).toString().padStart(2,"0"),N=l.getHours().toString().padStart(2,"0"),c=l.getMinutes().toString().padStart(2,"0");return`${f}.${n}. ${N}:${c}`}function or(s){const l=Math.ceil((s-Date.now())/6e4);return l<=0?"":l<60?`${l} min`:`${Math.ceil(l/60)} h`}function dr(s){if(!s)return"";const l=s-Date.now();if(l<0){const n=Math.abs(Math.round(l/36e5));return n<24?`${n}h überfällig`:`${Math.round(n/24)}d überfällig`}const f=Math.round(l/(1e3*60*60));return f<24?`in ${f}h`:`in ${Math.round(f/24)}d`}function ts({lead:s,isDragging:l=!1}){const[,f]=Ge(),n=p.useUtils(),{canCall:N,startCall:c}=Qt(),$={lead:"Neu",contacted:"Kontaktiert",appointment:"Termin",closed:"Abschluss",reactivation:"Reaktivierung",blacklisted:"Schwarze Liste"},b=p.leads.trackContact.useMutation({onSuccess:L=>{n.leads.kanban.invalidate(),n.leads.list.invalidate();const Q=s.status,B=L?.status;if(B&&Q!==B){const I=$[B]??B,ne=B==="reactivation"?"3 Kontaktversuche erreicht":`Erster Kontaktversuch â automatisch in â${I}" verschoben`;d.info(`${s.firstName} ${s.lastName} â â${I}"`,{description:ne,duration:5e3})}else d.success(`Kontakt getrackt (${L?.contactCount??""}à insgesamt)`)}}),g=p.leadActivities.logReached.useMutation({onSuccess:()=>{n.leads.kanban.invalidate(),d.success("Als erreicht markiert")}}),m=p.leadActivities.logCall.useMutation({onSuccess:()=>{n.leads.kanban.invalidate(),d.success("Anruf (nicht erreicht) getrackt")}}),S=p.leads.setBlacklisted.useMutation({onSuccess:()=>{n.leads.kanban.invalidate(),d.success(s.blacklisted?"Von Schwarzer Liste entfernt":"Zur Schwarzen Liste hinzugefügt")}}),A=p.leads.delete.useMutation({onSuccess:()=>{n.leads.kanban.invalidate(),d.success("Lead gelöscht")},onError:L=>d.error(L.message)}),u=p.appointments.confirmNextAppointmentByLead.useMutation({onSuccess:L=>{n.leads.kanban.invalidate(),n.leads.list.invalidate(),d.success(L?.confirmedAt?"Termin telefonisch bestätigt â":"Bestätigung aufgehoben")},onError:L=>d.error(L?.message??"Fehler")}),h=s.status==="appointment",M=h&&s.nextAppointmentAt!==null&&s.nextAppointmentAt>Date.now(),x=h&&s.pendingFeedback&&!s.noSale,w=!h&&!!s.nextContactAt&&s.nextContactAt<Date.now(),E=h?"":dr(s.nextContactAt),D=!!(s.hotUntil&&s.hotUntil>Date.now()),K=D?or(s.hotUntil):"",re={ads:"#f97316",website:"#10b981",online:"#10b981",termin_web:"#10b981",vertrag_web:"#10b981",widget:"#10b981",checkout:"#10b981",popup:"#10b981",walk_in:"#14b8a6",referral:"#3b82f6",call_center:"#8b5cf6",promo:"#8b5cf6",flyer:"#8b5cf6",studio_interessenten:"#64748b",former_member:"#64748b",magicline_churn:"#6b7280"}[s.source]??"#3f3f46";return e.jsx(ps,{style:{borderLeftWidth:3,borderLeftColor:re},className:`border cursor-grab active:cursor-grabbing transition-all hover:shadow-md ${l?"opacity-50 rotate-2 shadow-xl":""} ${D?"border-red-500/60 bg-red-500/8 shadow-red-500/10 shadow-md":w?"border-red-500/40 bg-red-500/5":x?"border-yellow-500/40 bg-yellow-500/5":"border-border bg-card"}`,children:e.jsxs(bs,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsxs("button",{className:"text-sm font-semibold text-foreground hover:text-primary text-left leading-tight",onClick:L=>{L.stopPropagation(),f(`/leads/${s.id}`)},children:[s.firstName," ",s.lastName]}
3),(s.noShowCount??0)>=2&&e.jsxs(xe,{className:"text-xs shrink-0 px-1.5 py-0 bg-red-500/15 text-red-500 border border-red-500/40 font-semibold",title:`${s.noShowCount}à nicht erschienen â nur nach verbindlicher Zusage einen Termin geben, keinen offenen Slot blockieren.`,children:["â ï¸ ",s.noShowCount,"à No-Show"]}),D&&e.jsxs(xe,{className:"text-xs shrink-0 px-1.5 py-0 bg-red-500/20 text-red-400 border-red-500/40 animate-pulse",children:["ð¥ ",K]}),!D&&w&&e.jsxs(xe,{variant:"destructive",className:"text-xs shrink-0 px-1.5 py-0",children:[e.jsx(De,{className:"h-2.5 w-2.5 mr-0.5"}),"Ãberfällig"]}),!D&&x&&e.jsxs(xe,{className:"text-xs shrink-0 px-1.5 py-0 bg-yellow-500/20 text-yellow-400 border-yellow-500/30",children:[e.jsx(De,{className:"h-2.5 w-2.5 mr-0.5"}),"Feedback offen"]}),!D&&!x&&s.lastFeedbackOutcome&&(()=>{const L=s.lastFeedbackOutcome,B={no_show:{label:"No-Show",cls:"bg-red-500/20 text-red-500 border-red-500/30"},not_interested:{label:"Kein Interesse",cls:"bg-gray-500/20 text-gray-500 border-gray-500/30"},follow_up:{label:"Follow-up",cls:"bg-blue-500/20 text-blue-500 border-blue-500/30"},thinking:{label:"Ãberlegt",cls:"bg-purple-500/20 text-purple-500 border-purple-500/30"},closed:{label:"Vertrag",cls:"bg-emerald-500/20 text-emerald-600 border-emerald-500/30"}}[L];return!B||M&&L!=="closed"?null:e.jsx(xe,{className:`text-xs shrink-0 px-1.5 py-0 ${B.cls}`,children:B.label})})(),s.lastActivityType==="wa_inbound"&&e.jsxs(xe,{className:"text-xs shrink-0 px-1.5 py-0 bg-emerald-500/30 text-emerald-700 dark:text-emerald-300 border-emerald-500/60 font-bold ring-2 ring-emerald-400/70 ring-offset-1 ring-offset-card animate-pulse shadow-md shadow-emerald-500/40",title:s.lastActivityAt?`WhatsApp-Antwort: ${Le(s.lastActivityAt)} â sofort reagieren`:"WhatsApp-Antwort â sofort reagieren",children:[e.jsx(Yt,{className:"h-2.5 w-2.5 mr-0.5"}),"WA-Antwort"]}),s.lastActivityType==="missed_call"&&e.jsxs(xe,{className:"text-xs shrink-0 px-1.5 py-0 bg-red-500/25 text-red-600 dark:text-red-300 border-red-500/60 font-bold animate-pulse",title:s.lastActivityAt?`Rückruf verpasst: ${Le(s.lastActivityAt)} â schnell zurückrufen!`:"Rückruf verpasst â schnell zurückrufen!",children:["ðµ Rückruf ",s.lastActivityAt?Le(s.lastActivityAt).split(" ")[1]:""]}),s.noSale&&!M&&e.jsx(xe,{className:"text-xs shrink-0 px-1.5 py-0 bg-red-600/20 text-red-700 dark:text-red-400 border-red-600/40 font-semibold",title:"Walk-In ohne Vertrag (>2h) â walk_in_no_signup_2h Flow ausgeloest",children:"ð¸ No-Sale"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-1 min-w-0",children:[s.phone&&e.jsx("a",{href:`tel:${s.phone}`,onClick:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onTouchStart:L=>L.stopPropagation(),className:"text-xs text-muted-foreground truncate hover:text-primary transition-colors cursor-pointer",title:"Klick zum Anrufen",children:s.phone}),e.jsx(pr,{utmSource:s.utmSource}),!ss(s.utmSource)&&s.source&&e.jsxs("span",{className:`shrink-0 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium 4 ${s.source==="ads"?"bg-blue-500/15 text-blue-400":s.source==="call_center"?"bg-orange-500/15 text-orange-400":s.source==="referral"?"bg-green-500/15 text-green-400":s.source==="walk_in"?"bg-purple-500/15 text-purple-400":s.source==="online"?"bg-sky-500/15 text-sky-400":s.source==="checkout"?"bg-yellow-500/15 text-yellow-400":s.source==="popup"?"bg-pink-500/15 text-pink-400":"bg-muted text-muted-foreground"}`,children:[e.jsx(ut,{source:s.source,className:"w-3 h-3"}),he[s.source]??s.source]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[h?M?e.jsxs("span",{className:"flex items-center gap-1 text-purple-400 flex-wrap",children:[e.jsx(Gt,{className:"h-3 w-3"}),Le(s.nextAppointmentAt),(()=>{const L=s.nextAppointmentConfirmedAt!=null,Q=s.nextAppointmentAt-Date.now(),B=!L&&Q>0&&Q<=12*36e5,I=ne=>{ne.stopPropagation(),!u.isPending&&u.mutate({leadId:s.id,confirmed:!L})};return L?e.jsx("button",{onClick:I,disabled:u.isPending,className:"px-1 py-0 rounded text-[10px] bg-green-500/20 text-green-600 dark:text-green-400 border border-green-500/30 hover:bg-green-500/30 cursor-pointer",title:`Telefonisch bestätigt am ${Le(s.nextAppointmentConfirmedAt)} â klicken zum Aufheben`,children:"â bestätigt"}):B?e.jsx("button",{onClick:I,disabled:u.isPending,className:"px-1 py-0 rounded text-[10px] bg-red-500/20 text-red-500 border border-red-500/30 hover:bg-red-500/30 cursor-pointer",title:"Noch nicht bestätigt â Termin in < 12 h. Klicken = telefonisch bestätigen",children:"â bestätigen"}):e.jsx("button",{onClick:I,disabled:u.isPending,className:"px-1 py-0 rounded text-[10px] bg-muted text-muted-foreground border border-border hover:bg-green-500/15 hover:text-green-500 hover:border-green-500/30 cursor-pointer",title:"Klicken = telefonisch bestätigen (Haken)",children:"â bestätigen"})})()]}):x?e.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[e.jsx(dt,{className:"h-3 w-3"}),"Feedback ausstehend"]}):s.noSale?e.jsxs("span",{className:"flex items-center gap-1 text-red-500",children:[e.jsx(dt,{className:"h-3 w-3"}),"No-Sale (auto)"]}
4):e.jsx("span",{className:"text-muted-foreground/50",children:"Kein Termin"}):E?e.jsxs("span",{className:`flex items-center gap-1 ${w?"text-red-400":""}`,children:[e.jsx(dt,{className:"h-3 w-3"}),E]}):e.jsx("span",{className:"text-muted-foreground/50",children:"Kein Termin"}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(be,{className:"h-3 w-3"}),s.contactCount??0,"Ã"]})]}),e.jsxs("div",{className:"flex items-center gap-1 pt-1",children:[N&&s.phone&&!s.blacklisted&&e.jsxs("button",{type:"button",className:"flex-1 h-8 inline-flex items-center justify-center gap-1.5 rounded-md text-xs font-bold bg-green-600 text-white hover:bg-green-700",title:`${s.phone} über das CRM anrufen â Ergebnis wird automatisch protokolliert`,onClick:L=>{L.stopPropagation(),c({phone:s.phone,leadId:s.id,brandId:s.brandId,name:`${s.firstName??""} ${s.lastName??""}`.trim()})},children:[e.jsx(be,{className:"h-3 w-3"})," Anrufen"]}),!N&&s.phone&&!s.blacklisted&&e.jsxs("a",{href:`tel:${s.phone}`,onClick:L=>L.stopPropagation(),className:"flex-1 h-8 inline-flex items-center justify-center gap-1.5 rounded-md text-xs font-bold border border-green-500/40 text-green-500 hover:bg-green-500/10",title:`${s.phone} anrufen (Gerät) â Ergebnis danach im â¯-Menü tracken`,children:[e.jsx(be,{className:"h-3 w-3"})," Anrufen"]}),e.jsxs(fs,{children:[e.jsx(js,{asChild:!0,children:e.jsx(y,{size:"sm",variant:"outline",className:"h-8 px-2.5",onClick:L=>L.stopPropagation(),title:"Mehr Aktionen",children:e.jsx(Ms,{className:"h-3.5 w-3.5"})})}),e.jsxs(Ns,{align:"end",onClick:L=>L.stopPropagation(),children:[e.jsxs(Ze,{onClick:()=>{g.mutate({leadId:s.id}),b.mutate({id:s.id})},disabled:g.isPending||s.blacklisted,children:[e.jsx(xt,{className:"h-3.5 w-3.5 mr-2 text-green-500"})," Erreicht (manuell)"]}),e.jsxs(Ze,{onClick:()=>{m.mutate({leadId:s.id}),b.mutate({id:s.id})},disabled:m.isPending||s.blacklisted,children:[e.jsx(Xt,{className:"h-3.5 w-3.5 mr-2 text-red-400"})," Nicht erreicht (manuell)"]}),e.jsx(vs,{}),e.jsxs(Ze,{onClick:()=>S.mutate({id:s.id,blacklisted:!s.blacklisted}),disabled:S.isPending,children:[e.jsx(Jt,{className:"h-3.5 w-3.5 mr-2"})," ",s.blacklisted?"Von Schwarzer Liste entfernen":"Zur Schwarzen Liste"]}),e.jsxs(Ze,{className:"text-destructive focus:text-destructive",onClick:()=>{confirm(`Lead "${s.firstName} ${s.lastName}" wirklich löschen?`)&&A.mutate({id:s.id})},disabled:A.isPending,children:[e.jsx(Ce,{className:"h-3.5 w-3.5 mr-2"})," Löschen"]})]})]}),e.jsx(y,{size:"sm",variant:"ghost",className:"h-8 text-xs px-2",onClick:L=>{L.stopPropagation(),f(`/leads/${s.id}`)},children:e.jsx(Es,{className:"h-3 w-3"})})]})]})})}function cr({lead:s}){const{attributes:l,listeners:f,setNodeRef:n,isDragging:N}=rr({id:`lead-${s.id}`,data:{lead:s}});return e.jsx("div",{ref:n,...f,...l,children:e.jsx(ts,{lead:s,isDragging:N})})}function ur({col:s,leads:l}){const{setNodeRef:f,isOver:n}=sr({id:s.key}),N=s.icon,c=80,[$,b]=o.useState(c),g=l.slice(0,$),m=Math.max(0,l.length-g.length);return e.jsxs("div",{className:"flex flex-col min-w-[240px] max-w-[280px] flex-shrink-0",children:[e.jsxs("div",{className:`flex items-center justify-between px-3 py-2 rounded-t-lg border ${s.bg} mb-1`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(N,{className:`h-4 w-4 ${s.color}`}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:s.label})]}),e.jsx(xe,{variant:"secondary",className:"text-xs",children:l.length})]}),e.jsx("div",{ref:f,className:`flex-1 min-h-[400px] rounded-b-lg border border-t-0 p-2 space-y-2 transition-colors overflow-y-auto max-h-[calc(100vh-280px)] ${n?"bg-primary/5 border-primary/40":"bg-muted/20 border-border"}`,children:l.length===0?e.jsx("div",{className:"flex items-center justify-center h-20 text-xs text-muted-foreground/50",children:"Keine Leads"}):e.jsxs(e.Fragment,{children:[g.map(S=>e.jsx(cr,{lead:S},S.id)),m>0&&e.jsxs("button",{type:"button",onClick:()=>b(S=>S+c*3),className:"w-full py-2 rounded-lg border border-dashed border-border text-xs font-semibold text-muted-foreground hover:text-foreground hover:border-primary/40",children:["â¼ ",Math.min(m,c*3)," weitere anzeigen (",g.length," von ",l.length,")"]})]})})]})}function mr({brandId:s,search:l,source:f,noShowOnly:n,noSaleOnly:N,engagementTier:c,hotOnly:$,dateFrom:b,dateTo:g,apptFilter:m,attemptsFilter:S,missedOnly:A}){const{canCall:u,startCall:h}
4=Qt(),[M,x]=o.useState(null),[w,E]=o.useState(null),[D,K]=o.useState(()=>{try{return localStorage.getItem("kanban_show_archived")==="1"}catch{return!1}}),fe=()=>K(j=>{const T=!j;try{localStorage.setItem("kanban_show_archived",T?"1":"0")}catch{}return T}),re=D?Wt:Wt.filter(j=>!ir.includes(j.key)),L=p.useUtils(),{data:Q,isLoading:B}=p.leads.kanban.useQuery({brandId:s,search:l||void 0,source:f&&f!=="all"?f:void 0,noShowOnly:n||void 0,noSaleOnly:N||void 0,engagementTier:c&&c!=="all"?c:void 0,hotOnly:$||void 0,dateFrom:b||void 0,dateTo:g||void 0,apptFilter:m&&m!=="all"?m:void 0,includeArchived:D||void 0},{staleTime:l||f||n||N||c||$||b||g||D||m&&m!=="all"?0:6e4}),I=p.leads.moveKanban.useMutation({onSuccess:()=>L.leads.kanban.invalidate(),onError:()=>d.error("Verschieben fehlgeschlagen")}),ne=p.leads.setBlacklisted.useMutation({onSuccess:()=>L.leads.kanban.invalidate()});p.leads.bulkMoveNoSalesToReactivation.useMutation({onSuccess:j=>{L.leads.kanban.invalidate();const T=j.byBucket;d.success(`${j.moved} No-Sales in Reaktivierung verschoben`,{description:`Walk-In: ${T.walkIn} · Trial: ${T.trial} · Magicline-Brand: ${T.magiclineBrand}`,duration:8e3})},onError:j=>d.error(j.message)});const de=Js(Pt(tr,{activationConstraint:{distance:8}}),Pt(er,{activationConstraint:{delay:600,tolerance:5}})),ce=Q?.columns,X=j=>{switch(S){case"0":return j===0;case"1-2":return j>=1&&j<=2;case"3-5":return j>=3&&j<=5;case"5plus":return j>5;default:return!0}},W=ce&&(S&&S!=="all"||A)?Object.fromEntries(Object.entries(ce).map(([j,T])=>[j,T.filter(z=>X(z.contactCount??0)&&(!A||z.lastActivityType==="missed_call"))])):ce,U=W&&{...W,sonstige:[...W.referral??[],...W.lost??[]]},V=U?Object.values(U).flat().filter(j=>j.lastActivityType==="missed_call"&&!j.blacklisted):[],Ne=new Set(V.map(j=>j.id)),i=U?[...U.lead??[],...U.contacted??[]].filter(j=>(j.contactCount??0)<=1&&!Ne.has(j.id)&&!j.blacklisted).slice(0,8):[],F=[...V,...i].slice(0,8),R=o.useRef(F);R.current=F,o.useEffect(()=>{const j=T=>{const z=Number(T?.detail?.leadId),_=R.current.find(pe=>pe.id!==z&&pe.phone&&!pe.blacklisted);if(!_)return;const ee=`${_.firstName??""} ${_.lastName??""}`.trim()||_.phone;d(`Nächster Anruf: ${ee}`,{duration:12e3,action:{label:"ð Anrufen",onClick:()=>h({phone:_.phone,leadId:_.id,brandId:_.brandId,name:ee})}})};return window.addEventListener("mm:call-ended",j),()=>window.removeEventListener("mm:call-ended",j)},[h]);function P(){if(!M||!U)return;const j=parseInt(M.replace("lead-",""));return ae(j)}function ae(j){if(U)for(const T of Object.values(U)){const z=T.find(_=>_.id===j);if(z)return z}}function Ae(j){x(j.active.id)}function Je(j){x(null);const{active:T,over:z}=j;if(!z)return;const _=parseInt(T.id.replace("lead-","")),ee=z.id,pe=ae(_);if(pe?.status===ee||ee==="blacklisted"&&pe?.blacklisted)return;if(ee==="blacklisted"||ee==="reactivation"||ee==="not_interested"){E({leadId:_,target:ee});return}P()?.blacklisted&&ne.mutate({id:_,blacklisted:!1});const $e={lead:"lead",contacted:"contacted",appointment:"appointment",closed:"closed",reactivation:"reactivation",not_interested:"not_interested",referral:"referral",lost:"lost",sonstige:"lost",blacklisted:"lead"};I.mutate({id:_,status:$e[ee]})}function Re(j){if(!w)return;const{leadId:T,target:z}=w;z==="blacklisted"?ne.mutate({id:T,blacklisted:!0,statusReason:j}):I.mutate({id:T,status:z,statusReason:j}),E(null)}const O=w?ae(w.leadId):null;if(B)return e.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4",children:re.map(j=>e.jsx("div",{className:"min-w-[240px] h-96 bg-muted/30 rounded-lg animate-pulse"},j.key))});const ge=P();return U&&Object.values(U).reduce((j,T)=>j+T.filter(z=>z.noSale).length,0),e.jsxs(Ys,{sensors:de,onDragStart:Ae,onDragEnd:Je,children:[!1,(V.length>0||i.length>0)&&e.jsx(xr,{missed:V,fresh:i,canCall:u,startCall:h}),e.jsxs("div",{className:"flex items-center justify-end gap-2 mb-2",children:[e.jsx(gr,{}),e.jsxs(y,{variant:"outline",size:"sm",className:"h-8 text-xs gap-1.5",onClick:fe,children:[D?e.jsx(Is,{className:"w-3.5 h-3.5"}):e.jsx(_s,{className:"w-3.5 h-3.5"}),D?"Schwarze Liste ausblenden":"Schwarze Liste einblenden"]})]}),e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-4",children:re.map(j=>e.jsx(ur,{col:j,leads:U?.[j.key]??[]},j.key))}),e.jsx(Xs,{children:ge?e.jsx(ts,{lead:ge,isDragging:!0}):null}),e.jsx(Gs,{open:w!==null,targetStatus:w?.target??null,leadName:O?`${O.firstName??""} ${O.lastName??""}`.trim():void 0,onConfirm:Re,onCancel:()=>E(null)})]})}function xr({missed:s,fresh:l,canCall:f,startCall:n}){const[N,c]=o.useState(()=>
4{try{return localStorage.getItem("anrufzentrale_collapsed")==="1"}catch{return!1}}),$=()=>c(u=>{const h=!u;try{localStorage.setItem("anrufzentrale_collapsed",h?"1":"0")}catch{}return h}),g=(p.telephony?.myDayStats?.useQuery?.(void 0,{staleTime:6e4,retry:!1})??{data:null}).data,m=g&&g.calls>0?Math.round(g.reached/g.calls*100):null,S=u=>{if(!u)return"";const h=Math.max(1,Math.round((Date.now()-u)/6e4));return h<60?`wartet ${h} Min.`:`wartet ${Math.floor(h/60)}:${String(h%60).padStart(2,"0")} Std.`},A=(u,h)=>{const M=`${u.firstName??""} ${u.lastName??""}`.trim()||u.phone||"â";return u.phone?f?e.jsxs("button",{type:"button",onClick:x=>{x.stopPropagation(),n({phone:u.phone,leadId:u.id,brandId:u.brandId,name:M})},className:`ml-auto shrink-0 inline-flex items-center gap-1 text-xs font-bold text-white rounded-md px-2.5 py-1.5 ${h}`,children:[e.jsx(be,{className:"w-3 h-3"})," Anrufen"]}):e.jsxs("a",{href:`tel:${u.phone}`,onClick:x=>x.stopPropagation(),className:`ml-auto shrink-0 inline-flex items-center gap-1 text-xs font-bold text-white rounded-md px-2.5 py-1.5 ${h}`,children:[e.jsx(be,{className:"w-3 h-3"})," Anrufen"]}):null};return e.jsxs("div",{className:"mb-3 rounded-xl border border-border bg-card/60",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap px-3 py-2 cursor-pointer select-none",onClick:$,title:N?"Ausklappen":"Einklappen",children:[e.jsx(xt,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-sm font-bold text-foreground",children:"Anruf-Zentrale"}),s.length>0&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-bold bg-red-500/15 text-red-500 border border-red-500/40 animate-pulse",children:["ðµ ",s.length," Rückruf",s.length===1?"":"e"]}),e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-bold bg-amber-500/15 text-amber-500 border border-amber-500/30",children:["ð¥ ",l.length," in der Warteschlange"]}),g&&(g.calls>0||g.reached>0)&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-bold bg-green-500/10 text-green-600 dark:text-green-400 border border-green-500/30",title:"DEINE Anrufe heute (seit 0 Uhr): automatisch aus der Telefonie + manuell getrackte. 'Erreicht' = angenommen und ⥠15 Sek. gesprochen.",children:["Heute: ",g.calls," Anrufe · ",g.reached," erreicht",m!=null?` (${m} %)`:""]}),e.jsx("span",{className:"ml-auto text-xs font-semibold text-muted-foreground",children:N?"â¼ ausklappen":"â² einklappen"})]}),!N&&e.jsxs("div",{className:"flex flex-col lg:flex-row gap-3 px-3 pb-3",children:[s.length>0&&e.jsxs("div",{className:"lg:w-[42%] rounded-lg border border-red-500/40 bg-red-500/5 p-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-xs font-bold text-red-500 uppercase tracking-wide",children:"ðµ Rückrufe â zuerst abarbeiten"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"älteste zuerst"})]}),e.jsx("div",{className:"space-y-1.5 max-h-44 overflow-y-auto pr-1",children:[...s].sort((u,h)=>(u.lastActivityAt??0)-(h.lastActivityAt??0)).map(u=>{const h=`${u.firstName??""} ${u.lastName??""}`.trim()||u.phone||"â";return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-red-500/20 bg-card px-2.5 py-1.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-foreground truncate",children:h}),e.jsx("div",{className:"text-[11px] text-red-500 font-medium truncate",children:u.lastActivityAt?`${Le(u.lastActivityAt)} · ${S(u.lastActivityAt)}`:"Rückruf verpasst"})]}),A(u,"bg-red-600 hover:bg-red-700")]},u.id)})})]}),l.length>0&&e.jsxs("div",{className:"flex-1 rounded-lg border border-border bg-background/40 p-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-xs font-bold text-amber-500 uppercase tracking-wide",children:"ð¥ Warteschlange â frisch & heià zuerst"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Reihenfolge: Quelle â Eingang"})]}),e.jsx("div",{className:"space-y-1.5 max-h-44 overflow-y-auto pr-1",children:l.map((u,h)=>{const M=`${u.firstName??""} ${u.lastName??""}`.trim()||u.phone||"â";return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border bg-card px-2.5 py-1.5",children:[e.jsx("span",{className:"shrink-0 w-5 text-center text-sm font-black text-amber-500",children:h+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-foreground truncate",children:M}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[he[u.source]??u.source," · ð ",u.contactCount??0,"Ã"]})]}),A(u,"bg-green-600 hover:bg-green-700")]},u.id)})})]})]})]})}const hr=[{value:"ads",label:"Werbeanzeigen"},{value:"website",label:"Webseite"},{value:"online",label:"Online"},{value:"termin_web",label:"Online-Termin"},{value:"vertrag_web",label:"Online-Vertrag"},{value:"widget",label:"Widget"},{value:"checkout",label:"Checkout"},{value:"popup",label:"Popup"},{value:"walk_in",label:"Walk-in"},{value:"referral",label:"Empfehlung"},{value:"call_center",label:"Call-Center"},{value:"promo",label:"Promo"},{value:"flyer",label:"Flyer"},{value:"gewinnspiel",label:"Gewinnspiel"},{value:"studio_interessenten",label:"Studio-Interessenten"},{value:"former_member",label:"Ehemalige Mitglieder"},{value:"magicline_churn",label:"Magicline-Abgänger"}];function gr(){const{user:s}=Ut(),[l,f]=o.useState(!1),n=p.useUtils(),N=p.leads.getProtectedSources.useQuery(void 0,{enabled:l,staleTime:3e4}),c=p.leads.setProtectedSources.useMutation({onSuccess:()=>{d.success("Schutz-Quellen gespeichert"),n.leads.kanban.invalidate(),N.refetch()},onError:S=>d.error(S.message)}),[$,b]=o.useState(null);if(o.useEffect(()=>{N.data?.sources&&$===null&&b(N.data.sources)},[N.data,$]),s?.role!=="admin")return null;const g=$??N.data?.sources??[],m=S=>b(g.includes(S)?g.filter(A=>A!==S):[...g,S]);return e.jsxs(e.Fragment,{children:[e.jsx(y,{variant:"outline",size:"sm",className:"h-8 text-xs gap-1.5",onClick:()=>f(!0),title:"Welche Quellen dürfen nie aus dem Board fallen?",children:"â Schutz-Quellen"}),l&&e.jsx("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center bg-black/60",onClick:()=>f(!1),children:e.jsxs("div",{className:"w-[440px] max-w-[92vw] max-h-[80vh] overflow-y-auto rounded-xl border border-border bg-card p-4 space-y-3",onClick:S=>S.stopPropagation(),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-foreground",children:"ð¡ Schutz-Quellen â nie ausblenden"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Jede Spalte zeigt max. 800 Karten. Geschützte Quellen belegen die Plätze IMMER zuerst â E-Mail-Marketing-Quellen füllen nur den Rest und dürfen rausrutschen."})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:hr.map(S=>{const A=g.includes(S.value);return e.jsxs("button",{onClick:()=>
4m(S.value),className:`px-2.5 py-1 rounded-md text-xs font-medium border transition-colors ${A?"bg-green-500/15 text-green-600 border-green-500/40":"bg-muted/40 text-muted-foreground border-border hover:bg-muted/60"}`,children:[A?"ð¡ ":"",S.label]},S.value)})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>f(!1),children:"Abbrechen"}),e.jsx(y,{size:"sm",disabled:c.isPending,onClick:()=>c.mutate({sources:g}),children:c.isPending?"Speichertâ¦":"Speichern"})]})]})})]})}function ss(s){const l=String(s||"").toLowerCase().trim();return l?/tiktok|tik_tok|^tt$|[^a-z]tt[^a-z]/.test(l)?"tiktok":/facebook|fb|meta/.test(l)?"facebook":/instagram|insta|(^|[^a-z])ig([^a-z]|$)/.test(l)?"instagram":/google|gads|adwords|youtube|yt/.test(l)?"google":null:null}function pr({utmSource:s}){const l=ss(s);if(!l)return null;const n={tiktok:{label:"TikTok",style:{background:"#010101",color:"#fff"},glyph:"âª"},facebook:{label:"Facebook",style:{background:"#1877F2",color:"#fff"},glyph:"f"},instagram:{label:"Instagram",style:{background:"linear-gradient(45deg,#feda75,#d62976,#4f5bd5)",color:"#fff"},glyph:"â"},google:{label:"Google",style:{background:"#fff",color:"#3c4043",border:"1px solid #dadce0"},glyph:"G"}}[l];return e.jsxs("span",{className:"shrink-0 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-semibold",style:n.style,title:`Anzeige: ${n.label}`,children:[e.jsx("span",{style:{fontWeight:900},children:n.glyph}),n.label]})}const br={lead_created:{icon:Rs,label:"Neuer Lead",color:"text-blue-400"},email_sent:{icon:qe,label:"E-Mail gesendet",color:"text-violet-400"},wa_sent:{icon:Fs,label:"WA gesendet",color:"text-green-400"},wa_failed:{icon:De,label:"WA gescheitert",color:"text-red-400"},wa_inbound:{icon:Ds,label:"Antwort eingegangen",color:"text-orange-400"},contract_signed:{icon:Ts,label:"Vertrag",color:"text-yellow-400"}};function fr(s){const l=Date.now()-s;return l<6e4?"gerade":l<36e5?`vor ${Math.floor(l/6e4)}m`:l<864e5?`vor ${Math.floor(l/36e5)}h`:`vor ${Math.floor(l/864e5)}d`}function jr({brandId:s,leadId:l,defaultDays:f=7}){const[,n]=Ge(),[N,c]=o.useState(f),[$,b]=o.useState(()=>{try{return localStorage.getItem("activityFilter")??"all"}catch{return"all"}}),g=w=>{b(w);try{localStorage.setItem("activityFilter",w)}catch{}},m=$==="all"?void 0:[$],{data:S,isLoading:A,refetch:u,isFetching:h}=p.whatsapp.activityFeed.useQuery({brandId:s,days:N,eventTypes:m,leadId:l},{refetchInterval:3e4}),M=S?.counts??{},x=S?.events??[];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(ct,{className:"h-4 w-4 text-muted-foreground"}),l?"Lead-Verlauf":"Aktivitäts-Verlauf",!A&&x.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",x.length," Events)"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{value:String(N),onValueChange:w=>c(Number(w)),children:[e.jsx(q,{className:"h-8 w-32 text-xs",children:e.jsx(J,{})}),e.jsxs(Y,{children:[e.jsx(k,{value:"1",children:"letzte 24h"}),e.jsx(k,{value:"7",children:"7 Tage"}),e.jsx(k,{value:"30",children:"30 Tage"}),e.jsx(k,{value:"90",children:"90 Tage"})]})]}),e.jsx(y,{size:"icon",variant:"ghost",onClick:()=>u(),className:"h-8 w-8",disabled:h,children:e.jsx(mt,{className:`h-3.5 w-3.5 ${h?"animate-spin":""}`})})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:[{key:"all",label:"Alle"},{key:"lead_created",label:"Leads"},{key:"email_sent",label:"E-Mails"},{key:"wa_sent",label:"WA gesendet"},{key:"wa_failed",label:"Gescheitert"},{key:"wa_inbound",label:"Antworten"},{key:"contract_signed",label:"Verträge"}].map(w=>{const E=$===w.key,D=w.key==="all"?x.length:M[w.key]??0;return e.jsxs("button",{onClick:()=>g(w.key),className:`px-2.5 py-1 rounded-md text-xs border transition-colors ${E?"bg-foreground
4/10 border-foreground/30 text-foreground font-medium":"border-border bg-muted/20 text-muted-foreground hover:bg-muted/40"}`,children:[w.label,$!=="all"&&w.key!=="all"&&E&&` (${D})`]},w.key)})}),A?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm gap-2",children:[e.jsx(zs,{className:"h-4 w-4 animate-spin"})," Lade Verlauf..."]}):x.length===0?e.jsx("div",{className:"text-center py-12 text-sm text-muted-foreground",children:"Keine Ereignisse im gewählten Zeitraum."}):e.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:e.jsx("ul",{className:"divide-y divide-border",children:x.map((w,E)=>{const D=br[w.type]??{icon:ct,label:w.type,color:"text-muted-foreground"},K=D.icon;return e.jsxs("li",{className:"flex gap-3 px-3 py-2.5 hover:bg-muted/10",children:[e.jsx("div",{className:`shrink-0 w-7 h-7 rounded-full flex items-center justify-center ${D.color} bg-muted/30`,children:e.jsx(K,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:`font-medium ${D.color}`,children:w.title}),w.leadName&&e.jsx("button",{className:"ml-2 text-foreground hover:underline",onClick:()=>w.leadId&&n(`/leads/${w.leadId}`),children:w.leadName}),!w.leadName&&w.phone&&e.jsx("span",{className:"ml-2 text-muted-foreground",children:w.phone})]}),e.jsxs("span",{className:"text-[11px] text-muted-foreground shrink-0",children:[fr(w.ts)," · ",new Date(w.ts).toLocaleString("de-DE",{dateStyle:"short",timeStyle:"short"})]})]}),w.detail&&e.jsx("p",{className:`text-xs mt-0.5 break-words ${w.type==="wa_failed"?"text-red-400 font-mono":"text-muted-foreground"}`,children:w.detail})]})]},E)})})}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Live-Refresh alle 30s. Klick auf Lead-Namen springt direkt zum Lead."})]})}function Nr({brandId:s,hotOnly:l,onToggleHotOnly:f}){const{data:n}=p.leadActivities.liveSignals.useQuery({brandId:s},{staleTime:1e4,refetchInterval:15e3});return!n||(n.writingNow??0)+(n.openedRecent??0)+(n.clickedRecent??0)+(n.noShowRecovery??0)===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3",children:[n.writingNow>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold bg-red-500/15 text-red-300 border border-red-500/30 animate-pulse",children:["ð¥ ",n.writingNow," ",n.writingNow===1?"Lead schreibt":"Leads schreiben"," gerade"]}),n.clickedRecent>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-cyan-500/15 text-cyan-300 border border-cyan-500/30",children:["ð ",n.clickedRecent," Link-Klick",n.clickedRecent===1?"":"s"," (60 Min)"]}),n.openedRecent>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-blue-500/15 text-blue-300 border border-blue-500/30",children:["ðï¸ ",n.openedRecent," Mail-Ãffnung",n.openedRecent===1?"":"en"," (30 Min)"]}),n.noShowRecovery>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-rose-500/15 text-rose-300 border border-rose-500/40",children:["â ",n.noShowRecovery," No-Show ohne Folgetermin"]}),f&&n.hotLeads>0&&!l&&e.jsxs("button",{onClick:f,className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-amber-500/15 text-amber-300 border border-amber-500/30 hover:bg-amber-500/25 transition-colors",children:["ð¯ ",n.hotLeads," heiÃe Leads â Filter aktivieren"]})]})}const vr={wa:"ð¬",email:"ð§",newsletter:"ð¨",appointment:"ð
",contract:"â
",system:"ð"};function wr({leadId:s,onClose:l}){const[,f]=Ge(),{data:n,isLoading:N}=p.leadActivities.activityStream.useQuery({leadId:s??0,limit:30},{enabled:!!s,staleTime:1e4,refetchInterval:2e4}),{data:c}=p.leads.byId.useQuery({id:s??0},{enabled:!!s,staleTime:3e4});if(!s)return null;const $=n?.events??[],b=g=>{const m=Date.now()-g;return m<6e4?"jetzt":m<36e5?`vor ${Math.floor(m/6e4)}m`:m<864e5?`vor ${Math.floor(m/36e5)}
4h`:new Date(g).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})};return e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:l,className:"fixed inset-0 z-40 bg-black/50 backdrop-blur-sm"}),e.jsxs("div",{className:"fixed top-0 right-0 z-50 h-full w-full sm:max-w-md bg-card border-l border-border shadow-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Lead-Quick-View"}),e.jsx("div",{className:"text-base font-bold text-foreground truncate",children:c?`${c.firstName??""} ${c.lastName??""}`.trim():"Lade..."}),c?.phone&&e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-0.5",children:[e.jsx(be,{className:"w-3 h-3"})," ",c.phone]}),c?.email&&e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(qe,{className:"w-3 h-3"})," ",c.email]})]}),e.jsx(y,{size:"icon",variant:"ghost",onClick:l,className:"shrink-0",children:e.jsx(Ps,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"flex gap-2 p-3 border-b border-border bg-muted/20",children:[e.jsxs(y,{size:"sm",variant:"default",className:"flex-1",onClick:()=>f(`/leads/${s}`),children:[e.jsx(es,{className:"w-3.5 h-3.5 mr-1.5"})," Lead öffnen"]}),c?.phone&&e.jsxs("a",{href:`https://wa.me/${String(c.phone).replace(/\D/g,"")}`,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium bg-green-500/15 text-green-400 border border-green-500/30 hover:bg-green-500/25 transition-colors",children:[e.jsx(Yt,{className:"w-3.5 h-3.5"})," WhatsApp"]}),c?.phone&&e.jsxs("a",{href:`tel:${c.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium bg-blue-500/15 text-blue-400 border border-blue-500/30 hover:bg-blue-500/25 transition-colors",children:[e.jsx(be,{className:"w-3.5 h-3.5"})," Anrufen"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:[N&&e.jsx("div",{className:"text-center text-xs text-muted-foreground py-6",children:"Lade Aktivitäten..."}),!N&&$.length===0&&e.jsx("div",{className:"text-center text-xs text-muted-foreground py-6",children:"Keine Aktivitäten."}),$.map((g,m)=>e.jsxs("div",{className:"flex gap-2 py-1.5 border-b border-border/30 last:border-0",children:[e.jsx("div",{className:"text-base shrink-0 leading-none mt-0.5",children:vr[g.channel]??"â¢"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs font-semibold text-foreground truncate",children:g.title}),e.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:b(g.ts)})]}),g.body&&e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:g.body})]})]},m))]}),e.jsx("div",{className:"p-3 border-t border-border bg-muted/10",children:e.jsxs(y,{size:"sm",variant:"outline",className:"w-full",onClick:()=>f(`/leads/${s}`),children:["Im Lead-Detail antworten ",e.jsx(Os,{className:"w-3.5 h-3.5 ml-1.5"})]})})]})]})}const Kt={lead:"status-lead",contacted:"status-contacted",appointment:"status-appointment",closed:"status-closed",referral:"status-referral",lost:"status-lost",blacklisted:"bg-gray-800 text-gray-400",not_interested:"bg-gray-700 text-gray-400"},yr=Object.fromEntries(Object.entries(Te).filter(([s])=>!Ht.includes(s))),kr=Object.fromEntries(Object.entries(Te).filter(([s])=>Ht.includes(s)));function Rr(){const[,s]=Ge(),{user:l}=Ut(),f=l?.role==="admin"||l?.role==="manager",[n,N]=o.useState(()=>{try{const t=localStorage.getItem("leads_view_mode");if(t==="list"||t==="kanban"||t==="duplicates"||t==="activity"||t==="eingang")return t}catch{}return"list"}),c=t=>{N(t);try{localStorage.setItem("leads_view_mode",t)}catch{}};o.useEffect(()=>{const t=sessionStorage.getItem("leads_scroll_y");t&&(requestAnimationFrame(()=>window.scrollTo(0,parseInt(t))),sessionStorage.removeItem("leads_scroll_y"))},[]);const $=t=>{sessionStorage.setItem("leads_scroll_y",String(window.scrollY)),s(`/leads/${t}`)},[b,g]=o.useState(""),[m,S]=o.useState(""),[A,u]=o.useState(()=>{try{return localStorage.getItem("leads_filter_status")??"active"}catch{return"active"}}
4);o.useEffect(()=>{const t=setTimeout(()=>{S(b),P(0)},400);return()=>clearTimeout(t)},[b]);const[h,M]=o.useState(()=>{try{return localStorage.getItem("leads_filter_source")??"all"}catch{return"all"}}),[x,w]=o.useState(()=>{try{return localStorage.getItem("leads_filter_brand")??"all"}catch{return"all"}}),[E,D]=o.useState(()=>{try{return localStorage.getItem("leads_filter_tier")??"all"}catch{return"all"}}),[K,fe]=o.useState(()=>{try{return localStorage.getItem("leads_filter_appt")??"all"}catch{return"all"}});o.useEffect(()=>{try{localStorage.setItem("leads_filter_appt",K)}catch{}},[K]);const[re,L]=o.useState(()=>{try{return localStorage.getItem("leads_filter_attempts")||"all"}catch{return"all"}});o.useEffect(()=>{try{localStorage.setItem("leads_filter_attempts",re)}catch{}},[re]);const[Q,B]=o.useState(()=>{try{return localStorage.getItem("leads_filter_hot")==="1"}catch{return!1}});o.useEffect(()=>{try{localStorage.setItem("leads_filter_hot",Q?"1":"0")}catch{}},[Q]);const[I,ne]=o.useState(()=>{try{return localStorage.getItem("leads_filter_nosale")==="1"}catch{return!1}});o.useEffect(()=>{try{localStorage.setItem("leads_filter_nosale",I?"1":"0")}catch{}},[I]);const[de,ce]=o.useState(!1),[X,Fe]=o.useState(()=>{try{if(typeof window<"u"&&new URLSearchParams(window.location.search).get("noShow")==="1")return!0}catch{}try{return localStorage.getItem("leads_filter_noshow")==="1"}catch{return!1}});o.useEffect(()=>{try{localStorage.setItem("leads_filter_noshow",X?"1":"0")}catch{}},[X]);const[W,U]=o.useState(()=>{try{return localStorage.getItem("leads_filter_date_from")??""}catch{return""}}),[V,Ne]=o.useState(()=>{try{return localStorage.getItem("leads_filter_date_to")??""}catch{return""}});o.useEffect(()=>{try{localStorage.setItem("leads_filter_date_from",W)}catch{}},[W]),o.useEffect(()=>{try{localStorage.setItem("leads_filter_date_to",V)}catch{}},[V]);const[i,F]=o.useState(null);o.useEffect(()=>{try{localStorage.setItem("leads_filter_status",A)}catch{}},[A]),o.useEffect(()=>{try{localStorage.setItem("leads_filter_source",h)}catch{}},[h]),o.useEffect(()=>{try{localStorage.setItem("leads_filter_brand",x)}catch{}},[x]),o.useEffect(()=>{try{localStorage.setItem("leads_filter_tier",E)}catch{}},[E]);const[R,P]=o.useState(0),[ae,Ae]=o.useState(!1),[Je,Re]=o.useState(!1),[O,ge]=o.useState(new Set),[j,T]=o.useState(!1),z=50,{data:_,isLoading:ee,isFetching:pe,isError:Pe,error:$e,refetch:H}=p.leads.list.useQuery({search:m||void 0,status:n==="eingang"||A==="all"?void 0:A,source:h==="all"?void 0:h,brandId:x==="all"?void 0:Number(x),engagementTier:E==="all"?void 0:E,noShowOnly:X||void 0,dateFrom:W||void 0,dateTo:V||void 0,sortBy:n==="eingang"?"created":void 0,limit:z,offset:R},{placeholderData:m?void 0:t=>t,staleTime:m?0:1e4,refetchOnMount:!0,refetchOnWindowFocus:!0,refetchInterval:15e3}),Oe=p.useUtils(),{data:ht,refetch:gt}=p.leads.duplicates.useQuery({limit:200},{enabled:n==="duplicates"}),pt=p.leads.reactivateFromDuplicate.useMutation({onSuccess:t=>{d.success(t?.info??"Lead reaktiviert + Flow gestartet"),gt(),H()},onError:t=>d.error(t.message)}),bt=p.leads.deleteDuplicate.useMutation({onSuccess:()=>{d.success("Eintrag gelöscht"),gt()},onError:t=>d.error(t.message)}),{data:Ve,refetch:rs}=p.leads.phoneDuplicateGroups.useQuery({},{enabled:n==="duplicates"}),ft=p.leads.merge.useMutation({onSuccess:t=>{d.success(`Zusammengeführt (${t?.merged??0} Dublette(n))`),rs(),H()},onError:t=>d.error(t.message)}),Ye=p.leads.reengageRecentDuplicates.useMutation({onSuccess:t=>{d.success(`${t?.reengaged??0} Wiederanmeldung(en) wieder bei âNeu" sichtbar (${t?.skipped??0} übersprungen: aktive Mitglieder/Termine).`,{duration:9e3}),H()},onError:t=>d.error(t?.message??"Fehler")}),[jt,ns]=o.useState(!1),Ie=o.useMemo(()=>{const t=Ve??[];let a=0,r=0,v=0,te=0;for(const se of t){const Z=Number(se.count??se.leads?.length??0);te+=Math.max(0,Z-1),Z===2?a++:Z===3?r++:Z>=4&&v++}return{people:t.length,two:a,three:r,four:v,extraLeads:te}},[Ve]),{data:je}=p.brands.list.useQuery(),[Nt,vt]=o.useState(!1),as=async()=>{vt(!0);try{const t={};x!=="all"&&(t.brandId=Number(x)),A!=="all"&&(t.status=A),h!=="all"&&(t.source=h),W&&(t.from=W),V&&(t.to=V);const a=await Oe.leads.exportAll.fetch(t),r=x==="all"?"Alle-Marken":je?.find(C=>C.id===Number(x))?.studioName??je?.find(C=>C.id===Number(x))?.name??`Brand-${x}`;if(!a.length){d.info(`Keine Leads für "${r}" in der aktuellen Auswahl gefunden.`);return}const v=["Lead-ID","Erstellt","Vorname","Nachname","E-Mail","Telefon","Status","Quelle","WhatsApp-Status","Engagement","StraÃe","PLZ","Stadt","Vertrag unterschrieben","Vertragswert","Zuletzt kontaktiert","Nächster Kontakt","Blacklist","E-Mail-Opt-In","Referral","Referral-Werber","UTM-Kampagne","Zugewiesen an","Marke","Studio","Notizen"],te=C=>{if(C==null)return"";const ie=String(C);return/[",\n]/.test(ie)?`"${ie.replace(/"/g,'""')}"`:ie},se=C=>
4C?new Date(Number(C)).toLocaleString("de-DE"):"",Z=[v.join(",")];for(const C of a)Z.push([C.id,C.createdAt?new Date(C.createdAt).toLocaleString("de-DE"):"",C.firstName??"",C.lastName??"",C.email??"",C.phone??"",Te[C.status]??C.status??"",he[C.source]??C.source??"",ks[C.whatsappStatus]??C.whatsappStatus??"",C.engagementTier??"",C.street??"",C.zipCode??"",C.city??"",C.contractSigned?"ja":"nein",C.contractValue??"",se(C.lastContactedAt),se(C.nextContactAt),C.blacklisted?"ja":"nein",C.emailOptIn?"ja":"nein",(()=>{const ie=C.utmCampaign,Tt=ie&&ie.startsWith("MAG-")?ie.slice(4):null;return C.referredById||Tt?"ja":"nein"})(),(()=>{const ie=C.utmCampaign;return(ie&&ie.startsWith("MAG-")?ie.slice(4):null)??(C.referredById?`Lead #${C.referredById}`:"")})(),C.utmCampaign??"",C.assignedUserName??"",C.brandName??"",C.studioName??"",C.notes??""].map(te).join(","));const me=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),hs=W||V?`_${W||"start"}_bis_${V||"heute"}`:"",gs=new Blob(["\uFEFF"+Z.join(` 5`)],{type:"text/csv;charset=utf-8"}),zt=URL.createObjectURL(gs),ot=document.createElement("a");ot.href=zt,ot.download=`leads-${me}${hs}-${new Date().toISOString().slice(0,10)}.csv`,ot.click(),URL.revokeObjectURL(zt),d.success(`${a.length} Lead${a.length===1?"":"s"} (${r}) exportiert`)}catch(t){d.error(t?.message??"Export fehlgeschlagen")}finally{vt(!1)}},wt=p.leads.create.useMutation({onSuccess:()=>{d.success("Lead erstellt"),Ae(!1),H()},onError:t=>{if(t.data?.code==="CONFLICT"&&t.message.startsWith("DUPLICATE:")){const[,a,...r]=t.message.split(":"),v=r.join(":");d.warning(`Duplikat: "${v}" existiert bereits (Lead #${a}). Klicke auf den Lead um ihn zu öffnen.`,{duration:8e3,action:{label:`#${a} öffnen`,onClick:()=>s(`/leads/${a}`)}})}else d.error(t.message)}}),ls=p.leadActivities.logReached.useMutation({onSuccess:()=>{Oe.leads.list.invalidate(),d.success("Als erreicht markiert")},onError:t=>d.error(t.message)}),is=p.leadActivities.logCall.useMutation({onSuccess:()=>{Oe.leads.list.invalidate(),d.success("Kontaktversuch getrackt (nicht erreicht)")},onError:t=>d.error(t.message)}),_e=p.appointments.markLastAsNoShow.useMutation({onSuccess:()=>{Oe.leads.list.invalidate(),d.success("Termin als No-Show markiert + appointment_no_show Flow getriggert")},onError:t=>d.error(t.message)}),os=p.leads.delete.useMutation({onSuccess:()=>{H(),d.success("Lead gelöscht")},onError:t=>d.error(t.message)}),[Xe,Be]=o.useState(null),[We,Me]=o.useState(""),ds=["Fehlklick","Zu teuer","Zu weit entfernt","Anderes Studio","Kein Bedarf","Zeitlich nicht möglich","Sonstiges"],yt=p.leads.update.useMutation({onSuccess:()=>{d.info('Lead als âKein Interesse" markiert',{description:A==="active"?'Lead ist aus der âAktiven Pipeline" ausgeblendet â Filter auf âKein Interesse" umstellen, um ihn wiederzufinden.':void 0,duration:6e3}),Be(null),Me(""),H()},onError:t=>d.error(t.message)}),et=p.leads.bulkDelete.useMutation({onSuccess:t=>{d.success(`${t.deleted} Lead${t.deleted!==1?"s":""} gelöscht`),ge(new Set),T(!1),H()},onError:t=>d.error(t.message)}),[kt,Ke]=o.useState(!1),[tt,Qe]=o.useState(""),{data:cs=[]}=p.whatsapp.flows.useQuery(void 0,{enabled:kt}),St=cs.filter(t=>t.active??t.isActive),st=p.whatsapp.triggerFlowBulk.useMutation({onSuccess:t=>{d.success(`Flow für ${t.enrolled} Lead${t.enrolled!==1?"s":""} ausgelöst${t.skipped?` · ${t.skipped} übersprungen`:""}`),Ke(!1),Qe(""),ge(new Set)},onError:t=>d.error(t.message)}),{data:Ee=0,refetch:Ct}=p.leads.countDeleted.useQuery(),{data:ue,refetch:Cr}=p.leads.statusBreakdown.useQuery({brandId:x==="all"?void 0:Number(x)}),{data:Lr}=p.leads.rescueDiagnose.useQuery(),[rt,Ue]=o.useState(!1),[le,Lt]=o.useState("studio_interessenten"),[oe,At]=o.useState(180),nt=p.leads.undoImport.useMutation({onError:t=>d.error(t?.message??"Fehler beim Entfernen")}),$t=p.leads.restoreImport.useMutation({onError:t=>d.error(t?.message??"Fehler beim Wiederherstellen")}),It=p.leads.countImport.useQuery({brandId:Number(x),source:le==="__all__"?"":le,minutes:oe},{enabled:rt&&x!=="all",staleTime:5e3}),at=It.data?.count??null,_t=p.leads.brandSourceCounts.useQuery({brandId:Number(x)},{enabled:rt&&x!=="all",staleTime:5e3}).data?.rows??[],{data:$r=[],refetch:us}=p.leads.nameDuplicates.useQuery({brandId:x==="all"?void 0:Number(x)});p.leads.mergeNames.useMutation({onSuccess:t=>{d.success(`Leads gemerged${t.mergedFields.length>0?` â übernommen: ${t.mergedFields.join(", ")}`:""}`),us(),H()},onError:t=>d.error(t.message)});const lt=p.leads.purgeDeleted.useMutation({onSuccess:t=>{d.success(`${t.purged} versteckte Lead${t.purged!==1?"s":""} endgültig gelöscht`),Ct(),H()},onError:t=>d.error(t.message)}),it=p.leads.restoreDeleted.useMutation({onSuccess:t=>{d.success(`${t.restored} versteckte Leads wiederhergestellt â sind jetzt wieder in der Liste sichtbar`),Ct(),H()},onError:t=>d.error(t.message)}),Mt=_?.rows??[],ve=Q?Mt.filter(t=>Number(t.hotnessScore??0)>=50||t.noShowNoFollowup):Mt,He=_?.total??0,Et=ve.length>0&&ve.every(t=>O.has(t.id)),ms=()=>ge(Et?new Set:new Set(ve.map(t=>
5t.id))),xs=t=>ge(a=>{const r=new Set(a);return r.has(t)?r.delete(t):r.add(t),r});return e.jsxs("div",{className:"agency-cockpit-dark -m-4 min-h-screen p-4 sm:p-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Leads"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"flex border border-border rounded-md overflow-hidden",children:[e.jsxs(y,{variant:n==="list"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-2 gap-1",onClick:()=>c("list"),title:"Listenansicht",children:[e.jsx(Vs,{className:"h-4 w-4"}),e.jsx("span",{className:"sm:hidden",children:"Liste"})]}),e.jsxs(y,{variant:n==="eingang"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-2 gap-1",onClick:()=>c("eingang"),title:"Eingang â alle Leads in Eingangs-Chronologie (neueste zuerst)",children:[e.jsx(Dt,{className:"h-4 w-4"}),e.jsx("span",{className:"sm:hidden",children:"Eingang"})]}),e.jsxs(y,{variant:n==="kanban"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-2 gap-1",onClick:()=>c("kanban"),title:"Kanban-Ansicht",children:[e.jsx(Bs,{className:"h-4 w-4"}),e.jsx("span",{className:"sm:hidden",children:"Kanban"})]}),e.jsx(y,{variant:n==="activity"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-2",onClick:()=>c("activity"),title:"Verlauf (E-Mails, WhatsApp, Verträge)",children:e.jsx(ct,{className:"h-4 w-4"})}),e.jsx(y,{variant:n==="duplicates"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-2 text-amber-400",onClick:()=>c("duplicates"),title:"Duplikate",children:e.jsx(Ws,{className:"h-4 w-4"})})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>Re(!0),children:[e.jsx(Zt,{className:"h-4 w-4 mr-1"})," CSV Import"]}),f&&e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>Ue(!0),title:"Einen gerade importierten CSV-Schwung wieder entfernen (umkehrbar)",children:[e.jsx(Ce,{className:"h-4 w-4 mr-1"})," Import rückgängig"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:as,disabled:Nt,title:"Aktuelle Auswahl (Marke/Status/Quelle/Zeitraum) als CSV herunterladen",children:[e.jsx(Ks,{className:"h-4 w-4 mr-1"})," ",Nt?"Exportâ¦":"CSV Export"]}),e.jsxs(y,{size:"sm",onClick:()=>Ae(!0),children:[e.jsx(Qs,{className:"h-4 w-4 mr-1"})," Neuer Lead"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Us,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ws,{placeholder:"Name, E-Mail, Telefon...",value:b,onChange:t=>g(t.target.value),onKeyDown:t=>t.key==="Escape"&&g(""),className:"pl-8 bg-card border-border"}),b&&e.jsx("button",{className:"absolute right-2 top-2 text-muted-foreground hover:text-foreground",onClick:()=>g(""),children:"â"})]}),e.jsxs("button",{onClick:()=>B(t=>
5!t),className:`px-3 py-2 rounded-md text-sm font-medium border transition-colors whitespace-nowrap ${Q?"bg-red-500/15 border-red-500/40 text-red-400":"bg-card border-border text-muted-foreground hover:bg-muted/40"}`,title:"Nur heiÃe Leads (Hotness-Score ⥠50 oder No-Show ohne Folgetermin)",children:["ð¥ ",Q?"Nur heiÃ":"Heià zuerst"]}),e.jsxs("button",{onClick:()=>Fe(t=>!t),className:`px-3 py-2 rounded-md text-sm font-medium border transition-colors whitespace-nowrap ${X?"bg-amber-500/15 border-amber-500/40 text-amber-400":"bg-card border-border text-muted-foreground hover:bg-muted/40"}`,title:"Nur Leads die einen No-Show-Termin ohne Folgetermin haben",children:["ð» ",X?"Nur No-Shows":"No-Shows"]}),e.jsxs("button",{onClick:()=>ne(t=>!t),className:`px-3 py-2 rounded-md text-sm font-medium border transition-colors whitespace-nowrap ${I?"bg-red-500/15 border-red-500/40 text-red-400":"bg-card border-border text-muted-foreground hover:bg-muted/40"}`,title:"Nur Leads die als No-Sale geflaggt sind (Walk-In > 2h ohne Vertrag · Trial > 2h ohne Vertrag · Magicline-Brand-Termin > 2h ohne Vertrag)",children:["ð¸ ",I?"Nur No-Sales":"No-Sales"]}),e.jsxs("button",{onClick:()=>ce(t=>!t),className:`px-3 py-2 rounded-md text-sm font-medium border transition-colors whitespace-nowrap ${de?"bg-red-500/15 border-red-500/40 text-red-400":"bg-card border-border text-muted-foreground hover:bg-muted/40"}`,title:"Nur Leads mit verpasstem Rückruf (haben die Studio-Nummer zurückgerufen, niemand konnte annehmen)",children:["ðµ ",de?"Nur Rückrufe":"Rückrufe"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 px-2 py-1 rounded-md bg-card border border-border max-w-full",children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:"Eingang"}),e.jsx("input",{type:"date",value:W,onChange:t=>{U(t.target.value),P(0)},className:"bg-transparent text-foreground text-sm border-0 outline-none px-1 min-w-0 w-[130px]",title:"Leads ab diesem Datum"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"}),e.jsx("input",{type:"date",value:V,onChange:t=>{Ne(t.target.value),P(0)},className:"bg-transparent text-foreground text-sm border-0 outline-none px-1 min-w-0 w-[130px]",title:"Leads bis (einschliesslich) diesem Datum"}),(W||V)&&e.jsx("button",{onClick:()=>{U(""),Ne(""),P(0)},className:"text-muted-foreground hover:text-foreground px-1",title:"Datum-Filter zuruecksetzen",children:"Ã"})]}),e.jsxs(G,{value:A,onValueChange:t=>{u(t),P(0)},children:[e.jsx(q,{className:"w-44 bg-card border-border",children:e.jsx(J,{placeholder:"Status"})}),e.jsxs(Y,{children:[e.jsx(k,{value:"all",children:"Alle Status"}),e.jsx(k,{value:"active",children:"Aktive Pipeline"}),e.jsx("div",{className:"px-2 py-1 text-[10px] text-muted-foreground uppercase tracking-wider",children:"Aktiv"}),Object.entries(yr).map(([t,a])=>e.jsx(k,{value:t,children:a},t)),e.jsx("div",{className:"px-2 py-1 text-[10px] text-muted-foreground uppercase tracking-wider border-t border-border mt-1 pt-2",children:"Abgeschlossen"}),Object.entries(kr).map(([t,a])=>e.jsx(k,{value:t,children:a},t))]})]}),e.jsxs(G,{value:h,onValueChange:t=>{M(t),P(0)},children:[e.jsx(q,{className:"w-40 bg-card border-border",children:e.jsx(J,{placeholder:"Quelle"})}),e.jsxs(Y,{children:[e.jsx(k,{value:"all",children:"Alle Quellen"}),Object.entries(he).map(([t,a])=>e.jsx(k,{value:t,children:a},t))]})]}),e.jsxs(G,{value:x,onValueChange:t=>{w(t),P(0)},children:[e.jsx(q,{className:"w-40 bg-card border-border",children:e.jsx(J,{placeholder:"Marke"})}),e.jsxs(Y,{children:[e.jsx(k,{value:"all",children:"Alle Marken"}),(je??[]).map(t=>e.jsx(k,{value:String(t.id),children:t.name},t.id))]})]}),e.jsxs(G,{value:E,onValueChange:t=>{D(t),P(0)},children:[e.jsx(q,{className:"w-44 bg-card border-border",title:"Filter nach Engagement-Tier (auto-berechnet)",children:e.jsx(J,{placeholder:"Engagement"})}),e.jsxs(Y,{children:[e.jsx(k,{value:"all",children:"Alle Tiers"}),e.jsx(k,{value:"hot",children:"ð¥ Hot (â¤7 Tage)"}),e.jsx(k,{value:"warm",children:"âï¸ Warm (â¤30 Tage)"}),e.jsx(k,{value:"lukewarm",children:"ð¥ï¸ Lukewarm (â¤90 Tage)"}),e.jsx(k,{value:"cold",children:"âï¸ Cold (90+ Tage ohne Engagement)"}),e.jsx(k,{value:"dormant",children:"ð Dormant (180+ Tage)"}),e.jsx(k,{value:"new",children:"ð New (noch keine Mail)"})]})]}),e.jsxs(G,{value:K,onValueChange:t=>{fe(t),P(0)},children:[e.jsx(q,{className:"w-48 bg-card border-border",title:"Filter nach Termindatum â zeigt nur Leads mit passendem Termin (Bestätigt-Status â/â/â auf der Karte)",children:e.jsx(J,{placeholder:"Termine"})}),e.jsxs(Y,{children:[e.jsx(k,{value:"all",children:"Alle Termine"}),e.jsx(k,{value:"today",children:"ð
Termine heute"}),e.jsx(k,{value:"tomorrow",children:"ð
Termine morgen"}),e.jsx(k,{value:"week",children:"ðï¸ Termine 7 Tage"}),e.jsx(k,{value:"unconfirmed",children:"â Nur unbestätigte"})]})]}),e.jsxs(G,{value:re,onValueChange:t=>{L(t),P(0)},children:[e.jsx(q,{className:"w-44 bg-card border-border",title:"Nach Anzahl Kontaktversuche filtern (Kanban)",children:e.jsx(J,{placeholder:"Kontaktversuche"})}),e.jsxs(Y,{children:[e.jsx(k,{value:"all",children:"Alle Versuche"}),e.jsx(k,{value:"0",children:"0à (noch nicht)"}),e.jsx(k,{value:"1-2",children:"1â2Ã"}),e.jsx(k,{value:"3-5",children:"3â5Ã"}),e.jsx(k,{value:"5plus",children:"5+Ã"})]})]}),e.jsx(y,{variant:"ghost",size:"icon",onClick:()=>H(),children:e.jsx(mt,{className:"h-4 w-4"})})]}),ue&&(ue.totalActive>0||ue.deleted>0)&&e.jsxs("div",{className:"px-3 py-2 rounded-lg bg-muted/30 text-xs flex items-center gap-3 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-foreground",children:ue.totalActive}),e.jsx("span",{className:"text-muted-foreground",children:"aktive Leads gesamt"}),ue.active.map(t=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsxs("span",{className:"text-muted-foreground",children:[t.status,":"]}),e.jsx("span",{className:"font-medium text-foreground",children:t.count})]},t.status)),ue.blacklisted>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"blacklisted:"}),e.jsx("span",{className:"font-medium text-red-300",children:ue.blacklisted})]}),ue.deleted>0&&e.jsxs("span",{className:"flex items-center gap-1 ml-auto",children:[e.jsx("span",{className:"text-muted-foreground",children:"versteckt:"}),e.jsx("span",{className:"font-medium text-orange-300",children:ue.deleted})]})]}),!1,!1,n==="kanban"&&e.jsx(mr,{brandId:x==="all"?void 0:Number(x),search:m||void 0,source:h,noShowOnly:X,noSaleOnly:I,engagementTier:E,hotOnly:Q,dateFrom:W||void 0,dateTo:V||void 0,apptFilter:K,attemptsFilter:re,missedOnly:de}),n==="activity"&&e.jsx(jr,{brandId:x==="all"?void 0:Number(x)}),n==="eingang"&&e.jsxs("div",{className:"rounded-lg border border-border overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground bg-muted/30 border-b border-border",children:["Alle Leads in Eingangs-Reihenfolge (neueste zuerst)",x==="all"?" · alle Studios":"",". ",_?.total!=null?`${_.total} gesamt.`:""]}),ee?e.jsx("div",{className:"p-4 space-y-2",children:Array.from({length:8}).map((t,a)=>e.jsx("div",{className:"h-9 bg-muted/30 rounded animate-pulse"},a))}):(_?.rows??[]).length===0?e.jsx("div",{className:"p-6 text-center text-sm text-muted-foreground",children:"Keine Leads im gewählten Zeitraum/Filter."}):e.jsx("div",{className:"divide-y divide-border",children:_.rows.map(t=>{const a=je?.find(te=>te.id===t.brandId),r=a?.studioName??a?.name??(t.brandId?`Brand-${t.brandId}`:"â ohne Studio"),v=t.createdAt?new Date(t.createdAt):null;return e.jsxs("button",{onClick:()=>$(t.id),className:"w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:"w-28 shrink-0 text-[11px] leading-tight text-muted-foreground tabular-nums",children:v?e.jsxs(e.Fragment,{children:[v.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"2-digit"}),e.jsx("br",{}),v.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})," Uhr"]}):"â"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-foreground truncate",children:[t.firstName,t.lastName].filter(
5Boolean).join(" ")||"(ohne Namen)"}),e.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:t.phone||t.email||"â"})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-1.5 w-40 shrink-0 text-[11px] text-muted-foreground",children:[e.jsx(ut,{source:t.source,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"truncate",children:he[t.source]??t.source??"â"})]}),e.jsx("div",{className:"hidden md:block w-40 shrink-0 text-[11px] text-muted-foreground truncate",children:r}),e.jsx("span",{className:`shrink-0 text-[10px] px-2 py-0.5 rounded-full ${Kt[t.status]??"bg-muted text-muted-foreground"}`,children:Te[t.status]??t.status})]},t.id)})}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border text-xs",children:[e.jsx(y,{variant:"outline",size:"sm",disabled:R===0,onClick:()=>P(Math.max(0,R-z)),children:"â Neuere"}),e.jsxs("span",{className:"text-muted-foreground",children:[R+1,"â",R+(_?.rows?.length??0),_?.total!=null?` von ${_.total}`:""]}),e.jsx(y,{variant:"outline",size:"sm",disabled:(_?.rows?.length??0)<z||_?.total!=null&&R+z>=_.total,onClick:()=>P(R+z),children:"Ãltere â"})]})]}),n==="duplicates"&&e.jsxs("div",{className:"space-y-3",children:[(Ve??[]).length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx("div",{className:"text-sm font-semibold text-foreground",children:"Mehrfach angemeldet"}),e.jsx("button",{onClick:()=>{window.confirm(`Alle Wiederanmeldungen der letzten 14 Tage wieder sichtbar bei âNeu" machen? 6 7Nur Sichtbarkeit â es gehen KEINE Nachrichten raus. Aktive Mitglieder/Termine bleiben unangetastet.`)&&Ye.mutate({days:14})},disabled:Ye.isPending,className:"text-xs font-medium px-3 h-8 rounded-md border border-primary/40 text-primary hover:bg-primary/10 disabled:opacity-50",title:"Holt zurückgekehrte Leads der letzten 14 Tage nach oben zu Neu â ohne Nachrichten zu senden",children:Ye.isPending?"Läuftâ¦":"ð Wiederanmeldungen (14 T.) sichtbar machen"})]}),e.jsxs("div",{className:"rounded-lg border border-border p-3 flex flex-wrap items-center gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-lg font-bold text-foreground",children:Ie.people})," ",e.jsx("span",{className:"text-muted-foreground",children:"Personen mehrfach"})]}),e.jsx("div",{className:"text-muted-foreground",children:"·"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:Ie.two})," ",e.jsx("span",{className:"text-muted-foreground",children:"2Ã"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:Ie.three})," ",e.jsx("span",{className:"text-muted-foreground",children:"3Ã"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:Ie.four})," ",e.jsx("span",{className:"text-muted-foreground",children:"4Ã+"})]}),e.jsx("div",{className:"text-muted-foreground",children:"·"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:Ie.extraLeads})," ",e.jsx("span",{className:"text-muted-foreground",children:"doppelte Zeilen gesamt"})]}),e.jsx("button",{onClick:()=>ns(t=>!t),className:"ml-auto text-xs font-medium text-primary hover:underline",children:jt?"Details ausblenden":"Details anzeigen & zusammenführen"})]}),jt&&(Ve??[]).map(t=>{const a=t.leads[0],r=t.leads.slice(1);return e.jsxs("div",{className:"rounded-lg border border-border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap mb-2",children:[e.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:[t.normPhone," · ",t.count," Leads"]}),e.jsx("button",{onClick:()=>{confirm(`Zusammenführen? 8 9BEHALTEN: #${a.id} ${a.firstName??""} ${a.lastName??""} (${a.status}) 10Dubletten (werden umgehängt + entfernt): ${r.map(v=>`#${v.id}`).join(", ")} 11 12Alle Termine/Verträge/Chats wandern auf den behaltenen Lead.`)&&ft.mutate({keptId:a.id,dupIds:r.map(v=>v.id)})},disabled:ft.isPending,className:"text-xs font-medium text-primary hover:underline disabled:opacity-50",children:"ð Zusammenführen"})]}),e.jsx("div",{className:"space-y-1",children:t.leads.map((v,te)=>e.jsxs("div",{className:`flex items-center gap-2 text-xs rounded px-2 py-1 ${te===0?"bg-emerald-500/10":"bg-muted/30"}`,children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-semibold ${te===0?"bg-emerald-500/20 text-emerald-600 dark:text-emerald-400":"bg-muted text-muted-foreground"}`,children:te===0?"BEHALTEN":"Dublette"}),e.jsxs("button",{onClick:()=>s(`/leads/${v.id}`),className:"font-medium text-foreground hover:underline",children:["#",v.id," ",v.firstName," ",v.lastName]}),e.jsxs("span",{className:"text-muted-foreground",children:[v.status,v.contractSigned||v.status==="closed"?" · Vertrag":""]}
12),e.jsxs("span",{className:"text-muted-foreground/70 ml-auto font-mono",children:[v.phone," · ",v.source]})]},v.id))})]},t.key)})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-amber-500/10 border border-amber-500/20 text-sm text-amber-300",children:[e.jsx(De,{className:"w-4 h-4 shrink-0"}),e.jsxs("span",{children:["Diese Liste zeigt alle abgewiesenen Duplikate. Die Original-Leads wurden ",e.jsx("strong",{children:"nicht verändert"})," â nur der Eingangsversuch wurde protokolliert."]})]}),(()=>{const t=m.toLowerCase(),a=t?(ht??[]).filter(r=>[r.firstName,r.lastName,r.phone,r.email,r.existingFirstName,r.existingLastName].some(v=>v?.toLowerCase().includes(t))):ht??[];return a.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:m?"Keine Treffer für diese Suche":"Keine Duplikate vorhanden"}):e.jsx("div",{className:"rounded-lg border border-border overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm min-w-[500px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/50 border-b border-border text-xs text-muted-foreground",children:[e.jsx("th",{className:"px-4 py-2.5 text-left",children:"Eingang (Duplikat)"}),e.jsx("th",{className:"px-4 py-2.5 text-left",children:"Telefon / E-Mail"}),e.jsx("th",{className:"px-4 py-2.5 text-left",children:"Kanal"}),e.jsx("th",{className:"px-4 py-2.5 text-left",children:"Existierender Lead"}),e.jsx("th",{className:"px-4 py-2.5 text-left",children:"Datum"}),e.jsx("th",{className:"px-2 py-2.5"})]})}),e.jsx("tbody",{children:a.map(r=>e.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/20",children:[e.jsxs("td",{className:"px-4 py-2.5",children:[e.jsxs("span",{className:"font-medium",children:[r.firstName," ",r.lastName]}),r.source&&e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:r.source})]}),e.jsxs("td",{className:"px-4 py-2.5 text-muted-foreground font-mono text-xs",children:[r.phone&&e.jsx("div",{children:r.phone}),r.email&&e.jsx("div",{children:r.email})]}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("span",{className:`px-1.5 py-0.5 rounded text-xs font-medium ${r.channel==="zapier"?"bg-orange-500/20 text-orange-300":r.channel==="api"?"bg-blue-500/20 text-blue-300":r.channel==="crm_manual"?"bg-purple-500/20 text-purple-300":"bg-muted text-muted-foreground"}`,children:r.channel})}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsxs("button",{onClick:()=>s(`/leads/${r.existingLeadId}`),className:"flex items-center gap-1 text-primary hover:underline text-xs",children:[e.jsx(es,{className:"w-3 h-3"}),"#",r.existingLeadId," ",r.existingFirstName," ",r.existingLastName]})}),e.jsx("td",{className:"px-4 py-2.5 text-xs text-muted-foreground",children:new Date(r.createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}),e.jsx("td",{className:"px-2 py-2.5",children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[e.jsx("button",{onClick:()=>{confirm(`Lead #${r.existingLeadId} ${r.existingFirstName??""} ${r.existingLastName??""} reaktivieren? 13 14⢠Status zurueck auf 'lead' (Neu) 15⢠Alte WhatsApp-Reminder werden gestoppt 16⢠new_lead-Flow startet frisch`)&&pt.mutate({duplicateLogId:r.id})},disabled:pt.isPending,className:"text-xs text-green-300 hover:text-green-200 hover:bg-green-500/10 transition-colors px-2 py-1 rounded",title:"Existierenden Lead reaktivieren als wäre er neu",children:"â» Reaktivieren"}),e.jsx("button",{onClick:()=>bt.mutate({id:r.id}),disabled:bt.isPending,className:"text-muted-foreground hover:text-destructive transition-colors p-1 rounded",title:"Eintrag löschen",children:e.jsx(Ce,{className:"w-3.5 h-3.5"})})]})})]},r.id))})]})})})()]}),n==="list"&&e.jsxs(e.Fragment,{children:[O.size>0&&e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 bg-primary/10 border border-primary/20 rounded-lg",children:[e.jsxs("span",{className:"text-sm font-medium text-primary",children:[O.size," Lead",O.size!==1?"s":""," ausgewählt"]}),e.jsxs(y,{size:"sm",className:"h-7 text-xs ml-auto gap-1 bg-yellow-400 hover:bg-yellow-300 text-black",onClick:()=>Ke(!0),children:[e.jsx(Hs,{className:"w-3.5 h-3.5"}),"Flow auslösen"]}),e.jsxs(y,{size:"sm",variant:"destructive",className:"h-7 text-xs",onClick:()=>T(!0),children:[e.jsx(Ce,{className:"w-3.5 h-3.5 mr-1"}),"Auswahl löschen"]}),e.jsx(y,{size:"sm",variant:"ghost",className:"h-7 text-xs",onClick:()=>ge(new Set),children:"Abwählen"})]}),e.jsx(Nr,{brandId:x==="all"?void 0:Number(x),hotOnly:Q,onToggleHotOnly:()=>B(!0)}),e.jsx(Sr,{rows:ve,isError:Pe,isLoading:ee,error:$e,onRefetch:H,onOpenDetail:t=>F(t)}),e.jsx("div",{className:`hidden md:block rounded-lg border border-border overflow-hidden transition-opacity ${pe&&_?"opacity-70":""}`,children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/50 border-b border-border",children:[e.jsx("th",{className:"px-4 py-3 w-8",children:e.jsx("button",{onClick:ms,className:"text-muted-foreground hover:text-foreground",children:Et?e.jsx(Ft,{className:"w-4 h-4 text-primary"}):e.jsx(Rt,{className:"w-4 h-4"})})}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-medium",children:"Name"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-medium",children:"Kontakt"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-medium",children:"Status"}),e.jsx("th",{className:"text-center px-3 py-3 text-xs text-muted-foreground font-medium",title:"Engagement-Tier (auto-berechnet aus Mail-Engagement)",children:"Engagement"}),e.jsx("th",{className:"text-center px-3 py-3 text-xs text-muted-foreground font-medium",title:"E-Mail Automatisierung",children:"â Mail"}),e.jsx("th",{className:"text-center px-3 py-3 text-xs text-muted-foreground font-medium",title:"WhatsApp Automatisierung",children:"ð¬ WA"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-medium",children:"Quelle"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-medium",children:"Studio"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-medium",children:"Eingegangen"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs text-muted-foreground font-medium",children:"Aktion"})]})}),e.jsx("tbody",{children:Pe?e.jsx("tr",{children:e.jsxs("td",{colSpan:11,className:"px-4 py-8 text-center",children:[e.jsx("div",{className:"text-red-400 text-sm font-semibold mb-1",children:"â Fehler beim Laden der Leads"}),e.jsx("div",{className:"text-xs text-muted-foreground font-mono break-all max-w-xl mx-auto whitespace-pre-wrap",children:$e?.message??"Unbe
16kannter Fehler"}),e.jsx(y,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>H(),children:"Neu laden"})]})}):_===void 0?Array.from({length:8}).map((t,a)=>e.jsx("tr",{className:"border-b border-border",children:Array.from({length:6}).map((r,v)=>e.jsx("td",{className:"px-4 py-3",children:e.jsx("div",{className:"h-4 bg-muted animate-pulse rounded w-24"})},v))},a)):Pe?e.jsx("tr",{children:e.jsxs("td",{colSpan:11,className:"px-4 py-12 text-center text-destructive",children:["Fehler beim Laden der Leads: ",$e?.message??"Unbekannter Fehler"]})}):ve.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:11,className:"px-4 py-12 text-center text-muted-foreground",children:"Keine Leads gefunden"})}):ve.map(t=>e.jsxs("tr",{className:`border-b border-border hover:bg-muted/30 cursor-pointer transition-colors ${O.has(t.id)?"bg-primary/5":""}`,onClick:a=>{a.metaKey||a.ctrlKey?$(t.id):F(t.id)},children:[e.jsx("td",{className:"px-4 py-3 w-8",onClick:a=>{a.stopPropagation(),xs(t.id)},children:O.has(t.id)?e.jsx(Ft,{className:"w-4 h-4 text-primary"}):e.jsx(Rt,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("td",{className:"px-4 py-3 font-medium text-foreground",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{children:[t.firstName," ",t.lastName]}),t.callbackRequestedAt&&e.jsx("span",{title:"Rückruf gewünscht â der Interessent möchte telefonisch sprechen",className:"inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded-full bg-orange-500/15 text-orange-600 font-semibold",children:"ð Rückruf"}),t.emailReplyUnread&&e.jsxs("span",{title:"Hat per E-Mail geantwortet â bitte antworten",className:"inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded-full bg-emerald-500/15 text-emerald-600 font-medium",children:[e.jsx(qe,{className:"w-3 h-3"})," Antwort"]}),(()=>{const a=Number(t.hotnessScore??0);if(a<50)return null;const r=a>=80?"bg-red-500/20 text-red-300 border-red-500/40":a>=65?"bg-orange-500/20 text-orange-300 border-orange-500/40":"bg-amber-500/15 text-amber-400 border-amber-500/30";return e.jsxs("span",{className:`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-bold border ${r}`,title:`Hotness-Score ${a} â Sales sollte hier zuerst dran`,children:["ð¥ ",a]})})(),t.noShowNoFollowup&&e.jsx("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-rose-500/15 text-rose-400 border border-rose-500/40",title:"No-Show ohne Folgetermin â Recovery faellig",children:"â No-Show · kein Folgetermin"}),t.noSale&&e.jsx("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-bold bg-red-600/15 text-red-700 dark:text-red-400 border border-red-600/40",title:"Walk-In ohne Vertrag (>2h) â walk_in_no_signup_2h Flow ausgeloest",children:"ð¸ No-Sale"}),e.jsx("button",{onClick:a=>{a.stopPropagation(),window.confirm(`Letzten offenen Termin von ${t.firstName??""} ${t.lastName??""} als No-Show markieren? Triggert automatisch den appointment_no_show Flow.`)&&_e.mutate({leadId:t.id})},disabled:_e.isPending&&_e.variables?.leadId===t.id,className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-red-500/10 text-red-400 border border-red-500/30 hover:bg-red-500/20 transition-colors",title:"Letzten offenen Termin als No-Show markieren â triggert appointment_no_show Flow",children:_e.isPending&&_e.variables?.leadId===t.id?"â¦":"ð« No-Show"}),(()=>{const a=t.lastActivityAt,r=t.lastActivityType;if(!a||!r)return null;const v=Math.floor((Date.now()-Number(a))/6e4);if(v>60)return null;const te=v<=1?"jetzt":v<60?`vor ${v}m`:`vor ${Math.floor(v/60)}h`;let se="bg-amber-500/15 text-amber-400 border-amber-500/30",Z="â¨",me=r;if(r==="wa_inbound")se="bg-red-500/15 text-red-400 border-red-500/30 animate-pulse",Z="ð¥",me="schreibt";else if(r==="wa_outbound")se="bg-green-500/15 text-green-400 border-green-500/30",Z="ð¬",me="WA gesendet";else if(r==="email_clicked")se="bg-cyan-500/15 text-cyan-400 border-cyan-500/30",Z="ð",me="Link geklickt";else if(r==="email_opened")se="bg-blue-500/15 text-blue-400 border-blue-500/30",Z="ðï¸",me="Mail geöffnet";else if(r==="email_inbound")se="bg-purple-500/15 text-purple-400 border-purple-500/30",Z="ð©",me="Mail geantwortet";else if(r==="appointment_booked")se="bg-purple-500/15 text-purple-400 border-purple-500/30",Z="ð
",me="Termin gebucht";else return null;return e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium border ${se}`,title:`${r} · ${te}`,children:[e.jsx("span",{children:Z}),me," ",te]}
16)})(),(()=>{const a=t.pendingSignupAt;if(!a)return null;const r=Math.floor((Date.now()-Number(a))/864e5),v=r>=3;return e.jsxs("span",{className:`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${v?"bg-red-500/15 text-red-400 border border-red-500/30 animate-pulse":"bg-yellow-500/15 text-yellow-400 border border-yellow-500/30"}`,title:v?`Vertrag seit ${r} Tagen unbestätigt!`:"Vertrag noch nicht durch Kunde bestätigt",children:[e.jsx(Dt,{className:"w-2.5 h-2.5"}),"Bestätigung ausstehend",r>0?` · ${r}d`:""]})})()]}),(()=>{const a=Number(t.emailSentCount??0),r=Number(t.waSentCount??0),v=Number(t.waFailedCount??0);return!a&&!r&&!v?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mt-0.5",children:[a>0&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1 py-0 rounded text-[10px] text-violet-400 bg-violet-500/10 border border-violet-500/30",title:`${a} E-Mail(s) gesendet`,children:["â ",a]}),r>0&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1 py-0 rounded text-[10px] text-green-400 bg-green-500/10 border border-green-500/30",title:`${r} WhatsApp-Nachricht(en) gesendet`,children:["ð¬ ",r]}),v>0&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1 py-0 rounded text-[10px] text-red-400 bg-red-500/10 border border-red-500/30",title:`${v} WA-Job(s) gescheitert`,children:["â ",v]})]})})()]}),e.jsxs("td",{className:"px-4 py-3 text-muted-foreground",children:[e.jsx("div",{children:t.phone||"â"}),e.jsx("div",{className:"text-xs",children:t.email||""})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${Kt[t.status]??""}`,children:Te[t.status]??t.status})}),e.jsx("td",{className:"px-3 py-3 text-center",children:(()=>{const a=t.engagementTier,v=a?{hot:{label:"ð¥ Hot",cls:"bg-red-500/15 text-red-400 border border-red-500/30",title:"Open/Click in den letzten 7 Tagen â bekommt alle Bulk-Mails"},warm:{label:"âï¸ Warm",cls:"bg-orange-500/15 text-orange-400 border border-orange-500/30",title:"Open/Click in den letzten 30 Tagen"},lukewarm:{label:"ð¥ï¸ Luke",cls:"bg-yellow-500/15 text-yellow-400 border border-yellow-500/30",title:"Open/Click in den letzten 90 Tagen"},cold:{label:"âï¸ Cold",cls:"bg-blue-500/15 text-blue-400 border border-blue-500/30",title:"Kein Engagement seit 90+ Tagen â max 1 Mail / 14 Tage"},dormant:{label:"ð Dorm",cls:"bg-gray-500/15 text-gray-400 border border-gray-500/30",title:"Kein Engagement seit 180+ Tagen â max 1 Mail / 60 Tage"},new:{label:"ð New",cls:"bg-zinc-500/15 text-zinc-400 border border-zinc-500/30",title:"Hat noch keine Mail bekommen"}}[a]:null;return v?e.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${v.cls}`,title:v.title,children:v.label}):e.jsx("span",{className:"text-muted-foreground/40 text-xs",children:"â"})})()}),e.jsx("td",{className:"px-3 py-3 text-center",children:(()=>{const a=Number(t.emailSentCount??0);return a>0?e.jsx("span",{className:"inline-flex items-center justify-center min-w-[1.5rem] h-5 px-1.5 rounded text-xs font-medium bg-violet-500/15 text-violet-400 border border-violet-500/30",title:`${a} Mail(s) gesendet`,children:a}):e.jsx("span",{className:"text-muted-foreground/40 text-xs",children:"â"})})()}),e.jsx("td",{className:"px-3 py-3 text-center",children:(()=>{const a=Number(t.waSentCount??0),r=Number(t.waFailedCount??0);return r>0&&a===0?e.jsxs("span",{className:"inline-flex items-center gap-0.5 justify-center min-w-[1.5rem] h-5 px-1.5 rounded text-xs font-medium bg-red-500/15 text-red-400 border border-red-500/30",title:`${r} WA-Job(s) gescheitert, kein Send erfolgt`,children:["â ",r]}):a>0?e.jsxs("span",{className:`inline-flex items-center gap-0.5 justify-center min-w-[1.5rem] h-5 px-1.5 rounded text-xs font-medium ${r>0?"bg-yellow-500/15 text-yellow-400 border border-yellow-500/30":"bg-green-500/15 text-green-400 border border-green-500/30"}`,title:`${a} WA gesendet${r>0?`, ${r} gescheitert`:""}`,children:[a,r>0&&" â "]}
16):e.jsx("span",{className:"text-muted-foreground/40 text-xs",children:"â"})})()}),e.jsxs("td",{className:"px-4 py-3",children:[t.source&&e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-medium 17 ${t.source==="ads"?"bg-blue-500/10 text-blue-400":t.source==="call_center"?"bg-orange-500/10 text-orange-400":t.source==="referral"?"bg-green-500/10 text-green-400":t.source==="walk_in"?"bg-purple-500/10 text-purple-400":t.source==="online"?"bg-sky-500/10 text-sky-400":t.source==="checkout"?"bg-yellow-500/10 text-yellow-400":t.source==="popup"?"bg-pink-500/10 text-pink-400":"bg-muted text-muted-foreground"}`,children:[e.jsx(ut,{source:t.source,className:"w-3 h-3"}),he[t.source]??t.source]}),!t.source&&e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"}),(()=>{const a=t.utmCampaign,r=a&&a.startsWith("MAG-")?a.slice(4):null;return!(t.referredById||r)?null:e.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-medium bg-emerald-500/10 text-emerald-400",title:`Ãber Empfehlungscode angemeldet${r?` (Werber-Nr. ${r})`:t.referredById?` (Werber-Lead #${t.referredById})`:""}`,children:[e.jsx(Zs,{className:"w-3 h-3"})," Referral"]})})()]}),e.jsx("td",{className:"px-4 py-3 text-muted-foreground text-xs",children:je?.find(a=>a.id===t.brandId)?.name??"â"}),e.jsxs("td",{className:"px-4 py-3 text-xs",children:[e.jsx("div",{className:"text-foreground/80 font-medium",children:ys(t.createdAt)}),e.jsx("div",{className:"text-muted-foreground",children:t.createdAt?new Date(t.createdAt).toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})+" Uhr":""})]}),e.jsx("td",{className:"px-4 py-3",onClick:a=>a.stopPropagation(),children:e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(y,{size:"sm",variant:"outline",className:"h-6 text-xs px-1.5 text-green-500 border-green-500/30 hover:bg-green-500/10 gap-1",onClick:()=>ls.mutate({leadId:t.id}),title:"Erreicht",children:[e.jsx(xt,{className:"h-3 w-3"}),t.reachedCount>0&&e.jsx("span",{className:"font-mono leading-none",children:t.reachedCount})]}),e.jsxs(y,{size:"sm",variant:"outline",className:"h-6 text-xs px-1.5 text-red-400 border-red-400/30 hover:bg-red-500/10 gap-1",onClick:()=>is.mutate({leadId:t.id}),title:"Nicht erreicht",children:[e.jsx(Xt,{className:"h-3 w-3"}),t.callCount>0&&e.jsx("span",{className:"font-mono leading-none",children:t.callCount})]}),e.jsx(y,{size:"sm",variant:"outline",className:"h-6 px-1.5 text-gray-400 border-gray-500/30 hover:bg-gray-500/10",onClick:()=>{Be(t.id),Me("")},title:"Kein Interesse",children:e.jsx(qt,{className:"h-3 w-3"})}),e.jsx(y,{size:"sm",variant:"ghost",className:"h-6 px-1.5 text-destructive hover:bg-destructive/10",onClick:()=>{confirm(`Lead "${t.firstName} ${t.lastName}" löschen?`)&&os.mutate({id:t.id})},title:"Löschen",children:e.jsx(Ce,{className:"h-3 w-3"})})]})})]},t.id))})]})})}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[He," Leads gesamt"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{variant:"outline",size:"sm",disabled:R===0,onClick:()=>P(Math.max(0,R-z)),children:"Zurück"}),e.jsxs("span",{className:"px-2 py-1 text-xs",children:[R+1,"â",Math.min(R+z,He)," von ",He]}),e.jsx(y,{variant:"outline",size:"sm",disabled:R+z>=He,onClick:()=>P(R+z),children:"Weiter"})]})]})]}),e.jsx(we,{open:ae,onOpenChange:Ae,children:e.jsxs(ye,{className:"bg-card border-border max-w-lg max-h-[90vh] flex flex-col",children:[e.jsx(ke,{className:"shrink-0",children:e.jsx(Se,{children:"Neuer Lead"})}),e.jsx("div",{className:"overflow-y-auto flex-1 pr-1",children:e.jsx(qs,{onSubmit:t=>wt.mutate(t),isLoading:wt.isPending})})]})}),e.jsx(lr,{open:Je,onOpenChange:Re,onSuccess:()=>H()}),e.jsx(we,{open:rt,onOpenChange:Ue,children:e.jsxs(ye,{className:"sm:max-w-md",children:[e.jsx(ke,{children:e.jsx(Se,{children:"Import rückgängig machen"})}),x==="all"?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Bitte oben zuerst ein ",e.jsx("strong",{children:"Studio"}),' auswählen (nicht âAlle") â dann kann der Import gezielt für dieses Studio zurückgenommen werden.']}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Entfernt die zuletzt importierten Leads für ",e.jsx("strong",{className:"text-foreground",children:je?.find(t=>
17t.id===Number(x))?.studioName??je?.find(t=>t.id===Number(x))?.name??`Studio ${x}`}),". Sie werden nur ",e.jsx("strong",{children:"ausgeblendet"})," (umkehrbar), nicht endgültig gelöscht."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Quelle"}),e.jsxs(G,{value:le,onValueChange:t=>Lt(t),children:[e.jsx(q,{children:e.jsx(J,{})}),e.jsxs(Y,{children:[e.jsx(k,{value:"__all__",children:"Alle Quellen (dieses Studio)"}),Object.entries(he).map(([t,a])=>e.jsx(k,{value:t,children:a},t))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Zeitraum"}),e.jsxs(G,{value:String(oe),onValueChange:t=>At(Number(t)),children:[e.jsx(q,{children:e.jsx(J,{})}),e.jsxs(Y,{children:[e.jsx(k,{value:"60",children:"Letzte Stunde"}),e.jsx(k,{value:"180",children:"Letzte 3 Stunden"}),e.jsx(k,{value:"1440",children:"Heute (24 Std.)"}),e.jsx(k,{value:"10080",children:"Letzte 7 Tage"}),e.jsx(k,{value:"43200",children:"Letzte 30 Tage"}),e.jsx(k,{value:"129600",children:"Letzte 90 Tage"}),e.jsx(k,{value:"5256000",children:"Alle (dieser Quelle)"})]})]})]})]}),_t.length>0&&e.jsxs("div",{className:"rounded-lg border border-border bg-background p-2.5",children:[e.jsx("div",{className:"text-[11px] font-semibold text-muted-foreground mb-1.5",children:"Aktive Leads dieses Studios je Quelle â klick die richtige an:"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:_t.map(t=>e.jsxs("button",{onClick:()=>{Lt(t.source),At(5256e3)},className:`text-xs rounded-full px-2.5 py-1 border ${le===t.source?"bg-primary text-primary-foreground border-primary":"bg-card text-foreground border-border hover:border-primary"}`,children:[he[t.source]??t.source,": ",e.jsx("strong",{children:t.count})]},t.source))})]}),e.jsx("div",{className:"rounded-lg border border-border bg-muted/30 p-3 text-sm",children:It.isFetching?e.jsx("span",{className:"text-muted-foreground",children:"Zähle â¦"}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{className:"text-foreground text-base",children:at??0})," Leads (",le==="__all__"?"alle Quellen":`Quelle â${he[le]??le}"`,", ",oe===60?"letzte Stunde":oe===180?"letzte 3 Std.":oe===1440?"heute":oe===10080?"letzte 7 Tage":oe===43200?"letzte 30 Tage":oe===129600?"letzte 90 Tage":"alle dieser Quelle",") werden ausgeblendet."]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{variant:"destructive",size:"sm",className:"flex-1",disabled:nt.isPending||!at,onClick:async()=>{try{const t=await nt.mutateAsync({brandId:Number(x),source:le==="__all__"?"":le,minutes:oe,dryRun:!1});d.success(`${t?.deleted??0} Leads ausgeblendet.`),Ue(!1),H()}catch(t){d.error(t?.message??"Entfernen fehlgeschlagen")}},children:nt.isPending?"Entferneâ¦":`${at??0} Leads entfernen`}),e.jsx(y,{variant:"ghost",size:"sm",disabled:$t.isPending,onClick:async()=>{try{const t=await $t.mutateAsync({brandId:Number(x),source:le==="__all__"?"":le,minutes:oe});d.success(`${t?.restored??0} Leads wiederhergestellt.`),Ue(!1),H()}catch(t){d.error(t?.message??"Wiederherstellen fehlgeschlagen")}},title:"Ein zuvor entferntes Paket wieder sichtbar machen",children:"â© Wiederherstellen"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:'Wiederherstellen macht ein gerade durchgeführtes âEntfernen" (gleiche Quelle/Zeitraum) rückgängig.'})]})]})}),e.jsx(we,{open:Xe!==null,onOpenChange:t=>{t||(Be(null),Me(""))},children:e.jsxs(ye,{className:"max-w-sm",children:[e.jsx(ke,{children:e.jsx(Se,{children:"Kein Interesse"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bitte wähle einen Grund aus:"}),e.jsx("div",{className:"flex flex-col gap-2 mt-1",children:ds.map(t=>e.jsx("button",{onClick:()=>Me(t),className:`text-left px-3 py-2 rounded text-sm border transition-colors ${We===t?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted/40"}`,children:t},t))}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(y,{className:"flex-1",disabled:!We||yt.isPending,onClick:()=>{Xe&&We&&yt.mutate({id:Xe,status:"not_interested",statusReason:We})},children:"Speichern"}),e.jsx(y,{variant:"outline",onClick:()=>{Be(null),Me("")},children:"Abbrechen"})]})]})}),Ee>0&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-muted/60 text-sm text-muted-foreground flex-wrap",children:[e.jsx(Ce,{className:"w-3.5 h-3.5 text-destructive/70"}),e.jsxs("span",{children:[Ee," versteckte Lead",Ee!==1?"s":""," im System"]}),e.jsxs("div",{className:"ml-auto flex gap-2",children:[e.jsx(y,{size:"sm",variant:"outline",className:"h-7 text-xs border-green-400/40 text-green-300 hover:bg-green-500/10",disabled:it.isPending,onClick:()=>{confirm(`${Ee} versteckte Leads wiederherstellen? 18 19Sie werden danach wieder in der Lead-Liste sichtbar.`)&&it.mutate({})},children:it.isPending?"Stellt wieder her...":"Wiederherstellen"}),e.jsx(y,{size:"sm",variant:"destructive",className:"h-7 text-xs",disabled:lt.isPending,onClick:()=>{confirm(`${Ee} versteckte Leads ENDGÃLTIG löschen? 20 21Das kann NICHT rückgängig gemacht werden!`)&<.mutate()},children:lt.isPending?"Löscht...":"Endgültig löschen"})]})]}),e.jsx(we,{open:j,onOpenChange:T,children:e.jsxs(ye,{className:"max-w-sm",children:[e.jsx(ke,{children:e.jsx(Se,{children:"Leads löschen"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Möchtest du wirklich ",e.jsxs("strong",{children:[O.size," Lead",O.size!==1?"s":""]})," unwiderruflich löschen?"]}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(y,{variant:"destructive",className:"flex-1",disabled:et.isPending,onClick:()=>et.mutate({ids:Array.from(O)}),children:et.isPending?"Löscht...":`${O.size} Lead${O.size!==1?"s":""} löschen`}),e.jsx(y,{variant:"outline",onClick:()=>T(!1),children:"Abbrechen"})]})]})}),e.jsx(we,{open:kt,onOpenChange:t=>{t||(Ke(!1),Qe(""))},children:e.jsxs(ye,{className:"max-w-md",children:[e.jsx(ke,{children:e.jsxs(Se,{children:["Flow für ",O.size," Lead",O.size!==1?"s":""," auslösen"]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"WhatsApp-Flow"}),e.jsxs(G,{value:tt,onValueChange:Qe,children:[e.jsx(q,{children:e.jsx(J,{placeholder:"Flow wählenâ¦"})}),e.jsxs(Y,{children:[St.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"Keine aktiven WhatsApp-Flows"}),St.map(t=>e.jsxs(k,{value:`${t.id}:${t.triggerType}`,children:["ð¬ ",t.name," · ",t.triggerType]},t.id))]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Der gewählte Flow wird für alle ausgewählten Leads gestartet â ",e.jsx("strong",{children:"ohne Quellen-Filter"})," (du wählst ihn ja bewusst). Verzögerungen, Ruhezeiten und der 24h-Doppel-Schutz greifen weiter, es entsteht also kein sofortiger Massen-Versand."]}),O.size>100&&e.jsx("p",{className:"text-xs text-amber-500",children:"â Du löst den Flow für mehr als 100 Leads aus â bitte sicher sein."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{className:"flex-1",disabled:!tt||st.isPending,onClick:()=>{const[t,a]=tt.split(":");st.mutate({leadIds:Array.from(O),flowId:Number(t),triggerType:a})},children:st.isPending?"Löst ausâ¦":`Für ${O.size} Lead${O.size!==1?"s":""} auslösen`}),e.jsx(y,{variant:"outline",onClick:()=>{Ke(!1),Qe("")},children:"Abbrechen"})]})]})]})}),e.jsx(wr,{leadId:i,onClose:()=>F(null)})]})}function Sr({rows:s,isError:l,isLoading:f,error:n,onRefetch:N,onOpenDetail:c}){if(l)return e.jsxs("div",{className:"md:hidden p-4 rounded-lg border border-red-500/30 bg-red-500/5",children:[e.jsx("div",{className:"text-red-400 text-sm font-semibold mb-1",children:"â Fehler beim Laden"}),e.jsx("div",{className:"text-xs text-muted-foreground break-words",children:n?.message??"Unbe
21kannter Fehler"}),e.jsx("button",{onClick:N,className:"mt-2 text-xs text-primary underline",children:"Erneut versuchen"})]});if(f)return e.jsx("div",{className:"md:hidden text-center py-8 text-sm text-muted-foreground",children:"Ladeâ¦"});if(s.length===0)return e.jsx("div",{className:"md:hidden text-center py-12 text-sm text-muted-foreground",children:"Keine Leads gefunden."});const $=b=>{if(!b)return"â";const g=typeof b=="number"?b:new Date(b).getTime(),m=Date.now()-g;return m<6e4?"gerade":m<36e5?`${Math.floor(m/6e4)}m`:m<864e5?`${Math.floor(m/36e5)}h`:`${Math.floor(m/864e5)}d`};return e.jsx("div",{className:"md:hidden space-y-2",children:s.map(b=>{const g=Number(b.hotnessScore??0),m=g>=80?"bg-red-500/15 text-red-300 border-red-500/40":g>=50?"bg-amber-500/15 text-amber-300 border-amber-500/30":"bg-zinc-500/10 text-zinc-400 border-border";return e.jsxs("div",{className:"p-3 rounded-lg border border-border bg-card cursor-pointer active:bg-muted/50 transition-colors",onClick:()=>c(b.id),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-semibold text-sm truncate flex items-center gap-1.5",children:[b.firstName," ",b.lastName,b.emailReplyUnread&&e.jsx(qe,{className:"w-3.5 h-3.5 text-emerald-600 shrink-0","aria-label":"Hat per E-Mail geantwortet"})]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:b.brandName??b.brand?.name??"â"}),b.email&&e.jsx("div",{className:"text-xs text-muted-foreground truncate mt-0.5",children:b.email}),b.phone&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:b.phone})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[g>0&&e.jsxs("span",{className:`px-2 py-0.5 rounded text-[10px] font-bold border ${m}`,children:["ð¥ ",g]}),(()=>{const S=b.engagementTier;if(!S)return null;const u={hot:{label:"ð¥ Hot",cls:"bg-red-500/15 text-red-400 border-red-500/30"},warm:{label:"âï¸ Warm",cls:"bg-orange-500/15 text-orange-400 border-orange-500/30"},lukewarm:{label:"ð¥ï¸ Luke",cls:"bg-yellow-500/15 text-yellow-400 border-yellow-500/30"},cold:{label:"âï¸ Cold",cls:"bg-blue-500/15 text-blue-400 border-blue-500/30"},dormant:{label:"ð Dorm",cls:"bg-gray-500/15 text-gray-400 border-gray-500/30"},new:{label:"ð New",cls:"bg-zinc-500/15 text-zinc-400 border-zinc-500/30"}}[S];return u?e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium border ${u.cls}`,children:u.label}):null})(),b.noShowNoFollowup&&e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-medium bg-rose-500/15 text-rose-400 border border-rose-500/40",children:"No-Show"}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:$(b.lastActivityAt??b.createdAt)})]})]}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[b.phone&&e.jsx("a",{href:`tel:${b.phone}`,onClick:S=>S.stopPropagation(),className:"flex-1 text-center text-xs py-2 rounded bg-blue-500/10 text-blue-300 border border-blue-500/30",children:"ð Anrufen"}),b.phone&&e.jsx("a",{href:`https://wa.me/${b.phone.replace(/\D/g,"")}`,target:"_blank",rel:"noreferrer",onClick:S=>S.stopPropagation(),className:"flex-1 text-center text-xs py-2 rounded bg-green-500/10 text-green-300 border border-green-500/30",children:"ð¬ WhatsApp"})]})]},b.id)})})}export{Rr as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.