1import{r as p,j as e,B as ye,C as Q,D as he,N as ut,dF as ht,s as re,aR as je,c$ as De,d0 as mt,P as Le,v as ue,aI as Ue,aJ as Ke,aK as He,H as Ge,aL as We,aM as be,S as Ae,bV as xt,a as ze,z as W,A as X,L as ie,dG as pt,dH as gt,y as ve,dA as we,dI as ft,dJ as yt,q as jt,aV as Se,aT as ce,aX as Y,aU as z,K as bt,x as Qe,G as xe,dK as vt,aO as Ce,aS as Xe,I as _t,dL as Ct,dM as wt,e as Je,be as St,ba as pe,w as Ie,dq as Nt,dN as Et,dO as Pt,dP as Dt,aW as Ye,dQ as Mt,dR as At,dS as Ft,g as Tt,dT as Ot,a$ as Lt,b0 as Re}from"./root-Bfop0rm5.js";import{g as me}from"./RouterProvider-BbsgWugL.js";import{H as It}from"./index-C97ZXgRl.js";import{u as Fe}from"./useMutation-DrGfYVG5.js";import{q as de}from"./queryOptions-BQvTFV_-.js";import{P as Rt,D as kt}from"./PathRegexMatcher-BDEadxHx.js";import{M as _e}from"./MatcherRow-CxZJE3n6.js";import{P as $t}from"./PathIsInListMatcher-ClJsz_vf.js";import{R as Ze}from"./ReactHighcharts-BNs6Sbty.js";import{a as Me,H as qt}from"./highcharts-react.min-BWR8lYuX.js";import"./hooks-BJhLWX9Q.js";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"distillery-frontend"};var n=new t.Error().stack;
1n&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[n]="f618a7fd-44ff-4bc0-bd36-7ad2b7d542a1",t._sentryDebugIdIdentifier="sentry-dbid-f618a7fd-44ff-4bc0-bd36-7ad2b7d542a1")}catch{}})();const Bt=({selectedAnalyticsConfig:t,availableAnalyticsConfigs:n,toggleAnalyticsConfig:r})=>(p.useEffect(()=>{n.length===1&&r(n[0])},[n]),e.jsx("div",{children:e.jsxs(ye,{children:[e.jsx(Q,{children:e.jsx(Q.Content,{children:e.jsx(Q.Title,{children:"Analytics Profile Selection"})})}),e.jsx("div",{className:"p-6",children:e.jsxs(he,{label:"Select Domain",value:t?.id,onChangeFunction:l=>{const s=n.find(a=>a.id===Number(l));s&&r(s)},onChangeParameters:[],children:[e.jsx("option",{value:"",disabled:!0,children:"No domain selected"}),n.map(l=>e.jsx("option",{value:l.id,children:l.domainName},l.domainName))]})})]})})),fe={chart:{backgroundColor:"transparent",plotBackgroundImage:"/assets/images/searchpilot-chart-background.png",fontFamily:"Source Sans Pro",events:{}},title:{text:"",style:{color:"#344054",fontFamily:"Source Sans Pro"}}
1,colors:["#2E90FA","#E80A84","#12B76A","#F79009","#06AED4","#8B5CF6"],credits:{enabled:!1},legend:{itemStyle:{color:"#344054"}},xAxis:{type:"datetime",labels:{style:{color:"#344054"}}},yAxis:{title:{text:"Metric Value",style:{color:"#344054"}},gridLineColor:"#EAECF0",labels:{style:{color:"#344054"}}},plotOptions:{series:{marker:{radius:0}},arearange:{marker:{radius:0}}},tooltip:{crosshairs:!0,shared:!0,backgroundColor:"#FFF",className:"text-right"},exporting:{buttons:{}},series:[]},ke=fe.colors,Vt="#9CA3AF",Ne=(t,n)=>{const r=n.findIndex(l=>l.id===String(t));return r===-1?Vt:ke[r%ke.length]},Te=(t,n)=>Math.round((new Date(n).getTime()-new Date(t).getTime())/(1e3*60*60*24)),Ut=["carbon.matchers.base.path_regex_match","carbon.matchers.base.list_contains_path","carbon.matchers.base.path_in_dataset"],et=t=>t.type==="or"&&"sub_expressions"in t,tt=t=>t.type==="and"&&"sub_expressions"in t,st=t=>et(t)||tt(t),Kt=t=>!!t.carbon_dotted_path&&Ut.includes(t.carbon_dotted_path),Ht={request_path_matches:"carbon.matchers.base.path_regex_match",request_path_in_list:"carbon.matchers.base.list_contains_path",request_path_in_dataset:"carbon.matchers.base.path_in_dataset"},Gt=t=>{if(t.carbon_function&&!t.carbon_dotted_path){const{carbon_function:n,...r}=t;return{...r,carbon_dotted_path:Ht[n]}}return t},rt=t=>{if(st(t)){const r=(t.sub_expressions||[]).map(rt).filter(l=>l!==null);return r.length===0?null:{...t,sub_expressions:r}}const n=Gt(t);return Kt(n)?n:null},Oe=t=>t.carbon_dotted_path==="carbon.matchers.base.path_in_dataset"?!0:st(t)?(t.sub_expressions||[]).some(Oe):!1,Wt=async({clientSlug:t})=>{const n=`/api/webapp/metrics_explorer/analytics_config/cl-${t}/`;return ut(n,{})},zt=({clientSlug:t,enabled:n=!0})=>de({queryKey:["analyticsConfig",t],queryFn:()=>Wt({clientSlug:t}),enabled:n,staleTime:1/0}),$e={last_30_days:30,last_60_days:60,last_90_days:90,last_120_days:120,last_365_days:365},ge=120,at=p.createContext(void 0),Qt=({children:t,clientSlug:n})=>{const[r,l]=p.useState([]),[s,a]=p.useState([]),[i,d]=p.useState("last_30_days"),[f,j]=p.useState(""),P=new Date(Date.now()-720*60*60*1e3).toISOString().slice(0,10),S=new Date().toISOString().slice(0,10),[w,E]=p.useState(P),[M,h]=p.useState(S),A=p.useRef(s.length);p.useEffect(()=>{A.current>0&&s.length===0&&d("last_30_days"),A.current=s.length},[s]);const[I,b]=p.useState(null),[v,F]=p.useState(!1),[R,k]=p.useState(!1),[H,q]=p.useState(null),[V,G]=p.useState(null),_=Fe({mutationFn:ht,onSuccess:L=>{G(L)}}),C=p.useMemo(()=>({type:"and",negate:!1,sub_expressions:[{carbon_dotted_path:"carbon.matchers.base.path_regex_match",carbon_kwargs:{path_regex:".*"},negate:!1,type:"matcher"}]}),[]),[g,O]=p.useState(C),[u,m]=p.useState([]),{data:o}=re(zt({clientSlug:n,enabled:!!n})),x=p.useMemo(()=>o?.results?o.results.map(L=>({id:L.id,domainName:L.domain_name,accounts:L.accounts.map(({id:T,name:B,slug:U})=>({id:T,name:B??"",slug:U??""})),dataSources:L.data_sources.map(T=>({id:T.id,downloadMethod:T.download_method,metrics:T.metrics.map(B=>({minSeenDate:T.min_seen_date,maxSeenDate:T.max_seen_date,id:B.id.toString(),name:B.name,label:`${B.name} - ${T.download_method}`,source:T.download_method,isPrimary:B.is_primary}))}))})):[],[o]);p.useEffect(()=>{x.length===1&&b(L=>L?.id===x[0].id?L:x[0])},[x]),p.useEffect(()=>{if(i==="custom")return;let L=S;if(s.length>0){const B=r.filter(U=>s.includes(U.id)).map(U=>U.maxSeenDate).filter(U=>!!U);B.length>0&&(L=B.reduce((U,ne)=>new Date(ne)>new Date(U)?ne:U))}if(h(L),$e[i]){const T=new Date(new Date(L).getTime()-$e[i]*1e3*60*60*24);E(T.toISOString().slice(0,10))}},[s,r,i,S]);const{startDateWarning:y,endDateWarning:c}=p.useMemo(()=>{if(s.length===0)return{startDateWarning:void 0,endDateWarning:void 0};const L=r.filter(le=>s.includes(le.id)),T=L.map(le=>le.minSeenDate).filter(le=>!!le),B=L.map(le=>le.maxSeenDate).filter(le=>!!le);if(T.length===0||B.length===0)return{startDateWarning:void 0,endDateWarning:void 0};T.sort(),B.sort();const U=T[0],ne=B[B.length-1],ct=w&&(w<U||w>ne)?"Date is outside of the available data range":void 0,dt=M&&(M<U||M>ne)?"Date is outside of the available data range":void 0;
1return{startDateWarning:ct,endDateWarning:dt}},[s,r,w,M]),N=p.useCallback(L=>{a(T=>T.includes(L)?T.filter(B=>B!==L):[...T,L]),F(!1)},[]),D=p.useCallback(L=>{b(B=>B?.id===L.id?null:L);const T=L.dataSources.flatMap(B=>B.metrics)??[];l(T),L.accounts.length===1&&j(L.accounts[0].slug),T.length===1?a([T[0].id]):a([]),k(!1),F(!1)},[]),$=p.useCallback((L,T)=>{E(L),h(T),d("custom"),F(!1)},[]),K=p.useCallback(()=>{F(!0),k(!0),q(Date.now()),G(null);const B=Te(w,M)>=ge?(()=>{const U=new Date(M);return U.setDate(U.getDate()-ge),U.toISOString().slice(0,10)})():w;_.mutate({domain_name:I?.domainName||"",metric_ids:s.map(U=>Number(U)),start_date:B,end_date:M,matching_expression:g,important_parameters:u,num_paths:100,maximum_data_points:100})},[I,s,w,M,g,u,_]),te=p.useCallback((...L)=>{const T=L.pop(),B=L;O(U=>{if(B.length===0)return T;const ne=je(U);return De(ne,B,T),ne}),F(!1)},[]),ae=p.useCallback((...L)=>{O(T=>{const B=je(T);return mt(B,L),B}),F(!1)},[]),J=p.useCallback((...L)=>{const T=L.pop(),B=L;O(U=>{const ne=je(U);return De(ne,B,T),ne}),F(!1)},[]);p.useEffect(()=>{Oe(g)||j("")},[g]);const se=p.useCallback(L=>{const T=L.trim();T&&(m(B=>B.includes(T)?B:[...B,T]),F(!1))},[]),Z=p.useCallback(L=>{m(T=>T.filter(B=>B!==L)),F(!1)},[]);p.useEffect(()=>{O(C),m([]),j("")},[I,C]);const oe=p.useMemo(()=>({selectedMetrics:s,toggleMetric:N,availableMetrics:r,availableAnalyticsConfigs:x,selectedAnalyticsConfig:I,toggleAnalyticsConfig:D,selectedRange:i,setSelectedRange:d,startDate:w,endDate:M,toggleTimeRange:$,shouldFetchData:v,hasEverFetchedData:R,lastFetchTimestamp:H,runAllKey:V,isRunAllLoading:_.isPending,runAllError:_.error,triggerDataFetch:K,matchingExpression:g,handleMatchingExpressionChange:te,handleMatchingExpressionDelete:ae,handleMatchingExpressionAdd:J,importantParameters:u,handleAddImportantParameter:se,handleDeleteImportantParameter:Z,selectedMatcherAccountSlug:f,setSelectedMatcherAccountSlug:j,startDateWarning:y,endDateWarning:c}),[s,N,r,i,d,w,M,$,x,I,D,v,R,H,V,_.isPending,_.error,K,g,te,ae,J,u,se,Z,f,y,c]);return e.jsx(at.Provider,{value:oe,children:t})},ee=()=>{const t=p.useContext(at);if(!t)throw new Error("useMetrics must be used within a MetricsProvider");return t},qe={"carbon.matchers.base.path_regex_match":{carbon_dotted_path:"carbon.matchers.base.path_regex_match",carbon_kwargs:{path_regex:".*"},negate:!1,type:"matcher"},"carbon.matchers.base.list_contains_path":{carbon_dotted_path:"carbon.matchers.base.list_contains_path",carbon_kwargs:{possible_paths:["/"],exclude_query_string:!0},negate:!1,type:"matcher"},"carbon.matchers.base.path_in_dataset":{carbon_dotted_path:"carbon.matchers.base.path_in_dataset",carbon_kwargs:{dataset_id:"",exclude_query_string:!0},negate:!1,type:"matcher"},and_matcher_false:{type:"and",negate:!1,sub_expressions:[]},or_matcher_false:{type:"or",negate:!1,sub_expressions:[]}},Xt=({level:t,handleAdd:n,handleAddParameters:r,allowCreatingGroups:l,availableAccounts:s,handleUpdateAccountSlug:a,accountSlug:i})=>{const[d,f]=p.useState(""),[j,P]=p.useState(!1),[S,w]=p.useState(!1),[E,M]=p.useState(i||""),h=()=>{if(!d||!qe[d])return;w(!0);const b=je(qe[d]);if(d==="carbon.matchers.base.path_in_dataset"){const v=E||i||(s?.length===1?s[0].slug:"");a(v)}n(...r,b),P(!1),w(!1),f(""),i||M("")},A=!!i,I=()=>{P(!1),f("")};return e.jsxs(e.Fragment,{children:[t>0?e.jsx(Le,{leftIcon:e.jsx(ue,{color:"white",hoverColor:void 0,name:"plus"}),variant:"primary",onClick:()=>P(!0),children:"Add Criteria"}):e.jsx(Le,{leftIcon:e.jsx(ue,{color:"white",hoverColor:void 0,name:"plus"}),variant:"primary",onClick:()=>P(!0),children:"Add Top-level Criteria"}),e.jsx(Ue,{open:j,onClose:I,children:e.jsxs(Ke,{children:[e.jsx(He,{title:"Add New Criteria"}),e.jsxs(Ge,{children:[e.jsxs(he,{value:d||"",onChangeFunction:b=>f(b),onChangeParameters:[],id:"add_matcher",children:[e.jsx("option",{value:""}),e.jsx("option",{value:"carbon.matchers.base.path_regex_match",children:"Path must match (regex)"}),e.jsx("option",{value:"carbon.matchers.base.path_in_dataset",children:"Path is in Dataset"}),e.jsx("option",{value:"carbon.matchers.base.list_contains_path",children:"Path is in the list"}),e.jsx("option",{value:"and_matcher_false",disabled:!l,children:"And group of multiple criteria"}),e.jsx("option",{value:"or_matcher_false",disabled:!l,children:"Or group of multiple criteria"})]}
1),d==="carbon.matchers.base.path_in_dataset"&&s&&s.length>1&&e.jsx("div",{className:"mt-4",children:e.jsxs(he,{value:E||i||"",onChangeFunction:b=>M(b),onChangeParameters:[],label:"Select Site",id:"add_matcher_site",disabled:A,helpText:A?"A dataset from this site is already in use.":null,children:[e.jsx("option",{value:"",children:"Select Site"}),s.map(b=>e.jsx("option",{value:b.slug,children:b.name},b.slug))]})})]}),e.jsxs(We,{classes:"flex gap-3 justify-end",children:[e.jsx(be,{variant:"primary",onClick:I,children:"Cancel"}),e.jsx(Ae,{variant:"primary",onClick:()=>h(),disabled:d===""||d==="carbon.matchers.base.path_in_dataset"&&!E&&!i&&s?.length!==1,loading:S,children:"Add"})]})]})})]})},Be=({matcher:t,level:n,handleUpdate:r,handleUpdateParameters:l,handleDelete:s,handleDeleteParameters:a,handleAdd:i,isOrMatcher:d,accountSlug:f="",availableAccounts:j=[],handleUpdateAccountSlug:P})=>{let S="AND";(d&&!t.negate||!d&&t.negate)&&(S="OR");const w=t.sub_expressions||[],E=w.filter(R=>R.carbon_dotted_path==="carbon.matchers.base.path_regex_match").length===1,M=w.map((R,k)=>{const H=R.carbon_dotted_path==="carbon.matchers.base.path_regex_match",q=n===0&&H&&E,V=k>0?e.jsx(_e,{level:n+1,validationIcon:null,deleteButton:null,children:e.jsx("div",{className:"text-sp-neutral-900 pl-2 text-xs",children:S})}):null;return e.jsxs("div",{children:[V,e.jsx(nt,{level:n+1,matcher:R,handleUpdate:r,handleUpdateParameters:["sub_expressions",k],handleDelete:s,handleDeleteParameters:["sub_expressions",k],handleAdd:i,handleAddParameters:["sub_expressions",k],preventDeleting:q,accountSlug:f,availableAccounts:j,handleUpdateAccountSlug:P})]},k)}),h=w.length===0?e.jsx(_e,{level:n+1,validationIcon:null,deleteButton:null,children:e.jsx("div",{className:"text-sp-neutral-900 mt-2 text-sm",children:"Empty group. You should either delete it, or add a new Criteria"})}):null,A=d?"or":"and",I=t.negate?"T":"F",b=`${A}-${I}`,v=R=>{const k=R.split("-"),H={...t};H.type=k[0],H.negate=k[1]==="T",r(...l,"self",H)},F=n>
10?e.jsx(_e,{level:n,validationIcon:null,deleteButton:e.jsx(xt,{disabled:!1,handleDelete:s,handleDeleteParameters:a}),children:e.jsx("div",{className:"w-full",children:e.jsxs(he,{value:b,onChangeFunction:R=>{v(R)},onChangeParameters:[],id:"path_regex_match_negate",children:[e.jsx("option",{value:"and-F",children:"All of the following must be True"}),e.jsx("option",{value:"or-T",children:"All of the following must be False"}),e.jsx("option",{value:"or-F",children:"At least one of the following must be True"}),e.jsx("option",{value:"and-T",children:"At least one of the following must be False"})]})})}):null;return e.jsxs(e.Fragment,{children:[F,M,h,e.jsx(_e,{level:n+1,validationIcon:null,deleteButton:null,children:e.jsx("div",{className:"flex justify-between",children:e.jsx(Xt,{level:n,handleAdd:i,handleAddParameters:["sub_expressions",-1],allowCreatingGroups:n<=1,availableAccounts:j,handleUpdateAccountSlug:P,accountSlug:f})})})]})},nt=({matcher:t,level:n,handleUpdate:r,handleUpdateParameters:l,handleDelete:s,handleDeleteParameters:a,handleAdd:i,handleAddParameters:d,preventDeleting:f=!1,accountSlug:j="",availableAccounts:P,handleUpdateAccountSlug:S})=>{const h={matcher:t,level:n,handleUpdate:(...A)=>{if(A.length===0)return;const I=A[A.length-1],b=A.slice(0,-1);let v=je(t);b.length>0&&b[b.length-1]==="self"?(b.pop(),v={...I}):De(v,b,I),r(...l,v)},handleUpdateParameters:[],handleDelete:(...A)=>{s(...a,...A)},handleDeleteParameters:[],handleAdd:(...A)=>{i(...d,...A)},handleAddParameters:[],validationLoading:!1,validation:void 0,preventDeleting:f,accountSlug:j,shouldPreviewExampleURLs:!1,handleSaveMatchingCriteria:null,hideValidationIcon:!0,availableAccounts:P,handleUpdateAccountSlug:S};return et(t)?e.jsx(Be,{...h,isOrMatcher:!0}):tt(t)?e.jsx(Be,{...h,isOrMatcher:!1}):t.carbon_dotted_path==="carbon.matchers.base.path_regex_match"?e.jsx(Rt,{...h}):t.carbon_dotted_path==="carbon.matchers.base.list_contains_path"?e.jsx($t,{...h}):t.carbon_dotted_path==="carbon.matchers.base.path_in_dataset"?e.jsx(kt,{...h}):null},Ee=W.object({id:W.number(),name:W.string(),slug:W.string()}),it=W.lazy(()=>W.object({carbon_dotted_path:W.string().optional(),type:W.string().optional(),negate:W.boolean().optional(),sub_expressions:W.array(it).optional(),carbon_kwargs:W.record(W.string(),W.unknown()).optional()}).passthrough()),Jt=W.object({id:W.number(),name:W.string(),slug:W.string(),type:W.string(),matching_expression:it,params_to_keep:W.array(W.string())}),Yt=W.object({response_sections:W.array(Ee).optional(),request_sections:W.array(Ee).optional(),api_sections:W.array(Ee).optional()}),Zt=async t=>{const n=await ze.get(`/api/webapp/account_dashboard/get/${t}/`);return Yt.parse(n.data)},es=async(t,n)=>{const r=await ze.get(`/api/webapp/section_dashboard/get/${t}/${n}/`);return Jt.parse(r.data)},ts=t=>re({queryKey:["accountDashboard",t],queryFn:()=>Zt(t),enabled:!!t}),ss=(t,n)=>re({queryKey:["sectionDetail",t,n],queryFn:()=>es(t,n),enabled:!!t&&!!n}),rs=({isOpen:t,onClose:n,availableAccounts:r,onImport:l})=>{const[s,a]=p.useState(""),[i,d]=p.useState(""),{data:f,isLoading:j}=ts(s),{data:P,isLoading:S}=ss(s,i),w=p.useMemo(()=>{if(!f)return[];const h=[];return f.response_sections&&h.push(...f.response_sections.map(A=>({...A,displayName:`${A.name} (response)`}))),f.request_sections&&h.push(...f.request_sections.map(A=>({...A,displayName:`${A.name} (request)`}))),f.api_sections&&h.push(...f.api_sections.map(A=>({...A,displayName:`${A.name} (api)`}))),h},[f]);p.useEffect(()=>{t&&r.length===1&&!s&&a(r[0].slug)},[t,r,s]);const E=()=>{if(P){const h=rt(P.matching_expression);l(h,P.params_to_keep,s),n(),a(""),d("")}},M=()=>{a(""),d(""),n()};return e.jsx(Ue,{open:t,onClose:M,defaultWidth:"w-2/3",children:e.jsxs(Ke,{children:[e.jsx(He,{title:"Import Site Section Configuration"}),e.jsxs(Ge,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("p",{className:"mt-1 text-base leading-5 text-gray-500",children:"Select a site section from your analytics config to import its matching criteria and important parameters into the metrics explorer configuration."}),e.jsx(X,{variant:"info",className:"mt-4",message:"Metrics Explorer Page Matching Criteria will only support path matchers. If the selected site section uses other matchers, they will be removed during the import."})]}),e.jsx("div",{className:"mb-6",children:e.jsxs(he,{label:"Select Account",value:s,onChangeFunction:h=>{a(h),d("")},onChangeParameters:[],children:[e.jsx("option",{value:"",disabled:!0,children:"No account selected"}),r.map(h=>e.jsx("option",{value:h.slug,children:h.name},h.slug))]})}),j&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ie,{})}),!j&&s&&w.length===0&&e.jsx("div",{className:"mb-6 rounded-lg border border-yellow-200 bg-yellow-50 p-4",children:e.jsx("p",{className:"text-sm text-yellow-700",children:"No sections foun
1d for this account."})}),!j&&s&&w.length>0&&e.jsx("div",{className:"mb-6",children:e.jsxs(he,{label:"Select Section",value:i,onChangeFunction:d,onChangeParameters:[],children:[e.jsx("option",{value:"",disabled:!0,children:"No site section selected"}),w.map(h=>e.jsx("option",{value:h.slug,children:h.displayName},h.id))]})})]}),e.jsx(We,{classes:"flex justify-end gap-3",children:e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(be,{variant:"primary",onClick:M,children:"Cancel"}),e.jsx(Ae,{variant:"primary",onClick:E,disabled:!i||!P,loading:S,children:"Import"})]})})]})})},as=me("/$clientSlug/metrics-explorer"),ns=t=>de({queryKey:["metricsExplorer","export","poll",t],queryFn:()=>{if(!t)throw new Error("Key is required for polling export");return ft(t)},enabled:!!t,staleTime:0,gcTime:0}),is=()=>{const{clientSlug:t}=as.useParams(),[n,r]=p.useState(void 0),l=p.useRef(null),{trackExport:s}=pt(),a=Fe({mutationFn:f=>gt(f),onSuccess:f=>{r(f),s(f)},onError:()=>{r(void 0)}}),i=re(ns(n));p.useEffect(()=>{if((i.isSuccess||i.isError||a.isError)&&l.current){const f=(Date.now()-l.current)/1e3,j=i.isError||a.isError||i.data?.status==="Error";ve(t,"Metrics Explorer Export Generated",{duration_seconds:f,duration_bucket:we(f),status:j?"Error":"Success"}),l.current=null}},[i.isSuccess,i.isError,i.data,a.isError,t]);const d=p.useCallback(async f=>(r(void 0),l.current=Date.now(),a.mutateAsync(f)),[a.mutateAsync]);return{data:i.data,isTriggering:a.isPending,isPolling:i.isFetching,isLoading:a.isPending||i.isLoading,isFetching:a.isPending||i.isFetching,isError:a.isError||i.isError,error:i.error||a.error,isSuccess:i.isSuccess,trigger:d,refetch:d}},os=me("/$clientSlug/metrics-explorer"),ot=(t,n="export")=>{const{clientSlug:r}=os.useParams();return re({queryKey:["metricsExplorer","recentRequests",r,t,n],queryFn:()=>{if(!t)throw new Error("Domain name is required");return yt(r,t,n)},enabled:!!t,refetchInterval:l=>{const s=l.state.data;return s?s.some(i=>i.status==="Pending")?5e3:!1:5e3}})},ls=({requests:t,isLoading:n,isError:r})=>{const[l,s]=p.useState(0),[a,i]=p.useState(10),{availableMetrics:d}=ee(),[f,j]=p.useState(null),P=jt(),S=async h=>{if(f!==h)try{j(h);const A=await vt(h);A.download_url?window.open(A.download_url,"_blank","noopener"):P.error("Download URL not found")}catch(A){P.error(`Failed to get download URL: ${A}`)}finally{j(null)}},w=t.slice(l,l+a),E=h=>{if(h.length===0||h.length===d.length)return"All metrics";const A=h.map(I=>d.find(b=>Number(b.id)===I)?.name).filter(Boolean);return A.length>0?A.join(", "):`Metrics (${h.length})`},M=h=>{switch(h){case"Complete":return e.jsx(xe,{colour:"green",text:"Complete",leftIcon:"successTick"});case"Pending":return e.jsx(xe,{colour:"blue",text:"Processing",leftIcon:"hourglassEmpty"});case"Error":return e.jsx(xe,{colour:"red",text:"Failed",leftIcon:"alertCircle"});case"Skipped":return e.jsx(xe,{colour:"gray",text:"Skipped"});default:return e.jsx(xe,{colour:"gray",text:h||"Unknown"})}};return e.jsx("div",{className:"mt-6",children:e.jsxs(ye,{children:[e.jsx(Q,{children:e.jsx(Q.Content,{children:e.jsx(Q.Title,{children:"Recent Exports"})})}),e.jsxs("div",{className:"p-6",children:[e.jsxs(Se,{tableLayout:"auto",children:[e.jsx("thead",{children:e.jsxs(ce,{children:[e.jsx(Y,{children:"Status"}),e.jsx(Y,{children:"Date Requested"}),e.jsx(Y,{children:"Analysis Scope"}),e.jsx(Y,{children:"Date Range"}),e.jsx(Y,{children:"Actions"})]})}),e.jsx("tbody",{children:n&&t.length===0?e.jsx(ce,{children:e.jsx(z,{colSpan:5,children:e.jsx("div",{className:"flex justify-center p-8",children:e.jsx(ie,{size:"lg"})})})}):r?e.jsx(ce,{children:e.jsx(z,{colSpan:5,children:e.jsx("div",{className:"rounded-md bg-red-50 p-8 text-center",children:e.jsx("p",{className:"text-sm text-red-500",children:"Failed to load recent exports."})})})}):t.length===0?e.jsx(ce,{children:e.jsx(z,{colSpan:5,children:e.jsx("div",{className:"bg-sp-neutral-50 rounded-md p-8 text-center",children:e.jsx("p",{className:"text-sp-neutral-500 text-sm",children:"No recent exports found."})})})}):w.map(h=>e.jsxs(ce,{children:[e.jsx(z,{children:M(h.status)}),e.jsx(z,{children:e.jsx("div",{className:"text-sm text-gray-600",children:new Date(h.created_at).toLocaleDateString()})}),e.jsx(z,{children:e.jsxs("div",{className:"max-w-md",children:[e.jsx("div",{className:"mb-1 text-sm font-medium text-gray-900",children:E(h.metric_ids)}),e.jsx("div",{className:"text-xs italic text-gray-500",children:h.matching_expression_summary.join(", ")})]})}),e.jsx(z,{children:e.jsxs("div",{className:"text-sm text-gray-900",children:[h.start_date," â ",h.end_date]})}),e.jsx(z,{children:e.jsx("div",{className:"flex items-center gap-2",children:h.status==="Complete"?f===h.key?e.jsx("div",{className:"p-2",children:e.jsx(ie,{size:"sm"})}):e.jsx(bt.Plain,{variant:"primary",iconName:"download",onClick:()=>S(h.key),tooltipText:"Download Export"}):null})})]},h.key))})]}),t.length>0&&e.jsx("div",{className:"mt-4",children:e.jsx(Qe,{totalCount:t.length,listItems:w,offset:l,limit:a,setOffset:s,setLimit:i,options:[5,10,20],allOption:!1})})]})]})})},cs=me("/$clientSlug/metrics-explorer"),ds=()=>{const{clientSlug:t}=cs.useParams(),{selectedAnalyticsConfig:n,selectedMetrics:r,startDate:l,endDate:s,matchingExpression:a,importantParameters:i,lastFetchTimestamp:d}=ee(),{isTriggering:f,trigger:j}=is(),{refetch:P}
1=ot(n?.domainName),S=Te(l,s),w=S>=ge,E=p.useCallback(async()=>{const M=d?(Date.now()-d)/1e3:null;ve(t,"Metrics Explorer Export Triggered",{time_since_run_analysis_seconds:M,time_since_run_analysis_bucket:M?we(M):null,domain_name:n?.domainName||"",metric_ids:r.map(h=>Number(h)),metrics_count:r.length,start_date:l,end_date:s,total_days:S,matching_expression:a,important_parameters:i.length>0?i:null,important_parameters_count:i.length,matching_expression_count:a.sub_expressions?Object.keys(a.sub_expressions).length:0}),await j({domain_name:n?.domainName||"",metric_ids:r.map(h=>Number(h)),start_date:l,end_date:s,matching_expression:a,important_parameters:i}),P()},[j,t,d,i,a,n,r,l,s,P]);return e.jsx(be,{variant:"primary",leftIcon:e.jsx(ue,{name:"download",color:"text-current"}),onClick:E,disabled:f||r.length===0,loading:f,loadingText:"Preparing export...",children:w?`Export full ${S} days`:"Export Data"})},us=()=>{const{selectedAnalyticsConfig:t}=ee(),{data:n,isLoading:r,isError:l}=ot(t?.domainName,"export");return e.jsx("div",{className:"mt-8",children:e.jsx(ls,{requests:n||[],isLoading:r,isError:l})})},hs=()=>{const{importantParameters:t,handleAddImportantParameter:n,handleDeleteImportantParameter:r}=ee(),[l,s]=p.useState(""),a=d=>{s(d)},i=()=>{l.trim()&&(n(l),s(""))};return e.jsxs("div",{className:"grid-cols-20/80 my-6 grid",children:[e.jsxs("div",{className:"mr-24",children:[e.jsx("label",{children:"Important Parameters"}),e.jsxs(Ce,{children:["Important parameters specify which URL query parameters should be preserved when normalizing URLs."," ",e.jsx(Xe,{message:"For example, if ['category', 'id'] are marked as important, /product?id=123&sort=up and /product?id=456&sort=down would be treated as two different normalized paths (/product?id=123 and /product?id=456), while non-important parameters like sort are stripped away. Without any important parameters specified, all query parameters would be removed, resulting in a single normalized path (/product). As a general rule, you should mark as important any parameters that appear in your canonical URLs, as these typically indicate genuinely distinct pages rather than variations of the same content.",children:e.jsx(ue,{name:"infoCircleLetterI",size:"sm"})})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"",children:e.jsxs("div",{className:"config-input-group",children:[e.jsx(_t,{hideLabel:!0,value:l,onChangeFunction:d=>a(d),onChangeParameters:[],label:"",placeholder:"Add new parameter",id:"important_parameter",required:!1,helpText:"",errorText:void 0}),e.jsx(be,{variant:"primary",loading:!1,onClick:i,children:"Add Parameter"})]})}),t&&t.length!==0?e.jsx("ul",{className:"flex flex-wrap py-2",children:t.map((d,f)=>e.jsx("li",{className:"my-2 mr-2 p-0 ",children:e.jsx(xe,{size:"lg",text:d,colour:"purple",rightIcon:"closeCross",onIconClick:()=>{r(d)}})},`${d}-${f}`))}):e.jsx("p",{className:"text-sp-neutral-800 my-2 py-2 text-sm",children:"No important parameters"})]})]})},ms=t=>de({queryKey:["metricsExplorer","exportPreview","poll",t],queryFn:()=>{if(!t)throw new Error("Key is required for polling export preview");return wt(t)},enabled:!!t,staleTime:0,gcTime:0}),xs=()=>{const[t,n]=p.useState(void 0),r=Fe({mutationFn:i=>Ct(i),onSuccess:i=>{n(i)},onError:()=>{n(void 0)}}),l=re(ms(t)),s=p.useCallback(async i=>(n(void 0),r.mutateAsync(i)),[r.mutateAsync]),a=p.useCallback(()=>{n(void 0)},[]);return{data:l.data,isTriggering:r.isPending,isPolling:l.isFetching,isLoading:r.isPending||l.isLoading,isFetching:r.isPending||l.isFetching,isError:r.isError||l.isError,error:l.error??r.error,isSuccess:l.isSuccess,trigger:s,reset:a}},ps=({isOpen:t,isStale:n,onRefresh:r})=>{const{selectedAnalyticsConfig:l,selectedMetrics:s,startDate:a,endDate:i,matchingExpression:d,importantParameters:f}=ee(),{data:j,trigger:P,reset:S,isLoading:w,isError:E,error:M}=xs(),h=p.useRef(!1),A=p.useRef(s.length>0),I=()=>{P({domain_name:l?.domainName??"",metric_ids:s.map(v=>Number(v)),start_date:a,end_date:i,matching_expression:d??{sub_expressions:[]},important_parameters:f??[]})};p.useEffect(()=>{const v=s.length>0,F=t&&!h.current,R=v&&!A.current;t&&v&&(F||R)&&I(),t||S(),h.current=t,A.current=v},[t,s.length]);const b=()=>{I(),r()};return t?s.length===0?e.jsx("div",{className:"p-4 text-center italic text-gray-500",children:"Select at least one metric to see a preview."}):e.jsxs("div",{className:"p-4",children:[n&&j&&!w&&e.jsx("div",{className:"mb-4",children:e.jsx(X,{variant:"warning",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-sm",children:["Configuration has changed. Preview data may be out of date."," ",e.jsx("button",{onClick:b,className:"text-sp-warning-800 cursor-pointer text-sm font-semibold underline",children:"Refresh preview"})]})})})}),w&&!j&&e.jsxs("div",{className:"flex flex-col items-center justify-center p-8",children:[e.jsx(ie,{size:"lg"}),e.jsx("div",{className:"mt-4 text-center",children:e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Loading preview..."})})]}),E&&e.jsx(X,{variant:"error",children:e.jsx("p",{children:M instanceof Error?M.message:"Failed to load preview data."})}),j&&e.jsx(e.Fragment,{children:j.preview_data&&j.preview_data.length>0?e.jsx("div",{className:"w-full overflow-y-auto",style:{maxHeight:"400px"},children:e.jsx("div",{className:"w-full",style:{overflowX:"hidden"},children:e.jsxs(Se,{tableLayout:"fixed",children:[e.jsx("thead",{children:e.jsxs(ce,{children:[e.jsx(Y,{style:{width:"50%"},children:"Path"}),e.jsx(Y,{style:{width:"35%"},children:"Normalised Path"}),e.jsx(Y,{style:{width:"15%"},children:"Date"})]})}),e.jsx("tbody",{children:j.preview_data.map((v,F)=>e.jsxs(ce,{children:[e.jsx(z,{className:"whitespace-normal break-words text-sm",children:v.path}),e.jsx(z,{className:"whitespace-normal break-words text-sm",children:v.normalised_path}),e.jsx(z,{className:"whitespace-nowrap text-sm",children:v.date})]},`${F}-${v.path}`))})]})})}):!w&&j.preview_data!==void 0&&e.jsx("div",{className:"p-8 text-center text-gray-500",children:"No data matched your criteria."})})]}):null},gs=me("/$clientSlug/metrics-explorer"),fs=()=>{const{clientSlug:t}=gs.useParams(),{selectedMetrics:n,toggleMetric:r,availableMetrics:l,triggerDataFetch:s,startDate:a,endDate:i,selectedRange:d,setSelectedRange:f,toggleTimeRange:j,matchingExpression:P,importantParameters:S,handleMatchingExpressionChange:w,handleMatchingExpressionDelete:E,handleMatchingExpressionAdd:M,selectedAnalyticsConfig:h,selectedMatcherAccountSlug:A,setSelectedMatcherAccountSlug:I,startDateWarning:b,endDateWarning:v,isRunAllLoading:F,handleAddImportantParameter:R}=ee(),[k,H]=p.useState(!1),[q,V]=p.useState(!1),[G,_]=p.useState(!1),C=p.useRef(h);p.useEffect(()=>{C.current!==h&&(H(!1),V(!1)),C.current=h},[h]),p.useEffect(()=>{k&&V(!0)},[n,a,i,P,S]);const g=Te(a,i),O=()=>{ve(t,"Metrics Explorer Run Analysis Triggered",{domain_name:h?.domainName||"",metric_ids:n.map(c=>Number(c)),metrics_count:n.length,start_date:a,end_date:i,selected_time_range:d,total_days:g,matching_expression:P,important_parameters:S.length>0?S:null,important_parameters_count:S.length,matching_expression_count:P.sub_expressions?Object.keys(P.sub_expressions).length:0})},u=c=>{f("custom"),j(c,i)},m=c=>{f("custom"),j(a,c)},o=g>=ge,x=Je("navigation-react-target","data-show-export-preview-table"),y=(c,N,D)=>
1{c&&(w(c),Oe(c)&&I(D)),N.forEach($=>{R($)})};return e.jsxs(e.Fragment,{children:[e.jsxs(ye,{children:[e.jsx(Q,{children:e.jsx(Q.Content,{children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(Q.Title,{children:"Analysis Configuration"}),e.jsx(be,{variant:"primary",onClick:()=>_(!0),leftIcon:e.jsx(ue,{name:"download",color:"text-current"}),children:"Import Site Section Config"})]})})}),e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"grid-cols-20/80 mb-6 grid",children:[e.jsxs("div",{className:"mr-24",children:[e.jsx("label",{children:"Available Metrics"}),e.jsxs(Ce,{children:["Select metrics to include in the analysis.",e.jsx("br",{}),"The first selected metric determines how the Popular Paths table is sorted. (To sort by a different metric, select that metric first.)"]})]}),e.jsxs("div",{className:"grid grid-cols-1 content-start",children:[e.jsxs("div",{className:"bg-sp-neutral-100 text-sp-neutral-500 grid grid-cols-3 py-3 pl-12",children:[e.jsx("h4",{className:"text-xs font-medium uppercase",children:"Metric Name"}),e.jsx("h4",{className:"text-xs font-medium uppercase",children:"Data Source"}),e.jsx("h4",{className:"text-xs font-medium uppercase",children:"Available Date Range"})]}),l.map(c=>e.jsxs("div",{className:`hover:bg-sp-neutral-50 flex px-4 py-6 transition-all ${n.includes(c.id)?"border-purple-500 bg-purple-50 hover:bg-purple-100":""}`,children:[e.jsx(St,{value:n.includes(c.id),onChangeFunction:()=>r(c.id),onChangeParameters:[c.name],id:c.id,"aria-label":`${c.name} (${c.source})`}),e.jsxs("div",{className:"flex grid w-full grid-cols-3 items-center items-center gap-3 pl-2",children:[e.jsxs("h4",{className:"flex items-center gap-2 text-sm font-medium text-gray-900",children:[c.name,c.isPrimary&&e.jsx(Xe,{message:"This is the primary metric.",children:e.jsx(ue,{name:"FaStar",size:"sm",color:"text-purple-500"})})]}),e.jsx("div",{className:"text-sm text-gray-600",children:c.source}),e.jsx("div",{className:"text-sm text-gray-600",children:c.minSeenDate&&c.maxSeenDate?`${c.minSeenDate} - ${c.maxSeenDate}`:"-"})]})]},c.id))]})]}),e.jsx(pe,{}),e.jsxs("div",{className:"grid-cols-20/80 my-6 grid",children:[e.jsxs("div",{className:"mr-24",children:[e.jsx("label",{children:"Page Matching Criteria"}),e.jsx(Ce,{children:"Specify how paths should be matched for the analysis."})]}),e.jsx("div",{children:e.jsx(nt,{matcher:P,handleUpdate:w,handleUpdateParameters:[],handleDelete:E,handleDeleteParameters:[],handleAdd:M,handleAddParameters:[],level:0,accountSlug:A,availableAccounts:h?.accounts||[],handleUpdateAccountSlug:I})})]}),e.jsx(pe,{}),e.jsx(hs,{}),e.jsx(pe,{}),e.jsxs("div",{className:"grid-cols-20/80 my-6 grid",children:[e.jsxs("div",{className:"mr-24",children:[e.jsx("label",{children:"Time Range"}),e.jsxs(Ce,{children:["Explore allows a maximum of ",ge," days. Export allows any date range. Defaults to the last 30 days."]})]}),e.jsxs("div",{className:"flex w-full flex-wrap content-start gap-4",children:[e.jsx("div",{className:"w-full lg:w-1/3",children:e.jsxs(he,{label:"Select Range",onChangeFunction:f,onChangeParameters:[],value:d,children:[e.jsx("option",{value:"last_30_days",children:"Last 30 days"}),e.jsx("option",{value:"last_60_days",children:"Last 60 days"}),e.jsx("option",{value:"last_90_days",children:"Last 90 days"}),e.jsx("option",{value:"last_120_days",children:"Last 120 days"}),e.jsx("option",{value:"last_365_days",children:"Last 365 days"}),e.jsx("option",{value:"custom",children:"Custom Range"})]})}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(Ie,{id:"start-date-from",label:"Start Date",value:a,updateDate:u,warningMessage:b}),e.jsx(Ie,{id:"start-date-to",label:"End Date",value:i,updateDate:m,warningMessage:v})]})]})]}),e.jsx(pe,{}),x&&e.jsxs("div",{className:"my-6",children:[e.jsx("div",{className:"flex cursor-pointer items-center justify-between py-2",onClick:()=>{H(!k),V(!1)},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{name:k?"chevronUp":"chevronDown",size:"sm"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Data Preview"})]})}),k&&e.jsx(ps,{isOpen:k,isStale:q,onRefresh:()=>V(!1)})]}),e.jsx(pe,{}),e.jsxs("div",{className:"mt-4 flex justify-end gap-x-3",children:[e.jsx(ds,{}),e.jsx(Ae,{variant:"primary",onClick:()=>{s(),O()},disabled:F||n.length===0||!P||typeof P=="object"&&Object.keys(P).length===0,leftIcon:e.jsx(ue,{name:"barChart",color:"text-current"}),children:o?`Explore last ${ge} days`:"Explore Data"})]})]})]}),e.jsx(rs,{isOpen:G,onClose:()=>_(!1),availableAccounts:h?.accounts||[],onImport:y})]})},ys=(t,n)=>{const r=t.daily_summary.map(({metric_id:l,data:s})=>({name:n.find(i=>i.id===String(l))?.name||`Metric ${l}`,id:String(l),type:"line",animation:!1,color:Ne(String(l),n),data:s}));return{...fe,xAxis:{...fe.xAxis,...Nt},series:r}},js=t=>de({queryKey:["metricsExplorer","coverageSummary","poll",t],queryFn:()=>
1{if(!t)throw new Error("Key is required for polling coverage summary");return Et(t)},enabled:!!t,staleTime:1/0}),bs=(t,n)=>{const r=re(js(t));return{data:r.data,isLoading:r.isLoading,isFetching:r.isFetching||!!n,isError:r.isError,error:r.error}},vs=me("/$clientSlug/metrics-explorer"),_s=t=>de({queryKey:["metricsExplorer","dailySummary","poll",t],queryFn:()=>{if(!t)throw new Error("Key is required for polling daily summary");return Pt(t)},enabled:!!t,staleTime:1/0}),Cs=(t,n)=>{const{clientSlug:r}=vs.useParams(),l=p.useRef(null);p.useEffect(()=>{t&&(l.current=Date.now())},[t]);const s=re(_s(t));return p.useEffect(()=>{if((s.isSuccess||s.isError)&&l.current){const a=(Date.now()-l.current)/1e3,i=s.isError||!!s.data?.error_message;ve(r,"Metrics Explorer Daily Summary Fetched",{duration_seconds:a,duration_bucket:we(a),status:i?"Error":"Success"}),l.current=null}},[s.isSuccess,s.isError,s.data,r]),{data:s.data,isLoading:s.isLoading,isFetching:s.isFetching||!!n,isError:s.isError,error:s.error}},ws=(t,n)=>{const r=Object.entries(t?.concentration_curve||{}).map(([l,s])=>{const a=n.find(d=>d.id===l),i=s.map(d=>[d.x,d.y]);return{name:a?.name||`Metric ${l}`,id:l,type:"line",animation:!1,color:Ne(l,n),data:[[0,0],...i]}});return{...fe,chart:{...fe.chart},xAxis:{title:{text:"Percentage of Paths"},min:0,max:100,labels:{format:"{value}%"}},yAxis:{title:{text:"Percentage of Value"},min:0,max:100,labels:{format:"{value}%"},gridLineWidth:1,gridLineColor:"#E5E7EB"},tooltip:{headerFormat:"<b>Top {point.x:.0f}% of Paths</b><br/>",pointFormat:"Contribute <b>{point.y:.0f}%</b> of total <b>{series.name}</b><br/>",shared:!0,crosshairs:!0},series:r}},Ss=t=>de({queryKey:["metricsExplorer","concentrationCurve","poll",t],queryFn:()=>{if(!t)throw new Error("Key is required for polling concentration curve");return Dt(t)},enabled:!!t,staleTime:1/0}),Ns=(t,n)=>{const r=re(Ss(t));return{data:r.data,isLoading:r.isLoading,isFetching:r.isFetching||!!n,isError:r.isError,error:r.error}},Es=()=>{const{availableMetrics:t,runAllKey:n,isRunAllLoading:r}=ee(),{data:l,isFetching:s,error:a}=Ns(n,r);return e.jsxs("div",{children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Concentration Curve"}),e.jsxs("div",{className:"p-6",children:[s&&e.jsxs("div",{className:"flex flex-col items-center justify-center p-12",children:[e.jsx(ie,{size:"lg"}),e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Loading concentration curve..."}),e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"This request can take 30-60 seconds to complete."}),e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"If this fails, please try again."})]})]}),!s&&a&&e.jsx(X,{variant:"error",children:e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-red-800",children:"Failed to load concentration curve"}),e.jsx("p",{className:"mt-2 text-sm text-red-700",children:a instanceof Error?l?.error_message??a.message:"An unexpected error occurred while loading concentration curve data. Please try again."})]})}),!s&&!a&&l&&e.jsx(Ze,{config:ws(l,t)})]})]})},Ps=({coverageData:t,isFetching:n,error:r,availableMetrics:l})=>{const s=p.useMemo(()=>t?.coverage_summary?Object.entries(t.coverage_summary).map(([a,i])=>{const d=l.find(f=>f.id===a);return{id:a,name:d?.name||`Metric ${a}`,source:d?.source||"Unknown",uniquePaths:i.num_unique_paths,dailyAverage:i.average_daily_sessions}}):[],[t,l]);return e.jsxs("div",{children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Coverage Summary"}),n&&e.jsxs("div",{className:"flex flex-col items-center justify-center p-12",children:[e.jsx(ie,{size:"lg"}),e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Loading coverage summary..."}),e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"This request can take 30-60 seconds to complete."}),e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"If this fails, please try again."})]})]}),!n&&r&&e.jsx("div",{className:"mb-4",children:e.jsx(X,{variant:"error",children:e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-red-800",children:"Failed to load coverage summary"}),e.jsx("p",{className:"mt-2 text-sm text-red-700",children:r instanceof Error?t?.error_message??r.message:"An unexpected error occurred while loading coverage summary data. Please try again."})]})})}),!n&&!r&&t&&e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Se,{children:[e.jsx("thead",{children:e.jsxs(Ye,{children:[e.jsx(Y,{children:"Metric"}),e.jsx(Y,{children:"Source"}),e.jsx(Y,{children:"Unique Paths"}),e.jsx(Y,{children:"Average Daily Sessions"})]})}),e.jsx("tbody",{children:s.map(a=>{const i=Ne(a.id,l);return e.jsxs(ce,{className:"text-sm text-gray-600",children:[e.jsx(z,{className:"text-gray-900",style:{borderLeft:`4px solid ${i}`},children:a.name}),e.jsx(z,{children:a.source}
1),e.jsx(z,{children:a.uniquePaths?a.uniquePaths.toLocaleString():"-"}),e.jsx(z,{children:a.dailyAverage?a.dailyAverage.toLocaleString(void 0,{maximumFractionDigits:0}):"-"})]},a.id)})})]})})]})},Ds=()=>{const{availableMetrics:t,shouldFetchData:n,startDate:r,endDate:l,runAllKey:s,isRunAllLoading:a}=ee(),[i,d]=p.useState(r),[f,j]=p.useState(l),{data:P,isFetching:S,error:w}=Cs(s,a),{data:E,isFetching:M,error:h}=bs(s,a);return p.useEffect(()=>{n&&(d(r),j(l))},[n,r,l]),e.jsx("div",{className:"flex flex-col gap-y-6",children:e.jsxs(ye,{children:[e.jsx(Q,{children:e.jsx("div",{className:"flex w-full items-center justify-between",children:e.jsxs(Q.Title,{children:["Metric Overview",e.jsxs("span",{className:"ml-4 font-mono text-sm text-gray-500",children:[i," â ",f]})]})})}),e.jsxs("div",{children:[e.jsx("div",{className:"p-6",children:e.jsx(Ps,{coverageData:E,isFetching:M,error:h??null,availableMetrics:t})}),e.jsxs("div",{className:"flex flex-col gap-y-8 p-6",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Trend Over Time"}),S&&e.jsxs("div",{className:"flex flex-col items-center justify-center p-12",children:[e.jsx(ie,{size:"lg"}),e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Loading overview metrics..."}),e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"This request can take 30-60 seconds to complete."}),e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"If this fails, please try again."})]})]}),!S&&w&&e.jsx(X,{variant:"error",children:e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-red-800",children:"Failed to load overview metrics"}),e.jsx("p",{className:"mt-2 text-sm text-red-700",children:w instanceof Error?P?.error_message??w.message:"An unexpected error occurred while loading overview metrics data. Please try again."})]})}),!S&&!w&&P&&e.jsx(Ze,{config:ys(P,t)})]}),e.jsx("div",{className:"p-6",children:e.jsx(Es,{})})]})]})})},Ms=me("/$clientSlug/metrics-explorer"),As=t=>de({queryKey:["metricsExplorer","popularPaths","poll",t],queryFn:()=>{if(!t)throw new Error("Key is required for polling popular paths");return Mt(t)},enabled:!!t,staleTime:1/0}),Fs=(t,n)=>{const{clientSlug:r}=Ms.useParams(),l=p.useRef(null);p.useEffect(()=>{t&&(l.current=Date.now())},[t]);const s=re(As(t));return p.useEffect(()=>{if((s.isSuccess||s.isError)&&l.current){const a=(Date.now()-l.current)/1e3,i=s.isError||!!s.data?.error_message;ve(r,"Metrics Explorer Popular Paths Fetched",{duration_seconds:a,duration_bucket:we(a),status:i?"Error":"Success"}),l.current=null}},[s.isSuccess,s.isError,s.data,r]),{data:s.data,isLoading:s.isLoading,isFetching:s.isFetching||!!n,isError:s.isError,error:s.error}},Ts=100,Os=10,Ls=()=>{const{selectedMetrics:t,availableMetrics:n,shouldFetchData:r,startDate:l,endDate:s,runAllKey:a,isRunAllLoading:i}=ee(),[d,f]=p.useState(l),[j,P]=p.useState(s),[S,w]=p.useState(t),[E,M]=p.useState(Os),[h,A]=p.useState(0),{data:I,isFetching:b,error:v}=Fs(a,i);p.useEffect(()=>{r&&(f(l),P(s),w(t),A(0))},[r,t,l,s]);const F=S.map(q=>({id:q,name:n.find(V=>V.id===q)?.name||`Metric ${q}`})),R=p.useMemo(()=>{if(!I?.popular_paths)return[];const q=Object.entries(I.popular_paths);if(S.length===0)return q;const V=S[0];return q.sort(([,G],[,_])=>{const C=G[V]||0;return(_[V]||0)-C})},[I?.popular_paths,S]),k=p.useMemo(()=>R.slice(h,h+E),[R,h,E]),H=R.length;return e.jsxs(ye,{children:[e.jsx(Q,{children:e.jsx(Q.Content,{children:e.jsxs(Q.Title,{children:["Popular Paths",e.jsxs("span",{className:"ml-4 font-mono text-sm text-gray-500",children:[d," â ",j]})]})})}),b&&e.jsxs("div",{className:"flex flex-col items-center justify-center p-12",children:[e.jsx(ie,{size:"lg"}),e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Loading popular paths..."}),e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"This request can take 30-60 seconds to complete."}),e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"If this fails, please try again."})]})]}),!b&&v&&e.jsx("div",{className:"p-6",children:e.jsx(X,{variant:"error",children:e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-red-800",children:"Failed to load popular paths"}),e.jsx("p",{className:"mt-2 text-sm text-red-700",children:v instanceof Error?I?.error_message??v.message:"An unexpected error occurred while loading popular paths data. Please try again."})]})})}),!b&&!v&&I&&e.jsx("div",{className:"flex flex-col gap-y-8 p-6",children:e.jsxs("div",{children:[e.jsxs(X,{className:"mb-4",variant:"info",children:["This table shows the top ",Ts," paths by total traffic for the selected date range, sorted by the first selected metric. To sort by another metric, select that metric first."]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full divide-y divide-gray-200",children:[e.jsx("thead",{className:"bg-gray-50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500",children:"Path"}),F.map(q=>e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500",children:q.name},q.id))]})}),e.jsx("tbody",{className:"divide-y divide-gray-200 bg-white",children:k.map(([q,V])=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"max-w-xs break-all px-6 py-4 text-sm font-medium text-gray-900",children:e.jsx("div",{className:"break-words",children:q})}),S.map(G=>{const _=V[G]||0,C=I.totals[G]||0,g=C>0?_/C*100:0;return e.jsxs("td",{className:"whitespace-nowrap px-6 py-4 text-sm text-gray-500",children:[_.toLocaleStr
1ing(),e.jsxs("span",{className:"ml-2 text-gray-400",children:["(",g.toFixed(1),"%)"]})]},G)})]},q))})]})}),H>0&&e.jsx("div",{className:"mt-4 border-t border-gray-200 pt-4",children:e.jsx(Qe,{totalCount:H,listItems:k,setLimit:M,setOffset:A,offset:h,limit:E,options:[10,25,50,100],allOption:!1})})]})})]})},Is=t=>de({queryKey:["metricsExplorer","metricCorrelation","poll",t],queryFn:()=>{if(!t)throw new Error("Key is required for polling metric correlation");return At(t)},enabled:!!t,staleTime:1/0}),Rs=(t,n)=>{const r=re(Is(t));return{data:r.data,isLoading:r.isLoading,isFetching:r.isFetching||!!n,isError:r.isError,error:r.error}},ks=()=>{const{selectedMetrics:t,availableMetrics:n,runAllKey:r,isRunAllLoading:l}=ee(),{data:s,isFetching:a,error:i}=Rs(r,l);if(a)return e.jsxs("div",{children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Correlation Analysis"}),e.jsxs("div",{className:"flex flex-col items-center justify-center p-12",children:[e.jsx(ie,{size:"lg"}),e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Calculating metric correlations..."}),e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"This request can take 30-60 seconds to complete."}),e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"If this fails, please try again."})]})]})]});if(i)return e.jsxs("div",{children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Correlation Analysis"}),e.jsx(X,{variant:"error",children:e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-red-800",children:"Failed to load metric correlations"}),e.jsx("p",{className:"mt-2 text-sm text-red-700",children:i instanceof Error?s?.error_message??i.message:"An unexpected error occurred while loading correlation data. Please try again."})]})})]});if(!a&&!i&&s){const{correlations:d,error_message:f}=s;if(f)return e.jsxs("div",{children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Correlation Analysis"}),e.jsx(X,{variant:"info",children:f})]});const j=n.filter(E=>t.includes(E.id)),P=(E,M)=>{const h=`${E},${M}`,A=`${M},${E}`;return(d[h]||d[A])?.correlation??null},S=E=>E===null?"-":E.toFixed(2),w=E=>{if(E===null)return"transparent";const M=Math.abs(E),h=Math.min(M,1)*.5;return E>0?`rgba(46, 144, 250, ${h})`:`rgba(180, 35, 24, ${h})`};return e.jsxs("div",{children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Correlation Analysis"}),e.jsxs(Se,{tableLayout:"fixed",children:[e.jsx("thead",{children:e.jsxs(Ye,{children:[e.jsx(Y,{style:{width:"200px"},children:"Metric"}),j.map(E=>e.jsx(Y,{className:"text-center",style:{flex:1},children:E.name},E.id))]})}),e.jsx("tbody",{children:j.map((E,M)=>e.jsxs(ce,{children:[e.jsx(z,{extraClasses:"font-medium text-gray-900",style:{borderLeft:`4px solid ${Ne(E.id,n)}`},children:E.name}),j.map((h,A)=>{if(A>M)return e.jsx(z,{},`${E.id}-${h.id}`);const I=P(E.id,h.id);return e.jsx(z,{extraClasses:"text-center",style:{backgroundColor:w(I)},children:S(I)},`${E.id}-${h.id}`)})]},E.id))})]})]})}return null},$s=(t,n,r,l)=>{const s=[],a=Object.entries(t);return a.forEach(([i])=>{const d=i.split(",").sort(),f=d.length>1,j=a.reduce((w,[E,M])=>{const h=E.split(",");return d.every(I=>h.includes(I))?w+Number(M):w},0),P=d.map(w=>n.find(E=>String(E.id)===w)?.name||w).join(" & ");let S;if(d.length===1){const w=r.indexOf(d[0]);w!==-1&&(S=l[w%l.length])}s.push({sets:d,value:Math.pow(j,.6),name:P,color:S,dataLabels:f?{enabled:!1}:void 0,realValue:j})}),s},qs=t=>de({queryKey:["metricsExplorer","pathOverlap","poll",t],queryFn:()=>{if(!t)throw new Error("Key is required for polling path overlap");return Ft(t)},enabled:!!t,staleTime:1/0}),Bs=(t,n)=>{const r=re(qs(t??void 0));return{data:r.data,isLoading:r.isLoading,isFetching:r.isFetching||!!n,isError:r.isError,error:r.error}};var Pe={exports:{}},Ve;function Vs(){return Ve||(Ve=1,(function(t){(function(n){t.exports?(n.default=n,t.exports=n):n(typeof Highcharts<"u"?Highcharts:void 0)})(function(n){var r=n?n._modules:{};function l(s,a,i,d){s.hasOwnProperty(a)||(s[a]=d.apply(null,i),typeof CustomEvent=="function"&&window.dispatchEvent(new CustomEvent("HighchartsM
1oduleLoaded",{detail:{path:a,module:s[a]}})))}l(r,"Core/Geometry/GeometryUtilities.js",[],function(){var s,a;return(a=s||(s={})).getCenterOfPoints=function(i){let d=i.reduce((f,j)=>(f.x+=j.x,f.y+=j.y,f),{x:0,y:0});return{x:d.x/i.length,y:d.y/i.length}},a.getDistanceBetweenPoints=function(i,d){return Math.sqrt(Math.pow(d.x-i.x,2)+Math.pow(d.y-i.y,2))},a.getAngleBetweenPoints=function(i,d){return Math.atan2(d.x-i.x,d.y-i.y)},s}),l(r,"Core/Geometry/CircleUtilities.js",[r["Core/Geometry/GeometryUtilities.js"]],function(s){var a;let{getAngleBetweenPoints:i,getCenterOfPoints:d,getDistanceBetweenPoints:f}=s;return(function(j){function P(b,v){let F=Math.pow(10,v);return Math.round(b*F)/F}function S(b){if(b<=0)throw Error("radius of circle must be a positive number.");return Math.PI*b*b}function w(b,v){return b*b*Math.acos(1-v/b)-(b-v)*Math.sqrt(v*(2*b-v))}function E(b,v){let F=f(b,v),R=b.r,k=v.r,H=[];if(F<R+k&&F>Math.abs(R-k)){let q=R*R,V=(q-k*k+F*F)/(2*F),G=Math.sqrt(q-V*V),_=b.x,C=v.x,g=b.y,O=v.y,u=_+V*(C-_)/F,m=g+V*(O-g)/F,o=-(G/F*(O-g)),x=-(G/F*(C-_));H=[{x:P(u+o,14),y:P(m-x,14)},{x:P(u-o,14),y:P(m+x,14)}]}return H}function M(b){return b.reduce((v,F,R,k)=>{let H=k.slice(R+1).reduce((q,V,G)=>{let _=[R,G+R+1];return q.concat(E(F,V).map(C=>(C.indexes=_,C)))},[]);return v.concat(H)},[])}function h(b,v){return f(b,v)<=v.r+1e-10}function A(b,v){return!v.some(function(F){return!h(b,F)})}function I(b){return M(b).filter(function(v){return A(v,b)})}j.round=P,j.getAreaOfCircle=S,j.getCircularSegmentArea=w,j.getOverlapBetweenCircles=function(b,v,F){let R=0;if(F<b+v){if(F<=Math.abs(v-b))R=S(b<v?b:v);else{let k=(b*b-v*v+F*F)/(2*F);R=w(b,b-k)+w(v,v-(F-k))}R=P(R,14)}return R},j.getCircleCircleIntersection=E,j.getCirclesIntersectionPoints=M,j.isCircle1CompletelyOverlappingCircle2=function(b,v){return f(b,v)+v.r<b.r+1e-10},j.isPointInsideCircle=h,j.isPointInsideAllCircles=A,j.isPointOutsideAllCircles=function(b,v){return!v.some(function(F){return h(b,F)})},j.getCirclesIntersectionPolygon=I,j.getAreaOfIntersectionBetweenCircles=function(b){let v=I(b),F;if(v.length>1){let R=d(v),k=(v=v.map(function(q){return q.angle=i(R,q),q}).sort(function(q,V){return V.angle-q.angle}))[v.length-1],H=v.reduce(function(q,V){let{startPoint:G}=q,_=d([G,V]),C=V.indexes.filter(function(g){return G.indexes.indexOf(g)>-1}).reduce(function(g,O){let u=b[O],m=i(u,V),o=i(u,G),x=o-(o-m+(o<m?2*Math.PI:0))/2,y=f(_,{x:u.x+u.r*Math.sin(x),y:u.y+u.r*Math.cos(x)}),{r:c}=u;return y>2*c&&(y=2*c),(!g||g.width>y)&&(g={r:c,largeArc:y>c?1:0,width:y,x:V.x,y:V.y}),g},null);if(C){let{r:g}=C;q.arcs.push(["A",g,g,0,C.largeArc,1,C.x,C.y]),q.startPoint=V}return q},{startPoint:k,arcs:[]}).arcs;H.length===0||H.length===1||(H.unshift(["M",k.x,k.y]),F={center:R,d:H})}return F}})(a||(a={})),a}),l(r,"Series/DrawPointUtilities.js",[],function(){return{draw:function(s,a){let{animatableAttribs:i,onComplete:d,css:f,renderer:j}=a,P=s.series&&s.series.chart.hasRendered?void 0:s.series&&s.series.options.animation,S=s.graphic;if(a.attribs={...a.attribs,class:s.getClassName()},s.shouldDraw())S||(S=a.shapeType==="text"?j.text():a.shapeType==="image"?j.image(a.imageUrl||"").attr(a.shapeArgs||{}):j[a.shapeType](a.shapeArgs||{}),s.graphic=S,S.add(a.group)),f&&S.css(f),S.attr(a.attribs).animate(i,!a.isNew&&P,d);else if(S){let w=()=>{s.graphic=S=S&&S.destroy(),typeof d=="function"&&d()};Object.keys(i).length?S.animate(i,void 0,()=>w()):w()}}}}),l(r,"Series/Venn/VennPoint.js",[r["Core/Series/SeriesRegistry.js"],r["Core/Utilities.js"]],function(s,a){let{scatter:{prototype:{pointClass:i}}}=s.seriesTypes,{isNumber:d}=a;return class extends i{isValid(){return d(this.value)}shouldDraw(){return!!this.shapeArgs}}}),l(r,"Series/Venn/VennSeriesDefaults.js",[],function(){return{borderColor:"#cccccc",borderDashStyle:"solid",borderWidth:1,brighten:0,clip:!1,colorByPoint:!0,dataLabels:{enabled:!0,verticalAlign:"middle",formatter:function(){return this.point.name}},inactiveOtherPoints:!0,marker:!1,opacity:.75,showInLegend:!1,legendType:"point",states:{hover:{opacity:1,borderColor:"#333333"},select:{color:"#cccccc",borderColor:"#000000",animation:!1},inactive:{opacity:.075}},tooltip:{pointFormat:"{point.name}: {point.value}"},legendSymbol:"rectangle"}}),l(r,"Series/Venn/VennUtils.js",[r["Core/Geometry/CircleUtilities.js"],r["Core/Geometry/GeometryUtilities.js"],r["Core/Utilities.js"]],function(s,a,i){let{getAreaOfCircle:d,getCircleCircleIntersection:f,getOverlapBetweenCircles:j,isPointInsideAllCircles:P,isPointInsideCircle:S,isPointOutsideAllCircles:w}=s,{getDistanceBetweenPoints:E}=a,{extend:M,isArray:h,isNumber:A,isObject:I,isString:b}=i;function v(_){let C={};return _.filter(g=>g.sets.length===2).forEach(g=>
1{g.sets.forEach((O,u,m)=>{I(C[O])||(C[O]={totalOverlap:0,overlapping:{}}),C[O]={totalOverlap:(C[O].totalOverlap||0)+g.value,overlapping:{...C[O].overlapping||{},[m[1-u]]:g.value}}})}),_.filter(H).forEach(g=>{let O=C[g.sets[0]];M(g,O)}),_}function F(_,C,g,O,u){let m=_(C),o=_(g),x=100,y=1e-10,c=g-C,N,D,$=1;if(C>=g)throw Error("a must be smaller than b.");if(m*o>0)throw Error("f(a) and f(b) must have opposite signs.");if(m===0)N=C;else if(o===0)N=g;else for(;$++<=x&&D!==0&&c>y;)c=(g-C)/2,m*(D=_(N=C+c))>0?C=N:g=N;return N}function R(_){let C=_.slice(0,-1),g=C.length,O=[],u=(m,o)=>(m.sum+=o[m.i],m);for(let m=0;m<g;m++)O[m]=C.reduce(u,{sum:0,i:m}).sum/g;return O}function k(_,C,g){let O=_+C;return g<=0?O:d(_<C?_:C)<=g?0:F(u=>g-j(_,C,u),0,O)}function H(_){return h(_.sets)&&_.sets.length===1}function q(_){let C={};return I(_)&&A(_.value)&&_.value>-1&&h(_.sets)&&_.sets.length>0&&!_.sets.some(function(g){let O=!1;return!C[g]&&b(g)?C[g]=!0:O=!0,O})}function V(_,C){return C.reduce(function(g,O){let u=0;if(O.sets.length>1){let m=O.value-(function(o){let x=0;if(o.length===2){let y=o[0],c=o[1];x=j(y.r,c.r,E(y,c))}return x})(O.sets.map(function(o){return _[o]}));u=Math.round(m*m*1e11)/1e11}return g+u},0)}function G(_,C){return C.totalOverlap!==void 0&&_.totalOverlap!==void 0?C.totalOverlap-_.totalOverlap:NaN}return{geometry:a,geometryCircles:s,addOverlapToSets:v,getCentroid:R,getDistanceBetweenCirclesByOverlap:k,getLabelWidth:function(_,C,g){let O=C.reduce((o,x)=>Math.min(x.r,o),1/0),u=g.filter(o=>!S(_,o)),m=function(o,x){return F(y=>{let c={x:_.x+x*y,y:_.y};return-(o-y)+(P(c,C)&&w(c,u)?0:Number.MAX_VALUE)},0,o)};return 2*Math.min(m(O,-1),m(O,1))},getMarginFromCircles:function(_,C,g){let O=C.reduce((u,m)=>{let o=m.r-E(_,m);return o<=u?o:u},Number.MAX_VALUE);return g.reduce((u,m)=>{let o=E(_,m)-m.r;return o<=u?o:u},O)},isSet:H,layoutGreedyVenn:function(_){let C=[],g={};_.filter(o=>o.sets.length===1).forEach(o=>{g[o.sets[0]]=o.circle={x:Number.MAX_VALUE,y:Number.MAX_VALUE,r:Math.sqrt(o.value/Math.PI)}});let O=(o,x)=>{let y=o.circle;y&&(y.x=x.x,y.y=x.y),C.push(o)};v(_);let u=_.filter(H).sort(G);O(u.shift(),{x:0,y:0});let m=_.filter(o=>o.sets.length===2);for(let o of u){let x=o.circle;if(!x)continue;let y=x.r,c=o.overlapping;O(o,C.reduce((N,D,$)=>{let K=D.circle;if(!K||!c)return N;let te=c[D.sets[0]],ae=k(y,K.r,te),J=[{x:K.x+ae,y:K.y},{x:K.x-ae,y:K.y},{x:K.x,y:K.y+ae},{x:K.x,y:K.y-ae}];for(let se of C.slice($+1)){let Z=se.circle,oe=c[se.sets[0]];if(!Z)continue;let L=k(y,Z.r,oe);J=J.concat(f({x:K.x,y:K.y,r:ae},{x:Z.x,y:Z.y,r:L}))}for(let se of J){x.x=se.x,x.y=se.y;let Z=V(g,m);Z<N.loss&&(N.loss=Z,N.coordinates=se)}return N},{loss:Number.MAX_VALUE,coordinates:void 0}).coordinates)}return g},loss:V,nelderMead:function(_,C){let g=function(y,c){return y.fx-c.fx},O=(y,c,N,D)=>c.map(($,K)=>y*$+N*D[K]),u=(y,c)=>(c.fx=_(c),y[y.length-1]=c,y),m=y=>{let c=y[0];return y.map(N=>{let D=O(.5,c,.5,N);return D.fx=_(D),D})},o=(y,c,N,D)=>{let $=O(N,y,D,c);return $.fx=_($),$},x=(y=>{let c=y.length,N=Array(c+1);N[0]=y,N[0].fx=_(y);for(let D=0;D<c;++D){let $=y.slice();$[D]=$[D]?1.05*$[D]:.001,$.fx=_($),N[D+1]=$}return N})(C);for(let y=0;y<100;y++){x.sort(g);let c=x[x.length-1],N=R(x),D=o(N,c,2,-1);if(D.fx<x[0].fx){let $=o(N,c,3,-2);x=u(x,$.fx<D.fx?$:D)}else if(D.fx>=x[x.length-2].fx){let $;x=D.fx>c.fx?($=o(N,c,.5,.5)).fx<c.fx?u(x,$):m(x):($=o(N,c,1.5,-.5)).fx<D.fx?u(x,$):m(x)}else x=u(x,D)}return x[0]},processVennData:function(_,C){let g=h(_)?_:[],O=g.reduce(function(m,o){var x;return o.sets&&q(x=o)&&H(x)&&x.value>0&&m.indexOf(o.sets[0])===-1&&m.push(o.sets[0]),m},[]).sort(),u=g.reduce(function(m,o){return o.sets&&q(o)&&!o.sets.some(function(x){return O.indexOf(x)===-1})&&(m[o.sets.sort().join(C)]={sets:o.sets,value:o.value||0}),m},{});
1return O.reduce(function(m,o,x,y){return y.slice(x+1).forEach(function(c){m.push(o+C+c)}),m},[]).forEach(function(m){if(!u[m]){let o={sets:m.split(C),value:0};u[m]=o}}),Object.keys(u).map(function(m){return u[m]})},sortByTotalOverlap:G}}),l(r,"Series/Venn/VennSeries.js",[r["Core/Animation/AnimationUtilities.js"],r["Core/Color/Color.js"],r["Core/Geometry/CircleUtilities.js"],r["Series/DrawPointUtilities.js"],r["Core/Geometry/GeometryUtilities.js"],r["Core/Series/SeriesRegistry.js"],r["Series/Venn/VennPoint.js"],r["Series/Venn/VennSeriesDefaults.js"],r["Series/Venn/VennUtils.js"],r["Core/Utilities.js"]],function(s,a,i,d,f,j,P,S,w,E){let{animObject:M}=s,{parse:h}=a,{getAreaOfIntersectionBetweenCircles:A,getCirclesIntersectionPolygon:I,isCircle1CompletelyOverlappingCircle2:b,isPointInsideAllCircles:v,isPointOutsideAllCircles:F}=i,{getCenterOfPoints:R}=f,{scatter:k}=j.seriesTypes,{addEvent:H,extend:q,isArray:V,isNumber:G,isObject:_,merge:C}=E;class g extends k{static getLabelPosition(u,m){let o=u.reduce((y,c)=>{let N=c.r/2;return[{x:c.x,y:c.y},{x:c.x+N,y:c.y},{x:c.x-N,y:c.y},{x:c.x,y:c.y+N},{x:c.x,y:c.y-N}].reduce((D,$)=>{let K=w.getMarginFromCircles($,u,m);return D.margin<K&&(D.point=$,D.margin=K),D},y)},{point:void 0,margin:-Number.MAX_VALUE}).point,x=w.nelderMead(y=>-w.getMarginFromCircles({x:y[0],y:y[1]},u,m),[o.x,o.y]);return v(o={x:x[0],y:x[1]},u)&&F(o,m)||(o=u.length>1?R(I(u)):{x:u[0].x,y:u[0].y}),o}static getLabelValues(u,m){let o=u.sets,x=m.reduce((N,D)=>{let $=o.indexOf(D.sets[0])>-1;return D.circle&&N[$?"internal":"external"].push(D.circle),N},{internal:[],external:[]});x.external=x.external.filter(N=>x.internal.some(D=>!b(N,D)));let y=g.getLabelPosition(x.internal,x.external),c=w.getLabelWidth(y,x.internal,x.external);return{position:y,width:c}}static layout(u){let m={},o={};if(u.length>0){let x=w.layoutGreedyVenn(u),y=u.filter(w.isSet);for(let c of u){let N=c.sets,D=N.join(),$=w.isSet(c)?x[D]:A(N.map(K=>x[K]));$&&(m[D]=$,o[D]=g.getLabelValues(c,y))}}return{mapOfIdToShape:m,mapOfIdToLabelValues:o}}static getScale(u,m,o){let x=o.bottom-o.top,y=o.right-o.left,c=(o.right+o.left)/2,N=(o.top+o.bottom)/2,D=Math.min(y>0?1/y*u:1,x>0?1/x*m:1);return{scale:D,centerX:u/2-c*D,centerY:m/2-N*D}}static updateFieldBoundaries(u,m){let o=m.x-m.r,x=m.x+m.r,y=m.y+m.r,c=m.y-m.r;return(!G(u.left)||u.left>o)&&(u.left=o),(!G(u.right)||u.right<x)&&(u.right=x),(!G(u.top)||u.top>c)&&(u.top=c),(!G(u.bottom)||u.bottom<y)&&(u.bottom=y),u}animate(u){if(!u){let m=M(this.options.animation);for(let o of this.points){let x=o.shapeArgs;if(o.graphic&&x){let y={},c={};x.d?y.opacity=.001:(y.r=0,c.r=x.r),o.graphic.attr(y).animate(c,m),x.d&&setTimeout(()=>{o&&o.graphic&&o.graphic.animate({opacity:1})},m.duration)}}}}drawPoints(){let u=this.chart,m=this.group,o=this.points||[],x=u.renderer;for(let y of o){let c={zIndex:V(y.sets)?y.sets.length:0},N=y.shapeArgs;u.styledMode||q(c,this.pointAttribs(y,y.state)),d.draw(y,{isNew:!y.graphic,animatableAttribs:N,attribs:c,group:m,renderer:x,shapeType:N&&N.d?"path":"circle"})}}init(){k.prototype.init.apply(this,arguments),delete this.opacity}pointAttribs(u,m){let o=this.options||{},x=u&&u.options||{},y=m&&o.states[m]||{},c=C(o,{color:u&&u.color},x,y);return{fill:h(c.color).brighten(c.brightness).get(),opacity:c.opacity,stroke:c.borderColor,"stroke-width":c.borderWidth,dashstyle:c.borderDashStyle}}translate(){let u=this.chart;this.processedXData=this.xData,this.generatePoints();let m=w.processVennData(this.options.data,g.splitter),{mapOfIdToShape:o,mapOfIdToLabelValues:x}=g.layout(m),y=Object.keys(o).filter(K=>{let te=o[K];return te&&G(te.r)}).reduce((K,te)=>g.updateFieldBoundaries(K,o[te]),{top:0,bottom:0,left:0,right:0}),c=g.getScale(u.plotWidth,u.plotHeight,y),N=c.scale,D=c.centerX,$=c.centerY;for(let K of this.points){let te=V(K.sets)?K.sets:[],ae=te.join(),J=o[ae],se=x[ae]||{},Z=K.options&&K.options.dataLabels,oe,L=se.width,T=se.position;if(J){if(J.r)oe={x:D+J.x*N,y:$+J.y*N,r:J.r*N};else if(J.d){let B=J.d;B.forEach(U=>{U[0]==="M"?(U[1]=D+U[1]*N,U[2]=$+U[2]*N):U[0]==="A"&&(U[1]=U[1]*N,U[2]=U[2]*N,U[6]=D+U[6]*N,U[7]=$+U[7]*N)}),oe={d:B}}T?(T.x=D+T.x*N,T.y=$+T.y*N):T={},G(L)&&(L=Math.round(L*N))}K.shapeArgs=oe,T&&oe&&(K.plotX=T.x,K.plotY=T.y),L&&oe&&(K.dlOptions=C(!0,{style:{width:L}},_(Z,!0)?Z:void 0)),K.name=K.options.name||te.join("â©")}}}return g.splitter="highcharts-split",g.defaultOptions=C(k.defaultOptions,S),q(g.prototype,{axisTypes:[],directTouch:!0,isCartesian:!1,pointArrayMap:["value"],pointClass:P,utils:w}),H(g,"afterSetOptions",function(O){let u=O.options.states||{};if(this.is("venn"))for(let m of Object.keys(u))u[m].halo=!1}),j.registerSeriesType("venn",g),g}),l(r,"masters/modules/venn.src.js",[r["Core/Globals.js"]],function(s){return s})})})(Pe)),Pe.exports}var Us=Vs();const Ks=Tt(Us);Ks(Me);const Hs=({data:t,colors:n})=>{const r=p.useMemo(()=>{const s=new Map;return t.forEach(a=>{a.sets.length===1&&a.color&&s.set(a.sets[0],a.color)}),t.map(a=>
1{if(a.sets.length>1&&!a.color){const i=a.sets.map(d=>s.get(d)).filter(d=>!!d);if(i.length>0){let d=0,f=0,j=0,P=0;i.forEach(E=>{const M=Me.color(E).rgba;d+=M[0],f+=M[1],j+=M[2],P+=M[3]});const S=i.length,w=`rgba(${Math.round(d/S)}, ${Math.round(f/S)}, ${Math.round(j/S)}, ${P/S})`;return{...a,color:w}}}return a})},[t]),l={chart:{type:"venn",marginTop:30},colors:n,title:{text:void 0},credits:{enabled:!1},tooltip:{enabled:!0,useHTML:!0,pointFormat:"<b>{point.name}</b><br/>Paths: {point.realValue}"},series:[{type:"venn",name:"Path Overlap",data:r,opacity:.8,borderWidth:1,borderColor:"#ffffff",dataLabels:{enabled:!0,useHTML:!0,format:'<div style="text-align: center">{point.name}</div>',verticalAlign:"center",allowOverlap:!0,style:{textOutline:"none",color:"#344054",fontSize:"13px",fontWeight:"600",fontFamily:"Source Sans Pro, sans-serif"}}}]};return e.jsx(qt,{highcharts:Me,options:l})},Gs=()=>{const{selectedMetrics:t,availableMetrics:n,runAllKey:r,isRunAllLoading:l}=ee(),{data:s,isFetching:a,error:i}=Bs(r,l);if(a)return e.jsxs("div",{className:"mt-8",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Path Overlap"}),e.jsxs("div",{className:"flex flex-col items-center justify-center p-12",children:[e.jsx(ie,{size:"lg"}),e.jsxs("div",{className:"mt-4 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Calculating path overlap..."}),e.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"This request can take 30-60 seconds to complete."})]})]})]});if(i)return e.jsxs("div",{className:"mt-8",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Path Overlap"}),e.jsx(X,{variant:"error",children:e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-red-800",children:"Failed to load path overlap data"}),e.jsx("p",{className:"mt-2 text-sm text-red-700",children:i instanceof Error?s?.error_message??i.message:"An unexpected error occurred while loading path overlap data."})]})})]});if(!a&&!i&&s){const{path_overlap:d,error_message:f}=s;if(f)return e.jsxs("div",{className:"mt-8",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Path Overlap"}),e.jsx(X,{variant:"info",children:f})]});const j=fe.colors,P=$s(d,n,t,j);return e.jsxs("div",{className:"mt-8",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-gray-900",children:"Path Overlap"}),Object.keys(d).length===0?e.jsx(X,{variant:"info",children:"No overlapping paths found for the selected metrics and time range."}):e.jsx(Hs,{data:P,colors:j})]})}return null},Ws=()=>{const{startDate:t,endDate:n,shouldFetchData:r}=ee(),[l,s]=p.useState(t),[a,i]=p.useState(n);return p.useEffect(()=>{r&&(s(t),i(n))},[r,t,n]),e.jsx("div",{className:"flex flex-col gap-y-6",children:e.jsxs(ye,{children:[e.jsx(Q,{children:e.jsxs(Q.Title,{children:["Metric Relationships",e.jsxs("span",{className:"ml-4 font-mono text-sm text-gray-500",children:[l," â ",a]})]})}),e.jsxs("div",{className:"p-6",children:[e.jsx(ks,{}),e.jsx(pe,{}),e.jsx(Gs,{})]})]})})},lt=me("/$clientSlug/metrics-explorer"),zs=()=>{const{clientSlug:t}=lt.useParams(),{selectedAnalyticsConfig:n,toggleAnalyticsConfig:r,availableAnalyticsConfigs:l,selectedMetrics:s,hasEverFetchedData:a,runAllError:i}=ee(),d=Je("navigation-react-target","data-can-see-metrics-relationship");p.useEffect(()=>{Ot(t,"Metrics Explorer Viewed",void 0)},[t]);let f=null;return n||(f=e.jsx("div",{children:e.jsx(X,{variant:"warning",message:"Please select a site to explore the data"})})),n&&(f=e.jsxs("div",{children:[e.jsx(fs,{}),i&&e.jsx(X,{variant:"error",message:`Failed to initiate analysis: ${i.message}`,className:"mb-6"}),s.length===0&&!a?e.jsx(X,{variant:"warning",message:"Please select at least one metric to explore the data"}):a?e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),d&&e.jsx(Ws,{}),e.jsx(Ls,{})]}):null,e.jsx(us,{})]})),e.jsxs(e.Fragment,{children:[e.jsx(It,{children:e.jsx("title",{children:"Metrics Explorer | SearchPilot"})}),e.jsxs(Lt,{children:[e.jsx(Re,{label:t,href:`/cl-${t}/dashboard/`}),e.jsx(Re,{label:"Metrics Explorer",href:"",currentCrumb:!0})]}),e.jsx("main",{className:"ml-auto w-full grow",children:e.jsxs("div",{className:"mx-auto mt-8 max-w-7xl items-center px-12",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("h1",{className:"text-sp-neutral-900 font-medium",children:"Metrics Explorer"}),e.jsx("p",{className:"text-md text-sp-neutral-400",children:"Configure and explore metrics across data sources"})]}),e.jsx(Bt,{selectedAnalyticsConfig:n,availableAnalyticsConfigs:l,toggleAnalyticsConfig:r}),f]})})]})},ir=()=>{const{clientSlug:t}=lt.useParams();return e.jsx(Qt,{clientSlug:t,children:e.jsx(zs,{})})};export{ir as default}; 2//# sourceMappingURL=MetricsExplorerApp-9QhWofkk.js.map
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.