1import{r as _,u as q,s as R,j as e,d as ze,e as te,X as Ze,v as Fe,a as Qe,aw as He,a5 as Ye,t as Xe}from"./main-C-kKf1tr.js";import{E as D,a as N,K as M,D as G,C as Je}from"./index-6ta8p8NP.js";import{D as Ve}from"./DateRangePicker-D-ZxXqx7.js";import{b as et,f as Q,a as Ie,r as tt,D as st}from"./date-range-DkiLrxEq.js";import{B as H}from"./badge-BWQuo6sg.js";import{C as ae,b as oe,c as le,a as ie}from"./card-vla6AO-c.js";import{S as pe,a as xe,b as fe,c as be,d as W}from"./select-BluAycEh.js";import{u as F}from"./useGTMDataContext-C81N52J7.js";import{R as nt}from"./refresh-cw-aYRxWT7W.js";import{D as rt}from"./DeliverabilityReport-o34wzYfA.js";import{T as at}from"./TemplateScoreboard-uzfIf8hU.js";import"./operator-vocab-fU8Wu3pW.js";import{g as ot,a as ge,t as lt}from"./chart-theme-DNqWPqrk.js";import{S as P}from"./skeleton-D2jGO_Cs.js";import{T as se,a as ne,b as E,c as j,d as re,e as g}from"./table-CvoVy4ka.js";import{u as Oe}from"./useGTMAnalytics-DImOSDGA.js";import{T as Ue}from"./triangle-alert-X4rmetZ9.js";import{R as it,B as ct,z as dt,X as ut,Y as mt,E as ht,F as pt,s as xt}from"./BarChart-BA9M-gP1.js";import{f as _e}from"./money-format-BekJzYpj.js";import{C as ft}from"./circle-alert-Bz62qDOr.js";import{C as bt}from"./calendar-check-C9bz-x7l.js";import{C as gt}from"./circle-check-TKiVhzW2.js";import{D as _t}from"./dollar-sign-QiW6P5iK.js";import{T as yt,a as jt,b as ye}from"./tabs-DuSzx1MW.js";import"./modulepreload-polyfill-B5Qt9EMX.js";import"./minus-jXzpusNS.js";import"./arrow-up-right-ohqp51LZ.js";import"./popover-CpD-wfX0.js";import"./Combination-CqjUFkX9.js";import"./en-US-Ci8aSh8k.js";import"./subDays-CRmmUGUv.js";import"./chevron-right-DEqS0_Tj.js";import"./chevron-left-Bjf7HtCE.js";import"./calendar-D9ym1O1h.js";import"./index-BdQq_4o_.js";import"./index-DLu0yQwV.js";import"./index-uPmhGrQD.js";import"./chevron-up-Be7ARLOX.js";import"./shield-check-BvuaOBsQ.js";import"./formatDistanceToNow-_m-ieCqh.js";import"./string-D05Vy0wW.js";import"./index-DGjD2zNc.js";import"./band-CquvqAHh.js";import"./init-Dmth1JHB.js";import"./ordinal-DILIJJjt.js";import"./linear-D-UfnGzu.js";import"./defaultLocale-DX6XiGOO.js";import"./time-Dg98zhZP.js";import"./index-Bi4RP6KP.js";const We=["sales_attribution","Sales Attribution","contact.sales_attribution","contact.sales attribution","lzT8lgDY26OG8n4L0zNF"];function z(t){return String(t??"").trim().toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9@. ]+/g," ").replace(/\s+/g," ").trim()}function Z(t){return z(t).replace(/[^a-z0-9@.]+/g,"")}function O(t){if(t==null||t==="")return null;if(Array.isArray(t))return t.map(O).find(Boolean)??null;if(typeof t=="object"){const s=t;return O(s.name)??O(s.label)??O(s.value)??O(s.email)??null}return String(t).trim()||null}function Nt(t){const s=We.map(Z);return[t.id,t.key,t.fieldKey,t.name,t.label].map(Z).some(r=>s.includes(r)||r.endsWith("salesattribution"))}function vt(t){if(!t||typeof t!="object")return null;const s=t,r=[s.customFields,s.custom_fields,s.fields].filter(Array.isArray);for(const a of r)for(const l of a)if(Nt(l))return O(l.value??l.fieldValue??l.values);const o=[s.customFields,s.custom_fields,s.fields,s].filter(a=>a&&typeof a=="object"&&!Array.isArray(a)),n=new Set(We.map(Z));for(const a of o)for(const[l,d]of Object.entries(a)){const c=Z(l);if(n.has(c)||c.endsWith("salesattribution"))return O(d)}return null}function wt(t){const s=t.trim();return s?s.split(/\s+/)[0]||s:"Unknown"}function kt(t,s){const r=new Set,o=t.trim();if(o){r.add(o.toLowerCase());const a=o.split(/\s+/).filter(Boolean);a[0]&&r.add(a[0].toLowerCase()),a.length>1&&r.add(a.join(" ").toLowerCase())}const n=(s??"").trim().toLowerCase();if(n){r.add(n);const a=n.split("@")[0];a&&r.add(a)}return[...r].filter(Boolean)}function je(t,s={}){const r=s instanceof Map?s:new Map(Object.entries(s));return(t??[]).map(o=>{const n=(o.full_name??o.email??"Unknown").trim()||"Unknown",a=r.get(o.user_id);return{user_id:o.user_id,name:n,shortName:wt(n),aliases:kt(n,o.email),...a?{channel:a}:{}}})}function St(t,s=[]){return t?s.find(r=>r.user_id===t)??null:null}function Lt(t,s=[]){if(!t)return"Unclassified";const r=z(t),o=s.find(n=>n.aliases.some(a=>r.includes(z(a))));return(o==null?void 0:o.channel)??"Unclassified"}function Ct(t){const s=z(t);return["booked","booked call","call booked","meeting booked","showed","won","closed won","client"].includes(s)}function At(t){const s=z(t);return["won","closed won","client","customer","aeo engine client"].includes(s)}
1function Tt(t,s=new Date,r=30){if(!t)return!1;const o=new Date(t);return Number.isNaN(o.getTime())?!1:o.getTime()>=s.getTime()-r*24*60*60*1e3&&o.getTime()<=s.getTime()}function Ne(t,s,r=new Date,o=30,n=[]){const a=n??[],l=new Map(s.map(i=>[i.id,i])),d=new Map(s.filter(i=>i.ghl_contact_id).map(i=>[i.ghl_contact_id,i])),c=t.filter(i=>Tt(i.created_at,r,o)).map(i=>{const m=i.crm_contact_id&&l.get(i.crm_contact_id)||i.ghl_contact_id&&d.get(i.ghl_contact_id)||null,k=vt({custom_fields:m==null?void 0:m.custom_fields})??null,x=St(i.sales_rep_id,a),v=i.sales_rep_id?"Assigned":"Unassigned",Y=(x==null?void 0:x.name)??v,X=Lt(k,a),U=i.lead_stage||i.stage;return{...i,name:[i.first_name,i.last_name].filter(Boolean).join(" ")||i.email||"Unknown lead",sales_attribution:k,sales_rep_name:Y,sales_rep_short_name:(x==null?void 0:x.shortName)??v,source_channel:X,crm_source:(m==null?void 0:m.source)??null,crm_last_synced_at:(m==null?void 0:m.last_synced_at)||(m==null?void 0:m.updated_at)||null,is_attributable:!!k,is_booked:Ct(U),is_won:At(U)}}).sort((i,m)=>new Date(m.created_at||0).getTime()-new Date(i.created_at||0).getTime()),p=c.filter(i=>i.is_attributable),h=new Map;for(const i of p){const m=i.sales_attribution||"Unknown",k=Z(m)||"unknown",x=h.get(k)||{key:k,label:m,channel:i.source_channel,leads:0,booked:0,won:0,winRate:0,reps:[]};x.leads+=1,i.is_booked&&(x.booked+=1),i.is_won&&(x.won+=1),x.reps.includes(i.sales_rep_name)||x.reps.push(i.sales_rep_name),x.winRate=x.leads?x.won/x.leads:0,h.set(k,x)}const w=[...h.values()].sort((i,m)=>m.leads-i.leads||i.label.localeCompare(m.label)),S=new Set(a.map(i=>i.user_id)),f=[...new Set(c.map(i=>i.sales_rep_id).filter(i=>!!i&&!S.has(i)))],u=[...a,...f.map(i=>({user_id:i,name:"Assigned",shortName:"Assigned",aliases:[]}))].map(i=>{const m=c.filter(x=>x.sales_rep_id===i.user_id),k=[...new Set(m.map(x=>x.sales_attribution).filter(Boolean))].sort();return{user_id:i.user_id,name:i.name,shortName:i.shortName,leads:m.length,attributable:m.filter(x=>x.is_attributable).length,booked:m.filter(x=>x.is_booked).length,won:m.filter(x=>x.is_won).length,winRate:m.length?m.filter(x=>x.is_won).length/m.length:0,sources:k}}).filter(i=>i.leads>0||i.attributable>0),$=new Map;for(const i of p){const m=i.sales_attribution||"Unknown",k=i.sales_rep_short_name,x=`${m}::${k}`,v=$.get(x)||{source:m,closer:k,leads:0,booked:0,won:0};v.leads+=1,i.is_booked&&(v.booked+=1),i.is_won&&(v.won+=1),$.set(x,v)}const b=["Internal","Partner","Unclassified"].map(i=>{const m=p.filter(v=>v.source_channel===i),k=[...new Set(m.map(v=>v.sales_attribution).filter(Boolean))].sort(),x=m.filter(v=>v.is_won).length;return{channel:i,leads:m.length,booked:m.filter(v=>v.is_booked).length,won:x,winRate:m.length?x/m.length:0,labels:k}}).filter(i=>i.leads>0||i.channel!=="Unclassified"),T=[...u].sort((i,m)=>m.attributable-i.attributable||m.leads-i.leads)[0]??null;return{refreshedAt:r.toISOString(),windowDays:o,totals:{scanned:c.length,attributable:p.length,booked:c.filter(i=>i.is_booked).length,won:c.filter(i=>i.is_won).length,unassigned:c.filter(i=>!i.sales_rep_id).length,uniqueSources:w.length,repsRepresented:u.length},topSource:w[0]??null,topRep:T,bySource:w,byRep:u,matrix:[...$.values()].sort((i,m)=>i.source.localeCompare(m.source)||i.closer.localeCompare(m.closer)),funnel:b,leads:c}}function Bt(t){return`${Math.round(t*1e3)/10}%`}const Rt=["id","first_name","last_name","email","company","title","linkedin_url","created_at","updated_at","stage","lead_stage","import_source","discovery_source","email_source","sales_rep_id","ghl_contact_id","crm_contact_id"].join(","),ve="id,ghl_contact_id,source,custom_fields,last_synced_at,updated_at";function Dt(t){return new Date(Date.now()-t*24*60*60*1e3).toISOString()}function $t(){const{dataBrandId:t,isSharedChild:s}=F(),r=_.useMemo(()=>Dt(30),[]);return q({queryKey:["gtm-sales-attribution-dashboard",t,r],enabled:!!t,staleTime:5*6e4,queryFn:async()=>{if(!t)return{...Ne([],[],new Date,30,[]),isSharedChild:!1,truncatedAt:null};const[o,n,a]=await Promise.all([R.from("gtm_operator_channels").select("user_id, channel").eq("company_context_id",t),R.rpc("gtm_operator_profiles_for_context",{p_company_context_id:t}),R.from("gtm_contacts").select(Rt).eq("company_context_id",t).gte("created_at",r).or("suppressed.is.null,suppressed.eq.false").order("created_at",{ascending:!1}).limit(5e3)]),l=new Map;if(o.error)console.warn("attribution channels fetch failed:",o.error.message);else for(const b of o.data??[])(b.channel==="Internal"||b.channel==="Partner")&&l.set(b.user_id,b.channel);let d=je([]);if(n.error?console.warn("attribution roster fetch failed:",n.error.message):d=je(n.data??[],l),a.error)throw a.error;const p=a.data||[],h=p.length===5e3?5e3:null,w=[...new Set(p.map(b=>
1b.crm_contact_id).filter(Boolean))],S=[...new Set(p.map(b=>b.ghl_contact_id).filter(Boolean))],f=[],L=(b,T)=>{const i=[];for(let m=0;m<b.length;m+=T)i.push(b.slice(m,m+T));return i};for(const b of L(w,100)){const{data:T,error:i}=await R.from("crm_contacts").select(ve).in("id",b);if(i)throw i;f.push(...T||[])}const u=S.filter(b=>!f.some(T=>T.ghl_contact_id===b));for(const b of L(u,100)){const{data:T,error:i}=await R.from("crm_contacts").select(ve).eq("company_context_id",t).in("ghl_contact_id",b);if(i)throw i;f.push(...T||[])}return{...Ne(p,f,new Date,30,d),isSharedChild:s,truncatedAt:h}}})}function we(t){return t?new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"}):"â"}function Mt(t,s,r){return!(s!=="all"&&t.sales_attribution!==s||r==="__unassigned__"&&t.sales_rep_id||r!=="all"&&r!=="__unassigned__"&&t.sales_rep_id!==r)}function Et(){const[t,s]=_.useState("all"),[r,o]=_.useState("all"),{data:n,isLoading:a,isError:l,error:d,refetch:c,isFetching:p}=$t(),h=_.useMemo(()=>((n==null?void 0:n.leads)||[]).filter(u=>Mt(u,t,r)),[n==null?void 0:n.leads,t,r]),w=(n==null?void 0:n.totals.attributable)??0,S=(n==null?void 0:n.totals.scanned)??0,f=!a&&!l&&S>0&&w===0,L=!a&&!l&&S===0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("div",{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"First-touch source from the CRM custom field Sales Attribution (last 30 days)."})}),e.jsxs(ze,{variant:"outline",size:"sm",className:"gap-2 self-start",onClick:()=>c(),disabled:p,children:[e.jsx(nt,{size:14,className:p?"animate-spin":""})," Refresh"]})]}),l?e.jsxs("div",{className:"border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-900",children:["Could not load CRM first-touch data: ",(d==null?void 0:d.message)||"unknown error","."]}):null,n!=null&&n.truncatedAt?e.jsxs("div",{className:"border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:["Showing the newest ",n.truncatedAt.toLocaleString()," contacts in this window â the full 30 days has more. Shares and splits below are computed over this subset only."]}):null,a?e.jsx("div",{className:"h-32 animate-pulse rounded-md border border-[#e7e5e4] bg-[#faf9f7]"}):f?e.jsx(D,{title:"Sales Attribution field is not populated",description:`${S.toLocaleString()} contacts were created in the last 30 days, but none have a Sales Attribution value in the CRM. Set that custom field on contacts in GoHighLevel (it syncs into custom fields here) to track first-touch source by rep.`}):L?e.jsx(D,{title:"No contacts in the last 30 days",description:"Once new contacts appear and the Sales Attribution field is set in the CRM, first-touch breakdowns will show here."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"border border-[#e7e5e4] bg-[#faf9f7] px-3 py-3",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.15em] text-muted-foreground",children:"With source"}),e.jsx("p",{className:"mt-1 text-2xl font-semibold tabular-nums",children:w.toLocaleString()}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:["of ",S.toLocaleString()," scanned"]})]}),e.jsxs("div",{className:"border border-[#e7e5e4] bg-[#faf9f7] px-3 py-3",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.15em] text-muted-foreground",children:"Sources"}),e.jsx("p",{className:"mt-1 text-2xl font-semibold tabular-nums",children:(n==null?void 0:n.totals.uniqueSources)??0})]}),e.jsxs("div",{className:"border border-[#e7e5e4] bg-[#faf9f7] px-3 py-3",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.15em] text-muted-foreground",children:"Booked"}),e.jsx("p",{className:"mt-1 text-2xl font-semibold tabular-nums",children:(n==null?void 0:n.totals.booked)??0})]}),e.jsxs("div",{className:"border border-[#e7e5e4] bg-[#faf9f7] px-3 py-3",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.15em] text-muted-foreground",children:"Won"}),e.jsx("p",{className:"mt-1 text-2xl font-semibold tabular-nums",children:(n==null?void 0:n.totals.won)??0})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(ae,{className:"bg-white shadow-sm",children:[e.jsx(oe,{className:"pb-3",children:e.jsx(le,{className:"text-base",children:"By
1source"})}),e.jsx(ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-left text-xs uppercase tracking-[0.12em] text-muted-foreground",children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"py-2 pr-3 font-medium",children:"Source"}),e.jsx("th",{className:"py-2 pr-3 text-right font-medium",children:"Leads"}),e.jsx("th",{className:"py-2 pr-3 text-right font-medium",children:"Booked"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Won"})]})}),e.jsx("tbody",{children:((n==null?void 0:n.bySource)||[]).slice(0,8).map(u=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-3 pr-3 font-medium text-foreground",children:u.label}),e.jsx("td",{className:"py-3 pr-3 text-right tabular-nums",children:u.leads}),e.jsx("td",{className:"py-3 pr-3 text-right tabular-nums",children:u.booked}),e.jsx("td",{className:"py-3 text-right tabular-nums",children:u.won})]},u.key))})]})})})]}),e.jsxs(ae,{className:"bg-white shadow-sm",children:[e.jsx(oe,{className:"pb-3",children:e.jsx(le,{className:"text-base",children:"By sales rep"})}),e.jsx(ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-left text-xs uppercase tracking-[0.12em] text-muted-foreground",children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"py-2 pr-3 font-medium",children:"Sales rep"}),e.jsx("th",{className:"py-2 pr-3 text-right font-medium",children:"Attributed"}),e.jsx("th",{className:"py-2 pr-3 text-right font-medium",children:"Booked"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Won"})]})}),e.jsx("tbody",{children:((n==null?void 0:n.byRep)||[]).map(u=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-3 pr-3 font-medium text-foreground",children:u.name}),e.jsx("td",{className:"py-3 pr-3 text-right tabular-nums",children:u.attributable}),e.jsx("td",{className:"py-3 pr-3 text-right tabular-nums",children:u.booked}),e.jsx("td",{className:"py-3 text-right tabular-nums",children:u.won})]},u.user_id))})]})})})]})]}),e.jsxs(ae,{className:"bg-white shadow-sm",children:[e.jsx(oe,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx(le,{className:"text-base",children:"Lead details"}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:[h.length," visible · refreshed ",we((n==null?void 0:n.refreshedAt)||null)]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs(pe,{value:t,onValueChange:s,children:[e.jsx(xe,{className:"w-full sm:w-[220px]",children:e.jsx(fe,{placeholder:"Source"})}),e.jsxs(be,{children:[e.jsx(W,{value:"all",children:"All sources"}),((n==null?void 0:n.bySource)||[]).map(u=>e.jsx(W,{value:u.label,children:u.label},u.key))]})]}),e.jsxs(pe,{value:r,onValueChange:o,children:[e.jsx(xe,{className:"w-full sm:w-[190px]",children:e.jsx(fe,{placeholder:"Sales rep"})}),e.jsxs(be,{children:[e.jsx(W,{value:"all",children:"All reps"}),((n==null?void 0:n.byRep)||[]).map(u=>e.jsx(W,{value:u.user_id,children:u.name},u.user_id)),e.jsx(W,{value:"__unassigned__",children:"Unassigned"})]})]})]})]})}),e.jsx(ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[720px] text-sm",children:[e.jsx("thead",{className:"text-left text-xs uppercase tracking-[0.12em] text-muted-foreground",children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"py-2 pr-3 font-medium",children:"Lead"}),e.jsx("th",{className:"py-2 pr-3 font-medium",children:"Company"}),e.jsx("th",{className:"py-2 pr-3 font-medium",children:"Source"}),e.jsx("th",{className:"py-2 pr-3 font-medium",children:"Sales rep"}),e.jsx("th",{className:"py-2 font-medium",children:"Created"})]})}),e.jsxs("tbody",{children:[h.slice(0,100).map(u=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-3 pr-3",children:[e.jsx("div",{className:"font-medium text-foreground",children:u.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email||"No email"})]}),e.jsx("td",{className:"py-3 pr-3",children:u.company||"â"}),e.jsx("td",{className:"py-3 pr-3",children:e.jsx(H,{variant:u.sales_attribution?"outline":"secondary",children:u.sales_attribution||"Missing"})}),e.jsx("td",{className:"py-3 pr-3",children:u.sales_rep_name}),e.jsx("td",{className:"py-3",children:we(u.created_at)})]},u.id)),h.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-8 text-center text-muted-foreground",children:"No leads match these filters."})}):null]})]})})})]}),((n==null?void 0:n.funnel)||[]).some(u=>u.leads>0)?e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:((n==null?void 0:n.funnel)||[]).map(u=>e.jsxs("div",{className:`rounded-xl border p-4 ${u.channel==="Partner"?"border-orange-200 bg-orange-50":"border-teal-200 bg-teal-50"}`,children:[e.jsxs("p",{className:"text-sm font-semibold text-foreground",children:[u.channel," sourced"]}),e.jsxs("div",{className:"mt-3 space-y-1.5 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Leads"}),e.jsx("strong",{children:u.leads})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Booked"}),e.jsx("strong",{children:u.booked})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Won"}),e.jsx("strong",{children:u.won})]})]}),e.jsxs("p",{className:"mt-3 text-xs font-medium text-muted-foreground",children:["Lead to win ",Bt(u.winRate)]})]},u.channel))}):null]})]})}const ke={funnel:{sent:0,replied:0,positive_reply:0,booked_call:0,bookings:0,showed:0,no_show:0,won:0,bounced:0,unsubscribed:0,negative_reply:0},rates:{reply_rate:0,positive_reply_rate:0,book_rate:0,show_rate:0,win_rate:0},by_sender:[],by_tier:[],by_campaign:[],by_source:[],by_channel:[],cross_check:{}},Se=24*60*60*1e3;function qt(t){const s=et();if(t.dateRange==="custom"&&t.dateFrom&&t.dateTo){const o=new Date(`${t.dateFrom}T00:00:00.000Z`),n=new Date(new Date(`${t.dateTo}T00:00:00.000Z`).getTime()+Se);return{from:o.toISOString(),to:n.toISOString()}}const r=t.dateRange==="7d"?7:t.dateRange==="90d"?90:30;return{from:new Date(s.getTime()-r*Se).toISOString(),to:s.toISOString()}}function ue(t){const{dataBrandId:s}=F(),r=_.useMemo(()=>qt(t),[t]);return q({queryKey:["gtm-attribution-funnel",s,t,r.from,r.to],enabled:!!s,staleTime:6e4,queryFn:async()=>
1{if(!s)return ke;const{data:o,error:n}=await R.rpc("gtm_attribution_funnel",{p_company_context_id:s,p_tier:t.tier==="all"?null:t.tier,p_sender:t.sender==="all"?null:t.sender,p_campaign_id:t.campaignId==="all"?null:t.campaignId,p_source:!t.source||t.source==="all"?null:t.source,p_date_from:r.from,p_date_to:r.to});if(n)throw n;const a={...ke,...o||{}};return t.source&&t.source!=="all"&&a.by_source.length>0&&(a.by_source=a.by_source.filter(l=>(l.source||l.canonical_source||"").toLowerCase()===t.source.toLowerCase())),a}})}function B(t){return typeof t=="string"&&t.length>0?t:null}function Le(t){const s=Number(t);return Number.isFinite(s)?s:null}function Ce(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Pt(t){return{entity_type:t.entity_type==="deal"?"deal":"booking",entity_id:String(t.entity_id??""),contact_id:B(t.contact_id),email:B(t.email),company:B(t.company),amount:Le(t.amount),event_at:String(t.event_at??""),source:B(t.source)??"unknown",first_touch_utm:Ce(t.first_touch_utm),last_touch_utm:Ce(t.last_touch_utm),click_count:Le(t.click_count)??0,rb2b_company_match:t.rb2b_company_match===!0,first_contacted_at:B(t.first_contacted_at),first_replied_at:B(t.first_replied_at),first_booked_call_at:B(t.first_booked_call_at),self_reported_source_raw:B(t.self_reported_source_raw),self_reported_source:B(t.self_reported_source),won_source:B(t.won_source),outbound_attributed:typeof t.outbound_attributed=="boolean"?t.outbound_attributed:null,booking_status:B(t.booking_status),acquisition_channel:B(t.acquisition_channel)}}async function Ft(t,s,r){const{data:o,error:n}=await R.rpc("gtm_attribution_readout",{p_company_context_id:t,p_from:s,p_to:r});if(n)throw n;return Array.isArray(o)?o.map(Pt):[]}function It(t){const s=new Date(`${t.dateTo}T00:00:00.000Z`);return s.setUTCDate(s.getUTCDate()+1),{from:`${t.dateFrom}T00:00:00.000Z`,to:s.toISOString()}}function Ot(t){const{dataBrandId:s}=F(),r=_.useMemo(()=>Q(t),[t]),o=_.useMemo(()=>It(r),[r]),n=q({queryKey:["gtm-attribution-readout",s,o.from,o.to],enabled:!!s,staleTime:6e4,queryFn:()=>Ft(s,o.from,o.to)});return{data:n.data??[],isLoading:n.isLoading,isError:n.isError,error:n.error}}function Ut(t){if(!t)return"â";const s=new Date(t);return Number.isNaN(s.getTime())?"â":s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"2-digit"})}function Wt(t){const s=typeof t.utm_source=="string"?t.utm_source:null,r=typeof t.utm_medium=="string"?t.utm_medium:null;return s&&r?`${s} / ${r}`:s||(typeof t.referrer=="string"?t.referrer:null)||"â"}const Kt={cancelled:"Cancelled",no_show:"No-show"};function Gt({row:t}){const s=t.booking_status?Kt[t.booking_status]:void 0;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-foreground",children:t.entity_type==="deal"?`Deal${t.amount!=null?` · $${t.amount.toLocaleString()}`:""}`:"Booking"}),s?e.jsx(H,{variant:"outline",className:"text-[10px] font-normal text-muted-foreground",children:s}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t.email||t.company||"Unknown contact"})]})}function zt({row:t}){return e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx("div",{children:e.jsx(H,{variant:"outline",children:t.source})}),e.jsx("div",{className:"text-muted-foreground",children:Wt(t.first_touch_utm)}),e.jsxs("div",{className:"text-muted-foreground",children:[t.click_count," click",t.click_count===1?"":"s",t.rb2b_company_match?" · RB2B match":""]})]})}function Zt({row:t}){return t.self_reported_source_raw?e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx(H,{variant:"secondary",children:t.self_reported_source||"unbucketed"}),e.jsxs("div",{className:"max-w-[220px] truncate text-muted-foreground",title:t.self_reported_source_raw,children:["â",t.self_reported_source_raw,"â"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not answered"})}function Qt({rangeValue:t}){const{data:s,isLoading:r,isError:o,error:n}=Ot(t);return e.jsx(N,{title:"Attribution readout",action:e.jsx("span",{className:"text-xs text-muted-foreground",children:"What software tracked vs. what they told us â shown side by side, not merged"}),children:r?e.jsx(P,{className:"h-40 w-full"}):o?e.jsxs("div",{className:"border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700",children:["Failed to load attribution readout: ",te(n)]}):s.length===0?e.jsx(D,{density:"compact",title:"No bookings or realized deal
1s in this window",description:"Widen the date range to see the software vs. self-reported lens for recent bookings and deals."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(se,{children:[e.jsx(ne,{children:e.jsxs(E,{className:"border-[#e7e5e4] hover:bg-transparent",children:[e.jsx(j,{className:"text-console-label",children:"Entity"}),e.jsx(j,{className:"text-console-label",children:"Date"}),e.jsx(j,{className:"text-console-label",children:"What software tracked"}),e.jsx(j,{className:"text-console-label",children:"What they told us"})]})}),e.jsx(re,{children:s.map(a=>e.jsxs(E,{className:"border-[#e7e5e4]",children:[e.jsx(g,{className:"py-2 align-top",children:e.jsx(Gt,{row:a})}),e.jsx(g,{className:"py-2 align-top text-sm text-muted-foreground",children:Ut(a.event_at)}),e.jsx(g,{className:"py-2 align-top",children:e.jsx(zt,{row:a})}),e.jsx(g,{className:"py-2 align-top",children:e.jsx(Zt,{row:a})})]},`${a.entity_type}-${a.entity_id}`))})]})})})}function I(t){const s=Number(t);return Number.isFinite(s)?s:0}function Ht(t){return typeof t=="string"?t:""}function Yt(t,s=90){const{dataBrandId:r}=F(),o=q({queryKey:["gtm-message-score-breakdown",r,t,s],enabled:!!r,staleTime:6e4,queryFn:async()=>{const{data:n,error:a}=await R.rpc("gtm_message_score_breakdown",{p_ctx:r,p_window_days:s,p_group_by:t});if(a)throw a;return(Array.isArray(n)?n:[]).map(l=>{const d=l;return{bucket:Ht(d.bucket),messages:I(d.messages),replies:I(d.replies),positives:I(d.positives),bookings:I(d.bookings),reply_rate:I(d.reply_rate),positive_rate:I(d.positive_rate),booking_rate:I(d.booking_rate)}})}});return{data:_.useMemo(()=>[...o.data??[]].sort((n,a)=>a.booking_rate-n.booking_rate||a.messages-n.messages),[o.data]),isLoading:o.isLoading,isError:o.isError,error:o.error}}const Xt=[{value:"pain_angle",label:"Angle"},{value:"signal_family",label:"Signal"},{value:"cta_type",label:"CTA"},{value:"icp",label:"ICP"},{value:"sequence_step",label:"Step"}];function Ae(t){return t?t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase()):"Unknown"}function ce(t){return`${Math.round(t*100)}%`}function Jt(){const[t,s]=_.useState("pain_angle"),{data:r,isLoading:o,isError:n,error:a}=Yt(t);return e.jsx(N,{title:"What drives booked calls",action:e.jsx("div",{className:"flex items-center gap-1 rounded-md border border-[#e7e5e4] bg-[#faf9f7] p-1",children:Xt.map(l=>e.jsx("button",{type:"button",onClick:()=>s(l.value),className:`rounded px-2.5 py-1 text-xs transition-colors ${t===l.value?"bg-white text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:l.label},l.value))}),children:o?e.jsx(P,{className:"h-40 w-full"}):n?e.jsxs("div",{className:"border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700",children:["Failed to load message scores: ",te(a)]}):r.length===0?e.jsx(D,{density:"compact",title:"No scored messages in the last 90 days",description:"Outbound messages are scored nightly; the backfill fills history. Rows appear here after the first scoring pass."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(se,{children:[e.jsx(ne,{children:e.jsxs(E,{className:"border-[#e7e5e4] hover:bg-transparent",children:[e.jsx(j,{className:"text-console-label",children:Ae(t==="pain_angle"?"pain_angle":t)}),e.jsx(j,{className:"text-console-label text-right",children:"Scored"}),e.jsx(j,{className:"text-console-label text-right",children:"Replies"}),e.jsx(j,{className:"text-console-label text-right",children:"Positive"}),e.jsx(j,{className:"text-console-label text-right",children:"Booked"}),e.jsx(j,{className:"text-console-label text-right",children:"Reply rate"}),e.jsx(j,{className:"text-console-label text-right",children:"Positive rate"}),e.jsx(j,{className:"text-console-label text-right",children:"Booking rate"})]})}),e.jsx(re,{children:r.map(l=>e.jsxs(E,{className:"border-[#e7e5e4]",children:[e.jsx(g,{className:"font-medium text-foreground",children:Ae(l.bucket)}),e.jsx(g,{className:"text-right tabular-nums text-stone-600",children:l.messages.toLocaleString()}),e.jsx(g,{className:"text-right tabular-nums text-stone-600",children:l.replies.toLocaleStr
1ing()}),e.jsx(g,{className:"text-right tabular-nums text-stone-600",children:l.positives.toLocaleString()}),e.jsx(g,{className:"text-right tabular-nums text-stone-600",children:l.bookings.toLocaleString()}),e.jsx(g,{className:"text-right tabular-nums text-stone-600",children:ce(l.reply_rate)}),e.jsx(g,{className:"text-right tabular-nums text-stone-600",children:ce(l.positive_rate)}),e.jsx(g,{className:"text-right font-medium tabular-nums text-foreground",children:ce(l.booking_rate)})]},l.bucket||"unknown"))})]})})})}function K(t){const s=Number(t??0);return Number.isFinite(s)?s:0}function Te(t,s){return s?Math.round(t/s*1e3)/10:null}function Vt(){const{dataBrandId:t}=F();return q({queryKey:["gtm-source-performance",t],enabled:!!t,staleTime:6e4,queryFn:async()=>{if(!t)return[];const[{data:s,error:r},{data:o,error:n}]=await Promise.all([R.from("gtm_source_performance").select("import_source, track, icp_id, contacts, sequenced, positive, booked, won").eq("company_context_id",t),R.from("apollo_icp_configs").select("icp_id, persona_label").eq("company_context_id",t)]);if(r)throw r;const a=new Map;if(!n)for(const c of o??[])c.icp_id&&c.persona_label&&a.set(c.icp_id,c.persona_label);const l=new Map;for(const c of s??[]){const p=c.icp_id||"unassigned";l.has(p)||l.set(p,{icpId:p,icpLabel:a.get(p)||(p==="unassigned"?"No ICP assigned":p),contacts:0,sequenced:0,positive:0,booked:0,won:0,meetingsPer100Sequenced:null,sources:[]});const h=l.get(p),w=K(c.contacts),S=K(c.sequenced),f=K(c.positive),L=K(c.booked),u=K(c.won);h.contacts+=w,h.sequenced+=S,h.positive+=f,h.booked+=L,h.won+=u,h.sources.push({importSource:c.import_source||"unknown",track:c.track||"",contacts:w,sequenced:S,positive:f,booked:L,won:u,meetingsPer100Sequenced:Te(L,S)})}const d=[...l.values()].map(c=>({...c,meetingsPer100Sequenced:Te(c.booked,c.sequenced),sources:c.sources.sort((p,h)=>h.sequenced-p.sequenced)}));return d.sort((c,p)=>p.sequenced-c.sequenced),d}})}function es(){const{data:t,isLoading:s,isError:r}=Vt(),o=t??[];return e.jsx(N,{title:"Results per audience",children:s?e.jsx(P,{className:"h-40 w-full"}):r?e.jsx("div",{className:"border border-red-200 bg-red-50 px-4 py-6 text-sm text-red-700",children:"Failed to load audience results."}):o.length===0?e.jsx(D,{density:"compact",title:"No audience results for this brand"}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(se,{children:[e.jsx(ne,{children:e.jsxs(E,{children:[e.jsx(j,{children:"Audience"}),e.jsx(j,{className:"text-right",children:"Sequenced"}),e.jsx(j,{className:"text-right",children:"Booked"}),e.jsx(j,{className:"text-right",children:"Meetings per 100 sequenced"})]})}),e.jsx(re,{children:o.map(n=>e.jsxs(e.Fragment,{children:[e.jsxs(E,{children:[e.jsx(g,{className:"font-medium",children:n.icpLabel}),e.jsx(g,{className:"text-right tabular-nums",children:n.sequenced.toLocaleString()}),e.jsx(g,{className:"text-right tabular-nums",children:n.booked.toLocaleString()}),e.jsx(g,{className:"text-right tabular-nums",children:n.meetingsPer100Sequenced===null?"â":n.meetingsPer100Sequenced})]},n.icpId),n.sources.map(a=>e.jsxs(E,{className:"bg-stone-50/70 text-xs text-muted-foreground",children:[e.jsxs(g,{className:"pl-8",children:["â³ ",a.importSource,a.track?` · ${a.track}`:""]}),e.jsx(g,{className:"text-right tabular-nums",children:a.sequenced.toLocaleString()}),e.jsx(g,{className:"text-right tabular-nums",children:a.booked.toLocaleString()}),e.jsx(g,{className:"text-right tabular-nums",children:a.meetingsPer100Sequenced===null?"â":a.meetingsPer100Sequenced})]},`${n.icpId}:${a.importSource}:${a.track}`))]}))})]})})})}function ts({rangeValue:t}){var a,l;const{data:s}=Oe(t),r=s==null?void 0:s.operationalKpis,o=r==null?void 0:r.activeEmailOutreach,n=r==null?void 0:r.activeLinkedinOutreach;return e.jsx(N,{title:"Email vs LinkedIn",children:e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(M,{label:"Active email outreach",value:((a=o==null?void 0:o.value)==null?void 0:a.toLocaleString())??"â",delta:e.jsx(G,{current:o==null?void 0:o.current,previous:o==null?void 0:o.previous,unavailable:!!(o!=null&&o.error)})}),e.jsx(M,{label:"Active LinkedIn outreach",value:((l=n==null?void 0:n.value)==null?void 0:l.toLocaleStr
1ing())??"â",delta:e.jsx(G,{current:n==null?void 0:n.current,previous:n==null?void 0:n.previous,unavailable:!!(n!=null&&n.error)})})]})})}function A(t){const s=Number(t??0);return Number.isFinite(s)?s:0}function ss(t){var l,d;const s=t&&typeof t=="object"?t:{},r=s.overturn_breakdown&&typeof s.overturn_breakdown=="object"?s.overturn_breakdown:{},o=Array.isArray(s.by_scenario)?s.by_scenario.map(c=>({scenario:String(c.scenario??"unknown"),overturns:A(c.overturns)})):[],n=s.weekly_accuracy,a=n==null||n===""?null:Number.isFinite(Number(n))?Number(n):null;return{range:{from:String(((l=s.range)==null?void 0:l.from)??""),to:String(((d=s.range)==null?void 0:d.to)??"")},inbound_conversations:A(s.inbound_conversations),auto_handled:A(s.auto_handled),escalated:A(s.escalated),escalation_rate:A(s.escalation_rate),human_reviewed:A(s.human_reviewed),overturns:A(s.overturns),overturn_rate:A(s.overturn_rate),overturn_breakdown:{rejects:A(r.rejects),material_edits:A(r.material_edits),decide_disagrees:A(r.decide_disagrees),relabels:A(r.relabels),flags:A(r.flags)},flags_raised:A(s.flags_raised),by_scenario:o,weekly_accuracy:a}}async function Be(t,s,r){const{data:o,error:n}=await R.rpc("gtm_reply_ops_metrics",{p_company_context_id:t,p_from:s,p_to:r});if(n)throw n;return ss(o)}function Re(t){const s=new Date(`${t.dateTo}T00:00:00.000Z`);return s.setUTCDate(s.getUTCDate()+1),{from:`${t.dateFrom}T00:00:00.000Z`,to:s.toISOString()}}function ns(t){const{dataBrandId:s}=F(),r=_.useMemo(()=>Q(t),[t]),o=_.useMemo(()=>Ie(t),[t]),n=_.useMemo(()=>Re(r),[r]),a=_.useMemo(()=>o?Re(o):null,[o]),l=_.useMemo(()=>tt(t).label,[t]),d=q({queryKey:["gtm-reply-ops-metrics",s,n.from,n.to],enabled:!!s,staleTime:6e4,queryFn:()=>Be(s,n.from,n.to)}),c=q({queryKey:["gtm-reply-ops-metrics",s,a==null?void 0:a.from,a==null?void 0:a.to],enabled:!!(s&&a),staleTime:6e4,queryFn:async()=>a?Be(s,a.from,a.to):null});return{data:d.data,previous:c.data??null,isLoading:d.isLoading,isError:d.isError,error:d.error,label:l}}function me(t,s=1){return t==null||!Number.isFinite(t)?"â":`${Number(t.toFixed(s))}%`}function rs(t){if(t==null||!Number.isFinite(t))return"â";const s=t<=1?t*100:t;return me(s,1)}function as({rangeValue:t}){const{data:s,previous:r,isLoading:o,isError:n,error:a,label:l}=ns(t);if(o)return e.jsx(N,{title:"Engine accuracy",children:e.jsx(P,{className:"h-28 w-full"})});if(n)return e.jsx(N,{title:"Engine accuracy",children:e.jsxs("div",{className:"border border-red-200 bg-red-50 px-4 py-6 text-sm text-red-700",children:["Failed to load reply ops metrics: ",te(a)]})});if(!s)return e.jsx(N,{title:"Engine accuracy",children:e.jsx(D,{density:"compact",title:"Select a brand to load engine accuracy"})});if(!(s.inbound_conversations>0||s.human_reviewed>0||s.flags_raised>0))return e.jsx(N,{title:"Engine accuracy",children:e.jsx(D,{density:"compact",title:"No reply activity in this window",description:"Inbound conversations and human reviews in the selected range will show overturn and escalation rates here."})});const c=s.weekly_accuracy==null?null:s.weekly_accuracy<=1?s.weekly_accuracy*100:s.weekly_accuracy,p=(r==null?void 0:r.weekly_accuracy)==null?null:r.weekly_accuracy<=1?r.weekly_accuracy*100:r.weekly_accuracy;return e.jsxs(N,{title:"Engine accuracy",action:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:l}),children:[e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[e.jsx(M,{label:"Weekly accuracy",value:rs(s.weekly_accuracy),caption:s.weekly_accuracy==null?"Eval runs not yet recorded":"From latest eval run in range",delta:e.jsx(G,{current:c,previous:p,unavailable:c==null&&p==null})}),e.jsx(M,{label:"Overturn rate",value:me(s.overturn_rate),caption:`${s.overturns.toLocaleString()} of ${s.human_reviewed.toLocaleString()} reviewed · aspire <5%`,delta:e.jsx(G,{current:s.overturn_rate,previous:r==null?void 0:r.overturn_rate,unavailable:r==null})}),e.jsx(M,{label:"Escalation rate",value:me(s.escalation_rate),caption:`${s.escalated.toLocaleString()} of ${s.inbound_conversations.toLocaleString()} inbound · band 10â15%`,delta:e.jsx(G,{current:s.escalation_rate,previous:r==null?void 0:r.escalation_rate,unavailable:r==null})})]}),s.flags_raised>0||s.overturn_breakdown.rejects>0||s.overturn_breakdown.material_edits>0?e.jsxs("p",{className:"mt-3 text-[11px] text-stone-500",children:["Overturns this window: ",s.overturn_breakdown.rejects," rejects ·"," ",s.overturn_breakdown.material_edits," material edits ·"," ",s.overturn_breakdown.decide_disagrees," decide disagrees ·"," ",s.flags_raised," flags",s.overturn_breakdown.relabels>0?` (${s.overturn_breakdown.relabels} re-labels)`:"","."]}):null]})}function De(t,s){if(!t)return null;const r=Math.max(t-s,0);return Math.round(r/t*1e3)/10}function os(t,s){const r=new Map((s??[]).map(o=>[o.key,o.count]));return t.map((o,n)=>{if(n===0)return{key:o.key,label:o.label,fromLabel:"",count:o.count,dropoffPct:null,compareDropoffPct:null};const a=t[n-1],l=De(a.count,o.count),d=r.get(a.key),c=r.get(o.key),p=d!==void 0&&c!==void 0?De(d,c):null;return{key:o.key,label:o.label,fromLabel:a.label,count:o.count,dropoffPct:l,compareDropoffPct:p}})}function ls(t){const s=t.filter(r=>r.dropoffPct!==null);return s.length===0?null:s.reduce((r,o)=>o.dropoffPct>r.dropoffPct?o:r)}function is(t){const s=ls(t);if(!s||s.dropoffPct===null)return"Not enough data yet to call out a weak step.";let r="";return s.compareDropoffPct!==null&&(s.dropoffPct>s.compareDropoffPct?r=` â worse than the ${s.compareDropoffPct}% drop last period`:s.dropoffPct<s.compareDropoffPct?r=` â better than the ${s.compareDropoffPct}% drop last period`:r=" â unchanged from last period"),`The biggest leak is ${s.fromLabel} to ${s.label}: ${s.dropoffPct}% never make it through${r}.`}const cs=[{key:"sent",label:"Sent"},{key:"replied",label:"Replied"},{key:"positive_reply",label:"Positive"}],ds=["bg-teal-700","bg-teal-600","bg-teal-500"];function $e(t){return cs.map(s=>({key:s.key,label:s.label,count:Number((t==null?void 0:t[s.key])??0)}))}function us({rangeValue:t}){var c,p;const s=_.useMemo(()=>({tier:"all",sender:"all",campaignId:"all",source:"all",dateRange:"custom",...Q(t)}),[t]),r=_.useMemo(()=>Ie(t),[t]),o=_.useMemo(()=>r?{tier:"all",sender:"all",campaignId:"all",source:"all",dateRange:"custom",...r}:null,[r]),n=ue(s),a=ue(o??s);if(n.isLoading)return e.jsx(N,{title:"Funnel drop-off",children:e.jsx(P,{className:"h-64 w-full"})});if(n.isError)return e.jsx(N,{title:"Funnel drop-off",children:e.jsx("div",{className:"border border-red-200 bg-red-50 px-4 py-6 text-sm text-red-700",children:"Failed to load funnel drop-off data."})});if(!n.data||Number(((c=n.data.funnel)==null?void 0:c.sent)??0)===0)return e.jsx(N,{title:"Funnel drop-off",children:e.jsx(D,{density:"compact",title:"No outreach in this window"})});const l=os($e(n.data.funnel),r?$e((p=a.data)==null?void 0:p.funnel):void 0),d=Math.max(...l.map(h=>
1h.count),1);return e.jsxs(N,{title:"Funnel drop-off",children:[e.jsx("div",{className:"space-y-3",children:l.map((h,w)=>e.jsxs("div",{className:"grid grid-cols-[6rem_1fr_auto] items-center gap-3 text-sm",children:[e.jsx("span",{className:"font-medium text-stone-700",children:h.label}),e.jsx("div",{className:"h-7 overflow-hidden rounded-sm bg-stone-100",children:e.jsx("div",{className:`h-full ${ds[w]} rounded-sm`,style:{width:`${Math.max(h.count/d*100,h.count?2:0)}%`}})}),e.jsxs("span",{className:"min-w-24 text-right tabular-nums text-stone-600",children:[h.count.toLocaleString()," · ",h.dropoffPct===null?"â":`${h.dropoffPct}% drop`]})]},h.key))}),e.jsxs("div",{className:"mt-5 flex items-start gap-2 border border-amber-200 bg-amber-50 px-3 py-3 text-sm text-amber-900",children:[e.jsx(Ue,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:is(l)})]})]})}const ms=[["positive","Positive"],["negative","Negative"],["neutral","Neutral"],["solicitation","Solicitation"],["ooo","Out of office"],["bounce","Bounce"],["unsubscribe","Unsubscribe"]],de=t=>t==null?"â":`${Math.round(t*100)}%`;function hs({rangeValue:t}){var a;const{data:s,isLoading:r}=Oe(t),o=(a=s==null?void 0:s.operationalKpis)==null?void 0:a.replyMix,n=o==null?void 0:o.current;return e.jsx(N,{title:"Reply mix",children:r?e.jsx(P,{className:"h-48 w-full"}):n?e.jsxs("div",{className:"space-y-4",children:[o.negativeShareRising&&o.previousNegativeShare!==null&&o.negativeShare!==null?e.jsxs("div",{className:"flex items-center gap-2 border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900",children:[e.jsx(Ue,{className:"h-4 w-4 shrink-0"}),"Negative replies are rising â up from ",de(o.previousNegativeShare)," to ",de(o.negativeShare)," of the mix."]}):null,e.jsx("div",{className:"space-y-3",children:ms.map(([l,d])=>{const c=n.shares[l]??0,p=n.counts[l]??0;return e.jsxs("div",{className:"grid grid-cols-[8rem_1fr_auto] items-center gap-3 text-sm",children:[e.jsx("span",{className:"text-stone-700",children:d}),e.jsx("div",{className:"h-2 rounded-full bg-stone-100",children:e.jsx("div",{className:"h-full rounded-full bg-teal-600",style:{width:`${Math.max(c*100,c?2:0)}%`}})}),e.jsxs("span",{className:"min-w-20 text-right tabular-nums text-stone-600",children:[de(c)," · ",p.toLocaleString()]})]},l)})})]}):e.jsx(D,{density:"compact",title:"No reply mix data for this window"})})}const Ke=[{value:"source",label:"By source"},{value:"campaign",label:"By campaign"},{value:"sender",label:"By sender"},{value:"tier",label:"By tier"},{value:"channel",label:"By channel"}],ps=[{key:"sent",label:"Sent",href:null},{key:"replied",label:"Replied",href:"/dashboard/contacts?stage=warm"},{key:"positive_reply",label:"Positive",href:"/dashboard/contacts?stage=hot"},{key:"booked_call",label:"Booked",href:"/dashboard/contacts?stage=closing"},{key:"won",label:"Won",href:"/dashboard/contacts?stage=won"}],Me=["#0f766e","#0d9488","#14b8a6","#2dd4bf","#5eead4"],Ee=50;function xs(t,s){switch(t){case"source":return s.canonical_source||s.source||"Unknown";case"campaign":return s.name||s.campaign_id||"Unknown";case"sender":return s.sender||"Unknown";case"tier":return s.tier?s.tier.charAt(0).toUpperCase()+s.tier.slice(1):"Unknown";case"channel":return s.channel?s.channel.charAt(0).toUpperCase()+s.channel.slice(1):"Unknown"}}function fs(t,s){switch(t){case"source":return s.canonical_source||s.source||"";case"campaign":return s.campaign_id||"";case"sender":return s.sender||"";case"tier":return s.tier||"";case"channel":return""}}function bs(t,s){return s?`${Math.round((t??0)/s*1e3)/10}%`:"â"}function y(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function J(t){return typeof t!="number"||!Number.isFinite(t)?"â":`${Math.round(t*1e3)/10}%`}function gs(t){const s=[...t].filter(a=>y(a.sent)>0||y(a.replied)>0||y(a.won)>0).sort((a,l)=>y(l.sent)-y(a.sent)),r=s.slice(0,Ee),o=s.slice(Ee);if(o.length===0)return{top:r,other:null};const n=o.reduce((a,l)=>({sent:a.sent+y(l.sent),replied:a.replied+y(l.replied),positive_reply:a.positive_reply+y(l.positive_reply),booked_call:a.booked_call+y(l.booked_call),won:a.won+y(l.won),count:a.count+1}),{sent:0,replied:0,positive_reply:0,booked_call:0,won:0,count:0});return{top:r,other:n}}function _s({rows:t,dimension:s,activeKeyValue:r,onSelect:o}){var d;const{top:n,other:a}=_.useMemo(()=>gs(t),[t]);if(n.length===0&&!a)return e.jsx(D,{density:"compact",title:"No breakdown data for this window"});const l=(c,p,h,w,S,f,L,u)=>{const $=!!L;return e.jsxs(E,{onClick:$?()=>o(L):void 0,className:`border-[#e7e5e4] ${$?"cursor-pointer hover:bg-[#faf9f7]":""} ${$&&L===r?"bg-teal-50/60":""}`,children:[e.jsx(g,{className:"py-2 font-medium text-foreground",children:c}),e.jsx(g,{className:"py-2 text-right tabular-nums",children:p.toLocaleStr
1ing()}),e.jsx(g,{className:"py-2 text-right tabular-nums",children:h.toLocaleString()}),e.jsx(g,{className:"py-2 text-right tabular-nums",children:bs(h,p)}),e.jsx(g,{className:"py-2 text-right tabular-nums",children:w.toLocaleString()}),e.jsx(g,{className:"py-2 text-right tabular-nums",children:S.toLocaleString()}),e.jsx(g,{className:"py-2 text-right tabular-nums",children:f.toLocaleString()})]},u)};return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(se,{children:[e.jsx(ne,{children:e.jsxs(E,{className:"border-[#e7e5e4] hover:bg-transparent",children:[e.jsx(j,{className:"text-console-label",children:(d=Ke.find(c=>c.value===s))==null?void 0:d.label.replace("By ","")}),e.jsx(j,{className:"text-right text-console-label",children:"Sent"}),e.jsx(j,{className:"text-right text-console-label",children:"Replies"}),e.jsx(j,{className:"text-right text-console-label",children:"Reply %"}),e.jsx(j,{className:"text-right text-console-label",children:"Positive"}),e.jsx(j,{className:"text-right text-console-label",children:"Booked"}),e.jsx(j,{className:"text-right text-console-label",children:"Won"})]})}),e.jsxs(re,{children:[n.map((c,p)=>l(xs(s,c),y(c.sent),y(c.replied),y(c.positive_reply),y(c.booked_call),y(c.won),fs(s,c),`r${p}`)),a?l(`Other (${a.count})`,a.sent,a.replied,a.positive_reply,a.booked_call,a.won,"","other"):null]})]})})}function ys({funnel:t}){const s=Fe(),r=ps.map(n=>({stage:n.label,count:y(t==null?void 0:t[n.key]),href:n.href})),o=Math.max(...r.map(n=>n.count),1);return e.jsx("div",{className:"h-64",children:e.jsx(it,{width:"100%",height:"100%",children:e.jsxs(ct,{data:r,margin:{top:8,right:8,bottom:0,left:-16},children:[e.jsx(dt,{...ot}),e.jsx(ut,{dataKey:"stage",...ge}),e.jsx(mt,{...ge,domain:[0,Math.ceil(o*1.1)],allowDecimals:!1}),e.jsx(ht,{...lt}),e.jsx(pt,{dataKey:"count",name:"Contacts",radius:[4,4,0,0],onClick:n=>{n!=null&&n.href&&s(n.href)},children:r.map((n,a)=>e.jsx(xt,{fill:Me[a%Me.length],cursor:n.href?"pointer":void 0},a))})]})})})}function js({rangeValue:t}){var v,Y,X,U;const{dataBrandId:s}=F(),[r,o]=_.useState("all"),[n,a]=_.useState("all"),[l,d]=_.useState("all"),[c,p]=_.useState("all"),[h,w]=_.useState("source"),S=_.useMemo(()=>({tier:r,sender:n,campaignId:l,source:c,dateRange:"custom",...Q(t)}),[t,r,n,l,c]),{data:f,isLoading:L,isError:u,error:$}=ue(S),b=f==null?void 0:f.funnel,T=_.useMemo(()=>{if(!f)return[];switch(h){case"source":return f.by_source;case"campaign":return f.by_campaign;case"sender":return f.by_sender;case"tier":return f.by_tier;case"channel":return f.by_channel}},[f,h]),i=h==="channel"?"":h==="source"?c:h==="campaign"?l:h==="sender"?n:r,m=C=>{h==="source"?p(C):h==="campaign"?d(C):h==="sender"?a(C):h==="tier"&&o(C)},k=[{key:"tier",label:`Tier: ${r}`,show:r!=="all",clear:()=>o("all")},{key:"source",label:`Source: ${c}`,show:c!=="all",clear:()=>p("all")},{key:"campaign",label:`Campaign: ${l}`,show:l!=="all",clear:()=>d("all")},{key:"sender",label:`Sender: ${n}`,show:n!=="all",clear:()=>a("all")}].filter(C=>C.show),x=y(b==null?void 0:b.sent);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(as,{rangeValue:t}),e.jsx(us,{rangeValue:t}),e.jsx(es,{}),e.jsx(ts,{rangeValue:t}),e.jsx(N,{title:"Message performance",children:e.jsx(at,{})}),e.jsx(Jt,{}),e.jsx(hs,{rangeValue:t}),e.jsx(N,{title:"Deliverability",children:e.jsx(rt,{})}),e.jsxs("div",{className:"space-y-4",children:[k.length>0?e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:k.map(C=>e.jsxs("button",{type:"button",onClick:C.clear,className:"inline-flex items-center gap-1.5 rounded-md border border-[#e7e5e4] bg-[#faf9f7] px-2.5 py-1 text-xs text-stone-700 hover:border-teal-700/40 hover:bg-teal-50/50",children:[C.label,e.jsx(Ze,{size:12,className:"text-muted-foreground"})]},C.key))}):null,L?e.jsxs("div",{className:"space-y-4",children:[e.jsx(P,{className:"h-24 w-full"}),e.jsx(P,{className:"h-72 w-full"})]}):u?e.jsxs("div",{className:"border border-red-200 bg-red-50 px-4 py-6 text-sm text-red-700",children:["Failed to load attribution funnel: ",te($)]}):s?!b||x===0?e.jsx(D,{title:"No outreach in this window",description:"No sends were recorded for the selected range and filters. Try a wider range or clear filters."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 md:grid-cols-4",children:[e.jsx(M,{label:"Reply rate",value:J((v=f==null?void 0:f.rates)==null?void 0:v.reply_rate),caption:`${y(b.replied)} of ${x}`,href:"/dashboard/contacts?stage=warm"}),e.jsx(M,{label:"Positive reply rate",value:J((Y=f==null?void 0:f.rates)==null?void 0:Y.positive_reply_rate),caption:`${y(b.positive_reply
1)} of ${y(b.replied)}`,href:"/dashboard/contacts?stage=hot"}),e.jsx(M,{label:"Book rate",value:J((X=f==null?void 0:f.rates)==null?void 0:X.book_rate),caption:`${y(b.booked_call)} of ${x}${y(b.bookings)!==y(b.booked_call)?` · ${y(b.bookings)} bookings`:""}`,href:"/dashboard/contacts?stage=closing"}),e.jsx(M,{label:"Win rate",value:J((U=f==null?void 0:f.rates)==null?void 0:U.win_rate),caption:`${y(b.won)} of ${x}`,href:"/dashboard/contacts?stage=won"})]}),e.jsx(N,{title:"Cohort milestones",children:e.jsx(ys,{funnel:b})}),e.jsx(N,{title:"Breakdown",action:e.jsx("div",{className:"flex items-center gap-1 rounded-md border border-[#e7e5e4] bg-[#faf9f7] p-1",children:Ke.map(C=>e.jsx("button",{type:"button",onClick:()=>w(C.value),className:`rounded px-2.5 py-1 text-xs transition-colors ${h===C.value?"bg-white text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:C.label},C.value))}),children:e.jsx(_s,{rows:T,dimension:h,activeKeyValue:i,onSelect:m})})]}):e.jsx(D,{title:"Select a brand to load diagnostics",description:"The diagnostics view reads from your active brand's GTM context."})]}),e.jsx(N,{title:"CRM first-touch",children:e.jsx(Et,{})}),e.jsx(Qt,{rangeValue:t})]})}const he=["seo","aeo","linkedin","content","community","email","referral","paid","lg","direct","unattributed"],Ns={seo:"Organic Search / SEO",aeo:"AI Search / AEO",linkedin:"LinkedIn Inbound",content:"Content / Social",community:"Podcast / Community",email:"Email / Newsletter",referral:"Referral / Word of Mouth",paid:"Paid",lg:"Outbound / Lead Gen",direct:"Direct",unattributed:"Unattributed"},qe={booked:0,attended:0,won:0,revenue:0},vs=new Set(he);function V(t){const s=Number(t??0);return Number.isFinite(s)&&s>0?s:0}function ws(t){const s=typeof t=="string"?t.trim().toLowerCase():"";return vs.has(s)?s:"unattributed"}function ks(t){const s=new Map(he.map(n=>[n,{...qe}]));if(Array.isArray(t))for(const n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;const a=n,l=ws(a.channel),d=s.get(l);d.booked+=V(a.booked),d.attended+=V(a.attended),d.won+=V(a.won),d.revenue+=V(a.revenue)}const r=he.map(n=>({channel:n,label:Ns[n],...s.get(n)})),o=r.reduce((n,a)=>({booked:n.booked+a.booked,attended:n.attended+a.attended,won:n.won+a.won,revenue:n.revenue+a.revenue}),{...qe});return{channels:r,totals:o}}function Pe(t){return typeof t=="string"&&t.length>0?t:null}function Ge(t){const s=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=s.range&&typeof s.range=="object"&&!Array.isArray(s.range)?s.range:{},o=ks(s.channels);return{range:{from:Pe(r.from),to:Pe(r.to)},...o}}function Ss(t){const s=Q(t),r=new Date(`${s.dateTo}T00:00:00.000Z`);return r.setUTCDate(r.getUTCDate()+1),{from:`${s.dateFrom}T00:00:00.000Z`,to:r.toISOString()}}async function Ls(t,s,r){const{data:o,error:n}=await R.rpc("gtm_acquisition_outcomes",{p_company_context_id:t,p_from:s,p_to:r});if(n)throw n;return Ge(o)}function Cs(t,s={}){const{dataBrandId:r}=F(),o=_.useMemo(()=>Ss(t),[t]),n=q({queryKey:["gtm-acquisition-outcomes",r,o.from,o.to],enabled:!!r&&(s.enabled??!0),staleTime:6e4,queryFn:()=>Ls(r,o.from,o.to)});return{...n,outcomes:n.data??Ge(null)}}function As(t,s){return s<=0?"â":`${Math.round(t/s*100)}%`}function ee({label:t,value:s,detail:r,icon:o}){return e.jsxs("div",{className:"rounded-lg border border-stone-200 bg-white p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs font-medium uppercase tracking-wide text-stone-500",children:[e.jsx("span",{children:t}),e.jsx(o,{className:"h-4 w-4 text-stone-400"})]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold text-stone-900",children:s}),e.jsx("p",{className:"mt-1 text-xs text-stone-500",children:r})]})}function Ts(t){return t.filter(s=>s.booked>0||s.attended>0||s.won>0||s.revenue>0).sort((s,r)=>r.booked-s.booked||r.revenue-s.revenue||s.label.localeCompare(r.label))}function Bs({rangeValue:t}){const{outcomes:s,isLoading:r,isError:o,error:n}=Cs(t),a=Ts(s.channels);if(r)return e.jsxs("div",{className:"flex h-56 items-center justify-center gap-2 text-sm text-stone-500",children:[e.jsx(Qe,{className:"h-5 w-5 animate-spin"}),"Loading acquisition outcomesâ¦"]});if(o)return e.jsxs("div",{className:"rounded-lg border border-red-200 bg-red-50 p-5 text-sm text-red-700",children:["Could not load acquisition outcomes: ",n instanceof Error?n.message:"Unknown error"]});const l=s.totals;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950",children:[e.jsx(ft,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Qualification stages are not historically instrumented"}),e.jsx("p",{className:"mt-0.5 text-xs text-amber-800",children:"Storm has no trustworthy dated MQL, SQL or Proposal events yet, so this report starts at real bookings and does not reconstruct history from today's contact stage."})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(ee,{label:"Booked",value:l.booked.toLocaleStr
1ing(),detail:"Real calendar bookings",icon:bt}),e.jsx(ee,{label:"Attended",value:l.attended.toLocaleString(),detail:`${As(l.attended,l.booked)} of booked`,icon:He}),e.jsx(ee,{label:"Won",value:l.won.toLocaleString(),detail:"Closed in selected period",icon:gt}),e.jsx(ee,{label:"Realized revenue",value:_e(l.revenue,"USD",0),detail:"Recorded non-estimate deals",icon:_t})]}),e.jsxs("section",{className:"overflow-hidden rounded-lg border border-stone-200 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-stone-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-stone-900",children:"Outcomes by acquisition channel"}),e.jsx("p",{className:"text-xs text-stone-500",children:"Event dates stay fixed when a contact later progresses."})]}),e.jsxs(H,{variant:"outline",children:[a.length," active channels"]})]}),a.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-stone-500",children:"No booked, attended or won outcomes in this period."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[680px] text-sm",children:[e.jsx("thead",{className:"bg-stone-50 text-left text-xs uppercase tracking-wide text-stone-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2.5 font-medium",children:"Channel"}),e.jsx("th",{className:"px-4 py-2.5 text-right font-medium",children:"Booked"}),e.jsx("th",{className:"px-4 py-2.5 text-right font-medium",children:"Attended"}),e.jsx("th",{className:"px-4 py-2.5 text-right font-medium",children:"Won"}),e.jsx("th",{className:"px-4 py-2.5 text-right font-medium",children:"Recorded revenue"})]})}),e.jsx("tbody",{className:"divide-y divide-stone-100",children:a.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-3 font-medium text-stone-900",children:d.label}),e.jsx("td",{className:"px-4 py-3 text-right font-mono",children:d.booked}),e.jsx("td",{className:"px-4 py-3 text-right font-mono",children:d.attended}),e.jsx("td",{className:"px-4 py-3 text-right font-mono",children:d.won}),e.jsx("td",{className:"px-4 py-3 text-right font-mono",children:d.revenue>0?_e(d.revenue,"USD",0):"â"})]},d.channel))})]})})]})]})}function Cn(){const[t,s]=_.useState(st),r=Ye(),o=Fe(),[n]=Xe(),a=r.pathname.endsWith("/acquisition")||n.get("tab")==="acquisition"?"acquisition":"diagnostics",l=d=>{const c=new URLSearchParams(n);c.delete("tab"),o({pathname:d==="acquisition"?"/dashboard/analytics/performance/acquisition":"/dashboard/analytics/performance",search:c.toString()},{replace:!0})};return e.jsx("div",{className:"console-page flex-1 overflow-y-auto p-8",children:e.jsxs("div",{className:"mx-auto max-w-7xl",children:[e.jsx(Je,{kicker:"Analytics",title:"Performance",meta:e.jsx("span",{className:"font-mono",children:"Cross-channel performance · UTC"}),action:e.jsx(Ve,{value:t,onChange:s})}),e.jsxs(yt,{value:a,onValueChange:l,className:"space-y-5",children:[e.jsxs(jt,{children:[e.jsx(ye,{value:"diagnostics",children:"Diagnostics"}),e.jsx(ye,{value:"acquisition",children:"Acquisition"})]}),a==="diagnostics"?e.jsx(js,{rangeValue:t}):e.jsx(Bs,{rangeValue:t})]})]})})}export{Cn 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.