1import{c as va,r as p,d as _e,j as e,ah as os,ai as ds,aj as hs,ak as ms,al as me,U as Ys,k as ra,T as Fs,E as Y,a4 as xs,ad as Ce,ae as Se,af as Ae,B as ee,C as Mr,g as Tt,R as St,e5 as Cx,m as ia,h as De,a as Ya,f as ws,b8 as ta,aN as Va,u as ya,aw as Ts,e as vs,aZ as gr,a_ as jr,N as Es,a$ as br,b4 as oi,b1 as en,b0 as xt,aa as Dt,O as Vs,Q as Us,V as Bs,X as zs,Y as Ct,ab as Ue,I as Me,as as Ut,y as _a,S as ga,ag as pt,ax as di,A as Qs,l as Xs,aY as Sx,aC as Ca,dp as $t,ao as ec,dd as Rr,cI as Mi,b5 as yt,a6 as la,a7 as ca,a8 as Ee,a9 as Ve,aV as zn,aX as on,aM as La,M as Ax,i as _t,F as sn,aU as vo,c0 as Ua,am as mt,aA as fa,Z as kt,G as lm,aR as pa,aT as _x,aW as Tx,W as mi,av as vr,ac as ui,at as yo,e6 as Dx,K as Mn,ar as xi,ay as Px,b3 as Xa,c2 as No,b9 as Mx,aB as Rx,au as Lx,b as $x,aL as Ox,aF as hi,dQ as cm,dA as Zr}from"./index-BR4A0sgq.js";import{C as _,b as q,c as W,a as T,d as Oe,e as Ix}from"./card-BQRAYPnC.js";import{W as Fx}from"./workplace-back-K_v07imS.js";import{S as cs}from"./skeleton-CKfIbqNP.js";import{T as Is}from"./trending-up-C8x4f6dy.js";import{T as Et}from"./trending-down-BLgvuGbA.js";import{E as Hs}from"./eye-B5sXytUM.js";import{T as lt}from"./target-BCLsgPZm.js";import{D as ct}from"./dollar-sign-BxIfB_wC.js";import{A as ja}from"./activity-D92QV3tc.js";import{Z as oa}from"./zap-csR3s-zN.js";import{U as Za}from"./user-check-xwK7ypES.js";import{I as bs}from"./info-YVVFOHFE.js";import{T as nn,a as rn,b as ht,c as fs,d as ln,e as Ke}from"./table-Bhhsjcp9.js";import{G as ot}from"./globe-DvsM9Fly.js";import{B as om,n as pi,e as wo,S as ko,a as Ex,f as kl,L as Hn,b as Vx,A as Ux,i as Ur,c as Bx,d as dm,E as zx,g as Jr,h as qx,C as mm,j as Gx,k as Dn,l as Wx,G as Hx,m as dn,o as Co,u as Kx,p as um,_ as Rc,q as xm,r as qn,s as hm,t as Yx,v as pm,w as Qx,x as fm,y as Xx,z as Zx,D as gm,F as Jx,H as eh,I as sh,J as Lc,K as $c,M as Oc,N as jm,O as bm,P as vm,Q as th,R as ym,T as ah,U as nh,V as rh,W as ih,X as Zt,Y as Bt,Z as at,$ as lh,a0 as ft,a1 as Jt,a2 as gt,a3 as ch,a4 as oh,a5 as dh,a6 as mh,a7 as uh,a8 as xh,a9 as Nm,aa as hh,ab as wm,ac as ph,ad as fh,ae as $n,af as gh,ag as jh,ah as bh,ai as vh,aj as yh,ak as Nh,al as wh,am as kh,an as qe,ao as nr,ap as Ch,aq as Sh,ar as Ah,as as _h,at as Th,au as Dh,av as Ph,aw as Mh,ax as km,ay as On,az as ir,aA as Rh}from"./generateCategoricalChart-D_vwS-fM.js";import{B as Lr}from"./BarChart-BhHzc00Z.js";import{B as Qt}from"./brain-DyzTCBfU.js";import{C as Ft}from"./circle-check-big-CwTw8rd2.js";import{L as sc}from"./lightbulb-BMJ1VZz8.js";import{R as Pt}from"./refresh-cw-D2xlX_Eb.js";import{M as yr,T as Cl}from"./trophy-BkbFr4W6.js";import{M as Nr}from"./mouse-pointer-CeZCqn4Y.js";import{P as Lh}from"./percent--9jzVaFb.js";import{C as Zs}from"./chart-column-DW9vbGSG.js";import{c as Cm,f as Sm}from"./formatDistanceToNow-JpROVgWq.js";import{i as Am,a as $h}from"./isSameDay-xXo9sGtv.js";import{s as vt}from"./subDays-C7Zq6MQY.js";import{u as Oh}from"./useQueries-Bh-rnJFH.js";import{F as Ih}from"./filter-DB1_vcny.js";import{C as Fh}from"./chevrons-up-down-C1nUOGF6.js";import{A as Eh}from"./arrow-up-DcWPfD6r.js";import{A as tc}from"./arrow-down-D22OEWCZ.js";import{A as Ta,a as Da,b as Pa,c as Ma}from"./accordion-2DgIQouI.js";import{S as Sl}from"./separator-KHQZwnKP.js";import{P as Ic,a as Fc,b as Ec}from"./popover-DrgHFNXN.js";import{C as So}from"./calendar-CH71zK2e.js";import{e as At}from"./endOfDay-uuB1QXVt.js";import{R as _m,b as Vh,d as Uh,e as Bh,f as Ao,g as _o,C as zh,n as ei,h as qh,j as Gh,k as Tm,B as Wh,o as Dm,m as Pm,U as Hh,z as To}from"./monotone-lC34qx73.js";import{P as wr,a as kr}from"./PieChart-T4bQ__dl.js";import{U as si}from"./user-plus-BFgLRuOt.js";import{S as Wt}from"./share-2-CnDLEKUx.js";import{M as tt}from"./monitor-1mSnfU_f.js";import{S as Ht}from"./smartphone-DDnYROFP.js";import{T as Ga}from"./tablet-D8XirVaf.js";import{L as Vt,a as Vc}from"./LineChart-DFzaSvBn.js";import{C as Cs}from"./circle-help-s7PyCplq.js";import{U as Al}from"./user-x-gNjmm1ol.js";import{A as In,a as Mm}from"./AreaChart-rC545AqG.js";import{C as Kh}from"./code-ByZ0fUZ6.js";import{C as tn}from"./circle-x-CtKF91fz.js";import{S as Do}from"./slider-DRsLn8jR.js";import{F as fi}from"./flask-conical-CQTLqsZl.js";import{P as Po}from"./palette-CP5RKDz5.js";import{P as ac}from"./pause-BQuKwQN0.js";import{D as Yh}from"./database-Ch10txOC.js";import{C as Rm}from"./credit-card-DSSagc5h.js";import{H as nc}from"./heart-C1SU9J4A.js";import{S as Qh}from"./stethoscope-FyA10Iy0.js";import{u as Xh}from"./index-Blbz3as0.js";import{S as Mo,a as Ro,b as Zh,c as Jh,d as ep}from"./sheet-DoXexeVo.js";import{M as rc}from"./message-square-OPzaQTQ4.js";import{F as sp}from"./file-up-By3-c_zE.js";import{U as ic}from"./upload-C3xJ0BOc.js";import{C as _l}from"./copy-Bj0VH2MD.js";import{C as Ri,a as Li,b as $i}from"./collapsible-D39vguo0.js";import{A as tp,b as ap,c as np,d as rp,e as ip,f as lp,g as cp,h as op}from"./alert-dialog-CyG-xpFx.js";import{u as lc}from"./index.esm-ZjQWzdkY.js";import{t as cc}from"./zod-BFLALQWM.js";import{F as oc,a as Ms,b as Rs,c as Ls,d as Ks,e as $s,f as kn}from"./form-D03BNhnI.js";import{P as gi}from"./pencil-CEwbN56p.js";import{C as Br}from"./camera-3dgs4TOl.js";import{L as Lm}from"./layout-grid-CCil7xrB.js";import{L as $m}from"./list-Dw7Ns1KF.js";
1import{C as Lo}from"./calendar-days-Dyk0G5vB.js";import{L as dp}from"./languages-a2Avryor.js";import{W as Tl}from"./wand-sparkles-DvwQbLqy.js";import{I as mp}from"./image-Bt4NnfKR.js";import{o as Uc,e as up,s as st,a3 as Kn,c as zr}from"./types-CcUWbt7A.js";import{p as $o}from"./parseISO-B2jUGorH.js";import{S as Om}from"./sliders-horizontal-DBkHzW0e.js";import{V as ji}from"./video-K5ZX3mpy.js";import{M as xp}from"./mouse-pointer-2-BoNDtjie.js";import"./index-VIVmUpGT.js";import"./differenceInCalendarMonths-CFx4qfxO.js";import"./endOfMonth-BV_8B1rm.js";import"./addDays-DertLOPk.js";import"./index-CKTFME4P.js";import"./startOfMonth-CYCfJW7D.js";import"./isAfter-04Nb28HA.js";/** 2 * @license lucide-react v0.453.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const hp=va("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/** 7 * @license lucide-react v0.453.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const dc=va("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** 12 * @license lucide-react v0.453.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const pp=va("ChartLine",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]]);/** 17 * @license lucide-react v0.453.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const fp=va("ChartPie",[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",key:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]]);/** 22 * @license lucide-react v0.453.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const gp=va("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** 27 * @license lucide-react v0.453.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const jp=va("MessagesSquare",[["path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z",key:"p1xzt8"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1",key:"1cx29u"}]]);/** 32 * @license lucide-react v0.453.0 - ISC 33 * 34 * This source code is licensed under the ISC license. 35 * See the LICENSE file in the root directory of this source tree. 36 */const Oo=va("OctagonX",[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** 37 * @license lucide-react v0.453.0 - ISC 38 * 39 * This source code is licensed under the ISC license. 40 * See the LICENSE file in the root directory of this source tree. 41 */const Im=va("Tv",[["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",ry:"2",key:"10ag99"}],["polyline",{points:"17 2 12 7 7 2",key:"11pgbg"}]]);/** 42 * @license lucide-react v0.453.0 - ISC 43 * 44 * This source code is licensed under the ISC license. 45 * See the LICENSE file in the root directory of this source tree. 46 */const mc=va("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** 47 * @license lucide-react v0.453.0 - ISC 48 * 49 * This source code is licensed under the ISC license. 50 * See the LICENSE file in the root directory of this source tree. 51 */const Ra=va("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.5
515 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);function bp(s){return Am(s,Cm(s))}function vp(s){return Am(s,vt(Cm(s),1))}function Io(s,t){return $h(s,-t)}const yp=Math.PI/180,Np=180/Math.PI;var Fm=-.14861,Bc=1.78277,zc=-.29227,Oi=-.90649,Cr=1.97294,Fo=Cr*Oi,Eo=Cr*Bc,Vo=Bc*zc-Oi*Fm;function wp(s){if(s instanceof cn)return new cn(s.h,s.s,s.l,s.opacity);s instanceof _m||(s=Vh(s));var t=s.r/255,a=s.g/255,n=s.b/255,i=(Vo*n+Fo*t-Eo*a)/(Vo+Fo-Eo),r=n-i,l=(Cr*(a-i)-zc*r)/Oi,c=Math.sqrt(l*l+r*r)/(Cr*i*(1-i)),o=c?Math.atan2(l,r)*Np-120:NaN;return new cn(o<0?o+360:o,c,i,s.opacity)}function ba(s,t,a,n){return arguments.length===1?wp(s):new cn(s,t,a,n??1)}function cn(s,t,a,n){this.h=+s,this.s=+t,this.l=+a,this.opacity=+n}Uh(cn,ba,Bh(zh,{brighter(s){return s=s==null?_o:Math.pow(_o,s),new cn(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?Ao:Math.pow(Ao,s),new cn(this.h,this.s,this.l*s,this.opacity)},rgb(){var s=isNaN(this.h)?0:(this.h+120)*yp,t=+this.l,a=isNaN(this.s)?0:this.s*t*(1-t),n=Math.cos(s),i=Math.sin(s);return new _m(255*(t+a*(Fm*n+Bc*i)),255*(t+a*(zc*n+Oi*i)),255*(t+a*(Cr*n)),this.opacity)}}));function Em(s){return function t(a){a=+a;function n(i,r){var l=s((i=ba(i)).h,(r=ba(r)).h),c=ei(i.s,r.s),o=ei(i.l,r.l),d=ei(i.opacity,r.opacity);return function(u){return i.h=l(u),i.s=c(u),i.l=o(Math.pow(u,a)),i.opacity=d(u),i+""}}return n.gamma=t,n}(1)}Em(qh);var qc=Em(ei);function as(s){for(var t=s.length/6|0,a=new Array(t),n=0;n<t;)a[n]="#"+s.slice(n*6,++n*6);return a}const kp=as("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"),Cp=as("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),Sp=as("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),Ap=as("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"),_p=as("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),Tp=as("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),Dp=as("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),Pp=as("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),Vm=as("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),Mp=as("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"),Ps=s=>Gh(s[s.length-1]);var Ii=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(as);const Rp=Ps(Ii);var Fi=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(as);const Lp=Ps(Fi);var Ei=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(as);const $p=Ps(Ei);var Vi=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(as);const Op=Ps(Vi);var Ui=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(as);const Ip=Ps(Ui);var Bi=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(as);const Fp=Ps(Bi);var zi=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(as);const Ep=Ps(zi);var qi=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d
517191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(as);const Vp=Ps(qi);var Gi=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(as);const Up=Ps(Gi);var Wi=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(as);const Bp=Ps(Wi);var Hi=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(as);const zp=Ps(Hi);var Ki=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(as);const qp=Ps(Ki);var Yi=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(as);const Gp=Ps(Yi);var Qi=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(as);const Wp=Ps(Qi);var Xi=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(as);const Hp=Ps(Xi);var Zi=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(as);const Kp=Ps(Zi);var Ji=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(as);const Yp=Ps(Ji);var el=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(as);const Qp=Ps(el);var sl=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(as);const Xp=Ps(sl);var tl=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(as);const Zp=Ps(tl);var al=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(as);const Jp=Ps(al);var nl=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ec
51ae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(as);const ef=Ps(nl);var rl=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(as);const sf=Ps(rl);var il=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(as);const tf=Ps(il);var ll=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(as);const af=Ps(ll);var cl=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(as);const nf=Ps(cl);var ol=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(as);const rf=Ps(ol);function lf(s){return s=Math.max(0,Math.min(1,s)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-s*(35.34-s*(2381.73-s*(6402.7-s*(7024.72-s*2710.57)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+s*(170.73+s*(52.82-s*(131.46-s*(176.58-s*67.37)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+s*(442.36-s*(2482.43-s*(6167.24-s*(6614.94-s*2475.67)))))))+")"}const cf=qc(ba(300,.5,0),ba(-240,.5,1));var of=qc(ba(-100,.75,.35),ba(80,1.5,.8)),df=qc(ba(260,.75,.35),ba(80,1.5,.8)),qr=ba();function mf(s){(s<0||s>1)&&(s-=Math.floor(s));var t=Math.abs(s-.5);return qr.h=360*s-100,qr.s=1.5-1.5*t,qr.l=.8-.9*t,qr+""}var Gr=Tm(),uf=Math.PI/3,xf=Math.PI*2/3;function hf(s){var t;
vendor: 5,708 bytes, line 51
51return s=(.5-s)*Math.PI,Gr.r=255*(t=Math.sin(s))*t,Gr.g=255*(t=Math.sin(s+uf))*t,Gr.b=255*(t=Math.sin(s+xf))*t,Gr+""}function pf(s){return s=Math.max(0,Math.min(1,s)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+s*(1172.33-s*(10793.56-s*(33300.12-s*(38394.49-s*14825.05)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+s*(557.33+s*(1225.33-s*(3574.96-s*(1073.77+s*707.56)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+s*(3211.1-s*(15327.97-s*(27814-s*(22569.18-s*6838.66)))))))+")"}function dl(s){var t=s.length;return function(a){return s[Math.max(0,Math.min(t-1,Math.floor(a*t)))]}}const ff=dl(as("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var gf=dl(as("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),jf=dl(as("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),bf=dl(as("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0a
51a58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function Um(s,t){this._basis=new om(s),this._beta=t}Um.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var s=this._x,t=this._y,a=s.length-1;if(a>0)for(var n=s[0],i=t[0],r=s[a]-n,l=t[a]-i,c=-1,o;++c<=a;)o=c/a,this._basis.point(this._beta*s[c]+(1-this._beta)*(n+o*r),this._beta*t[c]+(1-this._beta)*(i+o*l));this._x=this._y=null,this._basis.lineEnd()},point:function(s,t){this._x.push(+s),this._y.push(+t)}};const vf=function s(t){function a(n){return t===1?new om(n):new Um(n,t)}return a.beta=function(n){return s(+n)},a}(.85);function bi(s,t,a){s._context.bezierCurveTo(s._x1+s._k*(s._x2-s._x0),s._y1+s._k*(s._y2-s._y0),s._x2+s._k*(s._x1-t),s._y2+s._k*(s._y1-a),s._x2,s._y2)}function Gc(s,t){this._context=s,this._k=(1-t)/6}Gc.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:bi(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2,this._x1=s,this._y1=t;break;case 2:this._point=3;default:bi(this,s,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=s,this._y0=this._y1,this._y1=this._y2,this._y2=t}};const yf=function s(t){function a(n){return new Gc(n,t)}return a.tension=function(n){return s(+n)},a}(0);function Wc(s,t){this._context=s,this._k=(1-t)/6}Wc.prototype={areaStart:pi,areaEnd:pi,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._x3=s,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=s,this._y4=t);break;case 2:this._point=3,this._x5=s,this._y5=t;break;default:bi(this,s,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=s,this._y0=this._y1,this._y1=this._y2,this._y2=t}};const Nf=function s(t){function a(n){return new Wc(n,t)}return a.tension=function(n){return s(+n)},a}(0);function Hc(s,t){this._context=s,this._k=(1-t)/6}Hc.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:bi(this,s,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=s,this._y0=this._y1,this._y1=this._y2,this._y2=t}};const wf=function s(t){function a(n){return new Hc(n,t)}return a.tension=function(n){return s(+n)},a}(0);function Kc(s,t,a){var n=s._x1,i=s._y1,r=s._x2,l=s._y2;if(s._l01_a>wo){var c=2*s._l01_2a+3*s._l01_a*s._l12_a+s._l12_2a,o=3*s._l01_a*(s._l01_a+s._l12_a);n=(n*c-s._x0*s._l12_2a+s._x2*s._l01_2a)/o,i=(i*c-s._y0*s._l12_2a+s._y2*s._l01_2a)/o}if(s._l23_a>wo){var d=2*s._l23_2a+3*s._l23_a*s._l12_a+s._l12_2a,u=3*s._l23_a*(s._l23_a+s._l12_a);r=(r*d+s._x1*s._l23_2a-t*s._l12_2a)/u,l=(l*d+s._y1*s._l23_2a-a*s._l12_2a)/u}s._context.bezierCurveTo(n,i,r,l,s._x2,s._y2)}function Bm(s,t){this._context=s,this._alpha=t}Bm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){if(s=+s,t=+t,this._point){var a=this._x2-s,n=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(a*a+n*n,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;break;case 2:this._point=3;default:Kc(this,s,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=s,this._y0=this._y1,this._y1=this._y2,this._y2=t}};const kf=function s(t){function a(n){return t?new Bm(n,t):new Gc(n,0)}return a.alpha=function(n){return s(+n)},a}(.5);function zm(s,t){this._context=s,this._alpha=t}zm.prototype={areaStart:pi,areaEnd:pi,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point:function(s,t){if(s=+s,t=+t,this._point){var a=this._x2-s,n=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(a*a+n*n,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=s,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=s,this._y4=t);break;case 2:this._point=3,this._x5=s,this._y5=t;break;default:Kc(this,s,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=s,this._y0=this._y1,this._y1=this._y2,this._y2=t}};const Cf=function s(t){function a(n){return t?new zm(n,t):new Wc(n,0)}return a.alpha=function(n){return s(+n)},a}(.5);function qm(s,t){this._context=s,this._alpha=t}qm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){if(s=+s,t=+t,this._point){var a=this._x2-s,n=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(a*a+n*n,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Kc(this,s,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=s,this._y0=this._y1,this._y1=this._y2,this._y2=t}};const Sf=function s(t){function a(n){return t?new qm(n,t):new Hc(n,0)}return a.alpha=function(n){return s(+n)},a}(.5);function Af({opportunity:s,icon:t}){const[a,n]=p.useState(!1),i={urgent:"bg-red-50 border-red-200 dark:bg-red-950 dark:border-red-800",high:"bg-amber-50 border-amber-200 dark:bg-amber-950 dar
51k:border-amber-800",medium:"bg-info-surface border-info-border dark:bg-blue-950 dark:border-blue-800",low:"bg-surface-page border-line dark:bg-gray-900 dark:border-gray-700"},r={urgent:"bg-red-500",high:"bg-amber-500",medium:"bg-blue-500",low:"bg-gray-500"},l={high_usage:"High Engagement",churn_risk:"Churn Risk",power_users:"Power Users",upsell:"Upsell Opportunity"};return e.jsxs("div",{className:`p-4 rounded-lg border ${i[s.priority]||i.low}`,"data-testid":`opportunity-card-${s.type}`,children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1",children:[e.jsx(t,{className:"h-5 w-5 mt-0.5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"font-medium",children:s.message}),e.jsx(Y,{className:`${r[s.priority]||"bg-gray-500"} text-white text-xs`,children:s.priority}),e.jsx(Y,{variant:"outline",className:"text-xs",children:l[s.type]||s.type})]}),s.thresholdDescription&&e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1 cursor-help",children:[e.jsx(bs,{className:"h-3 w-3"}),"Threshold: ",s.threshold,"+ ",s.type==="high_usage"?"actions":s.type==="power_users"?"patients":"%"]})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:s.thresholdDescription})})]})})]})]}),s.users&&s.users.length>0&&e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>n(!a),className:"ml-2","data-testid":`btn-expand-opportunity-${s.type}`,children:a?e.jsxs(e.Fragment,{children:[e.jsx(Mr,{className:"h-4 w-4 mr-1"}),"Hide Users"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tt,{className:"h-4 w-4 mr-1"}),"View ",s.users.length," User",s.users.length!==1?"s":""]})})]}),a&&s.users&&s.users.length>0&&e.jsx("div",{className:"mt-4 border-t pt-4",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Username"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Email"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Health System"}),e.jsx("th",{className:"text-right py-2 px-2 font-medium",children:"Metric"})]})}),e.jsx("tbody",{children:s.users.map(c=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2 px-2 font-medium",children:c.username}),e.jsx("td",{className:"py-2 px-2 text-muted-foreground",children:c.email||"â"}),e.jsx("td",{className:"py-2 px-2 text-muted-foreground",children:c.healthSystemName||"â"}),e.jsx("td",{className:"py-2 px-2 text-right",children:e.jsxs(Y,{variant:"secondary",children:[c.metricValue.toLocaleString()," ",c.metricLabel]})})]},c.id))})]})})})]})}function _f(){var m,v,g,w,k,b,S,A,F,de,M,G,D,$,se,J,le,C,I,y,f,R,O,N,re,H,pe,ye,Ie,ve,B,z,K;const[s,t]=p.useState({start:new Date(Date.now()-2592e6),end:new Date}),[a,n]=p.useState("daily"),{data:i,isLoading:r}=_e({queryKey:[`/api/analytics/summary?from=${s.start.toISOString()}&to=${s.end.toISOString()}`],staleTime:5*60*1e3,gcTime:10*60*1e3}),{data:l}=_e({queryKey:["/api/analytics/comprehensive?range=30d"],staleTime:5*60*1e3,gcTime:10*60*1e3}),{data:c}=_e({queryKey:["/api/analytics/predictive"],staleTime:5*60*1e3,gcTime:10*60*1e3});if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[...Array(4)].map((P,ue)=>e.jsx(cs,{className:"h-32"},ue))}),e.jsx(cs,{className:"h-64"})]});const o={totalVisits:((m=i==null?void 0:i.keyMetrics)==null?void 0:m.totalEncounters)||0,uniqueVisitors:((v=i==null?void 0:i.keyMetrics)==null?void 0:v.activeUsers)||0,signups:((g=i==null?void 0:i.keyMetrics)==null?void 0:g.totalUsers)||0,conversionRate:((w=i==null?void 0:i.keyMetrics)==null?void 0:w.conversionRate)||0},d=(P,ue)=>ue===0?0:((P-ue)/ue*100).toFixed(1),u=l?{totalVisits:d(((b=(k=l.current)==null?void 0:k.keyMetrics)==null?void 0:b.totalEncounters)||0,((A=(S=l.previous)==null?void 0:S.keyMetrics)==null?void 0:A.totalEncounters)||0),uniqueVisitors:d(((de=(F=l.current)==null?void 0:F.keyMetrics)==null?void 0:de.activeUsers)||0,((G=(M=l.previous)==null?void 0:M.keyMetrics)==null?void 0:G.activeUsers)||0),signups:d((($=(D=l.current)==null?void 0:D.keyMetrics)==null?void 0:$.totalUsers)||0,((J=(se=l.previous)==null?void 0:se.keyMetrics)==null?void 0:J.totalUsers)||0),conversionRate:d(((C=(le=l.current)==null?void 0:le.keyMetrics)==null?void 0:C.conversionRate)||0,((y=(I=l.previous)==null?void 0:I.keyMetrics)==null?void 0:y.conversionRate)||0)}:{totalVisits:"0",uniqueVisitors:"0",signups:"0",conversionRate:"
510"},x=l?{cpa:((f=l.kpis)==null?void 0:f.cpa)||0,ltv:((R=l.kpis)==null?void 0:R.ltv)||0,ltvCacRatio:((O=l.kpis)==null?void 0:O.ltvCacRatio)||0,churnRate:((N=l.kpis)==null?void 0:N.churnRate)||0,retentionRate:((re=l.kpis)==null?void 0:re.retentionRate)||0,avgRevenuePerUser:((H=l.kpis)==null?void 0:H.avgRevenuePerUser)||0}:null;return e.jsxs("div",{className:"space-y-6","data-median":"marketing-metrics-dashboard",children:[e.jsx("div",{className:"flex gap-4","data-median":"metrics-controls",children:e.jsxs(os,{value:a,onValueChange:n,children:[e.jsx(ds,{className:"w-40",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"daily",children:"Daily"}),e.jsx(me,{value:"weekly",children:"Weekly"}),e.jsx(me,{value:"monthly",children:"Monthly"})]})]})}),x&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4","data-median":"advanced-metrics-grid",children:[e.jsxs(_,{"data-median":"cpa-card",children:[e.jsx(q,{className:"pb-3",children:e.jsx(W,{className:"text-sm font-medium",children:"Patient Acquisition Cost"})}),e.jsxs(T,{children:[e.jsxs("p",{className:"text-2xl font-bold",children:["$",x.cpa.toFixed(2)]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Per new patient"})]})]}),e.jsxs(_,{"data-median":"ltv-card",children:[e.jsx(q,{className:"pb-3",children:e.jsx(W,{className:"text-sm font-medium",children:"Patient Lifetime Value"})}),e.jsxs(T,{children:[e.jsxs("p",{className:"text-2xl font-bold",children:["$",x.ltv.toFixed(2)]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Average per patient"})]})]}),e.jsxs(_,{"data-median":"ltv-cac-ratio-card",children:[e.jsx(q,{className:"pb-3",children:e.jsx(W,{className:"text-sm font-medium",children:"LTV:CAC Ratio"})}),e.jsxs(T,{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[x.ltvCacRatio.toFixed(1),":1"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:x.ltvCacRatio>=3?"Healthy":"Needs improvement"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4","data-median":"metrics-summary-grid",children:[e.jsx(_,{"data-median":"total-visits-card",children:e.jsx(T,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Visits"}),e.jsx("p",{className:"text-2xl font-bold",children:o.totalVisits.toLocaleString()}),e.jsxs("p",{className:`text-xs flex items-center mt-1 ${Number(u.totalVisits)>=0?"text-green-600":"text-red-600"}`,children:[Number(u.totalVisits)>=0?e.jsx(Is,{className:"h-3 w-3 mr-1"}):e.jsx(Et,{className:"h-3 w-3 mr-1"}),Number(u.totalVisits)>=0?"+":"",u.totalVisits,"% from last period"]})]}),e.jsx(Hs,{className:"h-8 w-8 text-muted-foreground"})]})})}),e.jsx(_,{children:e.jsx(T,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Unique Visitors"}),e.jsx("p",{className:"text-2xl font-bold",children:o.uniqueVisitors.toLocaleString()}),e.jsxs("p",{className:`text-xs flex items-center mt-1 ${Number(u.uniqueVisitors)>=0?"text-green-600":"text-red-600"}`,children:[Number(u.uniqueVisitors)>=0?e.jsx(Is,{className:"h-3 w-3 mr-1"}):e.jsx(Et,{className:"h-3 w-3 mr-1"}),Number(u.uniqueVisitors)>=0?"+":"",u.uniqueVisitors,"% from last period"]})]}),e.jsx(Ys,{className:"h-8 w-8 text-muted-foreground"})]})})}),e.jsx(_,{children:e.jsx(T,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Signups"}),e.jsx("p",{className:"text-2xl font-bold",children:o.signups}),e.jsxs("p",{className:`text-xs flex items-center mt-1 ${Number(u.signups)>=0?"text-green-600":"text-red-600"}`,children:[Number(u.signups)>=0?e.jsx(Is,{className:"h-3 w-3 mr-1"}):e.jsx(Et,{className:"h-3 w-3 mr-1"}),Number(u.signups)>=0?"+":"",u.signups,"% from last period"]})]}),e.jsx(lt,{className:"h-8 w-8 text-muted-foreground"})]})})}),e.jsx(_,{children:e.jsx(T,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Conversion Rate"}),e.jsxs("p",{className:"text-2xl font-bold",children:[o.conversionRate,"%"]}),e.jsxs("p",{className:`text-xs flex items-center mt-1 ${Number(u.conversionRate)>=0?"text-green-600":"text-red-600"}`,children:[Number(u.conversionRate)>=0?e.jsx(Is,{className:"h-3 w-3 mr-1"}):e.jsx(Et,{className:"h-3 w-3 mr-1"}),Number(u.conversionRate)>=0?"+":"",u.conversionRate,"% from last period"]})]}),e.jsx(ct,{className:"h-8 w-8 text-muted-foreground"})]})})})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx(_,{children:e.jsxs(T,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Clinical Efficiency Metrics"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Avg SOAP Time"}),e.jsxs("p",{className:"text-xl font-semibold",children:[((pe=i.clinicalEfficiency)==null?void 0:pe.avgSOAPTime)||0," min"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Documents/Day"}),e.jsx("p",{className:"text-xl font-semibold",children:((ye=i.clinicalEfficiency)==null?void 0:ye.documentsProcessedPerDay)||0})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Orders/Encounter"}),e.jsx("p",{className:"text-xl font-semibold",children:((Ie=i.clinicalEfficiency)==null?void 0:Ie.ordersPerEncounter)||0})]})]})]})}),e.jsx(_,{children:e.jsxs(T,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Physician ROI & Time Savings"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ra,{className:"h-10 w-10 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Time Saved Daily"}),e.jsx("p",{className:"text-xl font-semibold",children:(ve=i.clinicalEfficiency)!=null&&ve.avgSOAPTime?`${(i.clinicalEfficiency.avgSOAPTime*.9/60).toFixed(1)} hrs`:"0 hrs"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ys,{className:"h-10 w-10 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Additional Patients/Day"}),e.jsx("p",{className:"text-xl font-semibold",children:(B=i.clinicalEfficiency)!=null&&B.avgSOAPTime?`+${Math.floor(i.clinicalEfficiency.avgSOAPTime*.9/60*4)}`:"0"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ct,{className:"h-10 w-10 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Revenue Gain/Month"}),e.jsxs("p",{className:"text-xl font-semibold",children:["$",(z=i.clinicalEfficiency)!=null&&z.avgSOAPTime?(i.clinicalEfficiency.avgSOAPTime*.9/60*4*150*20).toLocaleStr
51ing():"0"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ja,{className:"h-10 w-10 text-purple-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"ROI Percentage"}),e.jsx("p",{className:"text-xl font-semibold text-green-600",children:(K=i.clinicalEfficiency)!=null&&K.avgSOAPTime?`${Math.round(i.clinicalEfficiency.avgSOAPTime*.9/60*4*150*20/149*100)}%`:"0%"})]})]})]})]})}),i.opportunities&&i.opportunities.length>0&&e.jsx(_,{"data-testid":"card-marketing-opportunities",children:e.jsxs(T,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-semibold mb-4 flex items-center gap-2",children:[e.jsx(lt,{className:"h-5 w-5"}),"Marketing Opportunities"]}),e.jsx("div",{className:"space-y-4",children:i.opportunities.map((P,ue)=>{const V=P.type==="high_usage"?oa:P.type==="churn_risk"?Fs:P.type==="power_users"?Za:lt;return e.jsx(Af,{opportunity:P,icon:V},ue)})})]})})]})]})}function Fn(s){"@babel/helpers - typeof";return Fn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fn(s)}function Tf(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Df(s,t){for(var a=0;a<t.length;a++){var n=t[a];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,Hm(n.key),n)}}function Pf(s,t,a){return t&&Df(s.prototype,t),Object.defineProperty(s,"prototype",{writable:!1}),s}function Mf(s,t,a){return t=vi(t),Rf(s,Gm()?Reflect.construct(t,a||[],vi(s).constructor):t.apply(s,a))}function Rf(s,t){if(t&&(Fn(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Lf(s)}function Lf(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function Gm(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Gm=function(){return!!s})()}function vi(s){return vi=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(a){return a.__proto__||Object.getPrototypeOf(a)},vi(s)}function $f(s,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(t&&t.prototype,{constructor:{value:s,writable:!0,configurable:!0}}),Object.defineProperty(s,"prototype",{writable:!1}),t&&uc(s,t)}function uc(s,t){return uc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},uc(s,t)}function Wm(s,t,a){return t=Hm(t),t in s?Object.defineProperty(s,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):s[t]=a,s}function Hm(s){var t=Of(s,"string");return Fn(t)=="symbol"?t:t+""}function Of(s,t){if(Fn(s)!="object"||!s)return s;var a=s[Symbol.toPrimitive];if(a!==void 0){var n=a.call(s,t);if(Fn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}var ml=function(s){function t(){return Tf(this,t),Mf(this,t,arguments)}return $f(t,s),Pf(t,[{key:"render",value:function(){return null}}])}(p.Component);Wm(ml,"displayName","ZAxis");Wm(ml,"defaultProps",{zAxisId:0,range:[64,64],scale:"auto",type:"number"});var If=["option","isActive"];function lr(){return lr=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},lr.apply(this,arguments)}function Ff(s,t){if(s==null)return{};var a=Ef(s,t),n,i;if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);for(i=0;i<r.length;i++)n=r[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(a[n]=s[n])}return a}function Ef(s,t){if(s==null)return{};var a={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;a[n]=s[n]}return a}function Vf(s){var t=s.option,a=s.isActive,n=Ff(s,If);return typeof t=="string"?p.createElement(ko,lr({option:p.createElement(Ex,lr({type:t},n)),isActive:a,shapeType:"symbols"},n)):p.createElement(ko,lr({option:t,isActive:a,shapeType:"symbols"},n))}function En(s){"@babel/helpers - typeof";return En=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},En(s)}function cr(){return cr=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},cr.apply(this,arguments)}function Uo(s,t){var a=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),a.push.apply(a,n)}return a}function Gt(s){for(var t=1;t<arguments.length;t++){var a=arguments[t]!=null?arguments[t]:{};
vendor: 4,702 bytes, line 51
51t%2?Uo(Object(a),!0).forEach(function(n){Ba(s,n,a[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(a)):Uo(Object(a)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(a,n))})}return s}function Uf(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Bo(s,t){for(var a=0;a<t.length;a++){var n=t[a];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,Ym(n.key),n)}}function Bf(s,t,a){return t&&Bo(s.prototype,t),a&&Bo(s,a),Object.defineProperty(s,"prototype",{writable:!1}),s}function zf(s,t,a){return t=yi(t),qf(s,Km()?Reflect.construct(t,a||[],yi(s).constructor):t.apply(s,a))}function qf(s,t){if(t&&(En(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Gf(s)}function Gf(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function Km(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Km=function(){return!!s})()}function yi(s){return yi=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(a){return a.__proto__||Object.getPrototypeOf(a)},yi(s)}function Wf(s,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(t&&t.prototype,{constructor:{value:s,writable:!0,configurable:!0}}),Object.defineProperty(s,"prototype",{writable:!1}),t&&xc(s,t)}function xc(s,t){return xc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},xc(s,t)}function Ba(s,t,a){return t=Ym(t),t in s?Object.defineProperty(s,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):s[t]=a,s}function Ym(s){var t=Hf(s,"string");return En(t)=="symbol"?t:t+""}function Hf(s,t){if(En(s)!="object"||!s)return s;var a=s[Symbol.toPrimitive];if(a!==void 0){var n=a.call(s,t);if(En(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}var ul=function(s){function t(){var a;Uf(this,t);for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];return a=zf(this,t,[].concat(i)),Ba(a,"state",{isAnimationFinished:!1}),Ba(a,"handleAnimationEnd",function(){a.setState({isAnimationFinished:!0})}),Ba(a,"handleAnimationStart",function(){a.setState({isAnimationFinished:!1})}),Ba(a,"id",Kx("recharts-scatter-")),a}return Wf(t,s),Bf(t,[{key:"renderSymbolsStatically",value:function(n){var i=this,r=this.props,l=r.shape,c=r.activeShape,o=r.activeIndex,d=kl(this.props,!1);return n.map(function(u,x){var m=o===x,v=m?c:l,g=Gt(Gt({},d),u);return St.createElement(Hn,cr({className:"recharts-scatter-symbol",key:"symbol-".concat(u==null?void 0:u.cx,"-").concat(u==null?void 0:u.cy,"-").concat(u==null?void 0:u.size,"-").concat(x)},Vx(i.props,u,x),{role:"img"}),St.createElement(Vf,cr({option:v,isActive:m,key:"symbol-".concat(x)},g)))})}},{key:"renderSymbolsWithAnimation",value:function(){var n=this,i=this.props,r=i.points,l=i.isAnimationActive,c=i.animationBegin,o=i.animationDuration,d=i.animationEasing,u=i.animationId,x=this.state.prevPoints;return St.createElement(Ux,{begin:c,duration:o,isActive:l,easing:d,from:{t:0},to:{t:1},key:"pie-".concat(u),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(m){var v=m.t,g=r.map(function(w,k){var b=x&&x[k];if(b){var S=Ur(b.cx,w.cx),A=Ur(b.cy,w.cy),F=Ur(b.size,w.size);return Gt(Gt({},w),{},{cx:S(v),cy:A(v),size:F(v)})}var de=Ur(0,w.size);return Gt(Gt({},w),{},{size:de(v)})});return St.createElement(Hn,null,n.renderSymbolsStatically(g))})}},{key:"renderSymbols",value:function(){var n=this.props,i=n.points,r=n.isAnimationActive,l=this.state.prevPoints;return r&&i&&i.length&&(!l||!Bx(l,i))?this.renderSymbolsWithAnimation():this.renderSymbolsStatically(i)}},{key:"renderErrorBar",value:function(){var n=this.props.isAnimationActive;if(n&&!this.state.isAnimationFinished)return null;var i=this.props,r=i.points,l=i.xAxis,c=i.yAxis,o=i.children,d=dm(o,zx);return d?d.map(function(u,x){var m=u.props,v=m.direction,g=m.dataKey;return St.cloneElement(u,{key:"".concat(v,"-").concat(g,"-").concat(r[x]),data:r,xAxis:l,yAxis:c,layout:v==="x"?"vertical":"horizontal",dataPointFormatter:function(k,b){return{x:k.cx,y:k.cy,value:v==="x"?+k.node.x:+k.node.y,errorVal:Jr(k,b)}}})}):null}},{key:"renderLine",value:function(){var n=this.props,i=n.points,r=n.line,l=n.lineType,c=n.lineJointType,o=kl(this.props,!1),d=kl(r,!1),u,x;if(l==="joint")u=i.map(function(A){return{x:A.cx,y:A.cy}});
51else if(l==="fitting"){var m=qx(i),v=m.xmin,g=m.xmax,w=m.a,k=m.b,b=function(F){return w*F+k};u=[{x:v,y:b(v)},{x:g,y:b(g)}]}var S=Gt(Gt(Gt({},o),{},{fill:"none",stroke:o&&o.fill},d),{},{points:u});return St.isValidElement(r)?x=St.cloneElement(r,S):mm(r)?x=r(S):x=St.createElement(Gx,cr({},S,{type:c})),St.createElement(Hn,{className:"recharts-scatter-line",key:"recharts-scatter-line"},x)}},{key:"render",value:function(){var n=this.props,i=n.hide,r=n.points,l=n.line,c=n.className,o=n.xAxis,d=n.yAxis,u=n.left,x=n.top,m=n.width,v=n.height,g=n.id,w=n.isAnimationActive;if(i||!r||!r.length)return null;var k=this.state.isAnimationFinished,b=Cx("recharts-scatter",c),S=o&&o.allowDataOverflow,A=d&&d.allowDataOverflow,F=S||A,de=Dn(g)?this.id:g;return St.createElement(Hn,{className:b,clipPath:F?"url(#clipPath-".concat(de,")"):null},S||A?St.createElement("defs",null,St.createElement("clipPath",{id:"clipPath-".concat(de)},St.createElement("rect",{x:S?u:u-m/2,y:A?x:x-v/2,width:S?m:m*2,height:A?v:v*2}))):null,l&&this.renderLine(),this.renderErrorBar(),St.createElement(Hn,{key:"recharts-scatter-symbols"},this.renderSymbols()),(!w||k)&&Wx.renderCallByParent(this.props,r))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,prevPoints:i.curPoints}:n.points!==i.curPoints?{curPoints:n.points}:null}}])}(p.PureComponent);Ba(ul,"displayName","Scatter");Ba(ul,"defaultProps",{xAxisId:0,yAxisId:0,zAxisId:0,legendType:"circle",lineType:"joint",lineJointType:"linear",data:[],shape:"circle",hide:!1,isAnimationActive:!Hx.isSsr,animationBegin:0,animationDuration:400,animationEasing:"linear"});Ba(ul,"getComposedData",function(s){var t=s.xAxis,a=s.yAxis,n=s.zAxis,i=s.item,r=s.displayedData,l=s.xAxisTicks,c=s.yAxisTicks,o=s.offset,d=i.props.tooltipType,u=dm(i.props.children,dn),x=Dn(t.dataKey)?i.props.dataKey:t.dataKey,m=Dn(a.dataKey)?i.props.dataKey:a.dataKey,v=n&&n.dataKey,g=n?n.range:ml.defaultProps.range,w=g&&g[0],k=t.scale.bandwidth?t.scale.bandwidth():0,b=a.scale.bandwidth?a.scale.bandwidth():0,S=r.map(function(A,F){var de=Jr(A,x),M=Jr(A,m),G=!Dn(v)&&Jr(A,v)||"-",D=[{name:Dn(t.dataKey)?i.props.name:t.name||t.dataKey,unit:t.unit||"",value:de,payload:A,dataKey:x,type:d},{name:Dn(a.dataKey)?i.props.name:a.name||a.dataKey,unit:a.unit||"",value:M,payload:A,dataKey:m,type:d}];G!=="-"&&D.push({name:n.name||n.dataKey,unit:n.unit||"",value:G,payload:A,dataKey:v,type:d});var $=Co({axis:t,ticks:l,bandSize:k,entry:A,index:F,dataKey:x}),se=Co({axis:a,ticks:c,bandSize:b,entry:A,index:F,dataKey:m}),J=G!=="-"?n.scale(G):w,le=Math.sqrt(Math.max(J,0)/Math.PI);return Gt(Gt({},A),{},{cx:$,cy:se,x:$-le,y:se-le,xAxis:t,yAxis:a,zAxis:n,width:2*le,height:2*le,size:J,node:{x:de,y:M,z:G},tooltipPayload:D,tooltipPosition:{x:$,y:se},payload:A},u&&u[F]&&u[F].props)});return Gt({points:S},o)});function Kf(s,t){for(var a=-1,n=s==null?0:s.length;++a<n&&t(s[a],a,s)!==!1;);return s}var Yf=Kf,Qf=Rc,Xf=um,Zf=Object.prototype,Jf=Zf.hasOwnProperty;function eg(s,t,a){var n=s[t];(!(Jf.call(s,t)&&Xf(n,a))||a===void 0&&!(t in s))&&Qf(s,t,a)}var Yc=eg,sg=Yc,tg=Rc;function ag(s,t,a,n){var i=!a;a||(a={});for(var r=-1,l=t.length;++r<l;){var c=t[r],o=n?n(a[c],s[c],c,a,s):void 0;o===void 0&&(o=s[c]),i?tg(a,c,o):sg(a,c,o)}return a}var $r=ag,ng=$r,rg=xm;function ig(s,t){return s&&ng(t,rg(t),s)}var lg=ig;function cg(s){var t=[];if(s!=null)for(var a in Object(s))t.push(a);return t}var og=cg,dg=qn,mg=hm,ug=og,xg=Object.prototype,hg=xg.hasOwnProperty;function pg(s){if(!dg(s))return ug(s);var t=mg(s),a=[];for(var n in s)n=="constructor"&&(t||!hg.call(s,n))||a.push(n);return a}var fg=pg,gg=Yx,jg=fg,bg=pm;function vg(s){return bg(s)?gg(s,!0):jg(s)}var Or=vg,yg=$r,Ng=Or;function wg(s,t){return s&&yg(t,Ng(t),s)}var kg=wg,Ni={exports:{}};Ni.exports;(function(s,t){var a=Qx,n=t&&!t.nodeType&&t,i=n&&!0&&s&&!s.nodeType&&s,r=i&&i.exports===n,l=r?a.Buffer:void 0,c=l?l.allocUnsafe:void 0;function o(d,u){if(u)return d.slice();var x=d.length,m=c?c(x):new d.constructor(x);return d.copy(m),m}s.exports=o}
vendor: 2,488 bytes, line 51
51)(Ni,Ni.exports);var Qm=Ni.exports;function Cg(s,t){var a=-1,n=s.length;for(t||(t=Array(n));++a<n;)t[a]=s[a];return t}var Xm=Cg,Sg=$r,Ag=fm;function _g(s,t){return Sg(s,Ag(s),t)}var Tg=_g,Dg=Zx,Pg=gm,Mg=fm,Rg=Xx,Lg=Object.getOwnPropertySymbols,$g=Lg?function(s){for(var t=[];s;)Dg(t,Mg(s)),s=Pg(s);return t}:Rg,Zm=$g,Og=$r,Ig=Zm;function Fg(s,t){return Og(s,Ig(s),t)}var Eg=Fg,Vg=Jx,Ug=Zm,Bg=Or;function zg(s){return Vg(s,Bg,Ug)}var qg=zg,Gg=Object.prototype,Wg=Gg.hasOwnProperty;function Hg(s){var t=s.length,a=new s.constructor(t);return t&&typeof s[0]=="string"&&Wg.call(s,"index")&&(a.index=s.index,a.input=s.input),a}var Kg=Hg,zo=eh;function Yg(s){var t=new s.constructor(s.byteLength);return new zo(t).set(new zo(s)),t}var Qc=Yg,Qg=Qc;function Xg(s,t){var a=t?Qg(s.buffer):s.buffer;return new s.constructor(a,s.byteOffset,s.byteLength)}var Zg=Xg,Jg=/\w*$/;function ej(s){var t=new s.constructor(s.source,Jg.exec(s));return t.lastIndex=s.lastIndex,t}var sj=ej,qo=sh,Go=qo?qo.prototype:void 0,Wo=Go?Go.valueOf:void 0;function tj(s){return Wo?Object(Wo.call(s)):{}}var aj=tj,nj=Qc;function rj(s,t){var a=t?nj(s.buffer):s.buffer;return new s.constructor(a,s.byteOffset,s.length)}var Jm=rj,ij=Qc,lj=Zg,cj=sj,oj=aj,dj=Jm,mj="[object Boolean]",uj="[object Date]",xj="[object Map]",hj="[object Number]",pj="[object RegExp]",fj="[object Set]",gj="[object String]",jj="[object Symbol]",bj="[object ArrayBuffer]",vj="[object DataView]",yj="[object Float32Array]",Nj="[object Float64Array]",wj="[object Int8Array]",kj="[object Int16Array]",Cj="[object Int32Array]",Sj="[object Uint8Array]",Aj="[object Uint8ClampedArray]",_j="[object Uint16Array]",Tj="[object Uint32Array]";function Dj(s,t,a){var n=s.constructor;switch(t){case bj:return ij(s);case mj:case uj:return new n(+s);case vj:return lj(s,a);case yj:case Nj:case wj:case kj:case Cj:case Sj:case Aj:case _j:case Tj:return dj(s,a);case xj:return new n;case hj:case gj:return new n(s);case pj:return cj(s);case fj:return new n;case jj:return oj(s)}}var Pj=Dj,Mj=qn,Ho=Object.create,Rj=function(){function s(){}return function(t){if(!Mj(t))return{};if(Ho)return Ho(t);s.prototype=t;var a=new s;return s.prototype=void 0,a}}(),Lj=Rj,$j=Lj,Oj=gm,Ij=hm;function Fj(s){return typeof s.constructor=="function"&&!Ij(s)?$j(Oj(s)):{}}var eu=Fj,Ej=$c,Vj=Lc,Uj="[object Map]";function Bj(s){return Vj(s)&&Ej(s)==Uj}var zj=Bj,qj=zj,Gj=Oc,Ko=jm,Yo=Ko&&Ko.isMap,Wj=Yo?Gj(Yo):qj,Hj=Wj,Kj=$c,Yj=Lc,Qj="[object Set]";function Xj(s){return Yj(s)&&Kj(s)==Qj}
51var Zj=Xj,Jj=Zj,e0=Oc,Qo=jm,Xo=Qo&&Qo.isSet,s0=Xo?e0(Xo):Jj,t0=s0,a0=vm,n0=Yf,r0=Yc,i0=lg,l0=kg,c0=Qm,o0=Xm,d0=Tg,m0=Eg,u0=th,x0=qg,h0=$c,p0=Kg,f0=Pj,g0=eu,j0=ym,b0=bm,v0=Hj,y0=qn,N0=t0,w0=xm,k0=Or,C0=1,S0=2,A0=4,su="[object Arguments]",_0="[object Array]",T0="[object Boolean]",D0="[object Date]",P0="[object Error]",tu="[object Function]",M0="[object GeneratorFunction]",R0="[object Map]",L0="[object Number]",au="[object Object]",$0="[object RegExp]",O0="[object Set]",I0="[object String]",F0="[object Symbol]",E0="[object WeakMap]",V0="[object ArrayBuffer]",U0="[object DataView]",B0="[object Float32Array]",z0="[object Float64Array]",q0="[object Int8Array]",G0="[object Int16Array]",W0="[object Int32Array]",H0="[object Uint8Array]",K0="[object Uint8ClampedArray]",Y0="[object Uint16Array]",Q0="[object Uint32Array]",Os={};Os[su]=Os[_0]=Os[V0]=Os[U0]=Os[T0]=Os[D0]=Os[B0]=Os[z0]=Os[q0]=Os[G0]=Os[W0]=Os[R0]=Os[L0]=Os[au]=Os[$0]=Os[O0]=Os[I0]=Os[F0]=Os[H0]=Os[K0]=Os[Y0]=Os[Q0]=!0;Os[P0]=Os[tu]=Os[E0]=!1;function ti(s,t,a,n,i,r){var l,c=t&C0,o=t&S0,d=t&A0;if(a&&(l=i?a(s,n,i,r):a(s)),l!==void 0)return l;if(!y0(s))return s;var u=j0(s);if(u){if(l=p0(s),!c)return o0(s,l)}else{var x=h0(s),m=x==tu||x==M0;if(b0(s))return c0(s,c);if(x==au||x==su||m&&!i){if(l=o||m?{}:g0(s),!c)return o?m0(s,l0(l,s)):d0(s,i0(l,s))}else{if(!Os[x])return i?s:{};l=f0(s,x,c)}}r||(r=new a0);var v=r.get(s);if(v)return v;r.set(s,l),N0(s)?s.forEach(function(k){l.add(ti(k,t,a,k,s,r))}):v0(s)&&s.forEach(function(k,b){l.set(b,ti(k,t,a,b,s,r))});var g=d?o?x0:u0:o?k0:w0,w=u?void 0:g(s);return n0(w||s,function(k,b){w&&(b=k,k=s[b]),r0(l,b,ti(k,t,a,b,s,r))}),l}var X0=ti,Z0=ah;function J0(s){var t=s==null?0:s.length;return t?Z0(s,1):[]}var eb=J0,sb=eb,tb=rh,ab=nh;function nb(s){return ab(tb(s,void 0,sb),s+"")}
51var rb=nb,nu=ih({chartName:"ComposedChart",GraphicalChild:[Vt,In,Zt,ul],axisComponents:[{axisType:"xAxis",AxisComp:Bt},{axisType:"yAxis",AxisComp:at},{axisType:"zAxis",AxisComp:ml}],formatAxisMap:lh});function ib(){var i;const{data:s,isLoading:t}=_e({queryKey:["/api/admin/acquisition/stats"],refetchInterval:3e4});if(t)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[...Array(4)].map((r,l)=>e.jsx(cs,{className:"h-24"},l))}),e.jsx(cs,{className:"h-64"}),e.jsx(cs,{className:"h-96"})]});if(!s)return null;const a=Object.entries(s.signupsBySource||{}).map(([r,l])=>({source:r,count:l})).sort((r,l)=>l.count-r.count).slice(0,6),n=Object.entries(s.signupsByChannel||{}).map(([r,l])=>({channel:r,users:l,percentage:s.totalSignups>0?(l/s.totalSignups*100).toFixed(1):0,isPaid:r.toLowerCase().includes("paid")||r.toLowerCase().includes("cpc")})).sort((r,l)=>l.users-r.users);return e.jsxs("div",{className:"space-y-6","data-median":"acquisition-tracking",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4","data-median":"acquisition-summary-grid",children:[e.jsx(_,{"data-median":"total-signups-card",children:e.jsx(T,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Total Signups (30d)"}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:s.totalSignups})]}),e.jsx(Ys,{className:"h-8 w-8 text-blue-500"})]})})}),e.jsx(_,{"data-median":"top-source-card",children:e.jsx(T,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Top Source"}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:((i=Object.entries(s.signupsBySource||{}).sort(([,r],[,l])=>l-r)[0])==null?void 0:i[0])||"None"})]}),e.jsx(Is,{className:"h-8 w-8 text-green-500"})]})})}),e.jsx(_,{children:e.jsx(T,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Active Channels"}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:Object.keys(s.signupsByChannel||{}).length})]}),e.jsx(ot,{className:"h-8 w-8 text-purple-500"})]})})}),e.jsx(_,{children:e.jsx(T,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Active Campaigns"}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:Object.keys(s.signupsByCampaign||{}).length})]}),e.jsx(ia,{className:"h-8 w-8 text-orange-500"})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(_,{children:e.jsxs(T,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Acquisition Channels"}),e.jsx("div",{className:"space-y-3",children:n.length>0?n.map(r=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-500"}),e.jsx("span",{className:"text-sm",children:r.channel}),r.isPaid&&e.jsxs(Y,{variant:"secondary",className:"text-xs",children:[e.jsx(ct,{className:"h-3 w-3 mr-1"}),"Paid"]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[r.users," (",r.percentage,"%)"]})]},r.channel)):e.jsx("p",{className:"text-center text-muted-foreground",children:"No channel data available"})})]})}),e.jsx(_,{children:e.jsxs(T,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Top Traffic Sources"}),a.length>0?e.jsx(ft,{width:"100%",height:200,children:e.jsxs(Lr,{data:a,children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"source",angle:-45,textAnchor:"end",height:80}),e.jsx(at,{}),e.jsx(gt,{}),e.jsx(Zt,{dataKey:"count",fill:"#3b82f6"})]})}):e.jsx("div",{className:"h-[200px] flex items-center justify-center text-muted-foreground",children:e.jsx("p",{children:"No source data available"})})]})})]}),e.jsx(_,{children:e.jsxs(T,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Recent User Acquisitions"}),e.jsxs(nn,{children:[e.jsx(rn,{children:e.jsxs(ht,{children:[e.jsx(fs,{children:"Date/Time"}),e.jsx(fs,{children:"User"}),e.jsx(fs,{children:"Source"}),e.jsx(fs,{children:"Medium"}),e.jsx(fs,{children:"Campaign"}),e.jsx(fs,{children:"Referrer"})]})}),e.jsx(ln,{children:s.recentSignups&&s.recentSignups.length>0?s.recentSignups.map(r=>{var l,c,o;return e.jsxs(ht,{children:[e.jsx(Ke,{children:De(new Date(r.acquisitionDate),"MMM d, h:mm a")}),e.jsx(Ke,{children:e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[(l=r.user)==null?void 0:l.firstName," ",(c=r.user)==null?void 0:c.lastName]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(o=r.user)==null?void 0:o.email})]})}),e.jsx(Ke,{children:e.jsx(Y,{variant:"secondary",children:r.source||"direct"})}),e.jsx(Ke,{children:r.medium||"-"}),e.jsx(Ke,{children:r.campaign||"-"}),e.jsx(Ke,{className:"max-w-xs truncate",title:r.referrerUrl||"",children:r.referrerUrl||"-"})]},r.id)}):e.jsx(ht,{children:e.jsx(Ke,{className:"text-muted-foreground text-center",colSpan:6,children:"No acquisition data available yet. Data will populate as users sign up."})})})]})]})}),e.jsx(_,{children:e.jsxs(T,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"UTM Campaign Performance"}),Object.keys(s.signupsByCampaign||{}).length>0?e.jsx("div",{className:"space-y-4",children:Object.entries(s.signupsByCampaign||{}).sort(([,r],[,l])=>l-r).map(([r,l])=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-surface-page rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"font-bold",children:l}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Signups"})]})]},r))}):e.jsx("div",{className:"h-48 flex items-center justify-center text-muted-foreground",children:e.jsx("p",{children:"No UTM campaign data available yet"})})]})})]})}console.log("[MARKETING_INSIGHTS] Static mock insights removed - awaiting real data implementation");function lb(){const s=Ya(),[t,a]=p.useState(),{data:n,isLoading:i}=_e({queryKey:t?[`/api/marketing/insights?status=${t}`]:["/api/marketing/insights"]}),r=ws({mutationFn:async({id:x,status:m})=>{const v=await fetch(`/api/marketing/insights/${x}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:m})});if(!v.ok)throw new Error("Failed to update insight");return v.json()},onSuccess:()=>{s.invalidateQueries({queryKey:["/api/marketing/insights"]}),ta({title:"Insight updated",description:"The insight status has been updated successfully."})}}),l=ws({mutationFn:async()=>{const x=await fetch("/api/marketing/insights/generate",{method:"POST",headers:{"Content-Type":"application/json"}});if(!x.ok)throw new Error("Failed to generate insights");return x.json()},onSuccess:()=>{s.invalidateQueries({queryKey:["/api/marketing/insights"]}),ta({title:"Insights generated",description:"AI has analyzed your data and generated new insights."})}}),c=x=>{switch(x){case"warning":return e.jsx(Fs,{className:"h-5 w-5 text-yellow-600"});case"opportunity":return e.jsx(sc,{className:"h-5 w-5 text-blue-600"});case"success":return e.jsx(Ft,{className:"h-5 w-5 text-green-600"});default:return e.jsx(bs,{className:"h-5 w-5 text-ink-muted"})}},o=x=>{const m={high:"bg-red-100 text-red-800",medium:"bg-yellow-100 text-yellow-800",low:"bg-green-100 text-green-800"};return m[x]||m.low};if(i)return e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((x,m)=>e.jsx(cs,{className:"h-48"},m))});const d=n??[],u=d.length>0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Marketing Insights"}),e.jsxs(ee,{onClick:()=>l.mutate(),disabled:l.isPending,children:[e.jsx(Qt,{className:"h-4 w-4 mr-2"}),l.isPending?"Analyzing...":"Generate Insights"]})]}),u&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ee,{variant:t===void 0?"default":"outline",size:"sm",onClick:()=>a(void 0),children:"All Insights"}),e.jsx(ee,{variant:t==="active"?"default":"outline",size:"sm",onClick:()=>a("active"),children:"Active"}),e.jsx(ee,{variant:t==="acknowledged"?"default":"outline",size:"sm",onClick:()=>a("acknowledged"),children:"Acknowledged"}),e.jsx(ee,{variant:t==="implemented"?"default":"outline",size:"sm",onClick:()=>a("implemented"),children:"Implemented"})]}),u&&e.jsx("div",{className:"space-y-4",children:d.map(x=>e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[c(x.insightCategory),e.jsxs("div",{children:[e.jsx(W,{className:"text-lg",children:x.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:x.description})]})]}),e.jsx(Y,{variant:x.status==="active"?"default":"secondary",children:x.status})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"Recommended Actions:"}),x.recommendations.map((m,v)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Va,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("p",{className:"text-sm font-medium",children:m.action}),e.jsxs(Y,{className:o(m.impact),variant:"secondary",children:[m.impact," impact"]}),e.jsxs(Y,{variant:"outline",children:[m.effort," effort"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m.details})]})]},v))]}),x.status==="active"&&e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(ee,{size:"sm",onClick:()=>r.mutate({id:x.id,status:"acknowledged"}),children:"Acknowledge"}),e.jsx(ee,{size:"sm",variant:"outline",onClick:()=>r.mutate({id:x.id,status:"dismissed"}),children:"Dismiss"})]}),x.status==="acknowledged"&&e.jsx(ee,{size:"sm",className:"mt-4",onClick:()=>r.mutate({id:x.id,status:"implemented"}),children:"Mark as Implemented"})]})]},x.id))}),!u&&e.jsx(_,{children:e.jsxs(T,{className:"p-12 text-center",children:[e.jsx(Qt,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:'No insights available yet. Click "Generate Insights" to analyze your marketing data.'})]})})]})}function cb(){return console.log("[MARKETING_AUTOMATIONS] Automations feature not yet implemented - requires HubSpot/Marketo integration"),e.jsx(_,{children:e.jsxs(T,{className:"p-8 text-center",children:[e.jsx(oa,{className:"h-12 w-12 mx-auto mb-4 text-ink-faint"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Marketing Automations Not Yet Implemented"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"The marketing automation engine is planned but not yet built."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This feature will allow you to set up automated rules for pausing campaigns, adjusting budgets, running A/B tests, and responding to performance changes."})]})})}function ob(){var N,re;const{toast:s}=ya(),[t,a]=p.useState(!1),[n,i]=p.useState(null),[r,l]=p.useState(0),c=p.useRef(null),[o,d]=p.useState(!1),[u,x]=p.useState(De(vt(new Date,30),"yyyy-MM-dd")),[m,v]=p.useState(De(new Date,"yyyy-MM-dd")),[g,w]=p.useState(De(vt(new Date,1),"yyyy-MM-dd")),[k,b]=p.useState(!1),{data:S,isLoading:A,error:F}=_e({queryKey:["/api/analytics/channel-attribution?range=30d"],refetchInterval:t?1e4:!1});p.useEffect(()=>{if(t&&n){const H=setInterval(()=>{const pe=Math.floor((Date.now()-n.getTime())/1e3);l(pe)},1e3);return()=>clearInterval(H)}else l(0)},[t,n]);const de=H=>{const pe=Math.floor(H/60),ye=H%60;return pe===0?`${ye}s`:`${pe}m ${ye}s`},M=()=>r<10?"Starting batch processor...":r<30?"Batch 1/3: Running 9 database queries (30-day analytics)...":r<90?"Batch 2/3: Running 90-day summary queries (these are slower)...":r<180?"Batch 3/3: Syncing YouTube + Google Ads APIs...":r<300?"Still processing - some queries are taking longer than expected...":"Taking longer than usual - check production logs for [OvernightAnalytics]";p.useEffect(()=>{if(t&&(S!=null&&S.lastUpdated)){const H=S.lastUpdated;n&&new Date(H)>n&&(a(!1),i(null),c.current=H,Ts.invalidateQueries({queryKey:["/api/analytics/channel-attribution?range=30d"]}),Ts.invalidateQueries({queryKey:["/api/marketing/youtube-correlation/daily"]}),Ts.invalidateQueries({queryKey:["/api/analytics"]}),Ts.invalidateQueries({queryKey:["/api/marketing"]}),s({title:"Refresh Complete",description:"Marketing analytics cache has been updated."}))}},[S==null?void 0:S.lastUpdated,t,n,s]),p.useEffect(()=>{if(t&&n){const H=setTimeout(()=>{a(!1),i(null),s({title:"Refresh Taking Longer Than Expected",description:"The cache refresh is still running in the background. Check back in a few minutes.",variant:"destructive"})},6e5);return()=>clearTimeout(H)}},[t,n,s]);const G=ws({mutationFn:async H=>(await vs("POST","/api/analytics/cache/refresh",H)).json(),onMutate:()=>{i(new Date),a(!0),c.current=(S==null?void 0:S.lastUpdated)||null},onSuccess:H=>{s({title:"Refresh Started",description:H.note||"Analytics cache refresh is running in the background."})},onError:H=>{a(!1),i(null),s({title:"Refresh Failed",description:H instanceof Error?H.message:"Failed to start cache refresh",variant:"destructive"})}}),D=()=>{G.mutate({mode:"quick"})},$=()=>{G.mutate({mode:"single_day",date:g}),b(!1)},se=()=>{G.mutate({mode:"backfill",startDate:u,endDate:m}),d(!1)},J=()=>{confirm("Full refresh may timeout with large datasets. Are you sure?")&&G.mutate({mode:"full"})},le=(N=S==null?void 0:S.channelAttribution)==null?void 0:N.paid,C=(re=S==null?void 0:S.channelAttribution)==null?void 0:re.youtube,I=H=>{if(H==null)return"â";const pe=typeof H=="string"?parseFloat(H):H;
51return isNaN(pe)?"â":`$${pe.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`},y=H=>H==null?"â":H.toLocaleString(),f=H=>{if(H==null)return"â";const pe=typeof H=="string"?parseFloat(H):H;return isNaN(pe)?"â":`${pe.toFixed(2)}%`},R=H=>{if(H==null)return"â";if(H<60)return`${H} min`;const pe=Math.floor(H/60),ye=H%60;return`${pe.toLocaleString()}h ${ye}m`},O=H=>{if(!H)return"Never";const pe=new Date(H);return bp(pe)?`Today at ${De(pe,"h:mm a")}`:vp(pe)?`Yesterday at ${De(pe,"h:mm a")}`:Sm(pe,{addSuffix:!0})};return A?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(cs,{className:"h-5 w-48"}),e.jsx(cs,{className:"h-9 w-32"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(cs,{className:"h-6 w-40"})}),e.jsx(T,{children:e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(H=>e.jsxs("div",{children:[e.jsx(cs,{className:"h-4 w-20 mb-2"}),e.jsx(cs,{className:"h-8 w-24"})]},H))})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(cs,{className:"h-6 w-40"})}),e.jsx(T,{children:e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(H=>e.jsxs("div",{children:[e.jsx(cs,{className:"h-4 w-20 mb-2"}),e.jsx(cs,{className:"h-8 w-24"})]},H))})})]})]})]}):F?e.jsx(_,{className:"border-red-200 bg-red-50",children:e.jsxs(T,{className:"p-6 text-center",children:[e.jsx("p",{className:"text-red-600 font-medium",children:"Failed to load marketing data"}),e.jsx("p",{className:"text-sm text-red-500 mt-1",children:F.message})]})}):S!=null&&S.needsRefresh?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ra,{className:"h-4 w-4"}),e.jsx("span",{children:"Last updated: Never"})]}),e.jsxs(gr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx(ee,{disabled:G.isPending||t,size:"sm","data-testid":"button-refresh-data",children:t?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-4 w-4 mr-2 animate-spin"}),"Refreshing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Pt,{className:`h-4 w-4 mr-2 ${G.isPending?"animate-spin":""}`}),"Refresh Data",e.jsx(Tt,{className:"h-4 w-4 ml-1"})]})})}),e.jsxs(br,{align:"end",className:"w-56",children:[e.jsx(oi,{children:"Refresh Options"}),e.jsx(en,{}),e.jsxs(xt,{onClick:D,children:[e.jsx(Pt,{className:"h-4 w-4 mr-2"}),"Quick Refresh (Yesterday)"]}),e.jsxs(xt,{onClick:()=>d(!0),children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Backfill Date Range..."]})]})]})]}),e.jsx(_,{className:"border-amber-200 bg-amber-50",children:e.jsxs(T,{className:"p-6 text-center",children:[e.jsx(Dt,{className:"h-8 w-8 mx-auto text-amber-600 mb-2"}),e.jsx("p",{className:"text-amber-800 font-medium",children:"No cached data available"}),e.jsx("p",{className:"text-sm text-amber-600 mt-1",children:(S==null?void 0:S.message)||"Click 'Refresh Data' to fetch live marketing analytics."})]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground","data-testid":"text-last-updated",children:[e.jsx(ra,{className:"h-4 w-4"}),e.jsxs("span",{children:["Last updated: ",O(S==null?void 0:S.lastUpdated)]})]}),t&&e.jsxs("div",{className:"flex flex-col gap-1","data-testid":"text-refresh-status",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-600",children:[e.jsx(Es,{className:"h-3 w-3 animate-spin"}),e.jsxs("span",{className:"font-medium",children:["Elapsed: ",de(r)]})]}),e.jsx("div",{className:"text-xs text-muted-foreground pl-5",children:M()})]})]}),e.jsxs(gr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx(ee,{disabled:G.isPending||t,size:"sm",variant:"outline","data-testid":"button-refresh-data",children:t?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-4 w-4 mr-2 animate-spin"}),de(r)]}):e.jsxs(e.Fragment,{children:[e.jsx(Pt,{className:"h-4 w-4 mr-2"}),"Refresh Data",e.jsx(Tt,{className:"h-4 w-4 ml-1"})]})})}),e.jsxs(br,{align:"end",className:"w-56",children:[e.jsx(oi,{children:"Refresh Options"}),e.jsx(en,{}),e.jsxs(xt,{onClick:D,"data-testid":"menu-item-quick-refresh",children:[e.jsx(Pt,{className:"h-4 w-4 mr-2"}),"Quick Refresh (Yesterday)"]}),e.jsxs(xt,{onClick:()=>b(!0),"data-testid":"menu-item-single-day",children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Refresh Specific Day..."]}),e.jsxs(xt,{onClick:()=>d(!0),"data-testid":"menu-item-backfill",children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Backfill Date Range..."]}),e.jsx(en,{}),e.jsxs(xt,{onClick:J,className:"text-orange-600","data-testid":"menu-item-full-refresh",children:[e.jsx(Dt,{className:"h-4 w-4 mr-2"}),"Full Refresh (May Timeout)"]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4","data-testid":"marketing-performance-summary",children:[e.jsxs(_,{"data-testid":"card-google-ads-summary",children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(yr,{className:"h-5 w-5 text-blue-600"}),"Google Ads Performance",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:"Last 30 days"})]})}),e.jsx(T,{children:le&&!le.noDataForRange?e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ct,{className:"h-3 w-3"})," Total Spend"]}),e.jsx("p",{className:"text-xl font-bold text-blue-600",children:I(le.cost)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"})," Impressions"]}),e.jsx("p",{className:"text-xl font-bold",children:y(le.impressions)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"})," Clicks"]}),e.jsx("p",{className:"text-xl font-bold",children:y(le.clicks)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Lh,{className:"h-3 w-3"})," CTR"]}),e.jsx("p",{className:"text-xl font-bold text-green-600",children:f(le.ctr)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(lt,{className:"h-3 w-3"})," Conversions"]}),e.jsx("p",{className:"text-xl font-bold text-purple-600",children:y(le.conversions)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Zs,{className:"h-3 w-3"})," Cost/Conv"]}),e.jsx("p",{className:"text-xl font-bold text-orange-600",children:I(le.costPerConversion)})]})]}):e.jsxs("div",{className:"text-center py-4",children:[e.jsx(yr,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-muted-foreground",children:"No Google Ads campaigns in selected range"})]})})]}),e.jsxs(_,{"data-testid":"card-youtube-summary",children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ra,{className:"h-5 w-5 text-red-600"}),"YouTube Channel Performance",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:"Last 30 days"})]})}),e.jsx(T,{children:C&&!C.noDataForRange?e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"})," Total Views"]}),e.jsx("p",{className:"text-xl font-bold text-red-600",children:y(C.views)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ra,{className:"h-3 w-3"})," Watch Time"]}),e.jsx("p",{className:"text-xl font-bold",children:R(C.watchTimeMinutes)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ys,{className:"h-3 w-3"})," Subs Gained"]}),e.jsx("p",{className:"text-xl font-bold text-green-600",children:y(C.subscribersGained)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"})," Clicks"]}),e.jsx("p",{className:"text-xl font-bold",children:y(C.clicks)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Zs,{className:"h-3 w-3"})," Sessions"]}),e.jsx("p",{className:"text-xl font-bold",children:y(C.sessions)})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Is,{className:"h-3 w-3"})," Revenue"]}),e.jsx("p",{className:"text-xl font-bold text-green-600",children:C.revenue!==null?I(C.revenue):"N/A"})]})]}):e.jsxs("div",{className:"text-center py-4",children:[e.jsx(Ra,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-muted-foreground",children:(C==null?void 0:C.message)||"No YouTube data in selected range"})]})})]})]}),e.jsx(Vs,{open:k,onOpenChange:b,children:e.jsxs(Us,{children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Refresh Specific Day"}),e.jsx(Ct,{children:"Compute analytics for a specific date. This is useful if data for a particular day is missing or incorrect."})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{htmlFor:"single-day-date",children:"Date"}),e.jsx(Me,{id:"single-day-date",type:"date",value:g,onChange:H=>w(H.target.value),"data-testid":"input-single-day-date"})]})}),e.jsxs(Ut,{children:[e.jsx(ee,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(ee,{onClick:$,"data-testid":"button-confirm-single-day",children:"Refresh This Day"})]})]})}),e.jsx(Vs,{open:o,onOpenChange:d,children:e.jsxs(Us,{children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Backfill Date Range"}),e.jsx(Ct,{children:"Compute analytics for each day in a date range. This processes one day at a time to avoid timeouts. Estimated time: ~5 seconds per day."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{htmlFor:"backfill-start-date",children:"Start Date"}),e.jsx(Me,{id:"backfill-start-date",type:"date",value:u,onChange:H=>x(H.target.value),"data-testid":"input-backfill-start-date"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{htmlFor:"backfill-end-date",children:"End Date"}),e.jsx(Me,{id:"backfill-end-date",type:"date",value:m,onChange:H=>v(H.target.value),"data-testid":"input-backfill-end-date"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(()=>{const H=Math.ceil((new Date(m).getTime()-new Date(u).getTime())/864e5);return`This will process ${H} days. Estimated time: ${Math.ceil(H*5/60)} minutes.`})()})]}),e.jsxs(Ut,{children:[e.jsx(ee,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsx(ee,{onClick:se,"data-testid":"button-confirm-backfill",children:"Start Backfill"})]})]})})]})}const db=[25,50,100];function mb(s,t){const[a,n]=p.useState(s);return p.useEffect(()=>{const i=setTimeout(()=>{n(s)},t);return()=>{clearTimeout(i)}},[s,t]),a}function Ot({endpoint:s,columns:t,title:a,searchable:n=!1,exportable:i=!1,filterOptions:r=[],onRowClick:l,emptyMessage:c="No data available",dateRange:o,className:d}){var j,Q,je,ce,be,ss;
51const[u,x]=p.useState(1),[m,v]=p.useState(25),[g,w]=p.useState(""),[k,b]=p.useState(null),[S,A]=p.useState(null),[F,de]=p.useState({}),[M,G]=p.useState(void 0),[D,$]=p.useState(!1),[se,J]=p.useState(null),le=mb(g,300),C=p.useCallback(oe=>{const Ne=new URLSearchParams,Le=(oe==null?void 0:oe.page)??u,ae=oe!=null&&oe.forExport?1e4:(oe==null?void 0:oe.pageSize)??m;return Ne.set("page",Le.toString()),Ne.set("pageSize",ae.toString()),oe!=null&&oe.pageToken&&Ne.set("pageToken",oe.pageToken),Ne.set("startIndex",((Le-1)*ae).toString()),o.startDate&&Ne.set("startDate",De(o.startDate,"yyyy-MM-dd")),o.endDate&&Ne.set("endDate",De(o.endDate,"yyyy-MM-dd")),le&&Ne.set("search",le),k&&S&&(Ne.set("sortBy",k),Ne.set("sortOrder",S)),Object.entries(F).forEach(([xe,Fe])=>{Fe&&Ne.set(xe,Fe)}),Ne.toString()},[u,m,o,le,k,S,F]),I=p.useMemo(()=>{const oe=C();return[`${s}?${oe}`]},[s,C]),{data:y,isLoading:f,isError:R,error:O,refetch:N,isFetching:re}=_e({queryKey:I,staleTime:3e4});p.useEffect(()=>{x(1),G(void 0)},[le,k,S,F,o,m]);const H=oe=>{const Ne=t.find(Le=>Le.key===oe);Ne!=null&&Ne.sortable&&(k===oe?S==="asc"?A("desc"):S==="desc"?(b(null),A(null)):A("asc"):(b(oe),A("asc")))},pe=()=>{if(y!=null&&y.pagination.hasNextPage){const oe=u+1;x(oe),y.pagination.nextPageToken&&G(y.pagination.nextPageToken)}},ye=()=>{if(y!=null&&y.pagination.hasPrevPage&&u>1){const oe=u-1;x(oe),y.pagination.prevPageToken&&G(y.pagination.prevPageToken)}},Ie=oe=>{v(parseInt(oe,10)),x(1),G(void 0)},ve=(oe,Ne)=>{de(Le=>({...Le,[oe]:Ne==="all"?"":Ne}))},B=()=>{w(""),de({}),b(null),A(null),x(1),G(void 0)},z=g||Object.values(F).some(oe=>oe)||k,K=oe=>oe==null?"":typeof oe=="number"?oe.toLocaleString():typeof oe=="boolean"?oe?"Yes":"No":oe instanceof Date?De(oe,"yyyy-MM-dd"):String(oe),P=async oe=>{$(!0),J(oe);try{let Ne=[];if(oe==="current")Ne=(y==null?void 0:y.data)||[];else{const nt=C({page:1,forExport:!0}),ks=await fetch(`${s}?${nt}`,{credentials:"include"});if(!ks.ok)throw new Error("Failed to fetch export data");Ne=(await ks.json()).data}if(Ne.length===0)throw new Error("No data to export");const ae=[t.map(nt=>nt.header).join(",")];Ne.forEach(nt=>{const ks=t.map(Rt=>{const wt=nt[Rt.key];return`"${K(wt).replace(/"/g,'""')}"`});ae.push(ks.join(","))});const xe=ae.join(` 52`),Fe=new Blob([xe],{type:"text/csv;charset=utf-8;"}),X=URL.createObjectURL(Fe),Be=document.createElement("a");Be.href=X;const ns=`${a.toLowerCase().replace(/\s+/g,"-")}-${De(new Date,"yyyy-MM-dd")}.csv`;Be.setAttribute("download",ns),document.body.appendChild(Be),Be.click(),document.body.removeChild(Be),URL.revokeObjectURL(X)}catch(Ne){console.error("Export failed:",Ne)}finally{$(!1),J(null)}},ue=oe=>k!==oe?e.jsx(Fh,{className:"h-4 w-4 text-muted-foreground/50"}):S==="asc"?e.jsx(Eh,{className:"h-4 w-4 text-primary"}):e.jsx(tc,{className:"h-4 w-4 text-primary"}),V=()=>{if(!(y!=null&&y.pagination))return null;const{total:oe=0,page:Ne=1,pageSize:Le=m}=y.pagination;if(oe===0)return e.jsx("span",{className:"text-sm text-muted-foreground",children:"No results"});const ae=(Ne-1)*Le+1,xe=Math.min(Ne*Le,oe);return e.jsxs("span",{className:"text-sm text-muted-foreground","data-testid":"pagination-info",children:["Showing ",ae.toLocaleString(),"-",xe.toLocaleString()," of ",oe.toLocaleString()," results"]})},U=()=>Array.from({length:m}).map((oe,Ne)=>e.jsx(ht,{children:t.map((Le,ae)=>
52e.jsx(Ke,{children:e.jsx(cs,{className:"h-5 w-full"})},`skeleton-${Ne}-${ae}`))},`skeleton-${Ne}`));return e.jsxs(_,{className:_a("w-full",d),"data-testid":"paginated-data-grid",children:[e.jsx(q,{className:"pb-4",children:e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(W,{className:"text-xl font-semibold","data-testid":"grid-title",children:a}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsxs("div",{className:"relative",children:[e.jsx(ga,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(Me,{type:"text",placeholder:"Search...",value:g,onChange:oe=>w(oe.target.value),className:"pl-9 w-[200px] h-9","data-testid":"search-input"}),g&&e.jsx("button",{onClick:()=>w(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","data-testid":"clear-search",children:e.jsx(pt,{className:"h-4 w-4"})})]}),r.map(oe=>e.jsxs(os,{value:F[oe.key]||"all",onValueChange:Ne=>ve(oe.key,Ne),children:[e.jsxs(ds,{className:"w-[150px] h-9","data-testid":`filter-${oe.key}`,children:[e.jsx(Ih,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(hs,{placeholder:oe.label})]}),e.jsxs(ms,{children:[e.jsxs(me,{value:"all",children:["All ",oe.label]}),oe.options.map(Ne=>e.jsx(me,{value:Ne.value,children:Ne.label},Ne.value))]})]},oe.key)),z&&e.jsxs(ee,{variant:"ghost",size:"sm",onClick:B,className:"h-9","data-testid":"clear-filters",children:[e.jsx(pt,{className:"h-4 w-4 mr-1"}),"Clear"]}),i&&e.jsxs(gr,{children:[e.jsx(jr,{asChild:!0,children:e.jsxs(ee,{variant:"outline",size:"sm",className:"h-9",disabled:D||!((j=y==null?void 0:y.data)!=null&&j.length),"data-testid":"export-button",children:[D?e.jsx(Es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export"]})}),e.jsxs(br,{align:"end",children:[e.jsxs(xt,{onClick:()=>P("current"),disabled:D,"data-testid":"export-current",children:[e.jsx(gp,{className:"h-4 w-4 mr-2"}),"Export Current Page"]}),e.jsxs(xt,{onClick:()=>P("all"),disabled:D,"data-testid":"export-all",children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export All Data"]})]})]})]})]})}),e.jsxs(T,{className:"p-0",children:[R&&e.jsxs(Qs,{variant:"destructive",className:"mx-6 mb-4","data-testid":"error-alert",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsxs(Xs,{className:"flex items-center justify-between",children:[e.jsx("span",{children:(()=>{const oe=O instanceof Error?O.message:String(O);return oe.includes("YouTube Analytics API")||oe.includes("video_reporting")?"This data is temporarily unavailable from the YouTube API. Some analytics queries have limited support.":oe.includes("500")||oe.includes("Internal error")?"External service temporarily unavailable. Please try again later.":oe||"Failed to load data"})()}),e.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>N(),className:"ml-4","data-testid":"retry-button",children:[e.jsx(Pt,{className:"h-4 w-4 mr-1"}),"Retry"]})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(nn,{children:[e.jsx(rn,{children:e.jsx(ht,{className:"hover:bg-transparent",children:t.map(oe=>e.jsx(fs,{style:{width:oe.width},className:_a(oe.sortable&&"cursor-pointer select-none hover:bg-muted/50 transition-colors"),onClick:()=>oe.sortable&&H(oe.key),"data-testid":`column-header-${oe.key}`,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:oe.header}),oe.sortable&&ue(oe.key)]})},oe.key))})}),e.jsx(ln,{children:f?U():((Q=y==null?void 0:y.data)==null?void 0:Q.length)===0?e.jsx(ht,{children:e.jsx(Ke,{colSpan:t.length,className:"h-32 text-center text-muted-foreground","data-testid":"empty-state",children:c})}):(je=y==null?void 0:y.data)==null?void 0:je.map((oe,Ne)=>e.jsx(ht,{className:_a(l&&"cursor-pointer hover:bg-muted/80"),onClick:()=>l==null?void 0:l(oe),"data-testid":`data-row-${Ne}`,children:t.map(Le=>e.jsx(Ke,{"data-testid":`cell-${Le.key}-${Ne}`,children:Le.render?Le.render(oe[Le.key],oe):K(oe[Le.key])},Le.key))},Ne))})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-t px-6 py-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[V(),re&&!f&&e.jsx(Es,{className:"h-4 w-4 animate-spin text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Rows per page:"}),e.jsxs(os,{value:m.toString(),onValueChange:Ie,children:[e.jsx(ds,{className:"w-[70px] h-8","data-testid":"page-size-selector",children:e.jsx(hs,{})}),e.jsx(ms,{children:db.map(oe=>e.jsx(me,{value:oe.toString(),children:oe},oe))})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ee,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:ye,disabled:!((ce=y==null?void 0:y.pagination)!=null&&ce.hasPrevPage)||u<=1||f,"data-testid":"prev-page-button",children:e.jsx(Sx,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-2 text-sm text-muted-foreground","data-testid":"current-page",children:["Page ",u," of ",((be=y==null?void 0:y.pagination)==null?void 0:be.totalPages)||1]}),e.jsx(ee,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:pe,disabled:!((ss=y==null?void 0:y.pagination)!=null&&ss.hasNextPage)||f,"data-testid":"next-page-button",children:e.jsx(Ca,{className:"h-4 w-4"})})]})]})]})]})]})}const ub=[{key:"website_visit",label:"Website Visit",description:"Unique visitor sessions across all entry points: homepage (/), pricing (/pricing), demo videos (/learn), registration (/auth), and AI Scribe landing (/scribe). Deduplicated by session ID to count unique visitors, not page views. Includes sitelink attribution from Google Ads.",formula:null,source:"analytics_events (event_type: website_visit)",defaultLookback:30,unit:"count"},{key:"signup_started",label:"Sign Up Started",description:"User entered a valid, available username on the registration page (shown by green checkmark). This indicates genuine signup
52intent.",formula:null,source:"analytics_events (event_type: signup_started)",defaultLookback:30,unit:"count"},{key:"account_created",label:"Account Created",description:"User completed registration and their account was successfully created in the database.",formula:null,source:"users",defaultLookback:30,unit:"count"},{key:"first_patient_added",label:"First Patient Added",description:"User added their first patient record after account creation, indicating meaningful product engagement.",formula:null,source:"patients (first record per user)",defaultLookback:30,unit:"count"},{key:"active_subscriber",label:"Active Subscriber",description:"User with an active paid subscription. Excludes users in trial period or with churned/cancelled subscriptions.",formula:null,source:"subscriptions (status: active)",defaultLookback:30,unit:"count"},{key:"patient_acquisition_cost",label:"Patient Acquisition Cost",description:"The average cost to acquire a new patient through marketing efforts. Lower values indicate more efficient marketing spend.",formula:"Total Marketing Spend / Number of New Patients Acquired",source:"marketing_spend, patients",defaultLookback:30,unit:"currency"},{key:"user_lifetime_value",label:"User Lifetime Value",description:"The average total revenue generated per user over their entire subscription period. Used to evaluate customer profitability.",formula:"Average Revenue Per User à Average Customer Lifespan",source:"subscriptions, payments",defaultLookback:365,unit:"currency"},{key:"ltv_cac_ratio",label:"LTV:CAC Ratio",description:"Lifetime Value divided by Customer Acquisition Cost. A ratio above 3:1 typically indicates healthy unit economics.",formula:"User Lifetime Value / Customer Acquisition Cost",source:"calculated (ltv, cac)",defaultLookback:365,unit:"ratio"},{key:"new_users",label:"New Users",description:"Count of users who created accounts within the selected time period.",formula:"COUNT(users WHERE created_at BETWEEN start_date AND end_date)",source:"users",defaultLookback:30,unit:"count"},{key:"conversion_rate",label:"Conversion Rate",description:"Percentage of users who completed a target action from the previous funnel stage. Used to identify drop-off points.",formula:"(Users Completing Action / Users at Previous Stage) à 100",source:"analytics_events, users",defaultLookback:30,unit:"percentage"},{key:"impressions",label:"Impressions",description:"The number of times your ad was shown to users. Each time your ad appears on screen counts as one impression.",formula:null,source:"Google Ads API",defaultLookback:30,unit:"count"},{key:"clicks",label:"Clicks",description:"The number of times users clicked on your ad. This measures direct engagement and intent.",formula:null,source:"Google Ads API",defaultLookback:30,unit:"count"},{key:"ctr",label:"Click-Through Rate (CTR)",description:"The percentage of impressions that resulted in a click. Higher CTR indicates your ad resonates with your audience. Industry average is 2-4%.",formula:"(Clicks / Impressions) à 100",source:"Google Ads API",defaultLookback:30,unit:"percentage"},{key:"cost",label:"Ad Spend",description:"The total amount spent on advertising during the selected period.",formula:null,source:"Google Ads API",defaultLookback:30,unit:"currency"},{key:"avg_cpc",label:"Average Cost Per Click",description:"The average amount you pay each time someone clicks your ad. Lower CPCs mean more traffic for your budget.",formula:"Total Cost / Total Clicks",source:"Google Ads API",defaultLookback:30,unit:"currency"},{key:"conversions",label:"Conversions",description:"Valuable actions users took after clicking your ad (sign-ups, purchases, form submissions). Your primary success metric.",formula:null,source:"Google Ads API",defaultLookback:30,unit:"count"},{key:"cost_per_conversion",label:"Cost Per Conversion (CPA)",description:"The average cost to acquire one conversion. Lower CPA means more efficient advertising spend.",formula:"Total Cost / Conversions",source:"Google Ads API",defaultLookback:30,unit:"currency"},{key:"quality_score",label:"Quality Score",description:"A 1-10 score estimating ad quality based on expected CTR, ad relevance, and landing page experience. Higher scores lead to lower costs and better ad positions.",formula:null,source:"Google Ads API",defaultLookback:30,unit:"count"},{key:"roas",label:"Return on Ad Spend (ROAS)",description:"Revenue generated for every dollar spent on advertising. A ROAS of 4 means you earn $4 for every $1 spent.",formula:"Conversion Value / Cost",source:"Google Ads API",defaultLookback:30,unit:"ratio"},{key:"views",label:"Views",description:"Number of times your video was watched. A view counts when someone watches at least 30 seconds (or full video if shorter).",formula:null,source:"YouTube Analytics API",defaultLookback:30,unit:"count"},{key:"watch_time",label:"Watch Time",description:"Total minutes viewers spent watching your content. YouTube's algorithm prioritizes videos with high watch time.",formula:null,source:"YouTube Analytics API",defaultLookback:30,unit:"count"},{key:"avg_view_duration",label:"Average View Duration",description:"The average length of time viewers watch your video. Higher duration indicates more engaging content.",formula:null,source:"YouTube Analytics API",defaultLookback:30,unit:"count"},{key:"audience_retention",label:"Audience Retention",description:"Shows what percentage of viewers are still watching at each point in y
52our video. Steep drops indicate where viewers lose interest.",formula:null,source:"YouTube Analytics API",defaultLookback:30,unit:"percentage"},{key:"subscribers_gained",label:"Subscribers Gained",description:"New channel subscribers gained during this period. Indicates your content is compelling enough for viewers to want more.",formula:null,source:"YouTube Analytics API",defaultLookback:30,unit:"count"},{key:"engagement_rate",label:"Engagement Rate",description:"Percentage of viewers who interacted with your video (likes, comments, shares). Higher rates signal valuable content.",formula:"(Likes + Comments + Shares) / Views à 100",source:"YouTube Analytics API",defaultLookback:30,unit:"percentage"}],xb=new Map(ub.map(s=>[s.key,s]));function Wr(s){return xb.get(s)}const hc=[{value:"today",label:"Today",getRange:()=>({startDate:$t(new Date),endDate:At(new Date)})},{value:"yesterday",label:"Yesterday",getRange:()=>({startDate:$t(vt(new Date,1)),endDate:At(vt(new Date,1))})},{value:"3d",label:"Last 3 days",getRange:()=>({startDate:$t(vt(new Date,2)),endDate:At(new Date)})},{value:"7d",label:"Last 7 days",getRange:()=>({startDate:$t(vt(new Date,6)),endDate:At(new Date)})},{value:"14d",label:"Last 14 days",getRange:()=>({startDate:$t(vt(new Date,13)),endDate:At(new Date)})},{value:"21d",label:"Last 21 days",getRange:()=>({startDate:$t(vt(new Date,20)),endDate:At(new Date)})},{value:"30d",label:"Last 30 days",getRange:()=>({startDate:$t(vt(new Date,29)),endDate:At(new Date)})},{value:"60d",label:"Last 60 days",getRange:()=>({startDate:$t(vt(new Date,59)),endDate:At(new Date)})},{value:"90d",label:"Last 90 days",getRange:()=>({startDate:$t(vt(new Date,89)),endDate:At(new Date)})},{value:"6m",label:"Last 6 months",getRange:()=>({startDate:$t(Io(new Date,6)),endDate:At(new Date)})},{value:"12m",label:"Last 12 months",getRange:()=>({startDate:$t(Io(new Date,12)),endDate:At(new Date)})},{value:"all",label:"All time",getRange:()=>({startDate:new Date(2020,0,1),endDate:At(new Date)})}];function ai(s){const t=hc.find(a=>a.value===s);if(t){const a=t.getRange();return{preset:s,startDate:a.startDate,endDate:a.endDate,label:t.label}}return{preset:"30d",startDate:$t(vt(new Date,29)),endDate:At(new Date),label:"Last 30 days"}}function Dl(s,t){const a=s.getFullYear(),n=t.getFullYear();return a===n?`${De(s,"MMM d")} - ${De(t,"MMM d, yyyy")}`:`${De(s,"MMM d, yyyy")} - ${De(t,"MMM d, yyyy")}`}function Hr({value:s,onChange:t,compact:a=!1,className:n,allowedPresets:i}){const[r,l]=p.useState(!1),[c,o]=p.useState(s.preset==="custom"),[d,u]=p.useState(s.startDate),[x,m]=p.useState(s.endDate),v=p.useMemo(()=>!i||i.length===0?hc:hc.filter(A=>i.includes(A.value)),[i]),g=p.useMemo(()=>s.preset==="custom"?Dl(s.startDate,s.endDate):s.label,[s]),w=A=>{if(A==="custom")o(!0),u(s.startDate),m(s.endDate);else{const F=ai(A);t(F),o(!1),l(!1)}},k=()=>{if(d&&x){const A=$t(d),F=At(x);t({preset:"custom",startDate:A,endDate:F,label:Dl(A,F)}),l(!1)}},b=A=>{A&&(u(A),x&&A>x&&m(A))},S=A=>{A&&(m(A),d&&A<d&&u(A))};return a?e.jsxs(os,{value:s.preset,onValueChange:A=>w(A),children:[e.jsxs(ds,{className:_a("w-[150px] h-8 text-xs",n),"data-testid":"time-range-selector-compact",children:[e.jsx(ia,{className:"h-3 w-3 mr-1.5 text-muted-foreground"}),e.jsx(hs,{placeholder:"Select range"})]}),e.jsxs(ms,{children:[v.map(A=>e.jsx(me,{value:A.value,children:A.label},A.value)),(!i||i.includes("custom"))&&e.jsx(me,{value:"custom",children:"Custom range"})]})]}):e.jsxs(Ic,{open:r,onOpenChange:l,children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(ee,{variant:"outline",className:_a("justify-start text-left font-normal transition-all duration-200","hover:bg-accent hover:border-accent-foreground/20",!s&&"text-muted-foreground",n),"data-testid":"time-range-selector-trigger",children:[e.jsx(ia,{className:"mr-2 h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1",children:g}),e.jsx(Tt,{className:_a("ml-2 h-4 w-4 text-muted-foreground transition-transform duration-200",r&&"rotate-180")})]})}),e.jsx(Ec,{className:"w-auto p-0",align:"start","data-testid":"time-range-selector-popover",children:e.jsxs("div",{className:"flex",children:[e.jsxs("div",{className:"border-r p-3 space-y-1 min-w-[160px]",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2 px-2",children:"Qu
52ick Select"}),v.map(A=>e.jsxs("button",{onClick:()=>w(A.value),className:_a("w-full text-left px-3 py-2 text-sm rounded-md transition-colors","hover:bg-accent hover:text-accent-foreground","flex items-center justify-between",s.preset===A.value&&"bg-accent text-accent-foreground"),"data-testid":`preset-option-${A.value}`,children:[e.jsx("span",{children:A.label}),s.preset===A.value&&e.jsx(ec,{className:"h-4 w-4"})]},A.value)),e.jsx("div",{className:"border-t my-2"}),e.jsxs("button",{onClick:()=>w("custom"),className:_a("w-full text-left px-3 py-2 text-sm rounded-md transition-colors","hover:bg-accent hover:text-accent-foreground","flex items-center justify-between",s.preset==="custom"&&"bg-accent text-accent-foreground"),"data-testid":"preset-option-custom",children:[e.jsx("span",{children:"Custom range"}),s.preset==="custom"&&e.jsx(ec,{className:"h-4 w-4"})]})]}),c&&e.jsxs("div",{className:"p-3 space-y-4",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1",children:"Start Date"}),e.jsxs("div",{className:"border rounded-md p-2 bg-background",children:[e.jsx("p",{className:"text-sm font-medium mb-2 px-1",children:d?De(d,"MMM d, yyyy"):"Select date"}),e.jsx(So,{mode:"single",selected:d,onSelect:b,disabled:A=>A>new Date,initialFocus:!0,"data-testid":"calendar-start"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1",children:"End Date"}),e.jsxs("div",{className:"border rounded-md p-2 bg-background",children:[e.jsx("p",{className:"text-sm font-medium mb-2 px-1",children:x?De(x,"MMM d, yyyy"):"Select date"}),e.jsx(So,{mode:"single",selected:x,onSelect:S,disabled:A=>A>new Date||(d?A<d:!1),"data-testid":"calendar-end"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:d&&x?Dl(d,x):"Select a date range"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ee,{variant:"outline",size:"sm",onClick:()=>{o(!1),u(s.startDate),m(s.endDate)},"data-testid":"button-cancel-custom",children:"Cancel"}),e.jsx(ee,{size:"sm",onClick:k,disabled:!d||!x,"data-testid":"button-apply-custom",children:"Apply"})]})]})]})]})})]})}var hb=ch;function pb(s){return s&&s.length?hb(s):[]}var fb=pb;const gb=Rr(fb);var Xc=Fr(),es=s=>Ir(s,Xc),Zc=Fr();es.write=s=>Ir(s,Zc);var xl=Fr();es.onStart=s=>Ir(s,xl);var Jc=Fr();es.onFrame=s=>Ir(s,Jc);var eo=Fr();es.onFinish=s=>Ir(s,eo);var Rn=[];es.setTimeout=(s,t)=>{const a=es.now()+t,n=()=>{const r=Rn.findIndex(l=>l.cancel==n);~r&&Rn.splice(r,1),qa-=~r?1:0},i={time:a,handler:s,cancel:n};return Rn.splice(ru(a),0,i),qa+=1,iu(),i};var ru=s=>~(~Rn.findIndex(t=>t.time>s)||~Rn.length);es.cancel=s=>{xl.delete(s),Jc.delete(s),eo.delete(s),Xc.delete(s),Zc.delete(s)};es.sync=s=>{pc=!0,es.batchedUpdates(s),pc=!1};es.throttle=s=>{let t;function a(){try{s(...t)}finally{t=null}}function n(...i){t=i,es.onStart(a)}return n.handler=s,n.cancel=()=>{xl.delete(a),t=null},n};var so=typeof window<"u"?window.requestAnimationFrame:()=>{};es.use=s=>so=s;es.now=typeof performance<"u"?()=>performance.now():Date.now;es.batchedUpdates=s=>s();es.catch=console.error;es.frameLoop="always";es.advance=()=>{es.frameLoop!=="demand"?console.warn("Cannot call the manual advancement of rafz whilst frameLoop is not set as demand"):cu()};var za=-1,qa=0,pc=!1;function Ir(s,t){pc?(t.delete(s),s(0)):(t.add(s),iu())}function iu(){za<0&&(za=0,es.frameLoop!=="demand"&&so(lu))}function jb(){za=-1}function lu(){~za&&(so(lu),es.batchedUpdates(cu))}function cu(){const s=za;za=es.now();const t=ru(za);if(t&&(ou(Rn.splice(0,t),a=>a.handler()),qa-=t),!qa){jb();return}xl.flush(),Xc.flush(s?Math.min(64,za-s):16.667),Jc.flush(),Zc.flush(),eo.flush()}function Fr(){let s=new Set,t=s;return{add(a){qa+=t==s&&!s.has(a)?1:0,s.add(a)},delete(a){return qa-=t==s&&s.has(a)?1:0,s.delete(a)},flush(a){t.size&&(s=new Set,qa-=t.size,ou(t,n=>n(a)&&s.add(n)),qa+=s.size,t=s)}}}
52function ou(s,t){s.forEach(a=>{try{t(a)}catch(n){es.catch(n)}})}var bb=Object.defineProperty,vb=(s,t)=>{for(var a in t)bb(s,a,{get:t[a],enumerable:!0})},Mt={};vb(Mt,{assign:()=>Nb,colors:()=>Wa,createStringInterpolator:()=>ao,skipAnimation:()=>mu,to:()=>du,willAdvance:()=>no});function fc(){}var yb=(s,t,a)=>Object.defineProperty(s,t,{value:a,writable:!0,configurable:!0}),he={arr:Array.isArray,obj:s=>!!s&&s.constructor.name==="Object",fun:s=>typeof s=="function",str:s=>typeof s=="string",num:s=>typeof s=="number",und:s=>s===void 0};function Aa(s,t){if(he.arr(s)){if(!he.arr(t)||s.length!==t.length)return!1;for(let a=0;a<s.length;a++)if(s[a]!==t[a])return!1;return!0}return s===t}var Ye=(s,t)=>s.forEach(t);function zt(s,t,a){if(he.arr(s)){for(let n=0;n<s.length;n++)t.call(a,s[n],`${n}`);return}for(const n in s)s.hasOwnProperty(n)&&t.call(a,s[n],n)}var Nt=s=>he.und(s)?[]:he.arr(s)?s:[s];function or(s,t){if(s.size){const a=Array.from(s);s.clear(),Ye(a,t)}}var rr=(s,...t)=>or(s,a=>a(...t)),to=()=>typeof window>"u"||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent),ao,du,Wa=null,mu=!1,no=fc,Nb=s=>{s.to&&(du=s.to),s.now&&(es.now=s.now),s.colors!==void 0&&(Wa=s.colors),s.skipAnimation!=null&&(mu=s.skipAnimation),s.createStringInterpolator&&(ao=s.createStringInterpolator),s.requestAnimationFrame&&es.use(s.requestAnimationFrame),s.batchedUpdates&&(es.batchedUpdates=s.batchedUpdates),s.willAdvance&&(no=s.willAdvance),s.frameLoop&&(es.frameLoop=s.frameLoop)},dr=new Set,Kt=[],Pl=[],wi=0,hl={get idle(){return!dr.size&&!Kt.length},start(s){wi>s.priority?(dr.add(s),es.onStart(wb)):(uu(s),es(gc))},advance:gc,sort(s){if(wi)es.onFrame(()=>hl.sort(s));else{const t=Kt.indexOf(s);~t&&(Kt.splice(t,1),xu(s))}},clear(){Kt=[],dr.clear()}};function wb(){dr.forEach(uu),dr.clear(),es(gc)}function uu(s){Kt.includes(s)||xu(s)}function xu(s){Kt.splice(kb(Kt,t=>t.priority>s.priority),0,s)}function gc(s){const t=Pl;for(let a=0;a<Kt.length;a++){const n=Kt[a];wi=n.priority,n.idle||(no(n),n.advance(s),n.idle||t.push(n))}return wi=0,Pl=Kt,Pl.length=0,Kt=t,Kt.length>0}function kb(s,t){const a=s.findIndex(t);return a<0?s.length:a}var pl={transparent:0,aliceblue:4042850303,antiquewhite:4209760255,aqua:16777215,aquamarine:2147472639,azure:4043309055,beige:4126530815,bisque:4293182719,black:255,blanchedalmond:4293643775,blue:65535,blueviolet:2318131967,brown:2771004159,burlywood:3736635391,burntsienna:3934150143,cadetblue:1604231423,chartreuse:2147418367,chocolate:3530104575,coral:4286533887,cornflowerblue:1687547391,cornsilk:4294499583,crimson:3692313855,cyan:16777215,darkblue:35839,darkcyan:9145343,darkgoldenrod:3095792639,darkgray:2846468607,darkgreen:6553855,darkgrey:2846468607,darkkhaki:3182914559,darkmagenta:2332068863,darkolivegreen:1433087999,darkorange:4287365375,darkorchid:2570243327,darkred:2332033279,darksalmon:3918953215,darkseagreen:2411499519,darkslateblue:1211993087,darkslategray:793726975,darkslategrey:793726975,darkturquoise:13554175,darkviolet:2483082239,deeppink:4279538687,deepskyblue:12582911,dimgray:1768516095,dimgrey:1768516095,dodgerblue:512819199,firebrick:2988581631,floralwhite:4294635775,forestgreen:579543807,fuchsia:4278255615,gainsboro:3705462015,ghostwhite:4177068031,gold:4292280575,goldenrod:3668254975,gray:2155905279,green:8388863,greenyellow:2919182335,grey:2155905279,honeydew:4043305215,hotpink:4285117695,indianred:3445382399,indigo:1258324735,ivory:4294963455,khaki:4041641215,lavender:3873897215,lavenderblush:4293981695,lawngreen:2096890111,lemonchiffon:4294626815,lightblue:2916673279,lightcoral:4034953471,lightcyan:3774873599,lightgoldenrodyellow:4210742015,lightgray:3553874943,lightgreen:2431553791,lightgrey:3553874943,lightpink:4290167295,lightsalmon:4288707327,lightseagreen:548580095,lightskyblue:2278488831,lightslategray:2005441023,lightslategrey:2005441023,lightsteelblue:2965692159,lightyellow:4294959359,lime:16711935,limegreen:852308735,linen:4210091775,magenta:4278255615,maroon:2147483903,mediumaquamarine:1724754687,mediumblue:52735,mediumorchid:3126187007,mediumpurple:2473647103,mediumseagreen:1018393087,mediumslateblue:2070474495,mediumspringgreen:16423679,mediumturquoise:1221709055,mediumvioletred:3340076543,midnightblue:421097727,mintcream:4127193855,mistyrose:4293190143,moccasin:4293178879,navajowhite:4292783615,navy:33023,oldlace:4260751103,olive:2155872511,olivedrab:1804477439,orange:4289003775,orangered:4282712319,orchid:3664828159,palegoldenrod:4008225535,palegreen:2566625535,paleturquoise:2951671551,palevioletred:3681588223,papayawhip:4293907967,peachpuff:4292524543,peru:3448061951,pink:4290825215,plum:3718307327,powderblue:2967529215,purple:2147516671,rebeccapurple:1714657791,red:4278190335,rosybrown:3163525119,royalblue:1097458175,saddlebrown:2336560127,salmon:4202722047,sandybrown:4104413439,seagreen:780883967,seashell:4294307583,sienna:2689740287,silver:3233857791,skyblue:2278484991,slateblue:1784335871,slategray:1887473919,slategrey:1887473919,snow:4294638335,springgreen:16744447,steelblue:1182971135,tan:3535047935,teal:8421631,thistle:3636451583,tomato:4284696575,turquoise:1088475391,violet:4001558271,wheat:4125012991,white:4294967295,whitesmoke:4126537215,yellow:4294902015,yellowgreen:2597139199},na="[-+]?\\d*\\.?\\d+",ki=na+"%";function fl(...s){return"\\(\\s*("+s.join(")\\s*,\\s*(")+")\\s*\\)"}var Cb=new RegExp("rgb"+fl(na,na,na)),Sb=new RegExp("rgba"+fl(na,na,na,na)),Ab=new RegExp("hsl"+fl(na,ki,ki)),_b=new RegExp("hsla"
52+fl(na,ki,ki,na)),Tb=/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,Db=/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,Pb=/^#([0-9a-fA-F]{6})$/,Mb=/^#([0-9a-fA-F]{8})$/;function Rb(s){let t;return typeof s=="number"?s>>>0===s&&s>=0&&s<=4294967295?s:null:(t=Pb.exec(s))?parseInt(t[1]+"ff",16)>>>0:Wa&&Wa[s]!==void 0?Wa[s]:(t=Cb.exec(s))?(Cn(t[1])<<24|Cn(t[2])<<16|Cn(t[3])<<8|255)>>>0:(t=Sb.exec(s))?(Cn(t[1])<<24|Cn(t[2])<<16|Cn(t[3])<<8|ed(t[4]))>>>0:(t=Tb.exec(s))?parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+"ff",16)>>>0:(t=Mb.exec(s))?parseInt(t[1],16)>>>0:(t=Db.exec(s))?parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+t[4]+t[4],16)>>>0:(t=Ab.exec(s))?(Zo(Jo(t[1]),Kr(t[2]),Kr(t[3]))|255)>>>0:(t=_b.exec(s))?(Zo(Jo(t[1]),Kr(t[2]),Kr(t[3]))|ed(t[4]))>>>0:null}function Ml(s,t,a){return a<0&&(a+=1),a>1&&(a-=1),a<1/6?s+(t-s)*6*a:a<1/2?t:a<2/3?s+(t-s)*(2/3-a)*6:s}function Zo(s,t,a){const n=a<.5?a*(1+t):a+t-a*t,i=2*a-n,r=Ml(i,n,s+1/3),l=Ml(i,n,s),c=Ml(i,n,s-1/3);return Math.round(r*255)<<24|Math.round(l*255)<<16|Math.round(c*255)<<8}function Cn(s){const t=parseInt(s,10);return t<0?0:t>255?255:t}function Jo(s){return(parseFloat(s)%360+360)%360/360}function ed(s){const t=parseFloat(s);return t<0?0:t>1?255:Math.round(t*255)}function Kr(s){const t=parseFloat(s);return t<0?0:t>100?1:t/100}function sd(s){let t=Rb(s);if(t===null)return s;t=t||0;const a=(t&4278190080)>>>24,n=(t&16711680)>>>16,i=(t&65280)>>>8,r=(t&255)/255;return`rgba(${a}, ${n}, ${i}, ${r})`}var Sr=(s,t,a)=>{if(he.fun(s))return s;if(he.arr(s))return Sr({range:s,output:t,extrapolate:a});if(he.str(s.output[0]))return ao(s);const n=s,i=n.output,r=n.range||[0,1],l=n.extrapolateLeft||n.extrapolate||"extend",c=n.extrapolateRight||n.extrapolate||"extend",o=n.easing||(d=>d);return d=>{const u=$b(d,r);return Lb(d,r[u],r[u+1],i[u],i[u+1],o,l,c,n.map)}};
52function Lb(s,t,a,n,i,r,l,c,o){let d=o?o(s):s;if(d<t){if(l==="identity")return d;l==="clamp"&&(d=t)}if(d>a){if(c==="identity")return d;c==="clamp"&&(d=a)}return n===i?n:t===a?s<=t?n:i:(t===-1/0?d=-d:a===1/0?d=d-t:d=(d-t)/(a-t),d=r(d),n===-1/0?d=-d:i===1/0?d=d+n:d=d*(i-n)+n,d)}function $b(s,t){for(var a=1;a<t.length-1&&!(t[a]>=s);++a);return a-1}var Ob={linear:s=>s},Ar=Symbol.for("FluidValue.get"),Vn=Symbol.for("FluidValue.observers"),dt=s=>!!(s&&s[Ar]),it=s=>s&&s[Ar]?s[Ar]():s,td=s=>s[Vn]||null;function Ib(s,t){s.eventObserved?s.eventObserved(t):s(t)}function Ha(s,t){const a=s[Vn];a&&a.forEach(n=>{Ib(n,t)})}var Er=class{constructor(s){if(!s&&!(s=this.get))throw Error("Unknown getter");Fb(this,s)}},Fb=(s,t)=>hu(s,Ar,t);function $a(s,t){if(s[Ar]){let a=s[Vn];a||hu(s,Vn,a=new Set),a.has(t)||(a.add(t),s.observerAdded&&s.observerAdded(a.size,t))}return t}function Ka(s,t){const a=s[Vn];if(a&&a.has(t)){const n=a.size-1;n?a.delete(t):s[Vn]=null,s.observerRemoved&&s.observerRemoved(n,t)}}var hu=(s,t,a)=>Object.defineProperty(s,t,{value:a,writable:!0,configurable:!0}),ni=/[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,Eb=/(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi,ad=new RegExp(`(${ni.source})(%|[a-z]+)`,"i"),Vb=/rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi,gl=/var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/,pu=s=>{const[t,a]=Ub(s);if(!t||to())return s;const n=window.getComputedStyle(document.documentElement).getPropertyValue(t);if(n)return n.trim();if(a&&a.startsWith("--")){const i=window.getComputedStyle(document.documentElement).getPropertyValue(a);return i||s}else{if(a&&gl.test(a))return pu(a);if(a)return a}return s},Ub=s=>{const t=gl.exec(s);if(!t)return[,];const[,a,n]=t;return[a,n]},Rl,Bb=(s,t,a,n,i)=>`rgba(${Math.round(t)}, ${Math.round(a)}, ${Math.round(n)}, ${i})`,Vr=s=>{Rl||(Rl=Wa?new RegExp(`(${Object.keys(Wa).join("|")})(?!\\w)`,"g"):/^\b$/);const t=s.output.map(r=>it(r).replace(gl,pu).replace(Eb,sd).replace(Rl,sd)),a=t.map(r=>r.match(ni).map(Number)),i=a[0].map((r,l)=>a.map(c=>{if(!(l in c))throw Error('The arity of each "output" value must be equal');return c[l]})).map(r=>Sr({...s,output:r}));return r=>{var o;const l=!ad.test(t[0])&&((o=t.find(d=>ad.test(d)))==null?void 0:o.replace(ni,""));let c=0;return t[0].replace(ni,()=>`${i[c++](r)}${l||""}`).replace(Vb,Bb)}},ro="react-spring: ",fu=s=>{const t=s;let a=!1;if(typeof t!="function")throw new TypeError(`${ro}once requires a function parameter`);return(...n)=>{a||(t(...n),a=!0)}},zb=fu(console.warn);function qb(){zb(`${ro}The "interpolate" function is deprecated in v9 (use "to" instead)`)}var Gb=fu(console.warn);function Wb(){Gb(`${ro}Directly calling start instead of using the api object is deprecated in v9 (use ".start" instead), this will be removed in later 0.X.0 versions`)}function jl(s){return he.str(s)&&(s[0]=="#"||/\d/.test(s)||!to()&&gl.test(s)||s in(Wa||{}))}var io=to()?p.useEffect:p.useLayoutEffect,Hb=()=>{const s=p.useRef(!1);return io(()=>(s.current=!0,()=>{s.current=!1}),[]),s};function gu(){const s=p.useState()[1],t=Hb();return()=>{t.current&&s(Math.random())}}var ju=s=>p.useEffect(s,Kb),Kb=[];function nd(s){const t=p.useRef(void 0);return p.useEffect(()=>{t.current=s}),t.current}var _r=Symbol.for("Animated:node"),Yb=s=>!!s&&s[_r]===s,ha=s=>s&&s[_r],lo=(s,t)=>yb(s,_r,t),bl=s=>s&&s[_r]&&s[_r].getPayload(),bu=class{constructor(){lo(this,this)}getPayload(){return this.payload||[]}},vl=class vu extends bu{constructor(t){super(),this._value=t,this.done=!0,this.durationProgress=0,he.num(this._value)&&(this.lastPosition=this._value)}static create(t){return new vu(t)}getPayload(){return[this]}getValue(){return this._value}setValue(t,a){return he.num(t)&&(this.lastPosition=t,a&&(t=Math.round(t/a)*a,this.done&&(this.lastPosition=t))),this._value===t?!1:(this._value=t,!0)}reset(){const{done:t}=this;this.done=!1,he.num(this._value)&&(this.elapsedTime=0,this.durationProgress=0,this.lastPosition=this._value,t&&(this.lastVelocity=null),this.v0=null)}},Ci=class yu extends vl{constructor(t){super(0),this._string=null,this._toString=Sr({output:[t,t]})}static create(t){return new yu(t)}getValue(){const t=this._string;return t??(this._string=this._toString(this._value))}setValue(t){if(he.str(t)){if(t==this._string)return!1;this._string=t,this._value=1}else if(super.setValue(t))this._string=null;else return!1;return!0}reset(t){t&&(this._toString=Sr({output:[this.getValue(),t]})),this._value=0,super.reset()}},Si={dependencies:null},gn=class extends bu{constructor(s){super(),this.source=s,this.setValue(s)}getValue(s){const t={};return zt(this.source,(a,n)=>{Yb(a)?t[n]=a.getValue(s):dt(a)?t[n]=it(a):s||(t[n]=a)}),t}setValue(s){this.source=s,this.payload=this._makePayload(s)}reset(){this.payload&&Ye(this.payload,s=>s.reset())}_makePayload(s){if(s){const t=new Set;return zt(s,this._addToPayload,t),Array.from(t)}}_addToPayload(s){Si.dependencies&&dt(s)&&Si.dependencies.add(s);const t=bl(s);t&&Ye(t,a=>this.add(a))}},Qb=class Nu extends gn{constructor(t){super(t)}static create(t){return new Nu(t)}getValue(){return this.source.map(t=>t.getValue())}setValue(t){const a=this.getPayload();return t.length==a.length?a.map((n,i)=>n.setValue(t[i])).some(Boolean):(super.setValue(t.map(Xb)),!0)}};function Xb(s){return(jl(s)?Ci:vl).create(s)}function jc(s){const t=ha(s);return t?t.constructor:he.arr(s)?Qb:jl(s)?Ci:vl}var rd=(s,t)=>{const a=!he.fun(s)||s.prototype&&s.prototype.isReactComponent;return p.forwardRef((n,i)=>{const r=p.useRef(null),l=a&&p.useCallback(g=>{r.current=ev(i,g)},[i]),[c,o]=Jb(n,t),d=gu(),u=()=>{const g=r.current;if(a&&!g)return;(g?t.applyAnimatedValues(g,c.getValue(!0)):!1)===!1&&d()},x=new Zb(u,o),m=p.useRef(void 0);io(()=>(m.current=x,Ye(o,g=>$a(g,x)),()=>{m.current&&(Ye(m.current.deps,g=>Ka(g,m.current)),es.cancel(m.current.update))})),p.useEffect(u,[]),ju(()=>()=>{const g=m.current;Ye(g.deps,w=>Ka(w,g))});const v=t.getComponentProps(c.getValue());return p.createElement(s,{...v,ref:l})})},Zb=class{constructor(s,t){this.update=s,this.deps=t}eventObserved(s){s.type=="change"&&es.write(this.update)}};function Jb(s,t){const a=new Set;return Si.dependencies=a,s.style&&(s={...s,style:t.createAnimatedStyle(s.style)}),s=new gn(s),Si.dependencies=null,[s,a]}function ev(s,t){return s&&(he.fun(s)?s(t):s.current=t),t}var id=Symbol.for("AnimatedComponent"),yl=(s,{applyAnimatedValues:t=()=>!1,createAnimatedStyle:a=i=>new gn(i),getComponentProps:n=i=>i}={})=>{const i={applyAnimatedValues:t,createAnimatedStyle:a,getComponentProps:n}
52,r=l=>{const c=ld(l)||"Anonymous";return he.str(l)?l=r[l]||(r[l]=rd(l,i)):l=l[id]||(l[id]=rd(l,i)),l.displayName=`Animated(${c})`,l};return zt(s,(l,c)=>{he.arr(s)&&(c=ld(l)),r[c]=r(l)}),{animated:r}},ld=s=>he.str(s)?s:s&&he.str(s.displayName)?s.displayName:he.fun(s)&&s.name||null;function Ja(s,...t){return he.fun(s)?s(...t):s}var mr=(s,t)=>s===!0||!!(t&&s&&(he.fun(s)?s(t):Nt(s).includes(t))),wu=(s,t)=>he.obj(s)?t&&s[t]:s,ku=(s,t)=>s.default===!0?s[t]:s.default?s.default[t]:void 0,sv=s=>s,co=(s,t=sv)=>{let a=tv;s.default&&s.default!==!0&&(s=s.default,a=Object.keys(s));const n={};for(const i of a){const r=t(s[i],i);he.und(r)||(n[i]=r)}return n},tv=["config","onProps","onStart","onChange","onPause","onResume","onRest"],av={config:1,from:1,to:1,ref:1,loop:1,reset:1,pause:1,cancel:1,reverse:1,immediate:1,default:1,delay:1,onProps:1,onStart:1,onChange:1,onPause:1,onResume:1,onRest:1,onResolve:1,items:1,trail:1,sort:1,expires:1,initial:1,enter:1,update:1,leave:1,children:1,onDestroyed:1,keys:1,callId:1,parentId:1};function nv(s){const t={};let a=0;if(zt(s,(n,i)=>{av[i]||(t[i]=n,a++)}),a)return t}function Cu(s){const t=nv(s);if(t){const a={to:t};return zt(s,(n,i)=>i in t||(a[i]=n)),a}return{...s}}function Tr(s){return s=it(s),he.arr(s)?s.map(Tr):jl(s)?Mt.createStringInterpolator({range:[0,1],output:[s,s]})(1):s}function rv(s){for(const t in s)return!0;return!1}function bc(s){return he.fun(s)||he.arr(s)&&he.obj(s[0])}function iv(s,t){var a;(a=s.ref)==null||a.delete(s),t==null||t.delete(s)}function lv(s,t){var a;t&&s.ref!==t&&((a=s.ref)==null||a.delete(s),t.add(s),s.ref=t)}var Su={default:{tension:170,friction:26},gentle:{tension:120,friction:14},wobbly:{tension:180,friction:12},stiff:{tension:210,friction:20},slow:{tension:280,friction:60},molasses:{tension:280,friction:120}},vc={...Su.default,mass:1,damping:1,easing:Ob.linear,clamp:!1},cv=class{constructor(){this.velocity=0,Object.assign(this,vc)}};function ov(s,t,a){a&&(a={...a},cd(a,t),t={...a,...t}),cd(s,t),Object.assign(s,t);for(const l in vc)s[l]==null&&(s[l]=vc[l]);let{frequency:n,damping:i}=s;const{mass:r}=s;return he.und(n)||(n<.01&&(n=.01),i<0&&(i=0),s.tension=Math.pow(2*Math.PI/n,2)*r,s.friction=4*Math.PI*i*r/n),s}function cd(s,t){if(!he.und(t.decay))s.duration=void 0;else{const a=!he.und(t.tension)||!he.und(t.friction);(a||!he.und(t.frequency)||!he.und(t.damping)||!he.und(t.mass))&&(s.duration=void 0,s.decay=void 0),a&&(s.frequency=void 0)}}var od=[],dv=class{constructor(){this.changed=!1,this.values=od,this.toValues=null,this.fromValues=od,this.config=new cv,this.immediate=!1}};function Au(s,{key:t,props:a,defaultProps:n,state:i,actions:r}){return new Promise((l,c)=>{let o,d,u=mr(a.cancel??(n==null?void 0:n.cancel),t);if(u)v();else{he.und(a.pause)||(i.paused=mr(a.pause,t));let g=n==null?void 0:n.pause;g!==!0&&(g=i.paused||mr(g,t)),o=Ja(a.delay||0,t),g?(i.resumeQueue.add(m),r.pause()):(r.resume(),m())}function x(){i.resumeQueue.add(m),i.timeouts.delete(d),d.cancel(),o=d.time-es.now()}function m(){o>0&&!Mt.skipAnimation?(i.delayed=!0,d=es.setTimeout(v,o),i.pauseQueue.add(x),i.timeouts.add(d)):v()}function v(){i.delayed&&(i.delayed=!1),i.pauseQueue.delete(x),i.timeouts.delete(d),s<=(i.cancelId||0)&&(u=!0);try{r.start({...a,callId:s,cancel:u},l)}catch(g){c(g)}}})}var oo=(s,t)=>t.length==1?t[0]:t.some(a=>a.cancelled)?Ln(s.get()):t.every(a=>a.noop)?_u(s.get()):aa(s.get(),t.every(a=>a.finished)),_u=s=>({value:s,noop:!0,finished:!0,cancelled:!1}),aa=(s,t,a=!1)=>({value:s,finished:t,cancelled:a}),Ln=s=>({value:s,cancelled:!0,finished:!1});function Tu(s,t,a,n){const{callId:i,parentId:r,onRest:l}=t,{asyncTo:c,promise:o}=a;return!r&&s===c&&!t.reset?o:a.promise=(async()=>{a.asyncId=i,a.asyncTo=s;const d=co(t,(k,b)=>b==="onRest"?void 0:k);let u,x;const m=new Promise((k,b)=>(u=k,x=b)),v=k=>{const b=i<=(a.cancelId||0)&&Ln(n)||i!==a.asyncId&&aa(n,!1);if(b)throw k.result=b,x(k),k},g=(k,b)=>{const S=new dd,A=new md;return(async()=>{if(Mt.skipAnimation)throw Dr(a),A.result=aa(n,!1),x(A),A;v(S);const F=he.obj(k)?{...k}:{...b,to:k};F.parentId=i,zt(d,(M,G)=>{he.und(F[G])&&(F[G]=M)});const de=await n.start(F);return v(S),a.paused&&await new Promise(M=>{a.resumeQueue.add(M)}),de})()};let w;if(Mt.skipAnimation)return Dr(a),aa(n,!1);try{let k;he.arr(s)?k=(async b=>{for(const S of b)await g(S)})(s):k=Promise.resolve(s(g,n.stop.bind(n))),await Promise.all([k.then(u),m]),w=aa(n.get(),!0,!1)}catch(k){if(k instanceof dd)w=k.result;else if(k instanceof md)w=k.result;else throw k}finally{i==a.asyncId&&(a.asyncId=r,a.asyncTo=r?c:void 0,a.promise=r?o:void 0)}return he.fun(l)&&es.batchedUpdates(()=>{l(w,n,n.item)}),w})()}function Dr(s,t){or(s.timeouts,a=>
52a.cancel()),s.pauseQueue.clear(),s.resumeQueue.clear(),s.asyncId=s.asyncTo=s.promise=void 0,t&&(s.cancelId=t)}var dd=class extends Error{constructor(){super("An async animation has been interrupted. You see this error because you forgot to use `await` or `.catch(...)` on its returned promise.")}},md=class extends Error{constructor(){super("SkipAnimationSignal")}},yc=s=>s instanceof mo,mv=1,mo=class extends Er{constructor(){super(...arguments),this.id=mv++,this._priority=0}get priority(){return this._priority}set priority(s){this._priority!=s&&(this._priority=s,this._onPriorityChange(s))}get(){const s=ha(this);return s&&s.getValue()}to(...s){return Mt.to(this,s)}interpolate(...s){return qb(),Mt.to(this,s)}toJSON(){return this.get()}observerAdded(s){s==1&&this._attach()}observerRemoved(s){s==0&&this._detach()}_attach(){}_detach(){}_onChange(s,t=!1){Ha(this,{type:"change",parent:this,value:s,idle:t})}_onPriorityChange(s){this.idle||hl.sort(this),Ha(this,{type:"priority",parent:this,priority:s})}},mn=Symbol.for("SpringPhase"),Du=1,Nc=2,wc=4,Ll=s=>(s[mn]&Du)>0,Ia=s=>(s[mn]&Nc)>0,Yn=s=>(s[mn]&wc)>0,ud=(s,t)=>t?s[mn]|=Nc|Du:s[mn]&=~Nc,xd=(s,t)=>t?s[mn]|=wc:s[mn]&=~wc,uv=class extends mo{constructor(s,t){if(super(),this.animation=new dv,this.defaultProps={},this._state={paused:!1,delayed:!1,pauseQueue:new Set,resumeQueue:new Set,timeouts:new Set},this._pendingCalls=new Set,this._lastCallId=0,this._lastToId=0,this._memoizedDuration=0,!he.und(s)||!he.und(t)){const a=he.obj(s)?{...s}:{...t,from:s};he.und(a.default)&&(a.default=!0),this.start(a)}}get idle(){return!(Ia(this)||this._state.asyncTo)||Yn(this)}get goal(){return it(this.animation.to)}get velocity(){const s=ha(this);return s instanceof vl?s.lastVelocity||0:s.getPayload().map(t=>t.lastVelocity||0)}get hasAnimated(){return Ll(this)}get isAnimating(){return Ia(this)}get isPaused(){return Yn(this)}get isDelayed(){return this._state.delayed}advance(s){let t=!0,a=!1;const n=this.animation;let{toValues:i}=n;const{config:r}=n,l=bl(n.to);!l&&dt(n.to)&&(i=Nt(it(n.to))),n.values.forEach((d,u)=>{if(d.done)return;const x=d.constructor==Ci?1:l?l[u].lastPosition:i[u];let m=n.immediate,v=x;if(!m){if(v=d.lastPosition,r.tension<=0){d.done=!0;return}let g=d.elapsedTime+=s;const w=n.fromValues[u],k=d.v0!=null?d.v0:d.v0=he.arr(r.velocity)?r.velocity[u]:r.velocity;let b;const S=r.precision||(w==x?.005:Math.min(1,Math.abs(x-w)*.001));if(he.und(r.duration))if(r.decay){const A=r.decay===!0?.998:r.decay,F=Math.exp(-(1-A)*g);v=w+k/(1-A)*(1-F),m=Math.abs(d.lastPosition-v)<=S,b=k*F}else{b=d.lastVelocity==null?k:d.lastVelocity;const A=r.restVelocity||S/10,F=r.clamp?0:r.bounce,de=!he.und(F),M=w==x?d.v0>0:w<x;let G,D=!1;const $=1,se=Math.ceil(s/$);for(let J=0;J<se&&(G=Math.abs(b)>A,!(!G&&(m=Math.abs(x-v)<=S,m)));++J){de&&(D=v==x||v>x==M,D&&(b=-b*F,v=x));const le=-r.tension*1e-6*(v-x),C=-r.friction*.001*b,I=(le+C)/r.mass;b=b+I*$,v=v+b*$}}else{let A=1;r.duration>0&&(this._memoizedDuration!==r.duration&&(this._memoizedDuration=r.duration,d.durationProgress>0&&(d.elapsedTime=r.duration*d.durationProgress,g=d.elapsedTime+=s)),A=(r.progress||0)+g/this._memoizedDuration,A=A>1?1:A<0?0:A,d.durationProgress=A),v=w+r.easing(A)*(x-w),b=(v-d.lastPosition)/s,m=A==1}d.lastVelocity=b,Number.isNaN(v)&&(console.warn("Got NaN while animating:",this),m=!0)}l&&!l[u].done&&(m=!1),m?d.done=!0:t=!1,d.setValue(v,r.round)&&(a=!0)});const c=ha(this),o=c.getValue();if(t){const d=it(n.to);(o!==d||a)&&!r.decay?(c.setValue(d),this._onChange(d)):a&&r.decay&&this._onChange(o),this._stop()}else a&&this._onChange(o)}set(s){return es.batchedUpdates(()=>{this._stop(),this._focus(s),this._set(s)}),this}pause(){this._update({pause:!0})}resume(){this._update({pause:!1})}finish(){if(Ia(this)){const{to:s,config:t}=this.animation;es.batchedUpdates(()=>{this._onStart(),t.decay||this._set(s,!1),this._stop()})}return this}update(s){return(this.queue||(this.queue=[])).push(s),this}start(s,t){let a;return he.und(s)?(a=this.queue||[],this.queue=[]):a=[he.obj(s)?s:{...t,to:s}],Promise.all(a.map(n=>this._update(n))).then(n=>oo(this,n))}stop(s){const{to:t}=this.animation;return this._focus(this.get()),Dr(this._state,s&&this._lastCallId),es.batchedUpdates(()=>this._stop(t,s)),this}reset(){this._update({reset:!0})}eventObserved(s){s.type=="change"?this._start():s.type=="priority"&&(this.priority=s.priority+1)}_prepareNode(s){const t=this.key||"";let{to:a,from:n}=s;a=he.obj(a)?a[t]:a,(a==null||bc(a))&&(a=void 0),n=he.obj(n)?n[t]:n,n==null&&(n=void 0);const i={to:a,from:n};return Ll(this)||(s.reverse&&([a,n]=[n,a]),n=it(n),he.und(n)?ha(this)||this._set(a):this._set(n)),i}_update({...s},t){const{key:a,defaultProps:n}=this;s.default&&Object.assign(n,co(s,(l,c)=>/^on/.test(c)?wu(l,a):l)),pd(this,s,"onProps"),Xn(this,"onProps",s,this);const i=this._prepareNode(s);if(Object.isFrozen(this))throw Error("Cannot animate a `SpringValue` object that is frozen. Did
52you forget to pass your component to `animated(...)` before animating its props?");const r=this._state;return Au(++this._lastCallId,{key:a,props:s,defaultProps:n,state:r,actions:{pause:()=>{Yn(this)||(xd(this,!0),rr(r.pauseQueue),Xn(this,"onPause",aa(this,Qn(this,this.animation.to)),this))},resume:()=>{Yn(this)&&(xd(this,!1),Ia(this)&&this._resume(),rr(r.resumeQueue),Xn(this,"onResume",aa(this,Qn(this,this.animation.to)),this))},start:this._merge.bind(this,i)}}).then(l=>{if(s.loop&&l.finished&&!(t&&l.noop)){const c=Pu(s);if(c)return this._update(c,!0)}return l})}_merge(s,t,a){if(t.cancel)return this.stop(!0),a(Ln(this));const n=!he.und(s.to),i=!he.und(s.from);if(n||i)if(t.callId>this._lastToId)this._lastToId=t.callId;else return a(Ln(this));const{key:r,defaultProps:l,animation:c}=this,{to:o,from:d}=c;let{to:u=o,from:x=d}=s;i&&!n&&(!t.default||he.und(u))&&(u=x),t.reverse&&([u,x]=[x,u]);const m=!Aa(x,d);m&&(c.from=x),x=it(x);const v=!Aa(u,o);v&&this._focus(u);const g=bc(t.to),{config:w}=c,{decay:k,velocity:b}=w;(n||i)&&(w.velocity=0),t.config&&!g&&ov(w,Ja(t.config,r),t.config!==l.config?Ja(l.config,r):void 0);let S=ha(this);if(!S||he.und(u))return a(aa(this,!0));const A=he.und(t.reset)?i&&!t.default:!he.und(x)&&mr(t.reset,r),F=A?x:this.get(),de=Tr(u),M=he.num(de)||he.arr(de)||jl(de),G=!g&&(!M||mr(l.immediate||t.immediate,r));if(v){const J=jc(u);if(J!==S.constructor)if(G)S=this._set(de);else throw Error(`Cannot animate between ${S.constructor.name} and ${J.name}, as the "to" prop suggests`)}const D=S.constructor;let $=dt(u),se=!1;if(!$){const J=A||!Ll(this)&&m;(v||J)&&(se=Aa(Tr(F),de),$=!se),(!Aa(c.immediate,G)&&!G||!Aa(w.decay,k)||!Aa(w.velocity,b))&&($=!0)}if(se&&Ia(this)&&(c.changed&&!A?$=!0:$||this._stop(o)),!g&&(($||dt(o))&&(c.values=S.getPayload(),c.toValues=dt(u)?null:D==Ci?[1]:Nt(de)),c.immediate!=G&&(c.immediate=G,!G&&!A&&this._set(o)),$)){const{onRest:J}=c;Ye(hv,C=>pd(this,t,C));const le=aa(this,Qn(this,o));rr(this._pendingCalls,le),this._pendingCalls.add(a),c.changed&&es.batchedUpdates(()=>{var C;c.changed=!A,J==null||J(le,this),A?Ja(l.onRest,le):(C=c.onStart)==null||C.call(c,le,this)})}A&&this._set(F),g?a(Tu(t.to,t,this._state,this)):$?this._start():Ia(this)&&!v?this._pendingCalls.add(a):a(_u(F))}_focus(s){const t=this.animation;s!==t.to&&(td(this)&&this._detach(),t.to=s,td(this)&&this._attach())}_attach(){let s=0;const{to:t}=this.animation;dt(t)&&($a(t,this),yc(t)&&(s=t.priority+1)),this.priority=s}_detach(){const{to:s}=this.animation;dt(s)&&Ka(s,this)}_set(s,t=!0){const a=it(s);if(!he.und(a)){const n=ha(this);if(!n||!Aa(a,n.getValue())){const i=jc(a);!n||n.constructor!=i?lo(this,i.create(a)):n.setValue(a),n&&es.batchedUpdates(()=>{this._onChange(a,t)})}}return ha(this)}_onStart(){const s=this.animation;s.changed||(s.changed=!0,Xn(this,"onStart",aa(this,Qn(this,s.to)),this))}_onChange(s,t){t||(this._onStart(),Ja(this.animation.onChange,s,this)),Ja(this.defaultProps.onChange,s,this),super._onChange(s,t)}_start(){const s=this.animation;ha(this).reset(it(s.to)),s.immediate||(s.fromValues=s.values.map(t=>t.lastPosition)),Ia(this)||(ud(this,!0),Yn(this)||this._resume())}_resume(){Mt.skipAnimation?this.finish():hl.start(this)}_stop(s,t){if(Ia(this)){ud(this,!1);const a=this.animation;Ye(a.values,i=>{i.done=!0}),a.toValues&&(a.onChange=a.onPause=a.onResume=void 0),Ha(this,{type:"idle",parent:this});const n=t?Ln(this.get()):aa(this.get(),Qn(this,s??a.to));rr(this._pendingCalls,n),a.changed&&(a.changed=!1,Xn(this,"onRest",n,this))}}};function Qn(s,t){const a=Tr(t),n=Tr(s.get());return Aa(n,a)}function Pu(s,t=s.loop,a=s.to){const n=Ja(t);if(n){const i=n!==!0&&Cu(n),r=(i||s).reverse,l=!i||i.reset;return Pr({...s,loop:t,default:!1,pause:void 0,to:!r||bc(a)?a:void 0,from:l?s.from:void 0,reset:l,...i})}}function Pr(s){const{to:t,from:a}=s=Cu(s),n=new Set;return he.obj(t)&&hd(t,n),he.obj(a)&&hd(a,n),s.keys=n.size?Array.from(n):null,s}function xv(s){const t=Pr(s);return he.und(t.default)&&(t.default=co(t)),t}function hd(s,t){zt(s,(a,n)=>a!=null&&t.add(n))}var hv=["onStart","onRest","onChange","onPause","onResume"];function pd(s,t,a){s.animation[a]=t[a]!==ku(t,a)?wu(t[a],s.key):void 0}function Xn(s,t,...a){var n,i,r,l;(i=(n=s.animation)[t])==null||i.call(n,...a),(l=(r=s.defaultProps)[t])==null||l.call(r,...a)}var pv=["onStart","onChange","onRest"],fv=1,gv=class{constructor(s,t){this.id=fv++,this.springs={},this.queue=[],this._lastAsyncId=0,this._active=new Set,this._changed=new Set,this._started=!1,this._state={paused:!1,pauseQueue:new Set,resumeQueue:new Set,timeouts:new Set},this._events={onStart:new Map,onChange:new Map,onRest:new Map},this._onFrame=this._onFrame.bind(this),t&&(this._flush=t),s&&this.start({default:!0,...s})}get idle(){return!this._state.asyncTo&&Object.values(this.springs).every(s=>s.idle&&!s.isDelayed&&!s.isPaused)}get item(){return this._item}set item(s){this._item=s}get(){const s={};return this.each((t,a)=>s[a]=t.get()),s}set(s){for(const t in s){const a=s[t];he.und(a)||this.springs[t].set(a)}}update(s){return s&&this.queue.push(Pr(s)),this}start(s){let{queue:t}=this;return s?t=Nt(s).map(Pr):this.queue=[],this._flush?this._flush(this,t):(Ou(this,t),kc(this,t))}stop(s,t){if(s!==!!s&&(t=s),t){const a=this.springs;Ye(Nt(t),n=>a[n].stop(!!s))}else Dr(this._state,this._lastAsyncId),this.each(a=>a.stop(!!s));return this}pause(s){if(he.und(s))this.start({pause:!0});else{const t=this.springs;Ye(Nt(s),a=>t[a].pause())}return this}resume(s){if(he.und(s))this.start({pause:!1});else{const t=this.springs;Ye(Nt(s),a=>t[a].resume())}return this}each(s){zt(this.springs,s)}_onFrame(){const{onStart:s,onChange:t,onRest:a}=this._events,n=this._active.size>0,i=this._changed.size>0;(n&&!this._started||i&&!this._started)&&(this._started=!0,or(s,([c,o])=>{o.value=this.get(),c(o,this,this._item)}));const r=!n&&this._started,l=i||r&&a.size?this.get():null;i&&t.size&&or(t,([c,o])=>{o.value=l,c(o,this,this._item)}),r&&(this._started=!1,or(a,([c,o])=>{o.value=l,c(o,this,this._item)}))}eventObserved(s){if(s.type=="change")this._changed.add(s.parent),s.idle||this._active.add(s.parent);else if(s.type=="idle")this._active.delete(s.parent);else return;es.onFrame(this._onFrame)}};function kc(s,t){return Promise.all(t.map(a=>Mu(s,a))).then(a=>oo(s,a))}async function Mu(s,t,a){const{keys:n,to:i,from:r,loop:l,onRest:c,onResolve:o}=t,d=he.obj(t.default)&&t.default;l&&(t.loop=!1),i===!1&&(t.to=null),r===!1&&(t.from=null);const u=he.arr(i)||he.fun(i)?i:void 0;u?(t.to=void 0,t.onRest=void 0,d&&(d.onRest=void 0)):Ye(pv,w=>{const k=t[w];if(he.fun(k)){const b=s._events[w];t[w]=({finished:S,cancelled:A})=>{const F=b.get(k);F?(S||(F.finished=!1),A&&(F.cancelled=!0)):b.set(k,{value:null,finished:S||!1,cancelled:A||!1})},d&&(d[w]=t[w])}});const x=s._state;t.pause===!x.paused?(x.paused=t.pause,rr(t.pause?x.pauseQueue:x.resumeQueue)):x.paused&&(t.pause=!0);const m=(n||Object.keys(s.springs)).map(w=>s.springs[w].start(t)),v=t.cancel===!0||ku(t,"cancel")===!0;(u||v&&x.asyncId)&&m.push(Au(++s._lastAsyncId,{props:t,state:x,actions:{pause:fc,resume:fc,start(w,k){v?(Dr(x,s._lastAsyncId),k(Ln(s))):(w.onRest=c,k(Tu(u,w,x,s)))}}})),x.paused&&await new Promise(w=>{x.resumeQueue.add(w)});const g=oo(s,await Promise.all(m));if(l&&g.finished&&!(a&&g.noop)){const w=Pu(t,l,i);if(w)return Ou(s,[w]),Mu(s,w,!0)}return o&&es.batchedUpdates(()=>o(g,s,s.item)),g}function fd(s,t){const a={...s.springs};return t&&Ye(Nt(t),n=>{he.und(n.keys)&&(n=Pr(n)),he.obj(n.to)||(n={...n,to:void 0}),$u(a,n,i=>Lu(i))}),Ru(s,a),a}function Ru(s,t){zt(t,(a,n)=>{s.springs[n]||(s.springs[n]=a,$a(a,s))})}function Lu(s,t){const a=new uv;return a.key=s,t&&$a(a,t),a}function $u(s,t,a){t.keys&&Ye(t.keys,n=>{(s[n]||(s[n]=a(n)))._prepareNode(t)})}function Ou(s,t){Ye(t,a=>{$u(s.springs,a,n=>Lu(n,s))})}var jv=p.createContext({pause:!1,immediate:!1}),bv=()=>{const s=[],t=function(n){Wb();const i=[];return Ye(s,(r,l)=>{if(he.und(n))i.push(r.start());else{const c=a(n,r,l);c&&i.push(r.start(c))}}),i};t.current=s,t.add=function(n){s.includes(n)||s.push(n)},t.delete=function(n){const i=s.indexOf(n);~i&&s.splice(i,1)},t.pause=function(){return Ye(s,n=>n.pause(...arguments)),this},t.resume=function(){return Ye(s,n=>n.resume(...arguments)),this},t.set=function(n){Ye(s,(i,r)=>{const l=he.fun(n)?n(r,i):n;l&&i.set(l)})},t.start=function(n){const i=[];return Ye(s,(r,l)=>{if(he.und(n))i.push(r.start());else{const c=this._getProps(n,r,l);c&&i.push(r.start(c))}}),i},t.stop=function(){return Ye(s,n=>n.stop(...arguments)),this},t.update=function(n){return Ye(s,(i,r)=>i.update(this._getProps(n,i,r))),this};const a=function(n,i,r){return he.fun(n)?n(r,i):n};return t._getProps=a,t};function Iu(s,t,a){const n=he.fun(t)&&t;
52n&&!a&&(a=[]);const i=p.useMemo(()=>n||arguments.length==3?bv():void 0,[]),r=p.useRef(0),l=gu(),c=p.useMemo(()=>({ctrls:[],queue:[],flush(b,S){const A=fd(b,S);return r.current>0&&!c.queue.length&&!Object.keys(A).some(de=>!b.springs[de])?kc(b,S):new Promise(de=>{Ru(b,A),c.queue.push(()=>{de(kc(b,S))}),l()})}}),[]),o=p.useRef([...c.ctrls]),d=p.useRef([]),u=nd(s)||0;p.useMemo(()=>{Ye(o.current.slice(s,u),b=>{iv(b,i),b.stop(!0)}),o.current.length=s,x(u,s)},[s]),p.useMemo(()=>{x(0,Math.min(u,s))},a);function x(b,S){for(let A=b;A<S;A++){const F=o.current[A]||(o.current[A]=new gv(null,c.flush)),de=n?n(A,F):t[A];de&&(d.current[A]=xv(de))}}const m=o.current.map((b,S)=>fd(b,d.current[S])),v=p.useContext(jv),g=nd(v),w=v!==g&&rv(v);io(()=>{r.current++,c.ctrls=o.current;const{queue:b}=c;b.length&&(c.queue=[],Ye(b,S=>S())),Ye(o.current,(S,A)=>{i==null||i.add(S),w&&S.start({default:v});const F=d.current[A];F&&(lv(S,F.ref),S.ref?S.queue.push(F):S.start(F))})}),ju(()=>()=>{Ye(c.ctrls,b=>b.stop(!0))});const k=m.map(b=>({...b}));return i?[k,i]:k}function Gn(s,t){const a=he.fun(s),[[n],i]=Iu(1,a?s:[s],a?[]:t);return a||arguments.length==2?[n,i]:n}var Fu=class extends mo{constructor(s,t){super(),this.source=s,this.idle=!0,this._active=new Set,this.calc=Sr(...t);const a=this._get(),n=jc(a);lo(this,n.create(a))}advance(s){const t=this._get(),a=this.get();Aa(t,a)||(ha(this).setValue(t),this._onChange(t,this.idle)),!this.idle&&gd(this._active)&&$l(this)}_get(){const s=he.arr(this.source)?this.source.map(it):Nt(it(this.source));return this.calc(...s)}_start(){this.idle&&!gd(this._active)&&(this.idle=!1,Ye(bl(this),s=>{s.done=!1}),Mt.skipAnimation?(es.batchedUpdates(()=>this.advance()),$l(this)):hl.start(this))}_attach(){let s=1;Ye(Nt(this.source),t=>{dt(t)&&$a(t,this),yc(t)&&(t.idle||this._active.add(t),s=Math.max(s,t.priority+1))}),this.priority=s,this._start()}_detach(){Ye(Nt(this.source),s=>{dt(s)&&Ka(s,this)}),this._active.clear(),$l(this)}eventObserved(s){s.type=="change"?s.idle?this.advance():(this._active.add(s.parent),this._start()):s.type=="idle"?this._active.delete(s.parent):s.type=="priority"&&(this.priority=Nt(this.source).reduce((t,a)=>Math.max(t,(yc(a)?a.priority:0)+1),0))}};function vv(s){return s.idle!==!1}function gd(s){return!s.size||Array.from(s).every(vv)}function $l(s){s.idle||(s.idle=!0,Ye(bl(s),t=>{t.done=!0}),Ha(s,{type:"idle",parent:s}))}var yv=(s,...t)=>new Fu(s,t);Mt.assign({createStringInterpolator:Vr,to:(s,t)=>new Fu(s,t)});var Eu=/^--/;function Nv(s,t){return t==null||typeof t=="boolean"||t===""?"":typeof t=="number"&&t!==0&&!Eu.test(s)&&!(ur.hasOwnProperty(s)&&ur[s])?t+"px":(""+t).trim()}var jd={};function wv(s,t){if(!s.nodeType||!s.setAttribute)return!1;const a=s.nodeName==="filter"||s.parentNode&&s.parentNode.nodeName==="filter",{className:n,style:i,children:r,scrollTop:l,scrollLeft:c,viewBox:o,...d}=t,u=Object.values(d),x=Object.keys(d).map(m=>a||s.hasAttribute(m)?m:jd[m]||(jd[m]=m.replace(/([A-Z])/g,v=>"-"+v.toLowerCase())));r!==void 0&&(s.textContent=r);for(const m in i)if(i.hasOwnProperty(m)){const v=Nv(m,i[m]);Eu.test(m)?s.style.setProperty(m,v):s.style[m]=v}x.forEach((m,v)=>{s.setAttribute(m,u[v])}),n!==void 0&&(s.className=n),l!==void 0&&(s.scrollTop=l),c!==void 0&&(s.scrollLeft=c),o!==void 0&&s.setAttribute("viewBox",o)}var ur={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},kv=(s,t)=>s+t.charAt(0).toUpperCase()+t.substring(1),Cv=["Webkit","Ms","Moz","O"];ur=Object.keys(ur).reduce((s,t)=>(Cv.forEach(a=>s[kv(a,t)]=s[t]),s),ur);var Sv=/^(matrix|translate|scale|rotate|skew)/,Av=/^(translate)/,_v=/^(rotate|skew)/,Ol=(s,t)=>he.num(s)&&s!==0?s+t:s,ri=(s,t)=>he.arr(s)?s.every(a=>ri(a,t)):he.num(s)?s===t:parseFloat(s)===t,Tv=class extends gn{constructor({x:t,y:a,z:n,...i}){const r=[],l=[];(t||a||n)&&(r.push([t||0,a||0,n||0]),l.push(c=>[`translate3d(${c.map(o=>Ol(o,"px")).join(",")})`,ri(c,0)])),zt(i,(c,o)=>
52{if(o==="transform")r.push([c||""]),l.push(d=>[d,d===""]);else if(Sv.test(o)){if(delete i[o],he.und(c))return;const d=Av.test(o)?"px":_v.test(o)?"deg":"";r.push(Nt(c)),l.push(o==="rotate3d"?([u,x,m,v])=>[`rotate3d(${u},${x},${m},${Ol(v,d)})`,ri(v,0)]:u=>[`${o}(${u.map(x=>Ol(x,d)).join(",")})`,ri(u,o.startsWith("scale")?1:0)])}}),r.length&&(i.transform=new Dv(r,l)),super(i)}},Dv=class extends Er{constructor(t,a){super(),this.inputs=t,this.transforms=a,this._value=null}get(){return this._value||(this._value=this._get())}_get(){let t="",a=!0;return Ye(this.inputs,(n,i)=>{const r=it(n[0]),[l,c]=this.transforms[i](he.arr(r)?r:n.map(it));t+=" "+l,a=a&&c}),a?"none":t}observerAdded(t){t==1&&Ye(this.inputs,a=>Ye(a,n=>dt(n)&&$a(n,this)))}observerRemoved(t){t==0&&Ye(this.inputs,a=>Ye(a,n=>dt(n)&&Ka(n,this)))}eventObserved(t){t.type=="change"&&(this._value=null),Ha(this,t)}},Pv=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"];Mt.assign({batchedUpdates:Mi.unstable_batchedUpdates,createStringInterpolator:Vr,colors:pl});var Mv=yl(Pv,{applyAnimatedValues:wv,createAnimatedStyle:s=>new Tv(s),getComponentProps:({scrollTop:s,scrollLeft:t,...a})=>a}),Vu=Mv.animated,Rv=Rc,Lv=um;function $v(s,t,a){(a!==void 0&&!Lv(s[t],a)||a===void 0&&!(t in s))&&Rv(s,t,a)}var Uu=$v,Ov=pm,Iv=Lc;function Fv(s){return Iv(s)&&Ov(s)}var Bu=Fv;function Ev(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}var zu=Ev,Vv=$r,Uv=Or;function Bv(s){return Vv(s,Uv(s))}var zv=Bv,bd=Uu,qv=Qm,Gv=Jm,Wv=Xm,Hv=eu,vd=mh,yd=ym,Kv=Bu,Yv=bm,Qv=uh,Xv=qn,Zv=dh,Jv=oh,Nd=zu,ey=zv;function sy(s,t,a,n,i,r,l){var c=Nd(s,a),o=Nd(t,a),d=l.get(o);if(d){bd(s,a,d);return}var u=r?r(c,o,a+"",s,t,l):void 0,x=u===void 0;if(x){var m=yd(o),v=!m&&Yv(o),g=!m&&!v&&Jv(o);u=o,m||v||g?yd(c)?u=c:Kv(c)?u=Wv(c):v?(x=!1,u=qv(o,!0)):g?(x=!1,u=Gv(o,!0)):u=[]:Zv(o)||vd(o)?(u=c,vd(c)?u=ey(c):(!Xv(c)||Qv(c))&&(u=Hv(o))):x=!1}x&&(l.set(o,u),i(u,o,n,r,l),l.delete(o)),bd(s,a,u)}var ty=sy,ay=vm,ny=Uu,ry=xh,iy=ty,ly=qn,cy=Or,oy=zu;function qu(s,t,a,n,i){s!==t&&ry(t,function(r,l){if(i||(i=new ay),ly(r))iy(s,t,l,a,qu,n,i);else{var c=n?n(oy(s,l),r,l+"",s,t,i):void 0;c===void 0&&(c=r),ny(s,l,c)}},cy)}var dy=qu,my=Nm,uy=hh;function xy(s){return my(function(t,a){var n=-1,i=a.length,r=i>1?a[i-1]:void 0,l=i>2?a[2]:void 0;for(r=s.length>3&&typeof r=="function"?(i--,r):void 0,l&&uy(a[0],a[1],l)&&(r=i<3?void 0:r,i=1),t=Object(t);++n<i;){var c=a[n];c&&s(t,c,n,r)}return t})}var hy=xy,py=dy,fy=hy,gy=fy(function(s,t,a){py(s,t,a)}),jy=gy;const by=Rr(jy);var vy=Yc,yy=wm,Ny=fh,wd=qn,wy=ph;function ky(s,t,a,n){if(!wd(s))return s;t=yy(t,s);for(var i=-1,r=t.length,l=r-1,c=s;c!=null&&++i<r;){var o=wy(t[i]),d=a;if(o==="__proto__"||o==="constructor"||o==="prototype")return s;if(i!=l){var u=c[o];d=n?n(u,o,c):void 0,d===void 0&&(d=wd(u)?u:Ny(t[i+1])?[]:{})}vy(c,o,d),c=c[o]}return s}var Gu=ky,Cy=Gu;function Sy(s,t,a){return s==null?s:Cy(s,t,a)}var Ay=Sy;const _y=Rr(Ay);function Cc(){return Cc=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},Cc.apply(null,arguments)}function Ty(s,t){if(s==null)return{};var a={};for(var n in s)if({}.hasOwnProperty.call(s,n)){if(t.indexOf(n)!==-1)continue;a[n]=s[n]}return a}var Dy=["outlineWidth","outlineColor","outlineOpacity"],Py=function(s){return s.outlineWidth,s.outlineColor,s.outlineOpacity,Ty(s,Dy)},My=["axis.ticks.text","axis.legend.text","legends.title.text","legends.text","legends.ticks.text","legends.title.text","labels.text","dots.text","markers.text","annotations.text"],Ry=function(s,t){return Cc({},t,s)},Ly=function(s,t){var a=by({},s,t);return My.forEach(function(n){_y(a,n,Ry($n(a,n),a.text))}),a},$y={background:"transparent",text:{fontFamily:"sans-serif",fontSize:11,fill:"#333333",outlineWidth:0,outlineColor:"#ffffff",outlineOpacity:1},axis:{domain:{line:{stroke:"transparent",strokeWidth:1}},ticks:{line:{stroke:"#777777",strokeWidth:1},text:{}},legend:{text:{fontSize:12}}},grid:{line:{stroke:"#dddddd",strokeWidth:1}}
52,legends:{hidden:{symbol:{fill:"#333333",opacity:.6},text:{fill:"#333333",opacity:.6}},text:{},ticks:{line:{stroke:"#777777",strokeWidth:1},text:{fontSize:10}},title:{text:{}}},labels:{text:{}},markers:{lineColor:"#000000",lineStrokeWidth:1,text:{}},dots:{text:{}},tooltip:{container:{background:"white",color:"inherit",fontSize:"inherit",borderRadius:"2px",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.25)",padding:"5px 9px"},basic:{whiteSpace:"pre",display:"flex",alignItems:"center"},chip:{marginRight:7},table:{},tableCell:{padding:"3px 5px"},tableCellValue:{fontWeight:"bold"}},crosshair:{line:{stroke:"#000000",strokeWidth:1,strokeOpacity:.75,strokeDasharray:"6 6"}},annotations:{text:{fontSize:13,outlineWidth:2,outlineColor:"#ffffff",outlineOpacity:1},link:{stroke:"#000000",strokeWidth:1,outlineWidth:2,outlineColor:"#ffffff",outlineOpacity:1},outline:{fill:"none",stroke:"#000000",strokeWidth:2,outlineWidth:2,outlineColor:"#ffffff",outlineOpacity:1},symbol:{fill:"#000000",outlineWidth:2,outlineColor:"#ffffff",outlineOpacity:1}}},Oy=function(s){return p.useMemo(function(){return Ly($y,s)},[s])},Wu=p.createContext(null),Iy={},Fy=function(s){var t=s.theme,a=t===void 0?Iy:t,n=s.children,i=Oy(a);return e.jsx(Wu.Provider,{value:i,children:n})},Na=function(){var s=p.useContext(Wu);if(s===null)throw new Error("Unable to find the theme, did you forget to wrap your component with ThemeProvider?");return s};function un(){return un=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},un.apply(null,arguments)}var Ey=["basic","chip","container","table","tableCell","tableCellValue"],Vy={pointerEvents:"none",position:"absolute",zIndex:10,top:0,left:0},kd=function(s,t){return"translate("+s+"px, "+t+"px)"},Hu=p.memo(function(s){var t,a=s.position,n=s.anchor,i=s.children,r=Na(),l=vn(),c=l.animate,o=l.config,d=S1(),u=d[0],x=d[1],m=p.useRef(!1),v=void 0,g=!1,w=x.width>0&&x.height>0,k=Math.round(a[0]),b=Math.round(a[1]);w&&(n==="top"?(k-=x.width/2,b-=x.height+14):n==="right"?(k+=14,b-=x.height/2):n==="bottom"?(k-=x.width/2,b+=14):n==="left"?(k-=x.width+14,b-=x.height/2):n==="center"&&(k-=x.width/2,b-=x.height/2),v={transform:kd(k,b)},m.current||(g=!0),m.current=[k,b]);var S=Gn({to:v,config:o,immediate:!c||g}),A=r.tooltip;A.basic,A.chip,A.container,A.table,A.tableCell,A.tableCellValue;var F=function(M,G){if(M==null)return{};var D={};for(var $ in M)if({}.hasOwnProperty.call(M,$)){if(G.indexOf($)!==-1)continue;D[$]=M[$]}return D}(A,Ey),de=un({},Vy,F,{transform:(t=S.transform)!=null?t:kd(k,b),opacity:S.transform?1:0});return e.jsx(Vu.div,{ref:u,style:de,children:i})});Hu.displayName="TooltipWrapper";var Sc=p.memo(function(s){var t=s.size,a=t===void 0?12:t,n=s.color,i=s.style;return e.jsx("span",{style:un({display:"block",width:a,height:a,background:n},i===void 0?{}:i)})}),Cd=p.memo(function(s){var t,a=s.id,n=s.value,i=s.format,r=s.enableChip,l=r!==void 0&&r,c=s.color,o=s.renderContent,d=Na(),u=mx(i);if(typeof o=="function")t=o();else{var x=n;u!==void 0&&x!==void 0&&(x=u(x)),t=e.jsxs("div",{style:d.tooltip.basic,children:[l&&e.jsx(Sc,{color:c,style:d.tooltip.chip}),x!==void 0?e.jsxs("span",{children:[a,": ",e.jsx("strong",{children:""+x})]}):a]})}return e.jsx("div",{style:d.tooltip.container,role:"tooltip",children:t})}),Uy={width:"100%",borderCollapse:"collapse"},By=p.memo(function(s){var t,a=s.title,n=s.rows,i=n===void 0?[]:n,r=s.renderContent,l=Na();return i.length?(t=typeof r=="function"?r():e.jsxs("div",{children:[a&&a,e.jsx("table",{style:un({},Uy,l.tooltip.table),children:e.jsx("tbody",{children:i.map(function(c,o){return e.jsx("tr",{children:c.map(function(d,u){return e.jsx("td",{style:l.tooltip.tableCell,children:d},u)})},o)})})})]}),e.jsx("div",{style:l.tooltip.container,children:t})):null});By.displayName="TableTooltip";var Ac=p.memo(function(s){var t=s.x0,a=s.x1,n=s.y0,i=s.y1,r=Na(),l=vn(),c=l.animate,o=l.config,d=p.useMemo(function(){return un({},r.crosshair.line,{pointerEvents:"none"})},[r.crosshair.line]),u=Gn({x1:t,x2:a,y1:n,y2:i,config:o,immediate:!c});return e.jsx(Vu.line,un({},u,{fill:"none",style:d}))});Ac.displayName="CrosshairLine";var zy=p.memo(function(s){var t,a,n=s.width,i=s.height,r=s.type,l=s.x,c=s.y;return r==="cross"?(t={x0:l,x1:l,y0:0,y1:i},a={x0:0,x1:n,y0:c,y1:c}):r==="top-left"?(t={x0:l,x1:l,y0:0,y1:c},a={x0:0,x1:l,y0:c,y1:c}):r==="top"?t={x0:l,x1:l,y0:0,y1:c}:r==="top-right"?(t={x0:l,x1:l,y0:0,y1:c},a={x0:l,x1:n,y0:c,y1:c}):r==="right"?a={x0:l,x1:n,y0:c,y1:c}:r==="bottom-right"?(t={x0:l,x1:l,y0:c,y1:i},a={x0:l,x1:n,y0:c,y1:c}):r==="bottom"?t={x0:l,x1:l,y0:c,y1:i}:r==="bottom-left"?(t={x0:l,x1:l,y0:c,y1:i},a={x0:0,x1:l,y0:c,y1:c}):r==="left"?a={x0:0,x1:l,y0:c,y1:c}:r==="x"?t={x0:l,x1:l,y0:0,y1:i}:r==="y"&&(a={x0:0,x1:n,y0:c,y1:c}),e.jsxs(e.Fragment,{children:[t&&e.jsx(Ac,{x0:t.x0,x1:t.x1,y0:t.y0,y1:t.y1}),a&&e.jsx(Ac,{x0:a.x0,x1:a.x1,y0:a.y0,y1:a.y1})]})});zy.displayName="Crosshair";var Ku=p.createContext({showTooltipAt:function(){},showTooltipFromEvent:function(){},hideTooltip:function(){}}),_c={isVisible:!1,position:[null,null],content:null,anchor:null}
52,Yu=p.createContext(_c),qy=function(s){var t=p.useState(_c),a=t[0],n=t[1],i=p.useCallback(function(c,o,d){var u=o[0],x=o[1];d===void 0&&(d="top"),n({isVisible:!0,position:[u,x],anchor:d,content:c})},[n]),r=p.useCallback(function(c,o,d){d===void 0&&(d="top");var u=s.current.getBoundingClientRect(),x=s.current.offsetWidth,m=x===u.width?1:x/u.width,v="touches"in o?o.touches[0]:o,g=v.clientX,w=v.clientY,k=(g-u.left)*m,b=(w-u.top)*m;d!=="left"&&d!=="right"||(d=k<u.width/2?"right":"left"),n({isVisible:!0,position:[k,b],anchor:d,content:c})},[s,n]),l=p.useCallback(function(){n(_c)},[n]);return{actions:p.useMemo(function(){return{showTooltipAt:i,showTooltipFromEvent:r,hideTooltip:l}},[i,r,l]),state:a}},Qu=function(){var s=p.useContext(Ku);if(s===void 0)throw new Error("useTooltip must be used within a TooltipProvider");return s},Gy=function(){var s=p.useContext(Yu);if(s===void 0)throw new Error("useTooltipState must be used within a TooltipProvider");return s},Wy=function(s){return s.isVisible},Hy=function(){var s=Gy();return Wy(s)?e.jsx(Hu,{position:s.position,anchor:s.anchor,children:s.content}):null},Ky=function(s){var t=s.container,a=s.children,n=qy(t),i=n.actions,r=n.state;return e.jsx(Ku.Provider,{value:i,children:e.jsx(Yu.Provider,{value:r,children:a})})},Xu=/^--/;function Yy(s,t){return t==null||typeof t=="boolean"||t===""?"":typeof t=="number"&&t!==0&&!Xu.test(s)&&!(xr.hasOwnProperty(s)&&xr[s])?t+"px":(""+t).trim()}var Sd={};function Qy(s,t){if(!s.nodeType||!s.setAttribute)return!1;const a=s.nodeName==="filter"||s.parentNode&&s.parentNode.nodeName==="filter",{className:n,style:i,children:r,scrollTop:l,scrollLeft:c,viewBox:o,...d}=t,u=Object.values(d),x=Object.keys(d).map(m=>a||s.hasAttribute(m)?m:Sd[m]||(Sd[m]=m.replace(/([A-Z])/g,v=>"-"+v.toLowerCase())));r!==void 0&&(s.textContent=r);for(const m in i)if(i.hasOwnProperty(m)){const v=Yy(m,i[m]);Xu.test(m)?s.style.setProperty(m,v):s.style[m]=v}x.forEach((m,v)=>{s.setAttribute(m,u[v])}),n!==void 0&&(s.className=n),l!==void 0&&(s.scrollTop=l),c!==void 0&&(s.scrollLeft=c),o!==void 0&&s.setAttribute("viewBox",o)}var xr={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Xy=(s,t)=>s+t.charAt(0).toUpperCase()+t.substring(1),Zy=["Webkit","Ms","Moz","O"];xr=Object.keys(xr).reduce((s,t)=>(Zy.forEach(a=>s[Xy(a,t)]=s[t]),s),xr);var Jy=/^(matrix|translate|scale|rotate|skew)/,eN=/^(translate)/,sN=/^(rotate|skew)/,Il=(s,t)=>he.num(s)&&s!==0?s+t:s,ii=(s,t)=>he.arr(s)?s.every(a=>ii(a,t)):he.num(s)?s===t:parseFloat(s)===t,tN=class extends gn{constructor({x:t,y:a,z:n,...i}){const r=[],l=[];(t||a||n)&&(r.push([t||0,a||0,n||0]),l.push(c=>[`translate3d(${c.map(o=>Il(o,"px")).join(",")})`,ii(c,0)])),zt(i,(c,o)=>{if(o==="transform")r.push([c||""]),l.push(d=>[d,d===""]);else if(Jy.test(o)){if(delete i[o],he.und(c))return;const d=eN.test(o)?"px":sN.test(o)?"deg":"";r.push(Nt(c)),l.push(o==="rotate3d"?([u,x,m,v])=>[`rotate3d(${u},${x},${m},${Il(v,d)})`,ii(v,0)]:u=>[`${o}(${u.map(x=>Il(x,d)).join(",")})`,ii(u,o.startsWith("scale")?1:0)])}}),r.length&&(i.transform=new aN(r,l)),super(i)}},aN=class extends Er{constructor(t,a){super(),this.inputs=t,this.transforms=a,this._value=null}get(){return this._value||(this._value=this._get())}_get(){let t="",a=!0;return Ye(this.inputs,(n,i)=>{const r=it(n[0]),[l,c]=this.transforms[i](he.arr(r)?r:n.map(it));t+=" "+l,a=a&&c}),a?"none":t}observerAdded(t){t==1&&Ye(this.inputs,a=>Ye(a,n=>dt(n)&&$a(n,this)))}observerRemoved(t){t==0&&Ye(this.inputs,a=>Ye(a,n=>dt(n)&&Ka(n,this)))}eventObserved(t){t.type=="change"&&(this._value=null),Ha(this,t)}},nN=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"];Mt.assign({batchedUpdates:Mi.unstable_batchedUpdates,createStringInterpolator:Vr,colors:pl});var rN=yl(nN,{applyAnimatedValues:Qy,createAnimatedStyle:s=>new tN(s),getComponentProps:({scrollTop:s,scrollLeft:t,...a})=>a}),iN=rN.animated;let Xt;
52typeof window<"u"?Xt=window:typeof self<"u"?Xt=self:Xt=global;let Tc=null,Dc=null;const Ad=20,Fl=Xt.clearTimeout,_d=Xt.setTimeout,El=Xt.cancelAnimationFrame||Xt.mozCancelAnimationFrame||Xt.webkitCancelAnimationFrame,Td=Xt.requestAnimationFrame||Xt.mozRequestAnimationFrame||Xt.webkitRequestAnimationFrame;El==null||Td==null?(Tc=Fl,Dc=function(t){return _d(t,Ad)}):(Tc=function([t,a]){El(t),Fl(a)},Dc=function(t){const a=Td(function(){Fl(n),t()}),n=_d(function(){El(a),t()},Ad);return[a,n]});function lN(s){let t,a,n,i,r,l,c;const o=typeof document<"u"&&document.attachEvent;if(!o){l=function(b){const S=b.__resizeTriggers__,A=S.firstElementChild,F=S.lastElementChild,de=A.firstElementChild;F.scrollLeft=F.scrollWidth,F.scrollTop=F.scrollHeight,de.style.width=A.offsetWidth+1+"px",de.style.height=A.offsetHeight+1+"px",A.scrollLeft=A.scrollWidth,A.scrollTop=A.scrollHeight},r=function(b){return b.offsetWidth!==b.__resizeLast__.width||b.offsetHeight!==b.__resizeLast__.height},c=function(b){if(b.target.className&&typeof b.target.className.indexOf=="function"&&b.target.className.indexOf("contract-trigger")<0&&b.target.className.indexOf("expand-trigger")<0)return;const S=this;l(this),this.__resizeRAF__&&Tc(this.__resizeRAF__),this.__resizeRAF__=Dc(function(){r(S)&&(S.__resizeLast__.width=S.offsetWidth,S.__resizeLast__.height=S.offsetHeight,S.__resizeListeners__.forEach(function(de){de.call(S,b)}))})};let m=!1,v="";n="animationstart";const g="Webkit Moz O ms".split(" ");let w="webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "),k="";{const b=document.createElement("fakeelement");if(b.style.animationName!==void 0&&(m=!0),m===!1){for(let S=0;S<g.length;S++)if(b.style[g[S]+"AnimationName"]!==void 0){k=g[S],v="-"+k.toLowerCase()+"-",n=w[S],m=!0;break}}}a="resizeanim",t="@"+v+"keyframes "+a+" { from { opacity: 0; } to { opacity: 0; } } ",i=v+"animation: 1ms "+a+"; "}const d=function(m){if(!m.getElementById("detectElementResize")){const v=(t||"")+".resize-triggers { "+(i||"")+'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; z-index: -1; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',g=m.head||m.getElementsByTagName("head")[0],w=m.createElement("style");w.id="detectElementResize",w.type="text/css",s!=null&&w.setAttribute("nonce",s),w.styleSheet?w.styleSheet.cssText=v:w.appendChild(m.createTextNode(v)),g.appendChild(w)}};return{addResizeListener:function(m,v){if(o)m.attachEvent("onresize",v);else{if(!m.__resizeTriggers__){const g=m.ownerDocument,w=Xt.getComputedStyle(m);w&&w.position==="static"&&(m.style.position="relative"),d(g),m.__resizeLast__={},m.__resizeListeners__=[],(m.__resizeTriggers__=g.createElement("div")).className="resize-triggers";const k=g.createElement("div");k.className="expand-trigger",k.appendChild(g.createElement("div"));const b=g.createElement("div");b.className="contract-trigger",m.__resizeTriggers__.appendChild(k),m.__resizeTriggers__.appendChild(b),m.appendChild(m.__resizeTriggers__),l(m),m.addEventListener("scroll",c,!0),n&&(m.__resizeTriggers__.__animationListener__=function(A){A.animationName===a&&l(m)},m.__resizeTriggers__.addEventListener(n,m.__resizeTriggers__.__animationListener__))}m.__resizeListeners__.push(v)}},removeResizeListener:function(m,v){if(o)m.detachEvent("onresize",v);else if(m.__resizeListeners__.splice(m.__resizeListeners__.indexOf(v),1),!m.__resizeListeners__.length){m.removeEventListener("scroll",c,!0),m.__resizeTriggers__.__animationListener__&&(m.__resizeTriggers__.removeEventListener(n,m.__resizeTriggers__.__animationListener__),m.__resizeTriggers__.__animationListener__=null);try{m.__resizeTriggers__=!m.removeChild(m.__resizeTriggers__)}catch{}}}}}class cN extends p.Component{constructor(...t){super(...t),this.state={height:this.props.defaultHeight||0,width:this.props.defaultWidth||0},this._autoSizer=null,this._detectElementResize=null,this._didLogDeprecationWarning=!1,this._parentNode=null,this._resizeObserver=null,this._timeoutId=null,this._onResize=()=>{this._timeoutId=null;const{disableHeight:a,disableWidth:n,onResize:i}=this.props;if(this._parentNode){const r=window.getComputedStyle(this._parentNode)||{},l=parseFloat(r.paddingLeft||"0"),c=parseFloat(r.paddingRight||"0"),o=parseFloat(r.paddingTop||"0"),d=parseFloat(r.paddingBottom||"0"),u=this._parentNode.getBoundingClientRect(),x=u.height-o-d,m=u.width-l-c;if(!a&&this.state.height!==x||!n&&this.state.width!==m){this.setState({height:x,width:m});const v=()=>{this._didLogDeprecationWarning||(this._didLogDeprecationWarning=!0,console.warn("scaledWidth and scaledHeight parameters have been deprecated; use width and height instead"))};
52typeof i=="function"&&i({height:x,width:m,get scaledHeight(){return v(),x},get scaledWidth(){return v(),m}})}}},this._setRef=a=>{this._autoSizer=a}}componentDidMount(){const{nonce:t}=this.props,a=this._autoSizer?this._autoSizer.parentNode:null;if(a!=null&&a.ownerDocument&&a.ownerDocument.defaultView&&a instanceof a.ownerDocument.defaultView.HTMLElement){this._parentNode=a;const n=a.ownerDocument.defaultView.ResizeObserver;n!=null?(this._resizeObserver=new n(()=>{this._timeoutId=setTimeout(this._onResize,0)}),this._resizeObserver.observe(a)):(this._detectElementResize=lN(t),this._detectElementResize.addResizeListener(a,this._onResize)),this._onResize()}}componentWillUnmount(){this._parentNode&&(this._detectElementResize&&this._detectElementResize.removeResizeListener(this._parentNode,this._onResize),this._timeoutId!==null&&clearTimeout(this._timeoutId),this._resizeObserver&&this._resizeObserver.disconnect())}render(){const{children:t,defaultHeight:a,defaultWidth:n,disableHeight:i=!1,disableWidth:r=!1,doNotBailOutOnEmptyChildren:l=!1,nonce:c,onResize:o,style:d={},tagName:u="div",...x}=this.props,{height:m,width:v}=this.state,g={overflow:"visible"},w={};let k=!1;return i||(m===0&&(k=!0),g.height=0,w.height=m,w.scaledHeight=m),r||(v===0&&(k=!0),g.width=0,w.width=v,w.scaledWidth=v),l&&(k=!1),p.createElement(u,{ref:this._setRef,style:{...g,...d},...x},!k&&t(w))}}function oN(s,t,a,n){var i=this,r=p.useRef(null),l=p.useRef(0),c=p.useRef(0),o=p.useRef(null),d=p.useRef([]),u=p.useRef(),x=p.useRef(),m=p.useRef(s),v=p.useRef(!0);m.current=s;var g=typeof window<"u",w=!t&&t!==0&&g;if(typeof s!="function")throw new TypeError("Expected a function");t=+t||0;var k=!!(a=a||{}).leading,b=!("trailing"in a)||!!a.trailing,S="maxWait"in a,A="debounceOnServer"in a&&!!a.debounceOnServer,F=S?Math.max(+a.maxWait||0,t):null;p.useEffect(function(){return v.current=!0,function(){v.current=!1}},[]);var de=p.useMemo(function(){var M=function(C){var I=d.current,y=u.current;return d.current=u.current=null,l.current=C,c.current=c.current||C,x.current=m.current.apply(y,I)},G=function(C,I){w&&cancelAnimationFrame(o.current),o.current=w?requestAnimationFrame(C):setTimeout(C,I)},D=function(C){if(!v.current)return!1;var I=C-r.current;return!r.current||I>=t||I<0||S&&C-l.current>=F},$=function(C){return o.current=null,b&&d.current?M(C):(d.current=u.current=null,x.current)},se=function C(){var I=Date.now();if(k&&c.current===l.current&&J(),D(I))return $(I);if(v.current){var y=t-(I-r.current),f=S?Math.min(y,F-(I-l.current)):y;G(C,f)}},J=function(){n&&n({})},le=function(){if(g||A){var C=Date.now(),I=D(C);if(d.current=[].slice.call(arguments),u.current=i,r.current=C,I){if(!o.current&&v.current)return l.current=r.current,G(se,t),k?M(r.current):x.current;if(S)return G(se,t),M(r.current)}return o.current||G(se,t),x.current}};return le.cancel=function(){var C=o.current;C&&(w?cancelAnimationFrame(o.current):clearTimeout(o.current)),l.current=0,d.current=r.current=u.current=o.current=null,C&&n&&n({})},le.isPending=function(){return!!o.current},le.flush=function(){return o.current?$(Date.now()):x.current},le},[k,S,t,F,b,w,g,A,n]);return de}function dN(s,t){return s===t}function mN(s,t,a){var n=a&&a.equalityFn||dN,i=p.useRef(s),r=p.useState({})[1],l=oN(p.useCallback(function(o){i.current=o,r({})},[r]),t,a,r),c=p.useRef(s);return n(c.current,s)||(l(s),c.current=s),[i.current,l]}var uN=jh,xN=bh,hN=vh,pN=gh,fN=Oc,gN=yh,jN=200;function bN(s,t,a,n){var i=-1,r=xN,l=!0,c=s.length,o=[],d=t.length;if(!c)return o;a&&(t=pN(t,fN(a))),n?(r=hN,l=!1):t.length>=jN&&(r=gN,l=!1,t=new uN(t));e:for(;++i<c;){var u=s[i],x=a==null?u:a(u);if(u=n||u!==0?u:0,l&&x===x){for(var m=d;m--;)if(t[m]===x)continue e;o.push(u)}else r(t,x,n)||o.push(u)}return o}var vN=bN,yN=vN,NN=Nm,wN=Bu,kN=NN(function(s,t){return wN(s)?yN(s,t):[]}),CN=kN;const Zu=Rr(CN);function SN(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function Ai(s,t){if((a=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"))<0)return null;var a,n=s.slice(0,a);return[n.length>1?n[0]+n.slice(2):n,+s.slice(a+1)]}function AN(s){return s=Ai(Math.abs(s)),s?s[1]:NaN}function _N(s,t){return function(a,n){for(var i=a.length,r=[],l=0,c=s[0],o=0;i>0&&c>0&&(o+c+1>n&&(c=Math.max(1,n-o)),r.push(a.substring(i-=c,i+c)),!((o+=c+1)>n));)c=s[l=(l+1)%s.length];return r.reverse().join(t)}}function TN(s){return function(t){return t.replace(/[0-9]/g,function(a){return s[+a]})}}var DN=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Pc(s){if(!(t=DN.exec(s)))throw new Error("invalid format: "+s);var t;return new uo({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}Pc.prototype=uo.prototype;function uo(s){this.fill=s.fill===void 0?" ":s.fill+"",this.align=s.align===void 0?">":s.align+"",this.sign=s.sign===void 0?"-":s.sign+"",this.symbol=s.symbol===void 0?"":s.symbol+"",this.zero=!!s.zero,this.width=s.width===void 0?void 0:+s.width,this.comma=!!s.comma,this.precision=s.precision===void 0?void 0:+s.precision,this.trim=!!s.trim,this.type=s.type===void 0?"":s.type+""}uo.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function PN(s){e:for(var t=s.length,a=1,n=-1,i;a<t;++a)switch(s[a]){case".":n=i=a;break;case"0":n===0&&(n=a),i=a;break;default:if(!+s[a])break e;n>0&&(n=0);break}return n>0?s.slice(0,n)+s.slice(i+1):s}var Ju;function MN(s,t){var a=Ai(s,t);if(!a)return s+"";var n=a[0],i=a[1],r=i-(Ju=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,l=n.length;return r===l?n:r>l?n+new Array(r-l+1).join("0"):r>0?n.slice(0,r)+"."+n.slice(r):"0."+new Array(1-r).join("0")+Ai(s,Math.max(0,t+r-1))[0]}function Dd(s,t){var a=Ai(s,t);if(!a)return s+"";var n=a[0],i=a[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}const Pd={"%":function(s,t){return(s*100).toFixed(t)},b:function(s){return Math.round(s).toString(2)},c:function(s){return s+""},d:SN,e:function(s,t){return s.toExponential(t)},f:function(s,t){return s.toFixed(t)},g:function(s,t){return s.toPrecision(t)},o:function(s){return Math.round(s).toString(8)},p:function(s,t){return Dd(s*100,t)},r:Dd,s:MN,X:function(s){return Math.round(s).toString(16).toUpperCase()},x:function(s){return Math.round(s).toString(16)}};function Md(s){return s}
vendor: 8,703 bytes, line 52
52var Rd=Array.prototype.map,Ld=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function RN(s){var t=s.grouping===void 0||s.thousands===void 0?Md:_N(Rd.call(s.grouping,Number),s.thousands+""),a=s.currency===void 0?"":s.currency[0]+"",n=s.currency===void 0?"":s.currency[1]+"",i=s.decimal+"",r=s.numerals===void 0?Md:TN(Rd.call(s.numerals,String)),l=s.percent===void 0?"%":s.percent+"",c=s.minus+"",o=s.nan===void 0?"NaN":s.nan+"";function d(x){x=Pc(x);var m=x.fill,v=x.align,g=x.sign,w=x.symbol,k=x.zero,b=x.width,S=x.comma,A=x.precision,F=x.trim,de=x.type;de==="n"?(S=!0,de="g"):Pd[de]||(A===void 0&&(A=12),F=!0,de="g"),(k||m==="0"&&v==="=")&&(k=!0,m="0",v="=");var M=w==="$"?a:w==="#"&&/[boxX]/.test(de)?"0"+de.toLowerCase():"",G=w==="$"?n:/[%p]/.test(de)?l:"",D=Pd[de],$=/[defgprs%]/.test(de);A=A===void 0?6:/[gprs]/.test(de)?Math.max(1,Math.min(21,A)):Math.max(0,Math.min(20,A));function se(J){var le=M,C=G,I,y,f;if(de==="c")C=D(J)+C,J="";else{J=+J;var R=J<0||1/J<0;if(J=isNaN(J)?o:D(Math.abs(J),A),F&&(J=PN(J)),R&&+J==0&&g!=="+"&&(R=!1),le=(R?g==="("?g:c:g==="-"||g==="("?"":g)+le,C=(de==="s"?Ld[8+Ju/3]:"")+C+(R&&g==="("?")":""),$){for(I=-1,y=J.length;++I<y;)if(f=J.charCodeAt(I),48>f||f>57){C=(f===46?i+J.slice(I+1):J.slice(I))+C,J=J.slice(0,I);break}}}S&&!k&&(J=t(J,1/0));var O=le.length+J.length+C.length,N=O<b?new Array(b-O+1).join(m):"";switch(S&&k&&(J=t(N+J,N.length?b-C.length:1/0),N=""),v){case"<":J=le+J+C+N;break;case"=":J=le+N+J+C;break;case"^":J=N.slice(0,O=N.length>>1)+le+J+C+N.slice(O);break;default:J=N+le+J+C;break}return r(J)}return se.toString=function(){return x+""},se}function u(x,m){var v=d((x=Pc(x),x.type="f",x)),g=Math.max(-8,Math.min(8,Math.floor(AN(m)/3)))*3,w=Math.pow(10,-g),k=Ld[8+g/3];return function(b){return v(w*b)+k}}return{format:d,formatPrefix:u}}var Yr,ex;LN({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"});function LN(s){return Yr=RN(s),ex=Yr.format,Yr.formatPrefix,Yr}var Vl=new Date,Ul=new Date;function Oa(s,t,a,n){function i(r){return s(r=arguments.length===0?new Date:new Date(+r)),r}return i.floor=function(r){return s(r=new Date(+r)),r},i.ceil=function(r){return s(r=new Date(r-1)),t(r,1),s(r),r},i.round=function(r){var l=i(r),c=i.ceil(r);return r-l<c-r?l:c},i.offset=function(r,l){return t(r=new Date(+r),l==null?1:Math.floor(l)),r},i.range=function(r,l,c){var o=[],d;if(r=i.ceil(r),c=c==null?1:Math.floor(c),!(r<l)||!(c>0))return o;do o.push(d=new Date(+r)),t(r,c),s(r);while(d<r&&r<l);return o},i.filter=function(r){return Oa(function(l){if(l>=l)for(;s(l),!r(l);)l.setTime(l-1)},function(l,c){if(l>=l)if(c<0)for(;++c<=0;)for(;t(l,-1),!r(l););else for(;--c>=0;)for(;t(l,1),!r(l););})},a&&(i.count=function(r,l){return Vl.setTime(+r),Ul.setTime(+l),s(Vl),s(Ul),Math.floor(a(Vl,Ul))},i.every=function(r){return r=Math.floor(r),!isFinite(r)||!(r>0)?null:r>1?i.filter(n?function(l){return n(l)%r===0}:function(l){return i.count(0,l)%r===0}):i}),i}const $N=1e3,xo=$N*60,ON=xo*60,ho=ON*24,sx=ho*7;var po=Oa(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*xo)/ho,s=>s.getDate()-1);po.range;function jn(s){return Oa(function(t){t.setDate(t.getDate()-(t.getDay()+7-s)%7),t.setHours(0,0,0,0)},function(t,a){t.setDate(t.getDate()+a*7)},function(t,a){return(a-t-(a.getTimezoneOffset()-t.getTimezoneOffset())*xo)/sx})}var tx=jn(0),_i=jn(1),IN=jn(2),FN=jn(3),Un=jn(4),EN=jn(5),VN=jn(6);tx.range;_i.range;IN.range;FN.range;Un.range;EN.range;VN.range;var xn=Oa(function(s){s.setMonth(0,1),s.setHours(0,0,0,0)},function(s,t){s.setFullYear(s.getFullYear()+t)},function(s,t){return t.getFullYear()-s.getFullYear()},function(s){return s.getFullYear()});xn.every=function(s){return!isFinite(s=Math.floor(s))||!(s>0)?null:Oa(function(t){t.setFullYear(Math.floor(t.getFullYear()/s)*s),t.setMonth(0,1),t.setHours(0,0,0,0)},function(t,a){t.setFullYear(t.getFullYear()+a*s)})};xn.range;var fo=Oa(function(s){s.setUTCHours(0,0,0,0)},function(s,t){s.setUTCDate(s.getUTCDate()+t)},function(s,t){return(t-s)/ho},function(s){return s.getUTCDate()-1});fo.range;function bn(s){return Oa(function(t){t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},function(t,a){t.setUTCDate(t.getUTCDate()+a*7)},function(t,a){return(a-t)/sx})}var ax=bn(0),Ti=bn(1),UN=bn(2),BN=bn(3),Bn=bn(4),zN=bn(5),qN=bn(6);ax.range;Ti.range;UN.range;BN.range;Bn.range;zN.range;qN.range;var hn=Oa(function(s){s.setUTCMonth(0,1),s.setUTCHours(0,0,0,0)},function(s,t){s.setUTCFullYear(s.getUTCFullYear()+t)},function(s,t){return t.getUTCFullYear()-s.getUTCFullYear()},function(s){return s.getUTCFullYear()});hn.every=function(s){return!isFinite(s=Math.floor(s))||!(s>0)?null:Oa(function(t){t.setUTCFullYear(Math.floor(t.getUTCFullYear()/s)*s),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},function(t,a){t.setUTCFullYear(t.getUTCFullYear()+a*s)})};hn.range;function Bl(s){if(0<=s.y&&s.y<100){var t=new Date(-1,s.m,s.d,s.H,s.M,s.S,s.L);return t.setFullYear(s.y),t}return new Date(s.y,s.m,s.d,s.H,s.M,s.S,s.L)}function zl(s){if(0<=s.y&&s.y<100){var t=new Date(Date.UTC(-1,s.m,s.d,s.H,s.M,s.S,s.L));return t.setUTCFullYear(s.y),t}return new Date(Date.UTC(s.y,s.m,s.d,s.H,s.M,s.S,s.L))}function Zn(s,t,a){return{y:s,m:t,d:a,H:0,M:0,S:0,L:0}}function GN(s){var t=s.dateTime,a=s.date,n=s.time,i=s.periods,r=s.days,l=s.shortDays,c=s.months,o=s.shortMonths,d=Jn(i),u=er(i),x=Jn(r),m=er(r),v=Jn(l),g=er(l),w=Jn(c),k=er(c),b=Jn(o),S=er(o),A={a:R,A:O,b:N,B:re,c:null,d:Vd,e:Vd,f:hw,g:kw,G:Sw,H:mw,I:uw,j:xw,L:nx,m:pw,M:fw,p:H,q:pe,Q:zd,s:qd,S:gw,u:jw,U:bw,V:vw,w:yw,W:Nw,x:null,X:null,y:ww,Y:Cw,Z:Aw,"%":Bd},F={a:ye,A:Ie,b:ve,B,c:null,d:Ud,e:Ud,f:Pw,g:Uw,G:zw,H:_w,I:Tw,j:Dw,L:ix,m:Mw,M:Rw,p:z,q:K,Q:zd,s:qd,S:Lw,u:$w,U:Ow,V:Iw,w:Fw,W:Ew,x:null,X:null,y:Vw,Y:Bw,Z:qw,"%":Bd},de={a:se,A:J,b:le,B:C,c:I,d:Fd,e:Fd,f:lw,g:Id,G:Od,H:Ed,I:Ed,j:aw,L:iw,m:tw,M:nw,p:$,q:sw,Q:ow,s:dw,S:rw,u:QN,U:XN,V:ZN,w:YN,W:JN,x:y,X:f,y:Id,Y:Od,Z:ew,"%":cw};A.x=M(a,A),A.X=M(n,A),A.c=M(t,A),F.x=M(a,F),F.X=M(n,F),F.c=M(t,F);function M(P,ue){return function(V){var U=[],j=-1,Q=0,je=P.length,ce,be,ss;for(V instanceof Date||(V=new Date(+V));++j<je;)P.charCodeAt(j)===37&&(U.push(P.slice(Q,j)),(be=$d[ce=P.charAt(++j)])!=null?ce=P.charAt(++j):be=ce==="e"?" ":"0",(ss=ue[ce])&&(ce=ss(V,be)),U.push(ce),Q=j+1);return U.push(P.slice(Q,j)),U.join("")}}function G(P,ue){return function(V){var U=Zn(1900,void 0,1),j=D(U,P,V+="",0),Q,je;if(j!=V.length)return null;if("Q"in U)return new Date(U.Q);if("s"in U)return new Date(U.s*1e3+("L"in U?U.L:0));if(ue&&!("Z"in U)&&(U.Z=0),"p"in U&&(U.H=U.H%12+U.p*12),U.m===void 0&&(U.m="q"in U?U.q:0),"V"in U){if(U.V<1||U.V>53)return null;"w"in U||(U.w=1),"Z"in U?(Q=zl(Zn(U.y,0,1)),je=Q.getUTCDay(),Q=je>4||je===0?Ti.ceil(Q):Ti(Q),Q=fo.offset(Q,(U.V-1)*7),U.y=Q.getUTCFullYear(),U.m=Q.getUTCMonth(),U.d=Q.getUTCDate()+(U.w+6)%7):(Q=Bl(Zn(U.y,0,1)),je=Q.getDay(),Q=je>4||je===0?_i.ceil(Q):_i(Q),Q=po.offset(Q,(U.V-1)*7),U.y=Q.getFullYear(),U.m=Q.getMonth(),U.d=Q.getDate()+(U.w+6)%7)}else("W"in U||"U"in U)&&("w"in U||(U.w="u"in U?U.u%7:"W"in U?1:0),je="Z"in U?zl(Zn(U.y,0,1)).getUTCDay():Bl(Zn(U.y,0,1)).getDay(),U.m=0,U.d="W"in U?(U.w+6)%7+U.W*7-(je+5)%7:U.w+U.U*7-(je+6)%7);return"Z"in U?(U.H+=U.Z/100|0,U.M+=U.Z%100,zl(U)):Bl(U)}}function D(P,ue,V,U){for(var j=0,Q=ue.length,je=V.length,ce,be;j<Q;){if(U>=je)return-1;if(ce=ue.charCodeAt(j++),ce===37){if(ce=ue.charAt(j++),be=de[ce in $d?ue.charAt(j++):ce],!be||(U=be(P,V,U))<0)return-1}else if(ce!=V.charCodeAt(U++))return-1}return U}function $(P,ue,V){var U=d.exec(ue.slice(V));return U?(P.p=u.get(U[0].toLowerCase()),V+U[0].length):-1}function se(P,ue,V){var U=v.exec(ue.slice(V));return U?(P.w=g.get(U[0].toLowerCase()),V+U[0].length):-1}function J(P,ue,V){var U=x.exec(ue.slice(V));return U?(P.w=m.get(U[0].toLowerCase()),V+U[0].length):-1}function le(P,ue,V){var U=b.exec(ue.slice(V));return U?(P.m=S.get(U[0].toLowerCase()),V+U[0].length):-1}function C(P,ue,V){var U=w.exec(ue.slice(V));return U?(P.m=k.get(U[0].toLowerCase()),V+U[0].length):-1}function I(P,ue,V){return D(P,t,ue,V)}function y(P,ue,V){return D(P,a,ue,V)}function f(P,ue,V){return D(P,n,ue,V)}function R(P){return l[P.getDay()]}function O(P){return r[P.getDay()]}function N(P){return o[P.getMonth()]}function re(P){return c[P.getMonth()]}function H(P){return i[+(P.getHours()>=12)]}function pe(P){return 1+~~(P.getMonth()/3)}function ye(P){return l[P.getUTCDay()]}function Ie(P){return r[P.getUTCDay()]}function ve(P){return o[P.getUTCMonth()]}function B(P){return c[P.getUTCMonth()]}function z(P){return i[+(P.getUTCHours()>=12)]}function K(P){return 1+~~(P.getUTCMonth()/3)}return{format:function(P){var ue=M(P+="",A);return ue.toString=function(){return P},ue}
vendor: 4,884 bytes, line 52
52,parse:function(P){var ue=G(P+="",!1);return ue.toString=function(){return P},ue},utcFormat:function(P){var ue=M(P+="",F);return ue.toString=function(){return P},ue},utcParse:function(P){var ue=G(P+="",!0);return ue.toString=function(){return P},ue}}}var $d={"-":"",_:" ",0:"0"},ut=/^\s*\d+/,WN=/^%/,HN=/[\\^$*+?|[\]().{}]/g;function ys(s,t,a){var n=s<0?"-":"",i=(n?-s:s)+"",r=i.length;return n+(r<a?new Array(a-r+1).join(t)+i:i)}function KN(s){return s.replace(HN,"\\$&")}function Jn(s){return new RegExp("^(?:"+s.map(KN).join("|")+")","i")}function er(s){return new Map(s.map((t,a)=>[t.toLowerCase(),a]))}function YN(s,t,a){var n=ut.exec(t.slice(a,a+1));return n?(s.w=+n[0],a+n[0].length):-1}function QN(s,t,a){var n=ut.exec(t.slice(a,a+1));return n?(s.u=+n[0],a+n[0].length):-1}function XN(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.U=+n[0],a+n[0].length):-1}function ZN(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.V=+n[0],a+n[0].length):-1}function JN(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.W=+n[0],a+n[0].length):-1}function Od(s,t,a){var n=ut.exec(t.slice(a,a+4));return n?(s.y=+n[0],a+n[0].length):-1}function Id(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.y=+n[0]+(+n[0]>68?1900:2e3),a+n[0].length):-1}function ew(s,t,a){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(a,a+6));return n?(s.Z=n[1]?0:-(n[2]+(n[3]||"00")),a+n[0].length):-1}function sw(s,t,a){var n=ut.exec(t.slice(a,a+1));return n?(s.q=n[0]*3-3,a+n[0].length):-1}function tw(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.m=n[0]-1,a+n[0].length):-1}function Fd(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.d=+n[0],a+n[0].length):-1}function aw(s,t,a){var n=ut.exec(t.slice(a,a+3));return n?(s.m=0,s.d=+n[0],a+n[0].length):-1}function Ed(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.H=+n[0],a+n[0].length):-1}function nw(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.M=+n[0],a+n[0].length):-1}function rw(s,t,a){var n=ut.exec(t.slice(a,a+2));return n?(s.S=+n[0],a+n[0].length):-1}function iw(s,t,a){var n=ut.exec(t.slice(a,a+3));return n?(s.L=+n[0],a+n[0].length):-1}function lw(s,t,a){var n=ut.exec(t.slice(a,a+6));return n?(s.L=Math.floor(n[0]/1e3),a+n[0].length):-1}function cw(s,t,a){var n=WN.exec(t.slice(a,a+1));return n?a+n[0].length:-1}function ow(s,t,a){var n=ut.exec(t.slice(a));return n?(s.Q=+n[0],a+n[0].length):-1}function dw(s,t,a){var n=ut.exec(t.slice(a));return n?(s.s=+n[0],a+n[0].length):-1}function Vd(s,t){return ys(s.getDate(),t,2)}function mw(s,t){return ys(s.getHours(),t,2)}function uw(s,t){return ys(s.getHours()%12||12,t,2)}function xw(s,t){return ys(1+po.count(xn(s),s),t,3)}function nx(s,t){return ys(s.getMilliseconds(),t,3)}function hw(s,t){return nx(s,t)+"000"}function pw(s,t){return ys(s.getMonth()+1,t,2)}function fw(s,t){return ys(s.getMinutes(),t,2)}function gw(s,t){return ys(s.getSeconds(),t,2)}function jw(s){var t=s.getDay();return t===0?7:t}function bw(s,t){return ys(tx.count(xn(s)-1,s),t,2)}function rx(s){var t=s.getDay();return t>=4||t===0?Un(s):Un.ceil(s)}function vw(s,t){return s=rx(s),ys(Un.count(xn(s),s)+(xn(s).getDay()===4),t,2)}function yw(s){return s.getDay()}function Nw(s,t){return ys(_i.count(xn(s)-1,s),t,2)}function ww(s,t){return ys(s.getFullYear()%100,t,2)}function kw(s,t){return s=rx(s),ys(s.getFullYear()%100,t,2)}function Cw(s,t){return ys(s.getFullYear()%1e4,t,4)}function Sw(s,t){var a=s.getDay();return s=a>=4||a===0?Un(s):Un.ceil(s),ys(s.getFullYear()%1e4,t,4)}function Aw(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+ys(t/60|0,"0",2)+ys(t%60,"0",2)}function Ud(s,t){return ys(s.getUTCDate(),t,2)}function _w(s,t){return ys(s.getUTCHours(),t,2)}function Tw(s,t){return ys(s.getUTCHours()%12||12,t,2)}function Dw(s,t){return ys(1+fo.count(hn(s),s),t,3)}function ix(s,t){return ys(s.getUTCMilliseconds(),t,3)}function Pw(s,t){return ix(s,t)+"000"}function Mw(s,t){return ys(s.getUTCMonth()+1,t,2)}function Rw(s,t){return ys(s.getUTCMinutes(),t,2)}function Lw(s,t){return ys(s.getUTCSeconds(),t,2)}function $w(s){var t=s.getUTCDay();return t===0?7:t}function Ow(s,t){return ys(ax.count(hn(s)-1,s),t,2)}function lx(s){var t=s.getUTCDay();return t>=4||t===0?Bn(s):Bn.ceil(s)}function Iw(s,t){return s=lx(s),ys(Bn.count(hn(s),s)+(hn(s).getUTCDay()===4),t,2)}function Fw(s){return s.getUTCDay()}function Ew(s,t){return ys(Ti.count(hn(s)-1,s),t,2)}function Vw(s,t){return ys(s.getUTCFullYear()%100,t,2)}function Uw(s,t){return s=lx(s),ys(s.getUTCFullYear()%100,t,2)}function Bw(s,t){return ys(s.getUTCFullYear()%1e4,t,4)}function zw(s,t){var a=s.getUTCDay();return s=a>=4||a===0?Bn(s):Bn.ceil(s),ys(s.getUTCFullYear()%1e4,t,4)}function qw(){return"+0000"}function Bd(){return"%"}function zd(s){return+s}function qd(s){return Math.floor(+s/1e3)}var Sn,cx;Gw({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Frid
52ay","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function Gw(s){return Sn=GN(s),cx=Sn.format,Sn.parse,Sn.utcFormat,Sn.utcParse,Sn}var Ww=Nh,Hw=Gu,Kw=wm;function Yw(s,t,a){for(var n=-1,i=t.length,r={};++n<i;){var l=t[n],c=Ww(s,l);a(c,l)&&Hw(r,Kw(l,s),c)}return r}var Qw=Yw,Xw=Qw,Zw=wh;function Jw(s,t){return Xw(s,t,function(a,n){return Zw(s,n)})}var e1=Jw,s1=e1,t1=rb;t1(function(s,t){return s==null?{}:s1(s,t)});var ox=p.createContext(),a1=function(s){var t=s.children,a=s.animate,n=a===void 0||a,i=s.config,r=i===void 0?"default":i,l=p.useMemo(function(){var c=kh(r)?Su[r]:r;return{animate:n,config:c}},[n,r]);return e.jsx(ox.Provider,{value:l,children:t})},vn=function(){return p.useContext(ox)},n1=function(s){var t=s.children,a=s.condition,n=s.wrapper;return a?p.cloneElement(n,{},t):t},r1={position:"relative"},i1=function(s){var t=s.children,a=s.theme,n=s.renderWrapper,i=n===void 0||n,r=s.isInteractive,l=r===void 0||r,c=s.animate,o=s.motionConfig,d=p.useRef(null);return e.jsx(Fy,{theme:a,children:e.jsx(a1,{animate:c,config:o,children:e.jsx(Ky,{container:d,children:e.jsxs(n1,{condition:i,wrapper:e.jsx("div",{style:r1,ref:d}),children:[t,l&&e.jsx(Hy,{})]})})})})},l1=function(s,t){return s.width===t.width&&s.height===t.height},c1=function(s){var t=s.children,a=s.width,n=s.height,i=s.onResize,r=s.debounceResize,l=mN({width:a,height:n},r,{equalityFn:l1})[0];return p.useEffect(function(){i==null||i(l)},[l,i]),e.jsx(e.Fragment,{children:t(l)})},o1=function(s){var t=s.children,a=s.defaultWidth,n=s.defaultHeight,i=s.onResize,r=s.debounceResize,l=r===void 0?0:r;return e.jsx(cN,{defaultWidth:a,defaultHeight:n,children:function(c){var o=c.width,d=c.height;return e.jsx(c1,{width:o,height:d,onResize:i,debounceResize:l,children:t})}})};function pn(){return pn=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},pn.apply(null,arguments)}function dx(s,t){if(s==null)return{};var a={};for(var n in s)if({}.hasOwnProperty.call(s,n)){if(t.indexOf(n)!==-1)continue;a[n]=s[n]}return a}var d1=["id","colors"],m1=function(s){var t=s.id,a=s.colors,n=dx(s,d1);return e.jsx("linearGradient",pn({id:t,x1:0,x2:0,y1:0,y2:1},n,{children:a.map(function(i){var r=i.offset,l=i.color,c=i.opacity;return e.jsx("stop",{offset:r+"%",stopColor:l,stopOpacity:c!==void 0?c:1},r)})}))},u1={linearGradient:m1},sr={color:"#000000",background:"#ffffff",size:4,padding:4,stagger:!1},x1=p.memo(function(s){var t=s.id,a=s.background,n=a===void 0?sr.background:a,i=s.color,r=i===void 0?sr.color:i,l=s.size,c=l===void 0?sr.size:l,o=s.padding,d=o===void 0?sr.padding:o,u=s.stagger,x=u===void 0?sr.stagger:u,m=c+d,v=c/2,g=d/2;return x===!0&&(m=2*c+2*d),e.jsxs("pattern",{id:t,width:m,height:m,patternUnits:"userSpaceOnUse",children:[e.jsx("rect",{width:m,height:m,fill:n}),e.jsx("circle",{cx:g+v,cy:g+v,r:v,fill:r}),x&&e.jsx("circle",{cx:1.5*d+c+v,cy:1.5*d+c+v,r:v,fill:r})]})}),Gd=function(s){return s*Math.PI/180},tr={spacing:5,rotation:0,background:"#000000",color:"#ffffff",lineWidth:2},h1=p.memo(function(s){var t=s.id,a=s.spacing,n=a===void 0?tr.spacing:a,i=s.rotation,r=i===void 0?tr.rotation:i,l=s.background,c=l===void 0?tr.background:l,o=s.color,d=o===void 0?tr.color:o,u=s.lineWidth,x=u===void 0?tr.lineWidth:u,m=Math.round(r)%360,v=Math.abs(n);m>180?m-=360:m>90?m-=180:m<-180?m+=360:m<-90&&(m+=180);var g,w=v,k=v;return m===0?g=` 53 M 0 0 L `+w+` 0 54 M 0 `+k+" L "+w+" "+k+` 55 `:m===90?g=` 56 M 0 0 L 0 `+k+` 57 M `+w+" 0 L "+w+" "+k+` 58 `:(w=Math.abs(v/Math.sin(Gd(m))),k=v/Math.sin(Gd(90-m)),g=m>0?` 59 M 0 `+-k+" L "+2*w+" "+k+` 60 M `+-w+" "+-k+" L "+w+" "+k+` 61 M `+-w+" 0 L "+w+" "+2*k+` 62 `:` 63 M `+-w+" "+k+" L "+w+" "+-k+` 64 M `+-w+" "+2*k+" L "+2*w+" "+-k+` 65 M 0 `+2*k+" L "+2*w+` 0 66 `),e.jsxs("pattern",{id:t,width:w,height:k,patternUnits:"userSpaceOnUse",children:[e.jsx("rect",{width:w,height:k,fill:c,stroke:"rgba(255, 0, 0, 0.1)",strokeWidth:0}),e.jsx("path",{d:g,strokeWidth:x,stroke:d,strokeLinecap:"square"})]})}),ar={color:"#000000",background:"#ffffff",size:4,padding:4,stagger:!1},p1=p.memo(function(s){var t=s.id,a=s.color,n=a===void 0?ar.color:a,i=s.background,r=i===void 0?ar.background:i,l=s.size,c=l===void 0?ar.size:l,o=s.padding,d=o===void 0?ar.padding:o,u=s.stagger,x=u===void 0?ar.stagger:u,m=c+d,v=d/2;return x===!0&&(m=2*c+2*d),e.jsxs("pattern",{id:t,width:m,height:m,patternUnits:"userSpaceOnUse",children:[e.jsx("rect",{width:m,height:m,fill:r}),e.jsx("rect",{x:v,y:v,width:c,height:c,fill:n}),x&&e.jsx("rect",{x:1.5*d+c,y:1.5*d+c,width:c,height:c,fill:n})]})}),f1={patternDots:x1,patternLines:h1,patternSquares:p1},g1=["type"],Wd=pn({},u1,f1),j1=p.memo(function(s){var t=s.defs;
66return!t||t.length<1?null:e.jsx("defs",{"aria-hidden":!0,children:t.map(function(a){var n=a.type,i=dx(a,g1);return Wd[n]?p.createElement(Wd[n],pn({key:i.id},i)):null})})}),b1=p.forwardRef(function(s,t){var a=s.width,n=s.height,i=s.margin,r=s.defs,l=s.children,c=s.role,o=s.ariaLabel,d=s.ariaLabelledBy,u=s.ariaDescribedBy,x=s.isFocusable,m=Na();return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:a,height:n,role:c,"aria-label":o,"aria-labelledby":d,"aria-describedby":u,focusable:x,tabIndex:x?0:void 0,ref:t,children:[e.jsx(j1,{defs:r}),e.jsx("rect",{width:a,height:n,fill:m.background}),e.jsx("g",{transform:"translate("+i.left+","+i.top+")",children:l})]})}),v1=p.memo(function(s){var t=s.size,a=s.color,n=s.borderWidth,i=s.borderColor;return e.jsx("circle",{r:t/2,fill:a,stroke:i,strokeWidth:n,style:{pointerEvents:"none"}})});p.memo(function(s){var t=s.x,a=s.y,n=s.symbol,i=n===void 0?v1:n,r=s.size,l=s.datum,c=s.color,o=s.borderWidth,d=s.borderColor,u=s.label,x=s.labelTextAnchor,m=x===void 0?"middle":x,v=s.labelYOffset,g=v===void 0?-12:v,w=s.ariaLabel,k=s.ariaLabelledBy,b=s.ariaDescribedBy,S=s.ariaHidden,A=s.ariaDisabled,F=s.isFocusable,de=F!==void 0&&F,M=s.tabIndex,G=M===void 0?0:M,D=s.onFocus,$=s.onBlur,se=s.testId,J=Na(),le=vn(),C=le.animate,I=le.config,y=Gn({transform:"translate("+t+", "+a+")",config:I,immediate:!C}),f=p.useCallback(function(O){D==null||D(l,O)},[D,l]),R=p.useCallback(function(O){$==null||$(l,O)},[$,l]);return e.jsxs(iN.g,{transform:y.transform,style:{pointerEvents:"none"},focusable:de,tabIndex:de?G:void 0,"aria-label":w,"aria-labelledby":k,"aria-describedby":b,"aria-disabled":A,"aria-hidden":S,onFocus:de&&D?f:void 0,onBlur:de&&$?R:void 0,"data-testid":se,children:[p.createElement(i,{size:r,color:c,datum:l,borderWidth:o,borderColor:d}),u&&e.jsx("text",{textAnchor:m,y:g,style:Py(J.dots.text),children:u})]})});var y1=p.memo(function(s){var t=s.width,a=s.height,n=s.axis,i=s.scale,r=s.value,l=s.lineStyle,c=s.textStyle,o=s.legend,d=s.legendNode,u=s.legendPosition,x=u===void 0?"top-right":u,m=s.legendOffsetX,v=m===void 0?14:m,g=s.legendOffsetY,w=g===void 0?14:g,k=s.legendOrientation,b=k===void 0?"horizontal":k,S=Na(),A=0,F=0,de=0,M=0;if(n==="y"?(de=i(r),F=t):(A=i(r),M=a),o&&!d){var G=function(D){var $=D.axis,se=D.width,J=D.height,le=D.position,C=D.offsetX,I=D.offsetY,y=D.orientation,f=0,R=0,O=y==="vertical"?-90:0,N="start";if($==="x")switch(le){case"top-left":f=-C,R=I,N="end";break;case"top":R=-I,N=y==="horizontal"?"middle":"start";break;case"top-right":f=C,R=I,N=y==="horizontal"?"start":"end";break;case"right":f=C,R=J/2,N=y==="horizontal"?"start":"middle";break;case"bottom-right":f=C,R=J-I,N="start";break;case"bottom":R=J+I,N=y==="horizontal"?"middle":"end";break;case"bottom-left":R=J-I,f=-C,N=y==="horizontal"?"end":"start";break;case"left":f=-C,R=J/2,N=y==="horizontal"?"end":"middle"}else switch(le){case"top-left":f=C,R=-I,N="start";break;case"top":f=se/2,R=-I,N=y==="horizontal"?"middle":"start";break;case"top-right":f=se-C,R=-I,N=y==="horizontal"?"end":"start";break;case"right":f=se+C,N=y==="horizontal"?"start":"middle";break;case"bottom-right":f=se-C,R=I,N="end";break;case"bottom":f=se/2,R=I,N=y==="horizontal"?"middle":"end";break;case"bottom-left":f=C,R=I,N=y==="horizontal"?"start":"end";break;case"left":f=-C,N=y==="horizontal"?"end":"middle"}return{x:f,y:R,rotation:O,textAnchor:N}}({axis:n,width:t,height:a,position:x,offsetX:v,offsetY:w,orientation:b});d=e.jsx("text",{transform:"translate("+G.x+", "+G.y+") rotate("+G.rotation+")",textAnchor:G.textAnchor,dominantBaseline:"central",style:c,children:o})}return e.jsxs("g",{transform:"translate("+A+", "+de+")",children:[e.jsx("line",{x1:0,x2:F,y1:0,y2:M,stroke:S.markers.lineColor,strokeWidth:S.markers.lineStrokeWidth,style:l}),d]})});p.memo(function(s){var t=s.markers,a=s.width,n=s.height,i=s.xScale,r=s.yScale;return t&&t.length!==0?t.map(function(l,c){return e.jsx(y1,pn({},l,{width:a,height:n,scale:l.axis==="y"?r:i}),c)}):null});var N1=function(s){var t=vn(),a=t.animate,n=t.config,i=function(c){var o=p.useRef();return p.useEffect(function(){o.current=c},[c]),o.current}(s),r=p.useMemo(function(){return Wh(i,s)},[i,s]),l=Gn({from:{value:0},to:{value:1},reset:!0,config:n,immediate:!a}).value;return yv(l,r)};p.createContext(void 0);var w1={basis:Mh,basisClosed:Ph,basisOpen:Dh,bundle:vf,cardinal:yf,cardinalClosed:Nf,cardinalOpen:wf,catmullRom:kf,catmullRomClosed:Cf,catmullRomOpen:Sf,linear:Hh,linearClosed:Th,monotoneX:Pm,monotoneY:Dm,natural
66:_h,step:Ah,stepAfter:Sh,stepBefore:Ch},go=Object.keys(w1);go.filter(function(s){return s.endsWith("Closed")});Zu(go,"bundle","basisClosed","basisOpen","cardinalClosed","cardinalOpen","catmullRomClosed","catmullRomOpen","linearClosed");Zu(go,"bundle","basisClosed","basisOpen","cardinalClosed","cardinalOpen","catmullRomClosed","catmullRomOpen","linearClosed");qe(Ii),qe(Fi),qe(Ei),qe(Vi),qe(Ui),qe(Bi),qe(zi),qe(qi),qe(Gi),qe(nl),qe(rl),qe(il),qe(ol),qe(ll),qe(cl),qe(Wi),qe(Hi),qe(Ki),qe(Yi),qe(Qi),qe(Xi),qe(Zi),qe(Ji),qe(el),qe(sl),qe(tl),qe(al);qe(Ii),qe(Fi),qe(Ei),qe(Vi),qe(Ui),qe(Bi),qe(zi),qe(qi),qe(Gi),qe(nl),qe(rl),qe(il),qe(ol),qe(ll),qe(cl),qe(Wi),qe(Hi),qe(Ki),qe(Yi),qe(Qi),qe(Xi),qe(Zi),qe(Ji),qe(el),qe(sl),qe(tl),qe(al);nr(Vm);var k1={top:0,right:0,bottom:0,left:0},C1=function(s,t,a){return a===void 0&&(a={}),p.useMemo(function(){var n=pn({},k1,a);return{margin:n,innerWidth:s-n.left-n.right,innerHeight:t-n.top-n.bottom,outerWidth:s,outerHeight:t}},[s,t,a])},S1=function(){var s=p.useRef(null),t=p.useState({left:0,top:0,width:0,height:0}),a=t[0],n=t[1],i=p.useState(function(){return typeof ResizeObserver>"u"?null:new ResizeObserver(function(r){var l=r[0];return n(l.contentRect)})})[0];return p.useEffect(function(){return s.current&&i!==null&&i.observe(s.current),function(){i!==null&&i.disconnect()}},[i]),[s,a]},A1=function(s){return typeof s=="function"?s:typeof s=="string"?s.indexOf("time:")===0?cx(s.slice("5")):ex(s):function(t){return""+t}},mx=function(s){return p.useMemo(function(){return A1(s)},[s])},_1=function(s){return mm(s)?s:function(t){return $n(t,s)}},T1=function(s){return p.useMemo(function(){return _1(s)},[s])};function Hd(s,t){(t==null||t>s.length)&&(t=s.length);for(var a=0,n=Array(t);a<t;a++)n[a]=s[a];return n}function D1(s,t){var a=typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(a)return(a=a.call(s)).next.bind(a);if(Array.isArray(s)||(a=function(i,r){if(i){if(typeof i=="string")return Hd(i,r);var l={}.toString.call(i).slice(8,-1);return l==="Object"&&i.constructor&&(l=i.constructor.name),l==="Map"||l==="Set"?Array.from(i):l==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(l)?Hd(i,r):void 0}}(s))||t){a&&(s=a);var n=0;return function(){return n>=s.length?{done:!0}:{done:!1,value:s[n++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. 67In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Di(){return Di=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},Di.apply(null,arguments)}var ux={nivo:["#e8c1a0","#f47560","#f1e15b","#e8a838","#61cdbb","#97e3d5"],category10:kp,accent:Cp,dark2:Sp,paired:Ap,pastel1:_p,pastel2:Tp,set1:Dp,set2:Pp,set3:Vm,tableau10:Mp},P1=Object.keys(ux),xx={brown_blueGreen:Ii,purpleRed_green:Fi,pink_yellowGreen:Ei,purple_orange:Vi,red_blue:Ui,red_grey:Bi,red_yellow_blue:zi,red_yellow_green:qi,spectral:Gi},M1=Object.keys(xx),R1={brown_blueGreen:Rp,purpleRed_green:Lp,pink_yellowGreen:$p,purple_orange:Op,red_blue:Ip,red_grey:Fp,red_yellow_blue:Ep,red_yellow_green:Vp,spectral:Up},hx={blues:nl,greens:rl,greys:il,oranges:ol,purples:ll,reds:cl,blue_green:Wi,blue_purple:Hi,green_blue:Ki,orange_red:Yi,purple_blue_green:Qi,purple_blue:Xi,purple_red:Zi,red_purple:Ji,yellow_green_blue:el,yellow_green:sl,yellow_orange_brown:tl,yellow_orange_red:al},L1=Object.keys(hx),$1={blues:ef,greens:sf,greys:tf,oranges:rf,purples:af,reds:nf,turbo:pf,viridis:ff,inferno:jf,magma:gf,plasma:bf,cividis:lf,warm:of,cool:df,cubehelixDefault:cf,blue_green:Bp,blue_purple:zp,green_blue:qp,orange_red:Gp,purple_blue_green:Wp,purple_blue:Hp,purple_red:Kp,red_purple:Yp,yellow_green_blue:Qp,yellow_green:Xp,yellow_orange_brown:Zp,yellow_orange_red:Jp},ql=Di({},ux,xx,hx),O1=function(s){return P1.includes(s)},I1=function(s){return M1.includes(s)},F1=function(s){return L1.includes(s)},E1={rainbow:mf,sinebow:hf};Di({},R1,$1,E1);var V1=function(s){return s.theme!==void 0},U1=function(s){return s.from!==void 0},B1=function(s,t){if(typeof s=="function")return s;if(km(s)){if(V1(s)){if(t===void 0)throw new Error("Unable to use color from theme as no theme was provided");var a=$n(t,s.theme);if(a===void 0)throw new Error("Color from theme is undefined at path: '"+s.theme+"'");return function(){return a}}if(U1(s)){var n=function(o){return $n(o,s.from)};if(Array.isArray(s.modifiers)){for(var i,r=[],l=function(){var o=i.value,d=o[0],u=o[1];if(d==="brighter")r.push(function(x){return x.brighter(u)});else if(d==="darker")r.push(function(x){return x.darker(u)});else{if(d!=="opacity")throw new Error("Invalid color modifier: '"+d+"', must be one of: 'brighter', 'darker', 'opacity'");r.push(function(x){return x.opacity=u,x})}},c=D1(s.modifiers);!(i=c()).done;)l();return r.length===0?n:function(o){return r.reduce(function(d,u){return u(d)},Tm(n(o))).toString()}}return n}throw new Error("Invalid color spec, you should either specify 'theme' or 'from' when using a config object")}return function(){return s}},Kd=function(s,t){return p.useMemo(function(){return B1(s,t)},[s,t])},z1=function(s,t){if(typeof s=="function")return s;var a=function(x){return $n(x,t)};if(Array.isArray(s)){var n=nr(s),i=function(x){return n(a(x))};return i.scale=n,i}if(km(s)){if(function(x){return x.datum!==void 0}(s))return function(x){return $n(x,s.datum)};if(function(x){return x.scheme!==void 0}(s)){if(O1(s.scheme)){var r=nr(ql[s.scheme]),l=function(x){return r(a(x))};return l.scale=r,l}if(I1(s.scheme)){if(s.size!==void 0&&(s.size<3||s.size>11))throw new Error("Invalid size '"+s.size+"' for diverging color scheme '"+s.scheme+"', must be between 3~11");var c=nr(ql[s.scheme][s.size||11]),o=function(x){return c(a(x))};return o.scale=c,o}if(F1(s.scheme)){if(s.size!==void 0&&(s.size<3||s.size>9))throw new Error("Invalid size '"+s.size+"' for sequential color scheme '"+s.scheme+"', must be between 3~9");var d=nr(ql[s.scheme][s.size||9]),u=function(x){return d(a(x))};return u.scale=d,u}}throw new Error("Invalid colors, when using an object, you should either pass a 'datum' or a 'scheme' property")}return function(){return s}},q1=function(s,t){return p.useMemo(function(){return z1(s,t)},[s,t])},px=/^--/;function G1(s,t){return t==null||typeof t=="boolean"||t===""?"":typeof t=="number"&&t!==0&&!px.test(s)&&!(hr.hasOwnProperty(s)&&hr[s])?t+"px":(""+t).trim()}var Yd={};function W1(s,t){if(!s.nodeType||!s.setAttribute)return!1;const a=s.nodeName==="filter"||s.parentNode&&s.parentNode.nodeName==="filter",{className:n,style:i,children:r,scrollTop:l,scrollLeft:c,viewBox:o,...d}=t,u=Object.values(d),x=Object.keys(d).map(m=>a||s.hasAttribute(m)?m:Yd[m]||(Yd[m]=m.replace(/([A-Z])/g,v=>"-"+v.toLowerCase())));r!==void 0&&(s.textContent=r);for(const m in i)if(i.hasOwnProperty(m)){const v=G1(m,i[m]);px.test(m)?s.style.setProperty(m,v):s.style[m]=v}
67x.forEach((m,v)=>{s.setAttribute(m,u[v])}),n!==void 0&&(s.className=n),l!==void 0&&(s.scrollTop=l),c!==void 0&&(s.scrollLeft=c),o!==void 0&&s.setAttribute("viewBox",o)}var hr={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},H1=(s,t)=>s+t.charAt(0).toUpperCase()+t.substring(1),K1=["Webkit","Ms","Moz","O"];hr=Object.keys(hr).reduce((s,t)=>(K1.forEach(a=>s[H1(a,t)]=s[t]),s),hr);var Y1=/^(matrix|translate|scale|rotate|skew)/,Q1=/^(translate)/,X1=/^(rotate|skew)/,Gl=(s,t)=>he.num(s)&&s!==0?s+t:s,li=(s,t)=>he.arr(s)?s.every(a=>li(a,t)):he.num(s)?s===t:parseFloat(s)===t,Z1=class extends gn{constructor({x:t,y:a,z:n,...i}){const r=[],l=[];(t||a||n)&&(r.push([t||0,a||0,n||0]),l.push(c=>[`translate3d(${c.map(o=>Gl(o,"px")).join(",")})`,li(c,0)])),zt(i,(c,o)=>{if(o==="transform")r.push([c||""]),l.push(d=>[d,d===""]);else if(Y1.test(o)){if(delete i[o],he.und(c))return;const d=Q1.test(o)?"px":X1.test(o)?"deg":"";r.push(Nt(c)),l.push(o==="rotate3d"?([u,x,m,v])=>[`rotate3d(${u},${x},${m},${Gl(v,d)})`,li(v,0)]:u=>[`${o}(${u.map(x=>Gl(x,d)).join(",")})`,li(u,o.startsWith("scale")?1:0)])}}),r.length&&(i.transform=new J1(r,l)),super(i)}},J1=class extends Er{constructor(t,a){super(),this.inputs=t,this.transforms=a,this._value=null}get(){return this._value||(this._value=this._get())}_get(){let t="",a=!0;return Ye(this.inputs,(n,i)=>{const r=it(n[0]),[l,c]=this.transforms[i](he.arr(r)?r:n.map(it));t+=" "+l,a=a&&c}),a?"none":t}observerAdded(t){t==1&&Ye(this.inputs,a=>Ye(a,n=>dt(n)&&$a(n,this)))}observerRemoved(t){t==0&&Ye(this.inputs,a=>Ye(a,n=>dt(n)&&Ka(n,this)))}eventObserved(t){t.type=="change"&&(this._value=null),Ha(this,t)}},e2=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"];Mt.assign({batchedUpdates:Mi.unstable_batchedUpdates,createStringInterpolator:Vr,colors:pl});var s2=yl(e2,{applyAnimatedValues:W1,createAnimatedStyle:s=>new Z1(s),getComponentProps:({scrollTop:s,scrollLeft:t,...a})=>a}),Qd=s2.animated;function pr(){return pr=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},pr.apply(null,arguments)}function Xd(s,t){if(s==null)return{};var a={};for(var n in s)if({}.hasOwnProperty.call(s,n)){if(t.indexOf(n)!==-1)continue;a[n]=s[n]}return a}var t2=["style","children"],a2=["outlineWidth","outlineColor","outlineOpacity"],fx=function(s){var t=s.style,a=s.children,n=Xd(s,t2),i=t.outlineWidth,r=t.outlineColor,l=t.outlineOpacity,c=Xd(t,a2);return e.jsxs(e.Fragment,{children:[i>0&&e.jsx(Qd.text,pr({},n,{style:pr({},c,{strokeWidth:2*i,stroke:r,strokeOpacity:l,strokeLinejoin:"round"}),children:a})),e.jsx(Qd.text,pr({},n,{style:c,children:a}))]})},n2=function(s){var t=s.x,a=s.y,n=s.size,i=s.fill,r=s.opacity,l=r===void 0?1:r,c=s.borderWidth,o=c===void 0?0:c,d=s.borderColor;return e.jsx("circle",{r:n/2,cx:t+n/2,cy:a+n/2,fill:i,opacity:l,strokeWidth:o,stroke:d===void 0?"transparent":d,style:{pointerEvents:"none"}})},r2=function(s){var t=s.x,a=s.y,n=s.size,i=s.fill,r=s.opacity,l=r===void 0?1:r,c=s.borderWidth,o=c===void 0?0:c,d=s.borderColor;return e.jsx("g",{transform:"translate("+t+","+a+")",children:e.jsx("path",{d:` 68 M`+n/2+` 0 69 L`+.8*n+" "+n/2+` 70 L`+n/2+" "+n+` 71 L`+.2*n+" "+n/2+` 72 L`+n/2+` 0 73 `,fill:i,opacity:l,strokeWidth:o,stroke:d===void 0?"transparent":d,style:{pointerEvents:"none"}})})},i2=function(s){var t=s.x,a=s.y,n=s.size,i=s.fill,r=s.opacity,l=r===void 0?1:r,c=s.borderWidth,o=c===void 0?0:c,d=s.borderColor;return e.jsx("rect",{x:t,y:a,fill:i,opacity:l,strokeWidth:o,stroke:d===void 0?"transparent":d,width:n,height:n,style:{pointerEvents:"none"}})},l2=function(s){var t=s.x,a=s.y,n=s.size,i=s.fill,r=s.opacity,l=r===void 0?1:r,c=s.borderWidth,o=c===void 0?0:c,d=s.borderColor;return e.jsx("g",{transform:"translate("+t+","+a+")",children:e.jsx("path",{d:` 74 M`+n/2+` 0 75 L`+n+" "+n+` 76 L0 `+n+` 77 L`+n/2+` 0 78 `,fill:i,opacity:l,strokeWidth:o,stroke:d===void 0?"transparent":d,style:{pointerEvents:"none"}})})};function an(){return an=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},an.apply(null,arguments)}var Yt={translateX:0,translateY:0,padding:0,itemsSpacing:0,itemDirection:"left-to-right",justify:!1,symbolShape:"square",symbolSize:16,symbolSpacing:8}
78,c2={top:0,right:0,bottom:0,left:0},gx=function(s){var t,a=s.direction,n=s.itemsSpacing,i=s.padding,r=s.itemCount,l=s.itemWidth,c=s.itemHeight;if(typeof i!="number"&&(typeof(t=i)!="object"||Array.isArray(t)||t===null))throw new Error("Invalid property padding, must be one of: number, object");var o=typeof i=="number"?{top:i,right:i,bottom:i,left:i}:an({},c2,i),d=o.left+o.right,u=o.top+o.bottom,x=l+d,m=c+u,v=(r-1)*n;return a==="row"?x=l*r+v+d:a==="column"&&(m=c*r+v+u),{width:x,height:m,padding:o}},o2=function(s){var t=s.anchor,a=s.translateX,n=s.translateY,i=s.containerWidth,r=s.containerHeight,l=s.width,c=s.height,o=a,d=n;switch(t){case"top":o+=(i-l)/2;break;case"top-right":o+=i-l;break;case"right":o+=i-l,d+=(r-c)/2;break;case"bottom-right":o+=i-l,d+=r-c;break;case"bottom":o+=(i-l)/2,d+=r-c;break;case"bottom-left":d+=r-c;break;case"left":d+=(r-c)/2;break;case"center":o+=(i-l)/2,d+=(r-c)/2}return{x:o,y:d}},d2=function(s){var t,a,n,i,r,l,c=s.direction,o=s.justify,d=s.symbolSize,u=s.symbolSpacing,x=s.width,m=s.height;switch(c){case"left-to-right":t=0,a=(m-d)/2,i=m/2,l="central",o?(n=x,r="end"):(n=d+u,r="start");break;case"right-to-left":t=x-d,a=(m-d)/2,i=m/2,l="central",o?(n=0,r="start"):(n=x-d-u,r="end");break;case"top-to-bottom":t=(x-d)/2,a=0,n=x/2,r="middle",o?(i=m,l="alphabetic"):(i=d+u,l="text-before-edge");break;case"bottom-to-top":t=(x-d)/2,a=m-d,n=x/2,r="middle",o?(i=0,l="text-before-edge"):(i=m-d-u,l="alphabetic")}return{symbolX:t,symbolY:a,labelX:n,labelY:i,labelAnchor:r,labelAlignment:l}},m2={circle:n2,diamond:r2,square:i2,triangle:l2},u2=function(s){var t,a,n,i,r,l,c,o,d,u,x,m=s.x,v=s.y,g=s.width,w=s.height,k=s.data,b=s.direction,S=b===void 0?Yt.itemDirection:b,A=s.justify,F=A===void 0?Yt.justify:A,de=s.textColor,M=s.background,G=M===void 0?"transparent":M,D=s.opacity,$=D===void 0?1:D,se=s.symbolShape,J=se===void 0?Yt.symbolShape:se,le=s.symbolSize,C=le===void 0?Yt.symbolSize:le,I=s.symbolSpacing,y=I===void 0?Yt.symbolSpacing:I,f=s.symbolBorderWidth,R=f===void 0?0:f,O=s.symbolBorderColor,N=O===void 0?"transparent":O,re=s.onClick,H=s.onMouseEnter,pe=s.onMouseLeave,ye=s.toggleSerie,Ie=s.effects,ve=p.useState({}),B=ve[0],z=ve[1],K=Na(),P=p.useCallback(function(Ne){if(Ie){var Le=Ie.filter(function(ae){return ae.on==="hover"}).reduce(function(ae,xe){return an({},ae,xe.style)},{});z(Le)}H==null||H(k,Ne)},[H,k,Ie]),ue=p.useCallback(function(Ne){if(Ie){var Le=Ie.filter(function(ae){return ae.on!=="hover"}).reduce(function(ae,xe){return an({},ae,xe.style)},{});z(Le)}pe==null||pe(k,Ne)},[pe,k,Ie]),V=d2({direction:S,justify:F,symbolSize:(t=B.symbolSize)!=null?t:C,symbolSpacing:y,width:g,height:w}),U=V.symbolX,j=V.symbolY,Q=V.labelX,je=V.labelY,ce=V.labelAnchor,be=V.labelAlignment,ss=[re,H,pe,ye].some(function(Ne){return Ne!==void 0}),oe=typeof J=="function"?J:m2[J];return e.jsxs("g",{transform:"translate("+m+","+v+")",style:{opacity:(a=B.itemOpacity)!=null?a:$},children:[e.jsx("rect",{width:g,height:w,fill:(n=B.itemBackgroun
78d)!=null?n:G,style:{cursor:ss?"pointer":"auto"},onClick:function(Ne){re==null||re(k,Ne),ye==null||ye(k.id)},onMouseEnter:P,onMouseLeave:ue}),p.createElement(oe,an({id:k.id,x:U,y:j,size:(i=B.symbolSize)!=null?i:C,fill:(r=(l=k.fill)!=null?l:k.color)!=null?r:"black",borderWidth:(c=B.symbolBorderWidth)!=null?c:R,borderColor:(o=B.symbolBorderColor)!=null?o:N},k.hidden?K.legends.hidden.symbol:void 0)),e.jsx(fx,{textAnchor:ce,style:an({},K.legends.text,{fill:(d=(u=(x=B.itemTextColor)!=null?x:de)!=null?u:K.legends.text.fill)!=null?d:"black",dominantBaseline:be,pointerEvents:"none",userSelect:"none"},k.hidden?K.legends.hidden.text:void 0),x:Q,y:je,children:k.label})]})},x2=function(s){var t=s.data,a=s.x,n=s.y,i=s.direction,r=s.padding,l=r===void 0?Yt.padding:r,c=s.justify,o=s.effects,d=s.itemWidth,u=s.itemHeight,x=s.itemDirection,m=x===void 0?Yt.itemDirection:x,v=s.itemsSpacing,g=v===void 0?Yt.itemsSpacing:v,w=s.itemTextColor,k=s.itemBackground,b=k===void 0?"transparent":k,S=s.itemOpacity,A=S===void 0?1:S,F=s.symbolShape,de=s.symbolSize,M=s.symbolSpacing,G=s.symbolBorderWidth,D=s.symbolBorderColor,$=s.onClick,se=s.onMouseEnter,J=s.onMouseLeave,le=s.toggleSerie,C=gx({itemCount:t.length,itemWidth:d,itemHeight:u,itemsSpacing:g,direction:i,padding:l}).padding,I=i==="row"?d+g:0,y=i==="column"?u+g:0;return e.jsx("g",{transform:"translate("+a+","+n+")",children:t.map(function(f,R){return e.jsx(u2,{data:f,x:R*I+C.left,y:R*y+C.top,width:d,height:u,direction:m,justify:c,effects:o,textColor:w,background:b,opacity:A,symbolShape:F,symbolSize:de,symbolSpacing:M,symbolBorderWidth:G,symbolBorderColor:D,onClick:$,onMouseEnter:se,onMouseLeave:J,toggleSerie:le},R)})})},h2=function(s){var t=s.data,a=s.containerWidth,n=s.containerHeight,i=s.translateX,r=i===void 0?Yt.translateX:i,l=s.translateY,c=l===void 0?Yt.translateY:l,o=s.anchor,d=s.direction,u=s.padding,x=u===void 0?Yt.padding:u,m=s.justify,v=s.itemsSpacing,g=v===void 0?Yt.itemsSpacing:v,w=s.itemWidth,k=s.itemHeight,b=s.itemDirection,S=s.itemTextColor,A=s.itemBackgroun
vendor: 3,733 bytes, line 78
78d,F=s.itemOpacity,de=s.symbolShape,M=s.symbolSize,G=s.symbolSpacing,D=s.symbolBorderWidth,$=s.symbolBorderColor,se=s.onClick,J=s.onMouseEnter,le=s.onMouseLeave,C=s.toggleSerie,I=s.effects,y=gx({itemCount:t.length,itemsSpacing:g,itemWidth:w,itemHeight:k,direction:d,padding:x}),f=y.width,R=y.height,O=o2({anchor:o,translateX:r,translateY:c,containerWidth:a,containerHeight:n,width:f,height:R}),N=O.x,re=O.y;return e.jsx(x2,{data:t,x:N,y:re,direction:d,padding:x,justify:m,effects:I,itemsSpacing:g,itemWidth:w,itemHeight:k,itemDirection:b,itemTextColor:S,itemBackground:A,itemOpacity:F,symbolShape:de,symbolSize:M,symbolSpacing:G,symbolBorderWidth:D,symbolBorderColor:$,onClick:se,onMouseEnter:J,onMouseLeave:le,toggleSerie:typeof C=="boolean"?void 0:C})};function Zd(s,t){let a;if(t===void 0)for(const n of s)n!=null&&(a<n||a===void 0&&n>=n)&&(a=n);else{let n=-1;for(let i of s)(i=t(i,++n,s))!=null&&(a<i||a===void 0&&i>=i)&&(a=i)}return a}function jx(s,t){let a;if(t===void 0)for(const n of s)n!=null&&(a>n||a===void 0&&n>=n)&&(a=n);else{let n=-1;for(let i of s)(i=t(i,++n,s))!=null&&(a>i||a===void 0&&i>=i)&&(a=i)}return a}function Wl(s,t){let a=0;if(t===void 0)for(let n of s)(n=+n)&&(a+=n);else{let n=-1;for(let i of s)(i=+t(i,++n,s))&&(a+=i)}return a}function p2(s){return s.target.depth}function f2(s){return s.depth}function g2(s,t){return t-1-s.height}function bx(s,t){return s.sourceLinks.length?s.depth:t-1}function j2(s){return s.targetLinks.length?s.depth:s.sourceLinks.length?jx(s.sourceLinks,p2)-1:0}function Qr(s){return function(){return s}}function Jd(s,t){return Pi(s.source,t.source)||s.index-t.index}function em(s,t){return Pi(s.target,t.target)||s.index-t.index}function Pi(s,t){return s.y0-t.y0}function Hl(s){return s.value}function b2(s){return s.index}function v2(s){return s.nodes}function y2(s){return s.links}function sm(s,t){const a=s.get(t);if(!a)throw new Error("missing: "+t);return a}function tm({nodes:s}){for(const t of s){let a=t.y0,n=a;for(const i of t.sourceLinks)i.y0=a+i.width/2,a+=i.width;for(const i of t.targetLinks)i.y1=n+i.width/2,n+=i.width}}function N2(){let s=0,t=0,a=1,n=1,i=24,r=8,l,c=b2,o=bx,d,u,x=v2,m=y2,v=6;function g(){const y={nodes:x.apply(null,arguments),links:m.apply(null,arguments)};return w(y),k(y),b(y),S(y),de(y),tm(y),y}g.update=function(y){return tm(y),y},g.nodeId=function(y){return arguments.length?(c=typeof y=="function"?y:Qr(y),g):c},g.nodeAlign=function(y){return arguments.length?(o=typeof y=="function"?y:Qr(y),g):o},g.nodeSort=function(y){return arguments.length?(d=y,g):d},g.nodeWidth=function(y){return arguments.length?(i=+y,g):i},g.nodePadding=function(y){return arguments.length?(r=l=+y,g):r},g.nodes=function(y){return arguments.length?(x=typeof y=="function"?y:Qr(y),g):x},g.links=function(y){return arguments.length?(m=typeof y=="function"?y:Qr(y),g):m},g.linkSort=function(y){return arguments.length?(u=y,g):u},g.size=function(y){return arguments.length?(s=t=0,a=+y[0],n=+y[1],g):[a-s,n-t]},g.extent=function(y){return arguments.length?(s=+y[0][0],a=+y[1][0],t=+y[0][1],n=+y[1][1],g):[[s,t],[a,n]]},g.iterations=function(y){return arguments.length?(v=+y,g):v};function w({nodes:y,links:f}){for(const[O,N]of y.entries())N.index=O,N.sourceLinks=[],N.targetLinks=[];const R=new Map(y.map((O,N)=>[c(O,N,y),O]));for(const[O,N]of f.entries()){N.index=O;let{source:re,target:H}=N;typeof re!="object"&&(re=N.source=sm(R,re)),typeof H!="object"&&(H=N.target=sm(R,H)),re.sourceLinks.push(N),H.targetLinks.push(N)}if(u!=null)for(const{sourceLinks:O,targetLinks:N}of y)O.sort(u),N.sort(u)}function k({nodes:y}){for(const f of y)f.value=f.fixedValue===void 0?Math.max(Wl(f.sourceLinks,Hl),Wl(f.targetLinks,Hl)):f.fixedValue}function b({nodes:y}){const f=y.length;
78let R=new Set(y),O=new Set,N=0;for(;R.size;){for(const re of R){re.depth=N;for(const{target:H}of re.sourceLinks)O.add(H)}if(++N>f)throw new Error("circular link");R=O,O=new Set}}function S({nodes:y}){const f=y.length;let R=new Set(y),O=new Set,N=0;for(;R.size;){for(const re of R){re.height=N;for(const{source:H}of re.targetLinks)O.add(H)}if(++N>f)throw new Error("circular link");R=O,O=new Set}}function A({nodes:y}){const f=Zd(y,N=>N.depth)+1,R=(a-s-i)/(f-1),O=new Array(f);for(const N of y){const re=Math.max(0,Math.min(f-1,Math.floor(o.call(null,N,f))));N.layer=re,N.x0=s+re*R,N.x1=N.x0+i,O[re]?O[re].push(N):O[re]=[N]}if(d)for(const N of O)N.sort(d);return O}function F(y){const f=jx(y,R=>(n-t-(R.length-1)*l)/Wl(R,Hl));for(const R of y){let O=t;for(const N of R){N.y0=O,N.y1=O+N.value*f,O=N.y1+l;for(const re of N.sourceLinks)re.width=re.value*f}O=(n-O+l)/(R.length+1);for(let N=0;N<R.length;++N){const re=R[N];re.y0+=O*(N+1),re.y1+=O*(N+1)}le(R)}}function de(y){const f=A(y);l=Math.min(r,(n-t)/(Zd(f,R=>R.length)-1)),F(f);for(let R=0;R<v;++R){const O=Math.pow(.99,R),N=Math.max(1-O,(R+1)/v);G(f,O,N),M(f,O,N)}}function M(y,f,R){for(let O=1,N=y.length;O<N;++O){const re=y[O];for(const H of re){let pe=0,ye=0;for(const{source:ve,value:B}of H.targetLinks){let z=B*(H.layer-ve.layer);pe+=C(ve,H)*z,ye+=z}if(!(ye>0))continue;let Ie=(pe/ye-H.y0)*f;H.y0+=Ie,H.y1+=Ie,J(H)}d===void 0&&re.sort(Pi),D(re,R)}}function G(y,f,R){for(let O=y.length,N=O-2;N>=0;--N){const re=y[N];for(const H of re){let pe=0,ye=0;for(const{target:ve,value:B}of H.sourceLinks){let z=B*(ve.layer-H.layer);pe+=I(H,ve)*z,ye+=z}if(!(ye>0))continue;let Ie=(pe/ye-H.y0)*f;H.y0+=Ie,H.y1+=Ie,J(H)}d===void 0&&re.sort(Pi),D(re,R)}}function D(y,f){const R=y.length>>1,O=y[R];se(y,O.y0-l,R-1,f),$(y,O.y1+l,R+1,f),se(y,n,y.length-1,f),$(y,t,0,f)}function $(y,f,R,O){for(;R<y.length;++R){const N=y[R],re=(f-N.y0)*O;re>1e-6&&(N.y0+=re,N.y1+=re),f=N.y1+l}}function se(y,f,R,O){for(;R>=0;--R){const N=y[R],re=(N.y1-f)*O;re>1e-6&&(N.y0-=re,N.y1-=re),f=N.y0-l}}function J({sourceLinks:y,targetLinks:f}){if(u===void 0){for(const{source:{sourceLinks:R}}of f)R.sort(em);for(const{target:{targetLinks:R}}of y)R.sort(Jd)}}function le(y){if(u===void 0)for(const{sourceLinks:f,targetLinks:R}of y)f.sort(em),R.sort(Jd)}function C(y,f){let R=y.y0-(y.sourceLinks.length-1)*l/2;for(const{target:O,width:N}of y.sourceLinks){if(O===f)break;R+=N+l}for(const{source:O,width:N}of f.targetLinks){if(O===y)break;R-=N}return R}function I(y,f){let R=f.y0-(f.targetLinks.length-1)*l/2;for(const{source:O,width:N}of f.targetLinks){if(O===y)break;R+=N+l}for(const{target:O,width:N}of y.sourceLinks){if(O===f)break;R-=N}return R}return g}var w2=X0,k2=1,C2=4;function S2(s){return w2(s,k2|C2)}var A2=S2;const _2=Rr(A2);var vx=/^--/;function T2(s,t){return t==null||typeof t=="boolean"||t===""?"":typeof t=="number"&&t!==0&&!vx.test(s)&&!(fr.hasOwnProperty(s)&&fr[s])?t+"px":(""+t).trim()}var am={};function D2(s,t){if(!s.nodeType||!s.setAttribute)return!1;const a=s.nodeName==="filter"||s.parentNode&&s.parentNode.nodeName==="filter",{className:n,style:i,children:r,scrollTop:l,scrollLeft:c,viewBox:o,...d}=t,u=Object.values(d),x=Object.keys(d).map(m=>a||s.hasAttribute(m)?m:am[m]||(am[m]=m.replace(/([A-Z])/g,v=>"-"+v.toLowerCase())));r!==void 0&&(s.textContent=r);for(const m in i)if(i.hasOwnProperty(m)){const v=T2(m,i[m]);vx.test(m)?s.style.setProperty(m,v):s.style[m]=v}x.forEach((m,v)=>{s.setAttribute(m,u[v])}),n!==void 0&&(s.className=n),l!==void 0&&(s.scrollTop=l),c!==void 0&&(s.scrollLeft=c),o!==void 0&&s.setAttribute("viewBox",o)}var fr={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},P2=(s,t)=>s+t.charAt(0).toUpperCase()+t.substring(1),M2=["Webkit","Ms","Moz","O"];fr=Object.keys(fr).reduce((s,t)=>(M2.forEach(a=>s[P2(a,t)]=s[t]),s),fr);var R2=/^(matrix|translate|scale|rotate|skew)/,L2=/^(translate)/,$2=
78/^(rotate|skew)/,Kl=(s,t)=>he.num(s)&&s!==0?s+t:s,ci=(s,t)=>he.arr(s)?s.every(a=>ci(a,t)):he.num(s)?s===t:parseFloat(s)===t,O2=class extends gn{constructor({x:s,y:t,z:a,...n}){const i=[],r=[];(s||t||a)&&(i.push([s||0,t||0,a||0]),r.push(l=>[`translate3d(${l.map(c=>Kl(c,"px")).join(",")})`,ci(l,0)])),zt(n,(l,c)=>{if(c==="transform")i.push([l||""]),r.push(o=>[o,o===""]);else if(R2.test(c)){if(delete n[c],he.und(l))return;const o=L2.test(c)?"px":$2.test(c)?"deg":"";i.push(Nt(l)),r.push(c==="rotate3d"?([d,u,x,m])=>[`rotate3d(${d},${u},${x},${Kl(m,o)})`,ci(m,0)]:d=>[`${c}(${d.map(u=>Kl(u,o)).join(",")})`,ci(d,c.startsWith("scale")?1:0)])}}),i.length&&(n.transform=new I2(i,r)),super(n)}},I2=class extends Er{constructor(s,t){super(),this.inputs=s,this.transforms=t,this._value=null}get(){return this._value||(this._value=this._get())}_get(){let s="",t=!0;return Ye(this.inputs,(a,n)=>{const i=it(a[0]),[r,l]=this.transforms[n](he.arr(i)?i:a.map(it));s+=" "+r,t=t&&l}),t?"none":s}observerAdded(s){s==1&&Ye(this.inputs,t=>Ye(t,a=>dt(a)&&$a(a,this)))}observerRemoved(s){s==0&&Ye(this.inputs,t=>Ye(t,a=>dt(a)&&Ka(a,this)))}eventObserved(s){s.type=="change"&&(this._value=null),Ha(this,s)}},F2=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"];Mt.assign({batchedUpdates:Mi.unstable_batchedUpdates,createStringInterpolator:Vr,colors:pl});var E2=yl(F2,{applyAnimatedValues:D2,createAnimatedStyle:s=>new O2(s),getComponentProps:({scrollTop:s,scrollLeft:t,...a})=>a}),yx=E2.animated;function fn(){return fn=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)({}).hasOwnProperty.call(a,n)&&(s[n]=a[n])}return s},fn.apply(null,arguments)}function Nx(s,t){if(s==null)return{};var a={};for(var n in s)if({}.hasOwnProperty.call(s,n)){if(t.indexOf(n)!==-1)continue;a[n]=s[n]}return a}var Yl={container:{display:"flex",alignItems:"center"},sourceChip:{marginRight:7},targetChip:{marginLeft:7,marginRight:7}},V2={center:j2,justify:bx,start:f2,end:g2},U2=function(s){return V2[s]},us={layout:"horizontal",align:"center",sort:"auto",colors:{scheme:"nivo"},nodeOpacity:.75,nodeHoverOpacity:1,nodeHoverOthersOpacity:.15,nodeThickness:12,nodeInnerPadding:0,nodeBorderWidth:1,nodeBorderColor:{from:"color",modifiers:[["darker",.5]]},nodeBorderRadius:0,linkOpacity:.25,linkHoverOpacity:.6,linkHoverOthersOpacity:.15,linkContract:0,linkBlendMode:"multiply",enableLinkGradient:!1,enableLabels:!0,label:"id",labelPosition:"inside",labelPadding:9,labelOrientation:"horizontal",labelTextColor:{from:"color",modifiers:[["darker",.8]]},labelComponent:fx,isInteractive:!0,nodeTooltip:function(s){var t=s.node;return e.jsx(Cd,{id:t.label,enableChip:!0,color:t.color})},linkTooltip:function(s){var t=s.link;return e.jsx(Cd,{id:e.jsxs("span",{style:Yl.container,children:[e.jsx(Sc,{color:t.source.color,style:Yl.sourceChip}),e.jsx("strong",{children:t.source.label})," > ",e.jsx("strong",{children:t.target.label}),e.jsx(Sc,{color:t.target.color,style:Yl.targetChip}),e.jsx("strong",{children:t.formattedValue})]})})},legends:[],layers:["links","nodes","labels","legends"],role:"img",animate:!0,motionConfig:"gentle"},B2=function(s){return s.id},z2=function(s){var t=s.data,a=s.valueFormat,n=s.layout,i=s.width,r=s.height,l=s.sort,c=s.align,o=s.colors,d=s.nodeThickness,u=s.nodeSpacing,x=s.nodeInnerPadding,m=s.nodeBorderColor,v=s.label,g=s.labelTextColor,w=p.useState(null),k=w[0],b=w[1],S=p.useState(null),A=S[0],F=S[1],de=p.useMemo(function(){if(l!=="auto")return l==="input"?null:l==="ascending"?function(O,N){return O.value-N.value}:l==="descending"?function(O,N){return N.value-O.value}:l},[l]),M=l==="input"?null:void 0,G=p.useMemo(function(){return typeof c=="function"?c:U2(c)},[c]),D=Na(),$=q1(o,"id"),se=Kd(m,D),J=T1(v),le=Kd(g,D),C=mx(a),I=p.useMemo(function(){return function(O){var N=O.data,re=O.formatValue,H=O.layout,pe=O.alignFunction,ye=O.sortFunction,Ie=O.linkSortMode,ve=O.nodeThickness,B=O.nodeSpacing,z=O.nodeInnerPadding,K=O.width,P=O.height,ue=O.getColor,V=O.getLabel,U=N2().nodeAlign(pe).nodeSort(ye).linkSort(Ie).nodeWidth(ve).nodePadding(B).size(H==="horizontal"?[K,P]:[P,K]).nodeId(B2),j=_2(N);
78return U(j),j.nodes.forEach(function(Q){if(Q.color=ue(Q),Q.label=V(Q),Q.formattedValue=re(Q.value),H==="horizontal")Q.x=Q.x0+z,Q.y=Q.y0,Q.width=Math.max(Q.x1-Q.x0-2*z,0),Q.height=Math.max(Q.y1-Q.y0,0);else{Q.x=Q.y0,Q.y=Q.x0+z,Q.width=Math.max(Q.y1-Q.y0,0),Q.height=Math.max(Q.x1-Q.x0-2*z,0);var je=Q.x0,ce=Q.x1;Q.x0=Q.y0,Q.x1=Q.y1,Q.y0=je,Q.y1=ce}}),j.links.forEach(function(Q){Q.formattedValue=re(Q.value),Q.color=Q.source.color,Q.pos0=Q.y0,Q.pos1=Q.y1,Q.thickness=Q.width,delete Q.y0,delete Q.y1,delete Q.width}),j}({data:t,formatValue:C,layout:n,alignFunction:G,sortFunction:de,linkSortMode:M,nodeThickness:d,nodeSpacing:u,nodeInnerPadding:x,width:i,height:r,getColor:$,getLabel:J})},[t,C,n,G,de,M,d,u,x,i,r,$,J]),y=I.nodes,f=I.links,R=p.useMemo(function(){return y.map(function(O){return{id:O.id,label:O.label,color:O.color}})},[y]);return{nodes:y,links:f,legendData:R,getNodeBorderColor:se,currentNode:k,setCurrentNode:b,currentLink:A,setCurrentLink:F,getLabelTextColor:le}},q2=function(s){var t=s.node,a=s.x,n=s.y,i=s.width,r=s.height,l=s.color,c=s.opacity,o=s.borderWidth,d=s.borderColor,u=s.borderRadius,x=s.setCurrent,m=s.isInteractive,v=s.onClick,g=s.tooltip,w=vn(),k=w.animate,b=w.config,S=Gn({x:a,y:n,width:i,height:r,opacity:c,color:l,config:b,immediate:!k}),A=Qu(),F=A.showTooltipFromEvent,de=A.hideTooltip,M=p.useCallback(function(se){x(t),F(p.createElement(g,{node:t}),se,"left")},[x,t,F,g]),G=p.useCallback(function(se){F(p.createElement(g,{node:t}),se,"left")},[F,t,g]),D=p.useCallback(function(){x(null),de()},[x,de]),$=p.useCallback(function(se){v==null||v(t,se)},[v,t]);return e.jsx(yx.rect,{x:S.x,y:S.y,rx:u,ry:u,width:S.width.to(function(se){return Math.max(se,0)}),height:S.height.to(function(se){return Math.max(se,0)}),fill:S.color,fillOpacity:S.opacity,strokeWidth:o,stroke:d,strokeOpacity:c,onMouseEnter:m?M:void 0,onMouseMove:m?G:void 0,onMouseLeave:m?D:void 0,onClick:m?$:void 0})},G2=function(s){var t=s.nodes,a=s.nodeOpacity,n=s.nodeHoverOpacity,i=s.nodeHoverOthersOpacity,r=s.borderWidth,l=s.getBorderColor,c=s.borderRadius,o=s.setCurrentNode,d=s.currentNode,u=s.currentLink,x=s.isCurrentNode,m=s.isInteractive,v=s.onClick,g=s.tooltip,w=function(k){return d||u?x(k)?n:i:a};return e.jsx(e.Fragment,{children:t.map(function(k){return e.jsx(q2,{node:k,x:k.x,y:k.y,width:k.width,height:k.height,color:k.color,opacity:w(k),borderWidth:r,borderColor:l(k),borderRadius:c,setCurrent:o,isInteractive:m,onClick:v,tooltip:g},k.id)})})},W2=function(s){var t=s.id,a=s.layout,n=s.startColor,i=s.endColor;return e.jsxs("linearGradient",fn({id:t,spreadMethod:"pad"},a==="horizontal"?{x1:"0%",x2:"100%",y1:"0%",y2:"0%"}:{x1:"0%",x2:"0%",y1:"0%",y2:"100%"},{children:[e.jsx("stop",{offset:"0%",stopColor:n}),e.jsx("stop",{offset:"100%",stopColor:i})]}))},H2=function(s){var t=s.link,a=s.layout,n=s.path,i=s.color,r=s.opacity,l=s.blendMode,c=s.enableGradient,o=s.setCurrent,d=s.tooltip,u=s.isInteractive,x=s.onClick,m=t.source.id+"."+t.target.id+"."+t.index,v=vn(),g=v.animate,w=v.config,k=N1(n),b=Gn({color:i,opacity:r,config:w,immediate:!g}),S=Qu(),A=S.showTooltipFromEvent,F=S.hideTooltip,de=p.useCallback(function($){o(t),A(p.createElement(d,{link:t}),$,"left")},[o,t,A,d]),M=p.useCallback(function($){A(p.createElement(d,{link:t}),$,"left")},[A,t,d]),G=p.useCallback(function(){o(null),F()},[o,F]),D=p.useCallback(function($){x==null||x(t,$)},[x,t]);return e.jsxs(e.Fragment,{children:[c&&e.jsx(W2,{id:m,layout:a,startColor:t.startColor||t.source.color,endColor:t.endColor||t.target.color}),e.jsx(yx.path,{fill:c?'url("#'+encodeURI(m)+'")':b.color,d:k,fillOpacity:b.opacity,onMouseEnter:u?de:void 0,onMouseMove:u?M:void 0,onMouseLeave:u?G:void 0,onClick:u?D:void 0,style:{mixBlendMode:l}})]})},K2=function(s){var t=s.links,a=s.layout,n=s.linkOpacity,i=s.linkHoverOpacity,r=s.linkHoverOthersOpacity,l=s.linkContract,c=s.linkBlendMode,o=s.enableLinkGradient,d=s.setCurrentLink,u=s.currentLink,x=s.currentNode,m=s.isCurrentLink,v=s.isInteractive,g=s.onClick,w=s.tooltip,k=function(S){return x||u?m(S)?i:r:n},b=p.useMemo(function(){return a==="horizontal"?(S=To().curve(Pm),function(A,F){var de=Math.max(1,A.thickness-2*F)/2,M=.12*(A.target.x0-A.source.x1),G=[[A.source.x1,A.pos0-de],[A.source.x1+M,A.pos0-de],[A.target.x0-M,A.pos1-de],[A.target.x0,A.pos1-de],[A.target.x0,A.pos1+de],[A.target.x0-M,A.pos1+de],[A.source.x1+M,A.pos0+de],[A.source.x1,A.pos0+de],[A.source.x1,A.pos0-de]];return S(G)+"Z"}):function(){var A=To().curve(Dm);return function(F,de){var M=Math.max(1,F.thickness-2*de)/2,G=.12*(F.target.y0-F.source.y1),D=[[F.pos0+M,F.source.y1],[F.pos0+M,F.source.y1+G],[F.pos1+M,F.target.y0-G],[F.pos1+M,F.target.y0],[F.pos1-M,F.target.y0],[F.pos1-M,F.target.y0-G],[F.pos0-M,F.source.y1+G],[F.pos0-M,F.source.y1],[F.pos0+M,F.source.y1]];return A(D)+"Z"}}();var S},[a]);return e.jsx(e.Fragment,{children:t.map(function(S){return e.jsx(H2,{link:S,layout:a,path:b(S,l),color:S.color,opacity:k(S),blendMode:c,enableGradient:o,setCurrent:d,isInteractive:v,onClick:g,tooltip:w},S.source.id+"."+S.target.id+"."+S.index)})})},Y2=function(s){var t=s.nodes,a=s.layout,n=s.width,i=s.height,r=s.labelPosition,l=s.labelPadding,c=s.labelOrientation,o=s.getLabelTextColor,d=s.labelComponent,u=Na(),x=c==="vertical"?-90:0,m=t.map(function(b){var S,A,F;return a==="horizontal"?(A=b.y+b.height/2,b.x<n/2?r==="inside"?(S=b.x1+l,F=c==="vertical"?"middle":"start"):(S=b.x-l,F=c==="vertical"?"middle":"end"):r==="inside"?(S=b.x-l,F=c==="vertical"?"middle":"end"):(S=b.x1+l,F=c==="vertical"?"middle":"start")):a==="vertical"&&(S=b.x+b.width/2,b.y<i/2?r==="inside"?(A=b.y1+l,F=c==="vertical"?"end":"middle"):(A=b.y-l,F=c==="vertical"?"start":"middle"):r==="inside"?(A=b.y-l,F=c==="vertical"?"start":"middle"):(A=b.y1+l,F=c==="vertical"?"end":"middle")),{id:b.id,label:b.label,x:S,y:A,textAnchor:F,color:o(b)}}),v=vn(),g=v.animate,w=v.config,k=Iu(m.length,m.map(function(b){return{transform:"translate("+b.x+", "+b.y+") rotate("+x+")",color:b.color,config:w,immediate:!g}}));return e.jsx(e.Fragment,{children:k.map(function(b,S){var A=m[S];return e.jsx(d,{dominantBaseline:"central",textAnchor:A.textAnchor,transform:b.transform,style:fn({},u.labels.text,{fill:b.color,pointerEvents:"none"}),node:t[S],children:A.label},A.id)})})},Q2=["isInteractive","animate","motionConfig","theme","renderWrapper"],X2=function(s){var t=s.data,a=s.valueFormat,n=s.layout,i=n===void 0?us.layout:n,r=s.sort,l=r===void 0?us.sort:r,c=s.align,o=c===void 0?us.align:c,d=s.width,u=s.height,x=s.margin,m=s.colors,v=m===void 0?us.colors:m,g=s.nodeThickness,w=g===void 0?us.nodeThickness:g,k=s.nodeSpacing,b
78=k===void 0?us.nodeThickness:k,S=s.nodeInnerPadding,A=S===void 0?us.nodeInnerPadding:S,F=s.nodeBorderColor,de=F===void 0?us.nodeBorderColor:F,M=s.nodeOpacity,G=M===void 0?us.nodeOpacity:M,D=s.nodeHoverOpacity,$=D===void 0?us.nodeHoverOpacity:D,se=s.nodeHoverOthersOpacity,J=se===void 0?us.nodeHoverOthersOpacity:se,le=s.nodeBorderWidth,C=le===void 0?us.nodeBorderWidth:le,I=s.nodeBorderRadius,y=I===void 0?us.nodeBorderRadius:I,f=s.linkOpacity,R=f===void 0?us.linkOpacity:f,O=s.linkHoverOpacity,N=O===void 0?us.linkHoverOpacity:O,re=s.linkHoverOthersOpacity,H=re===void 0?us.linkHoverOthersOpacity:re,pe=s.linkContract,ye=pe===void 0?us.linkContract:pe,Ie=s.linkBlendMode,ve=Ie===void 0?us.linkBlendMode:Ie,B=s.enableLinkGradient,z=B===void 0?us.enableLinkGradient:B,K=s.enableLabels,P=K===void 0?us.enableLabels:K,ue=s.labelComponent,V=ue===void 0?us.labelComponent:ue,U=s.labelPosition,j=U===void 0?us.labelPosition:U,Q=s.labelPadding,je=Q===void 0?us.labelPadding:Q,ce=s.labelOrientation,be=ce===void 0?us.labelOrientation:ce,ss=s.label,oe=ss===void 0?us.label:ss,Ne=s.labelTextColor,Le=Ne===void 0?us.labelTextColor:Ne,ae=s.nodeTooltip,xe=ae===void 0?us.nodeTooltip:ae,Fe=s.linkTooltip,X=Fe===void 0?us.linkTooltip:Fe,Be=s.isInteractive,ns=Be===void 0?us.isInteractive:Be,nt=s.onClick,ks=s.legends,Rt=ks===void 0?us.legends:ks,wt=s.layers,jt=wt===void 0?us.layers:wt,rs=s.role,ea=rs===void 0?us.role:rs,Je=s.ariaLabel,da=s.ariaLabelledBy,qt=s.ariaDescribedBy,Js=s.forwardedRef,qs=C1(d,u,x),ie=qs.margin,te=qs.innerWidth,fe=qs.innerHeight,ge=qs.outerWidth,We=qs.outerHeight,we=z2({data:t,valueFormat:a,layout:i,width:te,height:fe,sort:l,align:o,colors:v,nodeThickness:w,nodeSpacing:b,nodeInnerPadding:A,nodeBorderColor:de,label:oe,labelTextColor:Le}),gs=we.nodes,Ss=we.links,L=we.legendData,Re=we.getNodeBorderColor,Ge=we.currentNode,$e=we.setCurrentNode,Qe=we.currentLink,js=we.setCurrentLink,ze=we.getLabelTextColor,Ns=p.useMemo(function(){var Xe=function(){return!1},ls=function(){return!1};if(Qe&&(Xe=function(Ds){var _s=Ds.id;return _s===Qe.source.id||_s===Qe.target.id},ls=function(Ds){var _s=Ds.source,h=Ds.target;return _s.id===Qe.source.id&&h.id===Qe.target.id}),Ge){var As=[Ge.id];Ss.filter(function(Ds){var _s=Ds.source,h=Ds.target;return _s.id===Ge.id||h.id===Ge.id}).forEach(function(Ds){var _s=Ds.source,h=Ds.target;As.push(_s.id),As.push(h.id)}),As=gb(As),Xe=function(Ds){var _s=Ds.id;return As.includes(_s)},ls=function(Ds){var _s=Ds.source,h=Ds.target;return _s.id===Ge.id||h.id===Ge.id}}return{isCurrentNode:Xe,isCurrentLink:ls}},[Qe,Ge,Ss]),He=Ns.isCurrentNode,Gs=Ns.isCurrentLink,ne=p.useMemo(function(){return{links:Ss,nodes:gs,margin:ie,width:d,height:u,outerWidth:ge,outerHeight:We,currentNode:Ge,isCurrentNode:He,setCurrentNode:$e,currentLink:Qe,isCurrentLink:Gs,setCurrentLink:js,isInteractive:ns}},[Ss,gs,ie,d,u,ge,We,Ge,He,$e,Qe,Gs,js,ns]),ke={links:null,nodes:null,labels:null,legends:null};return jt.includes("links")&&(ke.links=e.jsx(K2,{links:Ss,layout:i,linkContract:ye,linkOpacity:R,linkHoverOpacity:N,linkHoverOthersOpacity:H,linkBlendMode:ve,enableLinkGradient:z,setCurrentLink:js,currentNode:Ge,currentLink:Qe,isCurrentLink:Gs,isInteractive:ns,onClick:nt,tooltip:X},"links")),jt.includes("nodes")&&(ke.nodes=e.jsx(G2,{nodes:gs,nodeOpacity:G,nodeHoverOpacity:$,nodeHoverOthersOpacity:J,borderWidth:C,borderRadius:y,getBorderColor:Re,setCurrentNode:$e,currentNode:Ge,currentLink:Qe,isCurrentNode:He,isInteractive:ns,onClick:nt,tooltip:xe},"nodes")),jt.includes("labels")&&P&&(ke.labels=e.jsx(Y2,{nodes:gs,layout:i,width:te,height:fe,labelPosition:j,labelPadding:je,labelOrientation:be,getLabelTextColor:ze,labelComponent:V},"labels")),jt.includes("legends")&&(ke.legends=e.jsx(p.Fragment,{children:Rt.map(function(Xe,ls){return e.jsx(h2,fn({},Xe,{containerWidth:te,containerHeight:fe,data:L}),"legend"+ls)})},"legends")),e.jsx(b1,{width:ge,height:We,margin:ie,role:ea,ariaLabel:Je,ariaLabelledBy:da,ariaDescribedBy:qt,ref:Js,children:jt.map(function(Xe,ls){var As;return typeof Xe=="function"?e.jsx(p.Fragment,{children:p.createElement(Xe,ne)},ls):(As=ke==null?void 0:ke[Xe])!=null?As:null})})},Z2=p.forwardRef(function(s,t){var a=s.isInteractive,n=a===void 0?us.isInteractive:a,i=s.animate,r=i===void 0?us.animate:i,l=s.motionConfig,c=l===void 0?us.motionConfig:l,o=s.theme,d=s.renderWrapper,u=Nx(s,Q2);return e.jsx(i1,{animate:r,isInteractive:n,motionConfig:c,renderWrapper:d,theme:o,children:e.jsx(X2,fn({isInteractive:n},u,{forwardedRef:t}))})}),J2=["defaultWidth","defaultHeight","onResize","debounceResize"],e4=p.forwardRef(function(s,t){var a=s.defaultWidth,n=s.defaultHeight,i=s.onResize,r=s.debounceResize,l=Nx(s,J2);return e.jsx(o1,{defaultWidth:a,defaultHeight:n,onResize:i,debounceResize:r,children:function(c){var o=c.width,d=c.height;return e.jsx(Z2,fn({width:o,height:d},l,{ref:t}))}})});console.log("[MARKETING_INSIGHTS] Static mock insights removed - awaiting real data implementation");function s4({section:s,errors:t}){const a=t==null?void 0:t.find(n=>n.section===s);return a?e.jsxs(Qs,{variant:"destructive",className:"mt-2",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsxs(Xs,{className:"text-xs",children:[e.jsx("span",{className:"font-medium",children:"API Error:"})," ",a.error||"Unknown error - check server logs"]})]}):null}function Lt(s){if(s==null)return"â";const t=typeof s=="string"?parseFloat(s):s;if(isNaN(t))return"â";const a=Math.floor(t/60),n=Math.round(t%60);return a>=1e3?`${(a/1e3).toFixed(1)}Kh`:a>0?`${a}h ${n}m`:`${n}m`}function is(s){if(s==null)return"â";const t=typeof s=="string"?parseFloat(s):s;return isNaN(t)?"â":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}
78K`:t.toLocaleString()}function An(s){if(s==null)return"â";const t=typeof s=="string"?parseFloat(s):s;return isNaN(t)?"â":`${t.toFixed(1)}%`}function et(s){if(s==null)return"â";const t=typeof s=="string"?parseFloat(s):s;return isNaN(t)?"â":`$${t.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Pn(s){if(s==null)return"â";const t=typeof s=="string"?parseFloat(s):s;return isNaN(t)?"â":`${t.toFixed(2)}%`}function Ws(s){if(s==null)return"â";const t=typeof s=="string"?parseFloat(s):s;return isNaN(t)?"â":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Fa(s){return s==null?"N/A":typeof s!="string"?String(s):s.replace(/_/g," ")}function It(s){return s==null?"":typeof s!="string"?String(s).toLowerCase():s.toLowerCase()}function Ql({score:s}){return s==null?e.jsx(Y,{variant:"outline",className:"text-xs",children:"N/A"}):s>=7?e.jsxs(Y,{className:"bg-green-500 text-white text-xs",children:["QS: ",s]}):s>=4?e.jsxs(Y,{className:"bg-yellow-500 text-white text-xs",children:["QS: ",s]}):e.jsxs(Y,{variant:"destructive",className:"text-xs",children:["QS: ",s]})}function Qa({status:s}){if(s==null)return e.jsx(Y,{variant:"outline",className:"text-xs",children:"Unknown"});const t=typeof s=="string"?s:String(s),a=t.toLowerCase();return a==="enabled"||a==="active"?e.jsx(Y,{className:"bg-green-500 text-white text-xs",children:t}):a==="paused"?e.jsx(Y,{className:"bg-yellow-500 text-white text-xs",children:t}):e.jsx(Y,{variant:"secondary",className:"text-xs",children:t})}function t4({open:s,onClose:t,timeRange:a}){var Ie,ve,B,z,K,P,ue,V,U;const[n,i]=p.useState("campaigns"),[r,l]=p.useState(null),[c,o]=p.useState(null),[d,u]=p.useState(null),[x,m]=p.useState(null),{data:v,isLoading:g}=_e({queryKey:[`/api/google-ads/summary?range=${a}`],enabled:s}),{data:w}=_e({queryKey:[`/api/google-ads/hourly-performance?range=${a}`],enabled:s&&n==="performance"}),{data:k}=_e({queryKey:[`/api/google-ads/daily-performance?range=${a}`],enabled:s&&n==="performance"}),{data:b}=_e({queryKey:[`/api/google-ads/devices?range=${a}`],enabled:s&&n==="performance"}),{data:S}=_e({queryKey:[`/api/google-ads/pmax-asset-groups/paginated?range=${a}`],enabled:s&&n==="advanced"}),{data:A}=_e({queryKey:[`/api/google-ads/conversion-actions/paginated?range=${a}`],enabled:s&&n==="advanced"}),{data:F}=_e({queryKey:["/api/google-ads/quality-scores-details"],enabled:s&&n==="advanced"}),{data:de}=_e({queryKey:[`/api/google-ads/landing-page-speed?range=${a}`],enabled:s&&n==="advanced"}),{data:M}=_e({queryKey:[`/api/google-ads/budget-utilization?range=${a}`],enabled:s&&n==="advanced"}),G=["#3B82F6","#10B981","#F59E0B","#EF4444","#8B5CF6","#EC4899"],D=p.useMemo(()=>{const j=new Date;let Q=new Date;switch(a){case"7d":Q.setDate(j.getDate()-7);break;case"30d":Q.setDate(j.getDate()-30);break;case"90d":Q.setDate(j.getDate()-90);break;case"1y":Q.setFullYear(j.getFullYear()-1);break;default:Q.setDate(j.getDate()-30)}return{startDate:Q,endDate:j}},[a]),$=j=>{i(j),l(null),o(null),u(null),m(null)},se=j=>{l(j.campaignId||j.id),o(j.campaignName||j.name),u(null),m(null)},J=j=>{u(j.adGroupId||j.id),m(j.adGroupName||j.name)},le=()=>{l(null),o(null),u(null),m(null)},C=()=>{u(null),m(null)},I=p.useMemo(()=>[{key:"campaignName",header:"Campaign Name",sortable:!0},{key:"status",header:"Status",sortable:!0,render:j=>e.jsx(Qa,{status:j})},{key:"campaignType",header:"Type",sortable:!0},{key:"cost",header:"Spend",sortable:!0,render:j=>et(j)},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"ctr",header:"CTR",sortable:!0,render:j=>Pn(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)},{key:"costPerConversion",header:"Cost/Conv",sortable:!0,render:j=>et(j)}],[]),y=p.useMemo(()=>[{key:"adGroupName",header:"Ad Group Name",sortable:!0},{key:"campaignName",header:"Campaign",sortable:!0},{key:"status",header:"Status",sortable:!0,render:j=>e.jsx(Qa,{status:j})},{key:"cost",header:"Spend",sortable:!0,render:j=>et(j)},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)}],[]),f=p.useMemo(()=>[{key:"adType",header:"Ad Type",sortable:!0},{key:"headlines",header:"Headlines",sortable:!1,render:(j,Q)=>e.jsx("div",{className:"max-w-xs truncate",title:j||Q.headline1,children:j||Q.headline1||"â"})},{key:"finalUrl",header:"Final URL",sortable:!1,render:j=>e.jsx("div",{className:"max-w-xs truncate text-blue-600",title:j,children:j||"â"})},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"ctr",header:"CTR",sortable:!0,render:j=>Pn(j)},{key:"cost",header:"Cost",sortable:!0,render:j=>et(j)}],[]),R=p.useMemo(()=>[{key:"keyword",header:"Keyword",sortable:!0},{key:"matchType",header:"Match Type",sortable:!0,render:j=>e.jsx(Y,{variant:"outline",className:"text-xs",children:j||"UNKNOWN"})},{key:"qualityScore",header:"Quality Score",sortable:!0,render:j=>e.jsx(Ql,{score:j})},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"avgCpc",header:"Avg CPC",sortable:!0,render:j=>et(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)}],[]),O=p.useMemo(()=>[{key:"searchTerm",header:"Search Term",sortable:!0},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"ctr",header:"CTR",sortable:!0,render:j=>Pn(j)},{key:"cost",header:"Cost",sortable:!0,render:j=>et(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)}],[]),N=p.useMemo(()=>[{key:"landingPageUrl",header:"Landing Page URL",sortable:!0,render:j=>e.jsx("div",{className:"max-w-md truncate text-blue-600",title:j,children:j||"â"})},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"cost",header:"Cost",sortable:!0,render:j=>et(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)}],[]),re=p.useMemo(()=>[{key:"country",header:"Country",sortable:!0}
78,{key:"region",header:"Region",sortable:!0},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"cost",header:"Cost",sortable:!0,render:j=>et(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)}],[]),H=p.useMemo(()=>[{key:"domain",header:"Competitor Domain",sortable:!0},{key:"impressionShare",header:"Impression Share",sortable:!0,render:j=>An(j)},{key:"overlapRate",header:"Overlap Rate",sortable:!0,render:j=>An(j)},{key:"positionAboveRate",header:"Position Above Rate",sortable:!0,render:j=>An(j)},{key:"topOfPageRate",header:"Top of Page Rate",sortable:!0,render:j=>An(j)}],[]),pe=p.useMemo(()=>[{key:"assetGroupName",header:"Asset Group",sortable:!0},{key:"campaignName",header:"Campaign",sortable:!0},{key:"status",header:"Status",sortable:!0,render:j=>e.jsx(Qa,{status:j})},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"ctr",header:"CTR",sortable:!0,render:j=>Pn(j)},{key:"cost",header:"Cost",sortable:!0,render:j=>et(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)},{key:"costPerConversion",header:"CPA",sortable:!0,render:j=>et(j)}],[]);p.useMemo(()=>[{key:"conversionActionName",header:"Conversion Action",sortable:!0},{key:"category",header:"Category",sortable:!0,render:j=>e.jsx(Y,{variant:"outline",className:"text-xs",children:Fa(j)})},{key:"type",header:"Type",sortable:!0},{key:"status",header:"Status",sortable:!0,render:j=>e.jsx(Qa,{status:j})},{key:"conversions",header:"Conversions",sortable:!0,render:j=>is(j)},{key:"conversionValue",header:"Value",sortable:!0,render:j=>et(j)},{key:"costPerConversion",header:"Cost/Conv",sortable:!0,render:j=>et(j)},{key:"conversionRate",header:"Conv Rate",sortable:!0,render:j=>An(j)}],[]),p.useMemo(()=>[{key:"keywordText",header:"Keyword",sortable:!0},{key:"matchType",header:"Match Type",sortable:!0,render:j=>e.jsx(Y,{variant:"outline",className:"text-xs",children:j||"UNKNOWN"})},{key:"qualityScore",header:"Quality Score",sortable:!0,render:j=>e.jsx(Ql,{score:j})},{key:"landingPageExperience",header:"Landing Page",sortable:!0,render:j=>e.jsx(Y,{variant:j==="ABOVE_AVERAGE"?"default":j==="AVERAGE"?"secondary":"destructive",className:"text-xs",children:Fa(j)})},{key:"expectedCtr",header:"Expected CTR",sortable:!0,render:j=>e.jsx(Y,{variant:j==="ABOVE_AVERAGE"?"default":j==="AVERAGE"?"secondary":"destructive",className:"text-xs",children:Fa(j)})},{key:"adRelevance",header:"Ad Relevance",sortable:!0,render:j=>e.jsx(Y,{variant:j==="ABOVE_AVERAGE"?"default":j==="AVERAGE"?"secondary":"destructive",className:"text-xs",children:Fa(j)})},{key:"adGroupName",header:"Ad Group",sortable:!0},{key:"campaignName",header:"Campaign",sortable:!0}],[]),p.useMemo(()=>[{key:"landingPageUrl",header:"Landing Page URL",sortable:!0,render:j=>e.jsx("div",{className:"max-w-md truncate text-blue-600",title:j,children:j||"â"})},{key:"mobileSpeedScore",header:"Speed Score",sortable:!0,render:j=>{if(j==null)return e.jsx(Y,{variant:"outline",children:"N/A"});const Q=typeof j=="string"?parseFloat(j):j;return isNaN(Q)?e.jsx(Y,{variant:"outline",children:"N/A"}):e.jsx(Y,{className:Q>=80?"bg-green-500":Q>=50?"bg-yellow-500":"bg-red-500",children:Q})}},{key:"mobileFriendlyClickRate",header:"Mobile Friendly %",sortable:!0,render:j=>An(j)},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"cost",header:"Cost",sortable:!0,render:j=>et(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)}],[]),p.useMemo(()=>[{key:"campaignName",header:"Campaign",sortable:!0},{key:"campaignStatus",header:"Status",sortable:!0,render:j=>e.jsx(Qa,{status:j})},{key:"dailyBudget",header:"Daily Budget",sortable:!0,render:j=>et(j)},{key:"actualSpend",header:"Actual Spend",sortable:!0,render:j=>et(j)},{key:"utilizationPercentage",header:"Utilization",sortable:!0,render:(j,Q)=>{const je=typeof j=="string"?parseFloat(j):j,ce=je==null||isNaN(je)?0:je,be=Q.utilizationStatus;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{value:Math.min(ce,100),className:"w-20 h-2"}),e.jsxs(Y,{className:be==="over"?"bg-red-500":be==="under"?"bg-amber-500":"bg-green-500",children:[ce.toFixed(0),"%"]})]})}},{key:"impressions",header:"Impressions",sortable:!0,render:j=>Ws(j)},{key:"clicks",header:"Clicks",sortable:!0,render:j=>Ws(j)},{key:"conversions",header:"Conv.",sortable:!0,render:j=>is(j)}],[]);const ye=p.useMemo(()=>[{key:"status",label:"Status",options:[{value:"ENABLED",label:"Enabled"},{value:"PAUSED",label:"Paused"},{value:"REMOVED",label:"Removed"}]}],[]);return s?e.jsx(Vs,{open:s,onOpenChange:t,children:e.jsxs(Us,{className:"max-w-6xl max-h-[90vh] overflow-hidden","data-testid":"google-ads-drilldown",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-2 text-xl",children:[e.jsx(ct,{className:"h-6 w-6 text-blue-500"}),"Google Ads Deep Dive",e.jsx(Y,{variant:"outline",className:"ml-2",children:"Live API Data"})]}),(v==null?void 0:v.fetchedAt)&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground mt-1",children:[e.jsx(ra,{className:"h-3 w-3"}),e.jsxs("span",{children:["Last synced: ",De(new Date(v.fetchedAt),"MMM d, yyyy h:mm a")]})]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-4 mb-4",children:[e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx(ct,{className:"h-5 w-5 mx-auto mb-1 text-green-500"}),e.jsx("div",{className:"text-2xl font-bold",children:et((v==null?void 0:v.totalCost)||(v==null?void 0:v.totalSpend))}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Spend"})]})}),e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx(Hs,{className:"h-5 w-5 mx-auto mb-1 text-blue-500"}),e.jsx("div",{className:"text-2xl font-bold",children:Ws(v==null?void 0:v.totalImpressions)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Impressions"})]})}),e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx(Nr,{className:"h-5 w-5 mx-auto mb-1 text-purple-500"}),e.jsx("div",{className:"text-2xl font-bold",children:Ws(v==null?void 0:v.totalClicks)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clicks"})]})}),e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx(lt,{className:"h-5 w-5 mx-auto mb-1 text-orange-500"}),e.jsx("div",{className:"text-2xl font-bold",children:is(v==null?void 0:v.totalConversions)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Conversions"})]})})]}),e.jsxs(la,{value:n,onValueChange:$,className:"flex-1",children:[e.jsxs(ca,{className:"grid w-full grid-cols-5",children:[e.jsxs(Ee,{value:"campaigns",className:"flex items-center gap-2","data-testid":"tab-campaigns",children:[e.jsx(Zs,{className:"h-4 w-4"}),"Campaigns"]}),e.jsxs(Ee,{value:"ads",className:"flex items-center gap-2","data-testid":"tab-ads",children:[e.jsx(fa,{className:"h-4 w-4"}),"Ads & Keywords"]}),e.jsxs(Ee,{value:"search",className:"flex items-center gap-2","data-testid":"tab-search",children:[e.jsx(ga,{className:"h-4 w-4"}),"Search & Landing"]}),e.jsxs(Ee,{value:"performance",className:"flex items-center gap-2","data-testid":"tab-performance",children:[e.jsx(ja,{className:"h-4 w-4"}),"Performance"]}),e.jsxs(Ee,{value:"advanced",className:"flex items-center gap-2","data-testid":"tab-advanced",children:[e.jsx(oa,{className:"h-4 w-4"}),"Advanced"]})]}),e.jsxs(kt,{className:"h-[55vh] mt-4",children:[e.jsxs(Ve,{value:"campaigns",className:"space-y-6 mt-0",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Zs,{className:"h-5 w-5 text-blue-500"}),"Campaigns",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(click row to filter ad groups)"})]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:"/api/google-ads/campaigns/paginated",columns:I,title:"",dateRange:D,searchable:!0,exportable:!0,filterOptions:ye,onRowClick:se})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(lt,{className:"h-5 w-5 text-green-500"}),"Ad Groups",c&&e.jsxs(Y,{variant:"secondary",className:"ml-2",children:["Filtered by: ",c,e.jsx("button",{onClick:le,className:"ml-1 hover:text-destructive",children:e.jsx(pt,{className:"h-3 w-3"})})]})]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:r?`/api/google-ads/ad-groups/paginated?campaignId=${r}`:"/api/google-ads/ad-groups/paginated",columns:y,title:"",dateRange:D,searchable:!0,exportable:!0,onRowClick:J})})]}),r&&e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Cl,{className:"h-5 w-5 text-yellow-500"}),"Auction Insights",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:["for ",c]})]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:`/api/google-ads/auction-insights/paginated?campaignId=${r}`,columns:H,title:"",dateRange:D,exportable:!0,emptyMessage:"No auction insights available for this campaign"})})]})]}),e.jsxs(Ve,{value:"ads",className:"space-y-6 mt-0",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(fa,{className:"h-5 w-5 text-amber-500"}),"Ads",c&&e.jsxs(Y,{variant:"secondary",className:"ml-2",children:["Campaign: ",c,e.jsx("button",{onClick:le,className:"ml-1 hover:text-destructive",children:e.jsx(pt,{className:"h-3 w-3"})})]}),x&&e.jsxs(Y,{variant:"secondary",className:"ml-2",children:["Ad Group: ",x,e.jsx("button",{onClick:C,className:"ml-1 hover:text-destructive",children:e.jsx(pt,{className:"h-3 w-3"})})]})]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:d?`/api/google-ads/ads/paginated?adGroupId=${d}`:r?`/api/google-ads/ads/paginated?campaignId=${r}`:"/api/google-ads/ads/paginated",columns:f,title:"",dateRange:D,searchable:!0,exportable:!0})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Cl,{className:"h-5 w-5 text-yellow-500"}),"Keywords",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(Quality Score: green â¥7, yellow 4-6, red <4)"})]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:d?`/api/google-ads/keywords/paginated?adGroupId=${d}`:r?`/api/google-ads/keywords/paginated?campaignId=${r}`:"/api/google-ads/keywords/paginated",columns:R,title:"",dateRange:D,searchable:!0,exportable:!0})})]})]}),e.jsxs(Ve,{value:"search",className:"space-y-6 mt-0",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ga,{className:"h-5 w-5 text-indigo-500"}
78),"Search Terms",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(what users actually typed)"})]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:"/api/google-ads/search-terms/paginated",columns:O,title:"",dateRange:D,searchable:!0,exportable:!0})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ot,{className:"h-5 w-5 text-blue-500"}),"Landing Pages"]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:"/api/google-ads/landing-pages/paginated",columns:N,title:"",dateRange:D,searchable:!0,exportable:!0})})]})]}),e.jsxs(Ve,{value:"performance",className:"space-y-6 mt-0",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(tt,{className:"h-5 w-5 text-purple-500"}),"Device Performance"]})}),e.jsx(T,{children:((Ie=b==null?void 0:b.devices)==null?void 0:Ie.length)>0?e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(wr,{children:[e.jsx(kr,{data:b.devices,dataKey:"clicks",nameKey:"device",cx:"50%",cy:"50%",outerRadius:80,label:({name:j,percent:Q})=>{const je=Q*100;return`${j} ${isNaN(je)?0:je.toFixed(0)}%`},children:b.devices.map((j,Q)=>e.jsx(dn,{fill:G[Q%G.length]},`cell-${Q}`))}),e.jsx(gt,{})]})})}),e.jsx("div",{className:"space-y-3",children:b.devices.map((j,Q)=>{var ce;const je=It(j.device);return e.jsxs("div",{className:"flex justify-between items-center p-3 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[je.includes("mobile")&&e.jsx(Ht,{className:"h-4 w-4 text-blue-500"}),je.includes("desktop")&&e.jsx(tt,{className:"h-4 w-4 text-purple-500"}),je.includes("tablet")&&e.jsx(Ga,{className:"h-4 w-4 text-green-500"}),je.includes("connected")&&e.jsx(Im,{className:"h-4 w-4 text-orange-500"}),!["mobile","desktop","tablet","connected"].some(be=>je.includes(be))&&e.jsx(ot,{className:"h-4 w-4 text-ink-soft"}),e.jsx("span",{className:"font-medium",children:j.device})]}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsxs("div",{className:"font-medium",children:[((ce=j.clicks)==null?void 0:ce.toLocaleString())||0," clicks"]}),e.jsx("div",{className:"text-muted-foreground",children:et(j.cost)}),e.jsx("div",{className:"text-xs text-blue-600",children:Pn(j.ctr)})]})]},Q)})})]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No device data available"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ra,{className:"h-5 w-5 text-orange-500"}),"Hourly Performance"]})}),e.jsx(T,{children:((ve=w==null?void 0:w.hourly)==null?void 0:ve.length)>0||((B=w==null?void 0:w.hourOfDay)==null?void 0:B.length)>0?e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(Vc,{data:w.hourly||w.hourOfDay,children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"hour",tickFormatter:j=>`${j}:00`}),e.jsx(at,{yAxisId:"left"}),e.jsx(at,{yAxisId:"right",orientation:"right"}),e.jsx(gt,{}),e.jsx(On,{}),e.jsx(Vt,{yAxisId:"left",type:"monotone",dataKey:"clicks",stroke:"#3B82F6",name:"Clicks",strokeWidth:2}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"conversions",stroke:"#10B981",name:"Conversions",strokeWidth:2})]})})}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No hourly data available"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ja,{className:"h-5 w-5 text-cyan-500"}),"Day of Week Performance"]})}),e.jsx(T,{children:((z=k==null?void 0:k.daily)==null?void 0:z.length)>0||((K=k==null?void 0:k.dayOfWeek)==null?void 0:K.length)>0?e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(Lr,{data:k.daily||k.dayOfWeek,children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"dayName"}),e.jsx(at,{}),e.jsx(gt,{}),e.jsx(On,{}),e.jsx(Zt,{dataKey:"clicks",fill:"#3B82F6",name:"Clicks"}),e.jsx(Zt,{dataKey:"conversions",fill:"#10B981",name:"Conversions"})]})})}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No day of week data available"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(sn,{className:"h-5 w-5 text-green-500"}),"Geographic Performance"]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:"/api/google-ads/geography/paginated",columns:re,title:"",dateRange:D,searchable:!0,exportable:!0})})]})]}),e.jsxs(Ve,{value:"advanced",className:"space-y-6 mt-0",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ct,{className:"h-5 w-5 text-green-500"}),"Budget Utilization",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(Under 80% = amber, Over 100% = red, 80-100% = optimal)"})]})}),e.jsx(T,{children:((P=M==null?void 0:M.data)==null?void 0:P.length)>
780?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-4",children:[e.jsx(_,{className:"bg-green-50 dark:bg-green-950",children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:M.data.filter(j=>j.utilizationStatus==="optimal").length}),e.jsx("div",{className:"text-xs text-green-700 dark:text-green-400",children:"Optimal Pacing"})]})}),e.jsx(_,{className:"bg-amber-50 dark:bg-amber-950",children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-amber-600",children:M.data.filter(j=>j.utilizationStatus==="under").length}),e.jsx("div",{className:"text-xs text-amber-700 dark:text-amber-400",children:"Under-spending"})]})}),e.jsx(_,{className:"bg-red-50 dark:bg-red-950",children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-red-600",children:M.data.filter(j=>j.utilizationStatus==="over").length}),e.jsx("div",{className:"text-xs text-red-700 dark:text-red-400",children:"Over-spending"})]})})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-3",children:"Campaign"}),e.jsx("th",{className:"text-left p-3",children:"Status"}),e.jsx("th",{className:"text-right p-3",children:"Daily Budget"}),e.jsx("th",{className:"text-right p-3",children:"Actual Spend"}),e.jsx("th",{className:"text-center p-3",children:"Utilization"})]})}),e.jsx("tbody",{children:M.data.map((j,Q)=>e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"p-3 font-medium",children:j.campaignName}),e.jsx("td",{className:"p-3",children:e.jsx(Qa,{status:j.campaignStatus})}),e.jsx("td",{className:"p-3 text-right",children:et(j.dailyBudget)}),e.jsx("td",{className:"p-3 text-right",children:et(j.actualSpend)}),e.jsx("td",{className:"p-3",children:e.jsx("div",{className:"flex items-center justify-center gap-2",children:(()=>{const je=j.utilizationPercentage,ce=typeof je=="string"?parseFloat(je):je,be=ce==null||isNaN(ce)?0:ce;return e.jsxs(e.Fragment,{children:[e.jsx(mt,{value:Math.min(be,100),className:"w-16 h-2"}),e.jsxs(Y,{className:j.utilizationStatus==="over"?"bg-red-500":j.utilizationStatus==="under"?"bg-amber-500":"bg-green-500",children:[be.toFixed(0),"%"]})]})})()})})]},Q))})]})})]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No budget utilization data available"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Cl,{className:"h-5 w-5 text-yellow-500"}),"Quality Score Dashboard",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(Green â¥7, Yellow 4-6, Red <4)"})]})}),e.jsx(T,{children:F!=null&&F.aggregates?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4 mb-4",children:[e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-blue-600",children:F.aggregates.averageQualityScore!=null&&!isNaN(F.aggregates.averageQualityScore)?F.aggregates.averageQualityScore.toFixed(1):"N/A"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Avg Quality Score"})]})}),e.jsx(_,{className:"bg-green-50 dark:bg-green-950",children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:F.aggregates.keywordsWithHighQS||0}),e.jsx("div",{className:"text-xs text-green-700 dark:text-green-400",children:"High QS (7-10)"})]})}),e.jsx(_,{className:"bg-yellow-50 dark:bg-yellow-950",children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-yellow-600",children:F.aggregates.keywordsWithMediumQS||0}),e.jsx("div",{className:"text-xs text-yellow-700 dark:text-yellow-400",children:"Medium QS (4-6)"})]})}),e.jsx(_,{className:"bg-red-50 dark:bg-red-950",children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-red-600",children:F.aggregates.keywordsWithLowQS||0}),e.jsx("div",{className:"text-xs text-red-700 dark:text-red-400",children:"Low QS (1-3)"})]})})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs(Y,{variant:"outline",children:[F.aggregates.percentHighQS!=null&&!isNaN(F.aggregates.percentHighQS)?F.aggregates.percentHighQS.toFixed(1):0,"% of keywords have QS ⥠7"]}),e.jsxs(Y,{variant:"outline",children:[(F.aggregates.totalKeywords||0).toLocaleStr
78ing()," total keywords"]})]}),((ue=F.qualityScores)==null?void 0:ue.length)>0&&e.jsx("div",{className:"border rounded-lg overflow-hidden max-h-64 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2",children:"Keyword"}),e.jsx("th",{className:"text-center p-2",children:"QS"}),e.jsx("th",{className:"text-center p-2",children:"Landing Page"}),e.jsx("th",{className:"text-center p-2",children:"CTR"}),e.jsx("th",{className:"text-center p-2",children:"Ad Relevance"})]})}),e.jsx("tbody",{children:F.qualityScores.slice(0,50).map((j,Q)=>e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"p-2 font-medium",children:j.keywordText}),e.jsx("td",{className:"p-2 text-center",children:e.jsx(Ql,{score:j.qualityScore})}),e.jsx("td",{className:"p-2 text-center",children:e.jsx(Y,{variant:j.landingPageExperience==="ABOVE_AVERAGE"?"default":j.landingPageExperience==="AVERAGE"?"secondary":"destructive",className:"text-xs",children:Fa(j.landingPageExperience)})}),e.jsx("td",{className:"p-2 text-center",children:e.jsx(Y,{variant:j.expectedCtr==="ABOVE_AVERAGE"?"default":j.expectedCtr==="AVERAGE"?"secondary":"destructive",className:"text-xs",children:Fa(j.expectedCtr)})}),e.jsx("td",{className:"p-2 text-center",children:e.jsx(Y,{variant:j.adRelevance==="ABOVE_AVERAGE"?"default":j.adRelevance==="AVERAGE"?"secondary":"destructive",className:"text-xs",children:Fa(j.adRelevance)})})]},Q))})]})})]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No quality score data available"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(lt,{className:"h-5 w-5 text-purple-500"}),"Conversion Actions",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(what's driving results)"})]})}),e.jsx(T,{children:((V=A==null?void 0:A.data)==null?void 0:V.length)>0?e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(wr,{children:[e.jsx(kr,{data:A.data.slice(0,6).map(j=>({name:j.conversionActionName,value:parseFloat(j.conversions)||0})),dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:j,percent:Q})=>{const je=Q*100;return`${j==null?void 0:j.slice(0,15)}... ${isNaN(je)?0:je.toFixed(0)}%`},children:A.data.slice(0,6).map((j,Q)=>e.jsx(dn,{fill:G[Q%G.length]},`cell-${Q}`))}),e.jsx(gt,{})]})})}),e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:A.data.slice(0,10).map((j,Q)=>e.jsxs("div",{className:"flex justify-between items-center p-2 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-sm",children:j.conversionActionName}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Y,{variant:"outline",className:"text-xs",children:Fa(j.category)}),e.jsx(Qa,{status:j.status})]})]}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("div",{className:"font-bold",children:is(parseFloat(j.conversions))}),e.jsx("div",{className:"text-xs text-muted-foreground",children:et(parseFloat(j.conversionValue))})]})]},Q))})]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No conversion action data available"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(oa,{className:"h-5 w-5 text-blue-500"}),"Performance Max Asset Groups",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(PMAX campaigns only)"})]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:"/api/google-ads/pmax-asset-groups/paginated",columns:pe,title:"",dateRange:D,searchable:!0,exportable:!0,emptyMessage:"No Performance Max asset groups found"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ht,{className:"h-5 w-5 text-cyan-500"}),"Landing Page Performance",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(mobile speed & friendliness)"})]})}),e.jsx(T,{children:((U=de==null?void 0:de.data)==null?void 0:U.length)>
780?e.jsx("div",{className:"border rounded-lg overflow-hidden max-h-72 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2",children:"Landing Page"}),e.jsx("th",{className:"text-center p-2",children:"Speed Score"}),e.jsx("th",{className:"text-center p-2",children:"Mobile Friendly"}),e.jsx("th",{className:"text-right p-2",children:"Clicks"}),e.jsx("th",{className:"text-right p-2",children:"Conv."})]})}),e.jsx("tbody",{children:de.data.map((j,Q)=>e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"p-2",children:e.jsx("div",{className:"max-w-xs truncate text-blue-600",title:j.landingPageUrl,children:j.landingPageUrl||"â"})}),e.jsx("td",{className:"p-2 text-center",children:j.mobileSpeedScore!==null?e.jsx(Y,{className:j.mobileSpeedScore>=80?"bg-green-500":j.mobileSpeedScore>=50?"bg-yellow-500":"bg-red-500",children:j.mobileSpeedScore}):e.jsx(Y,{variant:"outline",children:"N/A"})}),e.jsx("td",{className:"p-2 text-center",children:j.mobileFriendlyClickRate?e.jsxs(Y,{className:parseFloat(j.mobileFriendlyClickRate)>=90?"bg-green-500":parseFloat(j.mobileFriendlyClickRate)>=70?"bg-yellow-500":"bg-red-500",children:[j.mobileFriendlyClickRate,"%"]}):e.jsx(Y,{variant:"outline",children:"N/A"})}),e.jsx("td",{className:"p-2 text-right",children:Ws(j.clicks)}),e.jsx("td",{className:"p-2 text-right",children:is(parseFloat(j.conversions))})]},Q))})]})}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No landing page speed data available"})})]})]})]})]})]})}):null}function a4({video:s,open:t,onClose:a}){var r,l,c;const{data:n,isLoading:i}=_e({queryKey:[`/api/youtube/video/${s==null?void 0:s.videoId}/retention`],enabled:t&&!!(s!=null&&s.videoId)});return!t||!s?null:e.jsx(Vs,{open:t,onOpenChange:a,children:e.jsxs(Us,{className:"max-w-3xl max-h-[85vh] overflow-hidden","data-testid":"video-detail-dialog",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-5 w-5 text-red-500"}),s.title||"Video Analytics"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.videoId})]}),e.jsx(kt,{className:"h-[60vh] pr-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:((r=s.views)==null?void 0:r.toLocaleString())||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]})}),e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsxs("div",{className:"text-2xl font-bold",children:[Math.round((s.watchTimeMinutes||0)/60),"h"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Watch Time"})]})}),e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsxs("div",{className:"text-2xl font-bold text-green-600",children:["+",(s.subscribersGained||0).toLocaleString()]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Subscribers"})]})}),e.jsx(_,{children:e.jsxs(T,{className:"pt-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:s.averageViewDuration||"N/A"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Avg Duration"})]})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ja,{className:"h-5 w-5 text-blue-500"}),"Audience Retention Curve",e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsx(bs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Ae,{children:e.jsx("p",{children:"Shows where viewers drop off during the video"})})]})})]})}),e.jsx(T,{children:i?e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx("div",{className:"animate-spin h-6 w-6 border-4 border-blue-500 border-t-transparent rounded-full"})}):((l=n==null?void 0:n.retention)==null?void 0:l.length)>0?e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(Mm,{data:n.retention,children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"elapsedVideoTimeRatio",tickFormatter:o=>`${Math.round(o*100)}%`,label:{value:"Video Progress",position:"bottom",offset:-5}}),e.jsx(at,{tickFormatter:o=>`${Math.round(o*100)}%`,label:{value:"Viewers Retained",angle:-90,position:"insideLeft"}}),e.jsx(gt,{formatter:o=>{const d=o*100;return[`${isNaN(d)?0:d.toFixed(1)}%`,"Retention"]},labelFormatter:o=>`At ${Math.round(o*100)}% of video`}),e.jsx(In,{type:"monotone",dataKey:"audienceWatchRatio",stroke:"#3B82F6",fill:"#3B82F680",name:"Retention"})]})})}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ja,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No retention data available for this video"}),e.jsx("p",{className:"text-xs mt-1",children:"Retention data requires sufficient view count"})]})})]}),((c=n==null?void 0:n.retention)==null?void 0:c.length)>0&&e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Et,{className:"h-5 w-5 text-red-500"}),"Key Drop-off Points"]})}),e.jsx(T,{children:e.jsx("div",{className:"space-y-2",children:[.25,.5,.75].map(o=>{const d=n.retention.find(m=>
78Math.abs(m.elapsedVideoTimeRatio-o)<.05),u=(d==null?void 0:d.audienceWatchRatio)||0,x=isNaN(u*100)?0:u*100;return e.jsxs("div",{className:"flex justify-between items-center p-3 bg-muted/50 rounded-lg",children:[e.jsxs("span",{className:"font-medium",children:["At ",o*100,"%"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{value:x,className:"w-32 h-2"}),e.jsxs(Y,{variant:u>.5?"default":u>.25?"secondary":"destructive",children:[x.toFixed(1),"% retained"]})]})]},o)})})})]}),e.jsx(ee,{asChild:!0,className:"w-full",variant:"outline",children:e.jsxs("a",{href:`https://www.youtube.com/watch?v=${s.videoId}`,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(yt,{className:"h-4 w-4 mr-2"}),"Watch on YouTube"]})})]})})]})})}function n4({videoId:s,timeRange:t}){var l,c,o;const{data:a,isLoading:n}=_e({queryKey:[`/api/youtube-analytics/videos/${s}/enhanced-retention?range=${t}`],enabled:!!s});if(n)return e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx("div",{className:"animate-spin h-6 w-6 border-2 border-red-500 border-t-transparent rounded-full"})});if(!((l=a==null?void 0:a.retentionCurve)!=null&&l.length))return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No retention data available for this video"});const i=d=>{const u=Math.floor(d/60),x=d%60;return`${u}:${x.toString().padStart(2,"0")}`},r=a.retentionCurve.map(d=>({position:d.percentageWatched,retention:d.retentionRate,channelAverage:a.channelAverageRetention||void 0}));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm",children:a.videoTitle}),a.videoDuration>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Duration: ",i(a.videoDuration)]})]}),a.channelAverageRetention&&e.jsxs(Y,{variant:"outline",className:"text-xs",children:["Channel Avg: ",a.channelAverageRetention,"%"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(Vc,{data:r,children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"position",label:{value:"% of Video Watched",position:"bottom",offset:-5},tickFormatter:d=>`${d}%`}),e.jsx(at,{label:{value:"Viewers Remaining %",angle:-90,position:"insideLeft"},tickFormatter:d=>`${d}%`,domain:[0,100]}),e.jsx(gt,{formatter:(d,u)=>[`${d}%`,u==="retention"?"Viewers Remaining":"Channel Average"],labelFormatter:d=>`${d}% of video`}),a.channelAverageRetention&&e.jsx(ir,{y:a.channelAverageRetention,stroke:"#10B981",strokeDasharray:"5 5",label:{value:"Channel Avg",position:"right",fill:"#10B981",fontSize:10}}),e.jsx(Vt,{type:"monotone",dataKey:"retention",stroke:"#EF4444",strokeWidth:2,dot:!1,name:"retention"}),(c=a.dropOffPoints)==null?void 0:c.map((d,u)=>{var x;return e.jsx(Rh,{x:d.percentageWatched,y:((x=r.find(m=>m.position===d.percentageWatched))==null?void 0:x.retention)||0,r:d.severity==="high"?8:d.severity==="medium"?6:4,fill:d.severity==="high"?"#DC2626":d.severity==="medium"?"#F59E0B":"#6B7280",stroke:"white",strokeWidth:2},u)})]})})}),((o=a.dropOffPoints)==null?void 0:o.length)>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h5",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4 text-orange-500"}),"Significant Drop-off Points"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.dropOffPoints.map((d,u)=>e.jsxs(Y,{variant:d.severity==="high"?"destructive":"outline",className:d.severity==="medium"?"border-orange-300 text-orange-700":"",children:[d.percentageWatched,"% (-",d.dropOffRate,"%)"]},u))})]})]})}function r4({video:s,onClose:t}){const a=n=>{if(!n)return"â";const i=Math.floor(n/60),r=n%60;return`${i}:${r.toString().padStart(2,"0")}`};return e.jsxs(_,{className:"border-2 border-primary/20",children:[e.jsx(q,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Hs,{className:"h-5 w-5 text-blue-500"}),"Video Details"]}
78),e.jsx(ee,{variant:"ghost",size:"sm",onClick:t,children:e.jsx(pt,{className:"h-4 w-4"})})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"flex gap-4",children:[s.thumbnailUrl&&e.jsx("img",{src:s.thumbnailUrl,alt:s.title||s.videoTitle,className:"w-32 h-20 object-cover rounded-md"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("h4",{className:"font-medium",children:s.title||s.videoTitle}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.isShort&&e.jsx(Y,{className:"bg-purple-100 text-purple-700",children:"Short"}),s.isLive&&e.jsx(Y,{className:"bg-red-100 text-red-700",children:"Live"}),s.publishedAt&&e.jsx(Y,{variant:"outline",children:De(new Date(s.publishedAt),"MMM d, yyyy")}),s.duration&&e.jsx(Y,{variant:"outline",children:a(s.duration)})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mt-4",children:[e.jsxs("div",{className:"text-center p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-red-500",children:is(s.views||0)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]}),e.jsxs("div",{className:"text-center p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-500",children:is(s.likes||0)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Likes"})]}),e.jsxs("div",{className:"text-center p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-green-500",children:is(s.comments||0)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Comments"})]}),e.jsxs("div",{className:"text-center p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-purple-500",children:s.subscribersGained?`+${is(s.subscribersGained)}`:"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Subscribers"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-4",children:[e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-sm font-medium",children:"Watch Time"}),e.jsx("div",{className:"text-lg",children:Lt(s.estimatedMinutesWatched||s.watchTimeMinutes||0)})]}),e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-sm font-medium",children:"Avg View Duration"}),e.jsx("div",{className:"text-lg",children:s.averageViewDuration?`${Math.round(s.averageViewDuration)}s`:"â"})]})]})]})]})}function i4({open:s,onClose:t,selectedVideos:a,timeRange:n}){const[i,r]=p.useState("views"),[l,c]=p.useState("desc"),o=a.map(w=>w.videoId).join(","),{data:d,isLoading:u}=_e({queryKey:["/api/youtube-analytics/video-engagement-snapshots",o],queryFn:async()=>{const w=await fetch(`/api/youtube-analytics/video-engagement-snapshots?videoIds=${o}`);if(!w.ok)throw new Error("Failed to fetch snapshots");return w.json()},enabled:s&&a.length>0}),x=p.useMemo(()=>{var k;const w=new Map;return(k=d==null?void 0:d.snapshots)==null||k.forEach(b=>w.set(b.videoId,b)),a.map(b=>{const S=w.get(b.videoId);return{videoId:b.videoId,title:(S==null?void 0:S.videoTitle)||b.title||b.videoTitle||"Unknown Video",views:(S==null?void 0:S.views)??b.views??0,avgDuration:(S==null?void 0:S.averageViewDuration)??b.averageViewDuration??0,avgViewPercent:(S==null?void 0:S.averageViewPercentage)??b.averageViewPercentage??0,subscribersGained:(S==null?void 0:S.subscribersGained)??b.subscribersGained??0,hasSnapshot:!!S}})},[a,d]),m=p.useMemo(()=>[...x].sort((w,k)=>{let b,S;switch(i){case"title":b=w.title,S=k.title;break;case"views":b=w.views,S=k.views;break;case"avgDuration":b=w.avgDuration,S=k.avgDuration;break;case"avgViewPercent":b=w.avgViewPercent,S=k.avgViewPercent;break;case"subscribersGained":b=w.subscribersGained,S=k.subscribersGained;break;default:b=w.views,S=k.views}return typeof b=="string"?l==="asc"?b.localeCompare(S):S.localeCompare(b):l==="asc"?b-S:S-b}),[x,i,l]),v=w=>{i===w?c(k=>k==="asc"?"desc":"asc"):(r(w),c("desc"))},g=({column:w,label:k})=>e.jsx(fs,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>v(w),"data-testid":`sort-header-${w}`,children:e.jsxs("div",{className:"flex items-center gap-1",children:[k,i===w&&(l==="asc"?e.jsx(Is,{className:"h-3 w-3"}):e.jsx(Et,{className:"h-3 w-3"}))]})});return s?e.jsx(Vs,{open:s,onOpenChange:t,children:e.jsxs(Us,{className:"max-w-4xl max-h-[80vh] overflow-hidden","data-testid":"video-comparison-dialog",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-2 text-xl",children:[e.jsx(Zs,{className:"h-6 w-6 text-red-500"}),"Compare Videos (",a.length,")"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Side-by-side comparison of engagement metrics"})]}),u?e.jsx("div",{className:"flex items-center justify-center h-48","data-testid":"comparison-loading",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-red-500 border-t-transparent roun
78ded-full"})}):e.jsx(kt,{className:"max-h-[60vh]",children:e.jsxs(nn,{"data-testid":"comparison-table",children:[e.jsx(rn,{children:e.jsxs(ht,{children:[e.jsx(g,{column:"title",label:"Video Title"}),e.jsx(g,{column:"views",label:"Views"}),e.jsx(g,{column:"avgDuration",label:"Avg Duration"}),e.jsx(g,{column:"avgViewPercent",label:"Avg View %"}),e.jsx(g,{column:"subscribersGained",label:"Subs Gained"})]})}),e.jsx(ln,{children:m.map((w,k)=>e.jsxs(ht,{"data-testid":`comparison-row-${k}`,children:[e.jsx(Ke,{className:"max-w-[250px]",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-medium",children:w.title}),!w.hasSnapshot&&e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsx(Y,{variant:"outline",className:"text-xs",children:"Live"})}),e.jsx(Ae,{children:e.jsx("p",{className:"text-xs",children:"Using live data (no snapshot available)"})})]})})]})}),e.jsx(Ke,{className:"font-mono",children:is(w.views)}),e.jsx(Ke,{className:"font-mono",children:w.avgDuration?`${Math.round(w.avgDuration)}s`:"â"}),e.jsx(Ke,{className:"font-mono",children:w.avgViewPercent?`${w.avgViewPercent.toFixed(1)}%`:"â"}),e.jsx(Ke,{className:"font-mono",children:w.subscribersGained>0?e.jsxs("span",{className:"text-green-600",children:["+",is(w.subscribersGained)]}):is(w.subscribersGained)})]},w.videoId))})]})}),e.jsx(Ut,{children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.fetchedAt)&&e.jsxs("span",{children:["Data as of: ",De(new Date(d.fetchedAt),"MMM d, yyyy h:mm a")]})}),e.jsx(ee,{variant:"outline",onClick:t,"data-testid":"close-comparison-dialog",children:"Close"})]})})]})}):null}function l4({open:s,onClose:t,timeRange:a}){var R,O,N,re,H,pe,ye,Ie,ve;const[n,i]=p.useState(null),[r,l]=p.useState(null),[c,o]=p.useState("videos"),[d,u]=p.useState("all"),[x,m]=p.useState("all"),[v,g]=p.useState(null),[w,k]=p.useState(new Map),[b,S]=p.useState(!1),A=5,F=(B,z)=>{z.stopPropagation(),k(K=>{const P=new Map(K),ue=B.videoId;return P.has(ue)?P.delete(ue):P.size<A&&P.set(ue,{videoId:ue,title:B.title,videoTitle:B.videoTitle,views:B.views,watchTimeMinutes:B.watchTimeMinutes,averageViewDuration:B.averageViewDuration,averageViewPercentage:B.averageViewPercentage,subscribersGained:B.subscribersGained,likes:B.likes,comments:B.comments}),P})},de=()=>{k(new Map)},{data:M,isLoading:G}=_e({queryKey:[`/api/youtube/comprehensive?range=${a}`],enabled:s}),{data:D}=_e({queryKey:[`/api/youtube-analytics/demographics/paginated?range=${a}`],enabled:s&&c==="videos"}),$=["#EF4444","#F59E0B","#10B981","#3B82F6","#8B5CF6","#EC4899"],se=(M==null?void 0:M.errors)||[],J=p.useMemo(()=>{const B=new Date;let z=new Date;switch(a){case"7d":z.setDate(B.getDate()-7);break;case"30d":z.setDate(B.getDate()-30);break;case"90d":z.setDate(B.getDate()-90);break;case"1y":z.setFullYear(B.getFullYear()-1);break;default:z.setDate(B.getDate()-30)}return{startDate:z,endDate:B}},[a]),le=p.useMemo(()=>[{key:"compare",header:"",sortable:!1,width:"40px",render:(B,z)=>{const K=w.has(z.videoId),P=!K&&w.size>=A;return e.jsx("div",{onClick:ue=>F(z,ue),className:"flex items-center justify-center",children:e.jsx(lm,{checked:K,disabled:P,"data-testid":`checkbox-video-${z.videoId}`,className:"cursor-pointer"})})}},{key:"title",header:"Video Title",sortable:!0,render:(B,z)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate max-w-[200px]",children:B||(z==null?void 0:z.videoTitle)||"Unknown"}),(z==null?void 0:z.isShort)&&e.jsx(Y,{variant:"secondary",className:"text-xs bg-purple-100 text-purple-700",children:"Short"}),(z==null?void 0:z.isLive)&&e.jsx(Y,{variant:"secondary",className:"text-xs bg-red-100 text-red-700",children:"Live"})]})},{key:"views",header:"Views",sortable:!0,render:B=>is(B)},{key:"watchTimeMinutes",header:"Watch Time",sortable:!0,render:B=>Lt(B)},{key:"likes",header:"Likes",sortable:!0,render:B=>is(B)},{key:"comments",header:"Comments",sortable:!0,render:B=>is(B)},{key:"subscribersGained",header:"Subs Gained",sortable:!0,render:B=>B?`+${is(B)}`:"â"}],[w]),C=p.useMemo(()=>[{key:"searchTerm",header:"Search Term",sortable:!0},{key:"views",header:"Views",sortable:!0,render:B=>is(B)}
78,{key:"watchTimeMinutes",header:"Watch Time",sortable:!0,render:B=>Lt(B)},{key:"avgViewDuration",header:"Avg Duration",sortable:!0,render:B=>Lt(B)}],[]),I=p.useMemo(()=>[{key:"country",header:"Country",sortable:!0},{key:"views",header:"Views",sortable:!0,render:B=>is(B)},{key:"watchTimeMinutes",header:"Watch Time",sortable:!0,render:B=>Lt(B)},{key:"avgViewDuration",header:"Avg Duration",sortable:!0,render:B=>Lt(B)}],[]),y=p.useMemo(()=>[{key:"deviceType",header:"Device Type",sortable:!0},{key:"operatingSystem",header:"OS",sortable:!0},{key:"views",header:"Views",sortable:!0,render:B=>is(B)},{key:"watchTimeMinutes",header:"Watch Time",sortable:!0,render:B=>Lt(B)},{key:"avgViewDuration",header:"Avg Duration",sortable:!0,render:B=>Lt(B)}],[]),f=B=>{l(B.videoId),i(B)};return s?e.jsx(Vs,{open:s,onOpenChange:t,children:e.jsxs(Us,{className:"max-w-6xl max-h-[90vh] overflow-hidden","data-testid":"youtube-drilldown",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-2 text-xl",children:[e.jsx(pa,{className:"h-6 w-6 text-red-500"}),"YouTube Analytics Deep Dive",e.jsx(Y,{variant:"outline",className:"ml-2",children:"Live API Data"})]}),(M==null?void 0:M.fetchedAt)&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground mt-1",children:[e.jsx(ra,{className:"h-3 w-3"}),e.jsxs("span",{children:["Last synced: ",De(new Date(M.fetchedAt),"MMM d, yyyy h:mm a")]})]})]}),G?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-red-500 border-t-transparent rounded-full"})}):M!=null&&M.error?e.jsxs(Qs,{variant:"destructive",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx(Xs,{children:M.error})]}):e.jsxs(la,{value:c,onValueChange:o,className:"flex-1",children:[e.jsxs(ca,{className:"grid w-full grid-cols-3",children:[e.jsxs(Ee,{value:"videos",className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),"Videos"]}),e.jsxs(Ee,{value:"traffic",className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4"}),"Traffic & Search"]}),e.jsxs(Ee,{value:"audience",className:"flex items-center gap-2",children:[e.jsx(ot,{className:"h-4 w-4"}),"Geography & Devices"]})]}),e.jsxs(kt,{className:"h-[60vh] mt-4",children:[e.jsxs(Ve,{value:"videos",className:"space-y-6 mt-0",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(pa,{className:"h-5 w-5 text-red-500"}),"Video Performance",e.jsx("span",{className:"text-xs font-normal text-muted-foreground ml-2",children:"(click row for retention chart)"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Content:"}),e.jsxs(os,{value:d,onValueChange:B=>u(B),children:[e.jsx(ds,{className:"w-32 h-8","data-testid":"select-content-type",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"all",children:"All Videos"}),e.jsx(me,{value:"shorts",children:"Shorts Only"}),e.jsx(me,{value:"regular",children:"Regular Only"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Type:"}),e.jsxs(os,{value:x,onValueChange:B=>m(B),children:[e.jsx(ds,{className:"w-36 h-8","data-testid":"select-live-ondemand",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"all",children:"All"}),e.jsx(me,{value:"LIVE",children:"Live Streams"}),e.jsx(me,{value:"ON_DEMAND",children:"On-Demand"})]})]})]}),w.size>0&&e.jsxs("div",{className:"flex items-center gap-2 ml-2 pl-2 border-l",children:[e.jsxs(Y,{variant:"secondary",className:"text-xs",children:[w.size,"/",A," selected"]}),w.size>=2&&e.jsxs(ee,{size:"sm",variant:"default",onClick:()=>S(!0),"data-testid":"compare-selected-button",className:"h-8",children:[e.jsx(Zs,{className:"h-4 w-4 mr-1"}),"Compare Selected"]}),e.jsx(ee,{size:"sm",variant:"ghost",onClick:de,"data-testid":"clear-selection-button",className:"h-8 px-2",children:e.jsx(pt,{className:"h-4 w-4"})})]})]})]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:`/api/youtube-analytics/videos/filtered?contentType=${d}${x!=="all"?`&liveOrOnDemand=${x}`:""}`,columns:le,title:"",dateRange:J,searchable:!0,exportable:!0,onRowClick:f})})]}),r&&e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Is,{className:"h-5 w-5 text-orange-500"}),"Enhanced Audience Retention",e.jsx(Y,{variant:"outline",className:"ml-2",children:"With Drop-off Analysis"}),e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>l(null),className:"ml-auto",children:"Clear"})]})}),e.jsx(T,{children:e.jsx(n4,{videoId:r,timeRange:a})})]}),n&&e.jsx(r4,{video:n,onClose:()=>i(null)}),e.jsx(a4,{video:n,open:!!n,onClose:()=>i(null)}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ys,{className:"h-5 w-5 text-pink-500"}
78),"Viewer Demographics",e.jsx(Y,{variant:"outline",className:"ml-2",children:"Enhanced"})]})}),e.jsxs(T,{children:[e.jsx(s4,{section:"demographics",errors:se}),((R=D==null?void 0:D.data)==null?void 0:R.length)>0||((O=M==null?void 0:M.demographics)==null?void 0:O.length)>0?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(Zs,{className:"h-4 w-4 text-blue-500"}),"Age Group Distribution"]}),e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(Lr,{data:(()=>{const B=(D==null?void 0:D.data)||(M==null?void 0:M.demographics)||[],z={};return B.forEach(K=>{const P=K.ageGroup||"Unknown";z[P]||(z[P]={views:0,minutes:0}),z[P].views+=K.views||0,z[P].minutes+=K.estimatedMinutesWatched||0}),Object.entries(z).map(([K,P])=>({ageGroup:K,views:P.views,watchTimeHours:Math.round(P.minutes/60)}))})(),layout:"vertical",children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{type:"number"}),e.jsx(at,{dataKey:"ageGroup",type:"category",width:60}),e.jsx(gt,{formatter:(B,z)=>[is(B),z==="views"?"Views":"Watch Time (hrs)"]}),e.jsx(Zt,{dataKey:"views",fill:"#3B82F6",name:"Views"})]})})})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4 text-pink-500"}),"Gender Distribution"]}),e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(wr,{children:[e.jsx(kr,{data:(()=>{const B=(D==null?void 0:D.data)||(M==null?void 0:M.demographics)||[],z={};return B.forEach(K=>{const P=K.gender||"Unknown";z[P]=(z[P]||0)+(K.views||K.viewerPercentage||0)}),Object.entries(z).map(([K,P])=>({name:K,value:P,fill:It(K)==="male"?"#3B82F6":It(K)==="female"?"#EC4899":"#8B5CF6"}))})(),dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:B,percent:z})=>{const K=z*100;return`${B} ${isNaN(K)?0:K.toFixed(0)}%`},children:(()=>{const B=(D==null?void 0:D.data)||(M==null?void 0:M.demographics)||[],z={};return B.forEach(K=>{const P=K.gender||"Unknown";z[P]=(z[P]||0)+(K.views||K.viewerPercentage||0)}),Object.entries(z).map(([K],P)=>e.jsx(dn,{fill:It(K)==="male"?"#3B82F6":It(K)==="female"?"#EC4899":"#8B5CF6"},`cell-${P}`))})()}),e.jsx(gt,{formatter:B=>is(B)})]})})})]})]}),((N=D==null?void 0:D.data)==null?void 0:N.length)>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("h4",{className:"text-sm font-medium mb-3",children:"Detailed Breakdown by Age & Gender"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:D.data.slice(0,8).map((B,z)=>e.jsxs("div",{className:"flex flex-col p-3 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${It(B.gender)==="male"?"bg-blue-500":It(B.gender)==="female"?"bg-pink-500":"bg-purple-500"}`}),e.jsxs("span",{className:"font-medium text-sm",children:[B.ageGroup," - ",B.gender]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("div",{children:[is(B.views||0)," views"]}),e.jsx("div",{children:Lt(B.estimatedMinutesWatched||0)})]})]},z))})]})]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No demographic data available"})]})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Zs,{className:"h-5 w-5 text-cyan-500"}),"Playlist Performance"]})}),e.jsx(T,{children:((re=M==null?void 0:M.playlists)==null?void 0:re.length)>0?e.jsx("div",{className:"space-y-3",children:M.playlists.slice(0,10).map((B,z)=>e.jsx("div",{className:"p-4 bg-muted/50 rounded-lg",children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:B.playlistTitle||`Playlist ${B.playlistId}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:B.playlistId})]}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsxs("div",{className:"font-medium",children:[is(B.views)," views"]}),e.jsx("div",{className:"text-muted-foreground",children:Lt(B.watchTimeMinutes)})]})]})},z))}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No playlist data available"})})]})]}),e.jsxs(Ve,{value:"traffic",className:"space-y-6 mt-0",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ga,{className:"h-5 w-5 text-indigo-500"}),"YouTube Search Terms"]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:"/api/youtube-analytics/search-terms/paginated",columns:C,title:"",dateRange:J,searchable:!0,exportable:!0})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Wt,{className:"h-5 w-5 text-blue-500"}),"Traffic Sources",e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsx(bs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Ae,{children:e.jsx("p",{children:"Where your viewers discovered your videos"})})]})})]})}),e.jsx(T,{children:((H=M==null?void 0:M.trafficSources)==null?void 0:H.length)>
780?e.jsx("div",{className:"space-y-3",children:M.trafficSources.map((B,z)=>e.jsxs("div",{className:"flex justify-between items-center p-3 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:B.sourceLabel||B.source})]}),e.jsxs("div",{className:"flex gap-4 text-sm",children:[e.jsxs("span",{children:[is(B.views)," views"]}),e.jsx("span",{className:"text-muted-foreground",children:Lt(B.estimatedMinutesWatched)})]})]},z))}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No traffic source data available"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Za,{className:"h-5 w-5 text-green-500"}),"Videos Driving Subscriptions",e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsx(bs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Ae,{children:e.jsx("p",{children:"Which videos viewers were watching when they subscribed"})})]})})]})}),e.jsx(T,{children:((pe=M==null?void 0:M.subscriberSources)==null?void 0:pe.length)>0?e.jsx("div",{className:"space-y-3",children:M.subscriberSources.map((B,z)=>e.jsxs("div",{className:"flex justify-between items-center p-3 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx(pa,{className:"h-4 w-4 text-red-500 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:B.videoTitle||B.videoId})]}),e.jsxs("div",{className:"flex gap-4 text-sm flex-shrink-0",children:[e.jsxs("span",{className:"text-green-600",children:["+",(B.subscribersGained||0).toLocaleString()," subs"]}),e.jsxs("span",{className:"text-red-600",children:["-",(B.subscribersLost||0).toLocaleString()," lost"]})]})]},z))}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No subscriber source data available"})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Hs,{className:"h-5 w-5 text-orange-500"}),"Top Video Engagement"]})}),e.jsx(T,{children:((ye=M==null?void 0:M.endScreens)==null?void 0:ye.length)>0?e.jsx("div",{className:"space-y-2",children:M.endScreens.slice(0,5).map((B,z)=>e.jsxs("div",{className:"flex justify-between items-center p-2 bg-muted/50 rounded-lg text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:B.videoTitle||`Video ${B.videoId}`}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Y,{variant:"outline",children:[is(B.views)," views"]}),e.jsx("span",{className:"text-muted-foreground",children:Lt(B.estimatedMinutesWatched)})]})]},z))}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No video data"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Is,{className:"h-5 w-5 text-teal-500"}),"Video Social Engagement"]})}),e.jsx(T,{children:((Ie=M==null?void 0:M.cards)==null?void 0:Ie.length)>0?e.jsx("div",{className:"space-y-2",children:M.cards.slice(0,5).map((B,z)=>e.jsxs("div",{className:"flex justify-between items-center p-2 bg-muted/50 rounded-lg text-sm",children:[e.jsx("span",{className:"truncate flex-1",children:B.videoTitle||`Video ${B.videoId}`}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs("span",{title:"Likes",children:["ð ",is(B.likes)]}),e.jsxs("span",{title:"Comments",children:["ð¬ ",is(B.comments)]}),e.jsxs("span",{title:"Shares",children:["ð ",is(B.shares)]})]})]},z))}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No engagement data"})})]})]})]}),e.jsxs(Ve,{value:"audience",className:"space-y-6 mt-0",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(sn,{className:"h-5 w-5 text-green-500"}),"Geographic Performance"]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:"/api/youtube-analytics/geography/paginated",columns:I,title:"",dateRange:J,searchable:!0,exportable:!0})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(tt,{className:"h-5 w-5 text-purple-500"}),"Device Breakdown"]})}),e.jsx(T,{children:e.jsx(Ot,{endpoint:"/api/youtube-analytics/devices/paginated",columns:y,title:"",dateRange:J,searchable:!0,exportable:!0})})]}),((ve=M==null?void 0:M.deviceTypes)==null?void 0:ve.length)>0&&e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-lg",children:[e.jsx(tt,{className:"h-5 w-5 text-purple-500"}),"Device Distribution Chart"]})}),e.jsx(T,{children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsx("div",{className:"h-64",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(wr,{children:[e.jsx(kr,{data:M.deviceTypes,dataKey:"views",nameKey:"deviceType",cx:"50%",cy:"50%",outerRadius:80,label:({name:B,percent:z})=>{const K=z*100;return`${B}
78 ${isNaN(K)?0:K.toFixed(0)}%`},children:M.deviceTypes.map((B,z)=>e.jsx(dn,{fill:$[z%$.length]},`cell-${z}`))}),e.jsx(gt,{})]})})}),e.jsx("div",{className:"space-y-3",children:M.deviceTypes.map((B,z)=>{var K,P,ue,V;return e.jsxs("div",{className:"flex justify-between items-center p-3 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[((K=B.deviceType)==null?void 0:K.includes("MOBILE"))&&e.jsx(Ht,{className:"h-4 w-4"}),((P=B.deviceType)==null?void 0:P.includes("DESKTOP"))&&e.jsx(tt,{className:"h-4 w-4"}),((ue=B.deviceType)==null?void 0:ue.includes("TABLET"))&&e.jsx(Ga,{className:"h-4 w-4"}),((V=B.deviceType)==null?void 0:V.includes("TV"))&&e.jsx(Im,{className:"h-4 w-4"}),!["MOBILE","DESKTOP","TABLET","TV"].some(U=>{var j;return(j=B.deviceType)==null?void 0:j.includes(U)})&&e.jsx(tt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:B.deviceType})]}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsxs("div",{children:[is(B.views)," views"]}),e.jsx("div",{className:"text-muted-foreground",children:Lt(B.watchTimeMinutes)})]})]},z)})})]})})]})]})]})]}),e.jsx(i4,{open:b,onClose:()=>S(!1),selectedVideos:Array.from(w.values()),timeRange:a})]})}):null}const Xr=p.createContext({highlightedPath:null,highlightedNode:null,setHighlightedPath:()=>{},setHighlightedNode:()=>{}});function c4(){const[s,t]=p.useState("30d"),[a,n]=p.useState("all"),[i,r]=p.useState(!1),[l,c]=p.useState(!1),{data:o,isLoading:d}=_e({queryKey:[`/api/analytics/comprehensive?range=${s}&channel=${a}`]}),{data:u}=_e({queryKey:[`/api/analytics/channel-attribution?range=${s}`]}),{data:x}=_e({queryKey:["/api/analytics/predictive"]}),{data:m}=_e({queryKey:["/api/marketing/campaigns/roi"]}),g=(()=>{if(!o)return null;const D=o.current??null,$=o.previous??null,se=(D==null?void 0:D.marketingSpend)??null,J=(D==null?void 0:D.newPatients)??null;se===null&&console.log("[ANALYTICS] marketingSpend data is missing - displaying null state"),J===null&&console.log("[ANALYTICS] newPatients data is missing - displaying null state");const le=se!==null&&J!==null&&J>0?se/J:null,C=(D==null?void 0:D.avgRevenuePerPatient)??null,I=(D==null?void 0:D.avgPatientLifespanMonths)??null;C===null&&console.log("[ANALYTICS] avgRevenuePerPatient data is missing - displaying null state"),I===null&&console.log("[ANALYTICS] avgPatientLifespanMonths data is missing - displaying null state");const y=C!==null&&I!==null?C*I:null,f=y!==null&&le!==null&&le>0?y/le:null,R=(D==null?void 0:D.websiteVisitors)??null,O=(D==null?void 0:D.leads)??null,N=(D==null?void 0:D.appointments)??null,re=(D==null?void 0:D.newPatientsFromWeb)??null;R===null&&console.log("[ANALYTICS] websiteVisitors data is missing"),O===null&&console.log("[ANALYTICS] leads data is missing"),N===null&&console.log("[ANALYTICS] appointments data is missing"),re===null&&console.log("[ANALYTICS] newPatientsFromWeb data is missing");const H=R!==null&&O!==null&&R>0?O/R*100:null,pe=O!==null&&N!==null&&O>0?N/O*100:null,ye=N!==null&&re!==null&&N>0?re/N*100:null,Ie=(u==null?void 0:u.channelAttribution)??null;Ie===null?(console.log("[ANALYTICS] channelAttribution data is missing from /api/analytics/channel-attribution - displaying null state"),u!=null&&u.message&&console.log("[ANALYTICS] Channel attribution message:",u.message)):console.log("[ANALYTICS] Channel attribution data loaded:",Object.keys(Ie));const ve=(D==null?void 0:D.emailMetrics)??null,B=(D==null?void 0:D.socialMetrics)??null;ve===null&&console.log("[ANALYTICS] emailMetrics data is missing"),B===null&&console.log("[ANALYTICS] socialMetrics data is missing");const z=(V,U)=>V===null||U===null?null:U===0?V>0?100:null:(V-U)/U*100,K=($==null?void 0:$.cpa)??null,P=($==null?void 0:$.ltv)??null,ue=($==null?void 0:$.newPatients)??null;return{cpa:le,ltv:y,ltvCacRatio:f,newUsers:J,totalSpend:se,conversionRates:{visitorToLead:H,leadToAppointment:pe,appointmentToPatient:ye},channelPerformance:Ie,engagement:{email:ve,social:B},changes:{cpa:z(le,K),ltv:z(y,P),newUsers:z(J,ue)}}})(),w=()=>{const D=(x==null?void 0:x.churnRisk)&&x.churnRisk.length>0,$=x==null?void 0:x.highValueOpportunities,se=(x==null?void 0:x.campaignOptimizations)&&x.campaignOptimizations.length>0;return D||$||se?e.jsxs(_,{"data-testid":"card-predictive-insights",children:[e.jsx(q,{children:e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-5 w-5"}),"AI-Powered Predictive Insights"]})}),e.jsxs(T,{className:"space-y-4",children:[D&&e.jsxs(Qs,{className:"border-red-200 bg-red-50","data-testid":"alert-churn-risk",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsxs(Xs,{children:[e.jsxs("strong",{children:[x.churnRisk.length," patients at high churn risk"]}),e.jsx("ul",{className:"mt-2 text-sm",children:x.churnRisk.slice(0,3).map(le=>e.jsxs("li",{children:[le.name," - Last visit: ",le.lastVisitDays," days ago"]},le.id))}),e.jsx(ee,{size:"sm",variant:"outline",className:"mt-2","data-testid":"button-launch-campaign",children:"Launch Re-engagement Campaign"})]})]}),$&&e.jsxs(Qs,{className:"border-green-200 bg-green-50","data-testid":"alert-high-value",children:[e.jsx(Is,{className:"h-4 w-4"}),e.jsxs(Xs,{children:[e.jsx("strong",{children:"High-value patient opportunities detected"}),e.jsxs("p",{className:"text-sm mt-1",children:[x.highValueOpportunities.count," patients show indicators for additional services worth $",x.highValueOpportunities.potentialRevenue]}),e.jsx(ee,{size:"sm",variant:"outline",className:"mt-2","data-testid":"button-view-opportunities",children:"View Opportunities"})]})]}),se&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Campaign Optimization Suggestions"}),x.campaignOptimizations.map((le,C)=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-surface-page rounded","data-testid":`row-optimization-${C}
78`,children:[e.jsx("span",{className:"text-sm",children:le.suggestion}),e.jsxs(Y,{variant:"outline",className:"text-xs",children:["+",le.expectedImprovement,"% ROI"]})]},C))]})]})]}):(console.log("[ANALYTICS] PredictiveInsights: No predictive data available"),e.jsxs(_,{"data-testid":"card-predictive-insights-empty",children:[e.jsx(q,{children:e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-5 w-5"}),"AI-Powered Predictive Insights"]})}),e.jsxs(T,{className:"p-8 text-center",children:[e.jsx(Qt,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"Coming Soon"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"AI-powered predictive insights will analyze user behavior to identify:"}),e.jsxs("ul",{className:"text-sm text-muted-foreground mt-3 space-y-1",children:[e.jsx("li",{children:"⢠Users at risk of churn based on activity patterns"}),e.jsx("li",{children:"⢠High-value user opportunities for upselling"}),e.jsx("li",{children:"⢠Campaign optimization suggestions"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-4",children:"Requires: User activity data and engagement tracking"})]})]}))},k=()=>{const D={paid:"Google Ads campaigns - includes search, display, and video ads",direct:"Direct website visitors - people who typed your URL or used bookmarks",youtube:"YouTube channel analytics - views, subscribers, and watch time from your channel",organic:"Organic search traffic - visitors from Google, Bing, etc.",social:"Social media traffic - visitors from Facebook, Twitter, LinkedIn, etc.",email:"Email marketing traffic - visitors from email campaigns",referral:"Referral traffic - visitors from other websites linking to you"},$={"Sessions/Views":"Website sessions or YouTube video views depending on channel",Conversions:"Sign-ups, patient registrations, or subscribers gained",Cost:"Total advertising spend for this channel",Revenue:"Revenue attributed to this channel",CPA:"Cost Per Acquisition - how much you spent to get each conversion",ROI:"Return on Investment - (Revenue - Cost) / Cost à 100"},se=(K,P)=>{const ue=It(K);return ue==="youtube"&&It(P).includes("api")?"Enable YouTube Analytics API in Google Cloud Console to see your channel data":ue==="paid"?"No Google Ads campaigns active in the selected date range":P||"No data available - try a different date range"};if(!(g!=null&&g.channelPerformance))return console.log("[ANALYTICS] ChannelAttribution: No channel performance data available"),e.jsxs(_,{"data-testid":"card-channel-attribution-empty",children:[e.jsx(q,{children:e.jsx(W,{children:"Multi-Channel Attribution Analysis"})}),e.jsxs(T,{className:"p-8 text-center",children:[e.jsx(fp,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"No data available"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Channel attribution data has not been collected yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-3",children:"Requires: Google Ads, YouTube Analytics, or UTM-tagged traffic"})]})]});const J={organic:"#10b981",paid:"#3b82f6",social:"#8b5cf6",email:"#f59e0b",referral:"#ec4899",direct:"#6b7280",youtube:"#ff0000"},{toast:le}=ya(),[C,I]=p.useState(!1),[y,f]=p.useState(""),[R,O]=p.useState(De(new Date,"yyyy-MM-dd")),[N,re]=p.useState(""),[H,pe]=p.useState(""),ye=ws({mutationFn:async K=>await vs("POST","/api/marketing/manual-spend",K),onSuccess:()=>{le({title:"Spend Added",description:"Your manual promotion spend has been recorded."}),Ts.invalidateQueries({queryKey:["/api/analytics/channel-attribution"]}),I(!1),f(""),re(""),pe(""),O(De(new Date,"yyyy-MM-dd"))},onError:K=>{le({title:"Error",description:K.message||"Failed to add spend entry",variant:"destructive"})}}),Ie=()=>{if(!y||isNaN(parseFloat(y))||parseFloat(y)<=0){le({title:"Invalid Amount",description:"Please enter a valid positive amount",variant:"destructive"});return}ye.mutate({channel:"youtube",amount:y,spendDate:R,description:N||void 0,campaignName:H||void 0})},ve=Object.entries(g.channelPerformance).map(([K,P])=>{const ue=(P==null?void 0:P.sessions)??0,V=(P==null?void 0:P.patients)??null,U=(P==null?void 0:P.revenue)??null,j=(P==null?void 0:P.roi)??null,Q=(P==null?void 0:P.cost)!==void 0?P.cost:null,je=(P==null?void 0:P.clicks)??null,ce=(P==null?void 0:P.impressions)??null,be=(P==null?void 0:P.conversions)??null,ss=(P==null?void 0:P.noDataForRange)??!1,oe=(P==null?void 0:P.message)??null,Ne=(P==null?void 0:P.views)??null,Le=(P==null?void 0:P.watchTimeMinutes)??null,ae=(P==null?void 0:P.subscribersGained)??null,xe=(P==null?void 0:P.hasManualSpend)??!1;return{name:K.charAt(0).toUpperCase()+K.slice(1),sessions:ue,patients:V,revenue:U,roi:j,cost:Q,clicks:je,impressions:ce,conversions:be,noDataForRange:ss,message:oe,views:Ne,watchTimeMinutes:Le,subscribersGained:ae,hasManualSpend:xe}}),B=ve.some(K=>K.sessions>0),z=ve.filter(K=>K.noDataForRange);return e.jsxs(_,{"data-testid":"card-channel-attribution",children:[e.jsx(q,{children:e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(ot,{className:"h-5 w-5"}),"Multi-Channel Attribution Analysis"]})}),e.jsxs(T,{children:[z.length>0&&e.jsxs(Qs,{className:"mb-4 border-yellow-200 bg-yellow-50","data-testid":"alert-no-range-data",children:[e.jsx(bs,{className:"h-4 w-4"}),e.jsx(Xs,{children:e.jsx("div",{className:"space-y-1",children:z.map(K=>e.jsxs("div",{className:"text-sm",children:[e.jsxs("span",{className:"font-medium",children:[K.name,":"]})," ",se(K.name,K.message)]},K.name))})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-4",children:"Sessions by Channel"}),B?e.jsx(ft,{width:"100%",height:250,children:e.jsxs(wr,{data:ve.filter(K=>K.sessions>0),children:[e.jsx(kr,{dataKey:"sessions",cx:"50%",cy:"50%",outerRadius:80,label:({name:K,percent:P})=>{const ue=P*100;return`${K} ${isNaN(ue)?0:ue.toFixed(0)}%`},children:ve.filter(K=>K.sessions>0).map((K,P)=>e.jsx(dn,{fill:J[It(K.name)]||"#6b7280"},`cell-${P}`))}),e.jsx(gt,{})]})}):e.jsx("div",{className:"h-[250px] flex items-center justify-center text-muted-foreground",children:"No session data available"})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-4",children:"Cost by Channel"}),ve.some(K=>K.cost!==null&&K.cost>0)?e.jsx(ft,{width:"100%",height:250,children:e.jsxs(Lr,{data:ve.filter(K=>K.cost!==null&&K.cost>0),children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"name"}),e.jsx(at,{}),e.jsx(gt,{formatter:K=>
78`$${Number(K).toLocaleString()}`}),e.jsx(Zt,{dataKey:"cost",fill:"#3b82f6",children:ve.filter(K=>K.cost!==null&&K.cost>0).map((K,P)=>e.jsx(dn,{fill:J[It(K.name)]||"#3b82f6"},`cell-${P}`))})]})}):e.jsx("div",{className:"h-[250px] flex items-center justify-center text-muted-foreground",children:"No paid channel cost data available"})]})]}),e.jsxs("div",{className:"mt-6 overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm","data-testid":"table-channel-attribution",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2",children:"Channel"}),e.jsx("th",{className:"text-right py-2",children:e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 cursor-help",children:["Sessions/Views",e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:$["Sessions/Views"]})})]})})}),e.jsx("th",{className:"text-right py-2",children:e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 cursor-help",children:["Conversions",e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:$.Conversions})})]})})}),e.jsx("th",{className:"text-right py-2",children:e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 cursor-help",children:["Cost",e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:$.Cost})})]})})}),e.jsx("th",{className:"text-right py-2",children:e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 cursor-help",children:["Revenue",e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:$.Revenue})})]})})}),e.jsx("th",{className:"text-right py-2",children:e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 cursor-help",children:["CPA",e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:$.CPA})})]})})}),e.jsx("th",{className:"text-right py-2",children:e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 cursor-help",children:["ROI",e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:$.ROI})})]})})})]})}),e.jsx("tbody",{children:ve.map(K=>{const P=K.conversions!==null&&K.cost!==null&&K.cost>0&&K.conversions>0?(K.cost/K.conversions).toFixed(0):null,ue=It(K.name),V=ue==="youtube";return e.jsxs("tr",{className:"border-b","data-testid":`row-channel-${ue}`,children:[e.jsxs("td",{className:"py-2 font-medium",children:[e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 cursor-help",children:[K.name,e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{children:e.jsx("p",{children:D[ue]||`${K.name} traffic source`})})]})}),V&&K.watchTimeMinutes!==null&&K.watchTimeMinutes>0&&e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[Math.round(K.watchTimeMinutes/60).toLocaleString(),"h watch time"]})]}),e.jsx("td",{className:"text-right",children:K.sessions>0?e.jsxs(e.Fragment,{children:[K.sessions.toLocaleString(),V&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"views"})]}):e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx("td",{className:"text-right",children:V&&K.subscribersGained!==null&&K.subscribersGained>0?e.jsxs(e.Fragment,{children:["+",K.subscribersGained,e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"subs"})]}):K.conversions!==null&&K.conversions>0?K.conversions:e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[K.cost!==null&&K.cost>0?e.jsxs("span",{className:"flex items-center gap-1",children:["$",K.cost.toLocaleStr
78ing(),V&&K.hasManualSpend&&e.jsx(Y,{variant:"outline",className:"text-xs ml-1",children:"Manual"})]}):K.cost===null?e.jsx("span",{className:"text-xs text-muted-foreground",title:K.message||"Cost data not available via API",children:"N/A"}):e.jsx("span",{className:"text-muted-foreground",children:"$0"}),V&&e.jsxs(Vs,{open:C,onOpenChange:I,children:[e.jsx(zn,{asChild:!0,children:e.jsxs(ee,{variant:"ghost",size:"sm",className:"h-6 px-2","data-testid":"button-add-youtube-spend",children:[e.jsx(on,{className:"h-3 w-3 mr-1"}),"Add"]})}),e.jsxs(Us,{className:"sm:max-w-[425px]","data-testid":"dialog-add-spend",children:[e.jsx(Bs,{children:e.jsx(zs,{children:"Add YouTube Promotion Spend"})}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"spend-amount",children:"Amount ($) *"}),e.jsx(Me,{id:"spend-amount",type:"number",placeholder:"e.g., 500.00",value:y,onChange:U=>f(U.target.value),"data-testid":"input-spend-amount"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"spend-date",children:"Date *"}),e.jsx(Me,{id:"spend-date",type:"date",value:R,onChange:U=>O(U.target.value),"data-testid":"input-spend-date"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"spend-campaign",children:"Campaign Name (optional)"}),e.jsx(Me,{id:"spend-campaign",placeholder:"e.g., January Promotion Campaign",value:H,onChange:U=>pe(U.target.value),"data-testid":"input-spend-campaign"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"spend-description",children:"Description/Notes (optional)"}),e.jsx(La,{id:"spend-description",placeholder:"e.g., YouTube Studio promotion for new video series",value:N,onChange:U=>re(U.target.value),"data-testid":"input-spend-description"})]})]}),e.jsxs(Ut,{children:[e.jsx(ee,{type:"button",variant:"outline",onClick:()=>I(!1),"data-testid":"button-cancel-spend",children:"Cancel"}),e.jsx(ee,{type:"button",onClick:Ie,disabled:ye.isPending,"data-testid":"button-submit-spend",children:ye.isPending?"Adding...":"Add Spend"})]})]})]})]})}),e.jsx("td",{className:"text-right",children:K.revenue!==null?`$${K.revenue.toLocaleString()}`:e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx("td",{className:"text-right",children:P!==null?`$${P}`:e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx("td",{className:"text-right",children:K.roi!==null?e.jsxs(Y,{variant:K.roi>0?"default":"destructive",children:[K.roi,"%"]}):e.jsx("span",{className:"text-muted-foreground",children:"â"})})]},K.name)})})]}),ve.some(K=>It(K.name)==="youtube")&&e.jsx("p",{className:"text-xs text-muted-foreground mt-3",children:'Note: YouTube Studio promotion spend is not available via API. Use the "Add" button next to YouTube to enter your promotion spend for accurate ROI tracking.'})]})]})]})},b=({entry:D,index:$,entryPointRange:se})=>{const{data:J,isLoading:le,error:C}=_e({queryKey:["/api/analytics/entry-point-devices",D.entry_page,D.sitelink,se.startDate.toISOString()],queryFn:async()=>{const f=await fetch(`/api/analytics/entry-point-devices?entryPage=${encodeURIComponent(D.entry_page)}&sitelink=${encodeURIComponent(D.sitelink)}&startDate=${se.startDate.toISOString()}&endDate=${se.endDate.toISOString()}`);if(!f.ok){const R=await f.text();throw console.error(`[DEVICE_BREAKDOWN] API error for ${D.entry_page}/${D.sitelink}: ${f.status} - ${R}`),new Error(`Failed to fetch device data: ${f.status}`)}return f.json()}}),I=(J==null?void 0:J.devices)||[],y=(J==null?void 0:J.totalSessions)||0;return e.jsxs(_,{"data-testid":`section-devices-${$}`,children:[e.jsx(q,{className:"py-3 px-4",children:e.jsxs(W,{className:"text-sm flex items-center gap-2",children:[e.jsx(Ht,{className:"h-4 w-4"}),"Device Breakdown"]})}),e.jsx(T,{className:"py-3 px-4",children:le?e.jsxs("div",{className:"flex items-center justify-center py-4",children:[e.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-primary border-t-transparent rounded-full"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading device data..."})]}):C?e.jsxs("div",{className:"text-center py-4 text-red-600 text-sm",children:[e.jsx(Fs,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Failed to load device data"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:C.message})]}):I.length>0?e.jsx("div",{className:"space-y-3",children:I.map((f,R)=>{const O=f.deviceType||"unknown",N=O==="desktop"?tt:O==="mobile"?Ht:O==="tablet"?Ga:Cs,re=f.sessions||0,H=f.percentage||(y>0?(re/y*100).toFixed(1):"0");return e.jsxs("div",{className:"border rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(N,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium capitalize",children:O}),e.jsxs(Y,{variant:"outline",className:"text-xs",children:[re.toLocaleStr
78ing()," sessions"]})]}),e.jsxs("span",{className:"text-sm font-semibold",children:[H,"%"]})]}),e.jsx(mt,{value:parseFloat(String(H)),className:"h-2"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{className:"bg-muted rounded px-2 py-1",children:[e.jsx("span",{className:"text-muted-foreground block",children:"Avg Scroll"}),e.jsxs("span",{className:"font-medium",children:[f.avgScrollDepth||0,"%"]})]}),e.jsxs("div",{className:"bg-muted rounded px-2 py-1",children:[e.jsx("span",{className:"text-muted-foreground block",children:"Signup Rate"}),e.jsxs("span",{className:"font-medium",children:[f.signupRate||"0.0","%"]})]}),e.jsxs("div",{className:"bg-muted rounded px-2 py-1",children:[e.jsx("span",{className:"text-muted-foreground block",children:"Conversion"}),e.jsxs("span",{className:"font-medium",children:[f.paidRate||"0.0","%"]})]})]})]},R)})}):e.jsxs("div",{className:"text-center py-4 text-muted-foreground text-sm",children:[e.jsx(Ht,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No device breakdown data available"}),e.jsx("p",{className:"text-xs",children:"Device data will appear once visitors arrive from this entry point"})]})})]})},S=({entry:D,index:$,entryPointRange:se})=>{const{highlightedPath:J,highlightedNode:le,setHighlightedPath:C}=p.useContext(Xr),{data:I,isLoading:y,error:f}=_e({queryKey:["/api/analytics/entry-point-paths",D.entry_page,D.sitelink,se.startDate.toISOString()],queryFn:async()=>{const re=await fetch(`/api/analytics/entry-point-paths?entryPage=${encodeURIComponent(D.entry_page)}&sitelink=${encodeURIComponent(D.sitelink)}&startDate=${se.startDate.toISOString()}&endDate=${se.endDate.toISOString()}`);if(!re.ok){const H=await re.text();throw console.error(`[NAVIGATION_PATHS] API error for ${D.entry_page}/${D.sitelink}: ${re.status} - ${H}`),new Error(`Failed to fetch path data: ${re.status}`)}return re.json()}}),R=(I==null?void 0:I.paths)||[],O=re=>le?re.some(H=>H===le):!1,N=re=>{if(!J)return!1;const[H,pe]=J.split(" â ");return re.includes(H)&&re.includes(pe)};return e.jsxs(_,{"data-testid":`section-paths-${$}`,children:[e.jsx(q,{className:"py-3 px-4",children:e.jsxs(W,{className:"text-sm flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4"}),"Top Navigation Paths"]})}),e.jsx(T,{className:"py-3 px-4",children:y?e.jsxs("div",{className:"flex items-center justify-center py-4",children:[e.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-primary border-t-transparent rounded-full"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading path data..."})]}):f?e.jsxs("div",{className:"text-center py-4 text-red-600 text-sm",children:[e.jsx(Fs,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Failed to load navigation path data"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:f.message})]}):R.length>0?e.jsxs("div",{className:"space-y-2",children:[R.slice(0,5).map((re,H)=>{const pe=`path-${D.entry_page}-${D.sitelink}-${H}`,ye=re.pages||[],Ie=ye.length>0?ye.join(" â "):D.entry_page,ve=O(ye)||N(Ie);return e.jsxs("div",{className:`border rounded-lg p-3 transition-all duration-200 cursor-pointer ${ve?"bg-info-surface dark:bg-blue-950 border-blue-300 dark:border-blue-700 ring-2 ring-blue-200 dark:ring-blue-800":"hover:bg-muted/50"}`,"data-path-key":pe,onMouseEnter:()=>C(Ie),onMouseLeave:()=>C(null),children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("div",{className:`font-mono text-xs break-all ${ve?"text-info-ink-soft dark:text-blue-300 font-medium":"text-muted-foreground"}`,children:Ie})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs(Y,{variant:"outline",className:"text-xs",children:[(re.sessionCount||0).toLocaleString()," sessions"]}),re.conversionCount>0&&e.jsxs(Y,{variant:"default",className:"text-xs bg-green-600",children:[re.conversionCount," conversions"]})]})]}),re.avgScrollPerPage&&Object.keys(re.avgScrollPerPage).length>0&&e.jsxs("div",{className:"mt-2 flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Avg scroll: ",Math.round(Object.values(re.avgScrollPerPage).reduce((B,z)=>B+z,0)/Object.keys(re.avgScrollPerPage).length),"%"]}
78),e.jsxs("span",{className:"text-muted-foreground/70",children:["Conv. rate: ",re.conversionRate||"0.0","%"]})]})]},H)}),R.length>5&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2",children:["+",R.length-5," more paths"]})]}):e.jsxs("div",{className:"text-center py-4 text-muted-foreground text-sm",children:[e.jsx(Wt,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No navigation path data available"}),e.jsx("p",{className:"text-xs",children:"Path data will appear once visitors navigate through your site"})]})})]})},A=({entry:D,index:$,entryPointRange:se})=>{var pe,ye,Ie,ve,B;const[J,le]=p.useState(null),[C,I]=p.useState("all"),{data:y,isLoading:f,error:R}=_e({queryKey:["/api/analytics/entry-point-scroll",D.entry_page,D.sitelink,se.startDate.toISOString(),se.endDate.toISOString(),$,C],queryFn:async()=>{const z=await fetch(`/api/analytics/entry-point-scroll?entryPage=${encodeURIComponent(D.entry_page)}&sitelink=${encodeURIComponent(D.sitelink)}&startDate=${se.startDate.toISOStr
78ing()}&endDate=${se.endDate.toISOString()}&deviceType=${encodeURIComponent(C)}`);if(!z.ok){const K=await z.text();throw console.error(`[ENTRY_POINT_SCROLL] API error for ${D.entry_page}/${D.sitelink}: ${z.status} - ${K}`),new Error(`Failed to fetch scroll data: ${z.status}`)}return z.json()}}),O=z=>z>=60?"text-green-600 dark:text-green-400":z>=30?"text-yellow-600 dark:text-yellow-400":"text-red-600 dark:text-red-400",N=z=>z>=60?"bg-green-500":z>=30?"bg-yellow-500":"bg-red-500",re=z=>{const K=z.toLowerCase();return K==="mobile"||K.includes("phone")?e.jsx(Ht,{className:"h-3 w-3"}):K==="tablet"?e.jsx(Ga,{className:"h-3 w-3"}):e.jsx(tt,{className:"h-3 w-3"})},H=z=>z==="/"?"Home":z.split("/").filter(Boolean).pop()||z;return e.jsxs(_,{"data-testid":`section-scroll-depth-${$}`,children:[e.jsxs(q,{className:"py-3 px-4",children:[e.jsxs(W,{className:"text-sm flex items-center gap-2",children:[e.jsx(Hs,{className:"h-4 w-4"}),"Scroll Depth Analysis",e.jsx(Y,{variant:"outline",className:"text-xs ml-auto",children:"Entry-Point Specific"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Scroll behavior for sessions that landed on this entry point only"})]}),e.jsx(T,{className:"py-3 px-4",children:f?e.jsxs("div",{className:"flex items-center justify-center py-4","data-testid":`loading-scroll-depth-${$}`,children:[e.jsx("div",{className:"animate-spin w-5 h-5 border-2 border-primary border-t-transparent rounded-full"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading scroll data..."})]}):R?e.jsxs("div",{className:"text-center py-4 text-red-600 text-sm","data-testid":`error-scroll-depth-${$}`,children:[e.jsx(Fs,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Failed to load scroll depth data"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:R.message})]}):y&&y.sessionsWithScroll>0?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3","data-testid":`stats-grid-scroll-depth-${$}`,children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center","data-testid":`stat-avg-scroll-depth-${$}`,children:[e.jsxs("div",{className:`text-2xl font-bold ${O(y.avgScrollDepth)}`,children:[y.avgScrollDepth,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Scroll Depth"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center","data-testid":`stat-sessions-with-scroll-${$}`,children:[e.jsx("div",{className:"text-2xl font-bold",children:y.sessionsWithScroll}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sessions w/ Scroll"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center","data-testid":`stat-median-scroll-${$}`,children:[e.jsxs("div",{className:"text-2xl font-bold text-blue-600 dark:text-blue-400",children:[((pe=y.percentiles)==null?void 0:pe.p50)||0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Median (P50)"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center","data-testid":`stat-top10-scroll-${$}`,children:[e.jsxs("div",{className:"text-2xl font-bold text-purple-600 dark:text-purple-400",children:[((ye=y.percentiles)==null?void 0:ye.p90)||0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Top 10% (P90)"})]})]}),y.scrollDistribution&&y.scrollDistribution.length>0&&e.jsxs("div",{className:"space-y-2","data-testid":`chart-scroll-distribution-${$}`,children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Scroll Depth Distribution"}),e.jsx("div",{className:"flex items-end gap-1 h-16",children:y.scrollDistribution.map((z,K)=>{const P=Math.max(...y.scrollDistribution.map(U=>U.count)),ue=P>0?z.count/P*100:0,V=z.rangeStart+5;return e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx("div",{className:`flex-1 rounded-t transition-all hover:opacity-80 ${N(V)}`,style:{height:`${Math.max(ue,4)}%`,minHeight:"4px"},"data-testid":`bar-scroll-distribution-${$}-${K}`})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"font-medium",children:z.range}),e.jsxs("p",{className:"text-xs",children:[z.count," sessions (",z.percentage,"%)"]})]})]})},K)})}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground",children:[e.jsx("span",{children:"0%"}),e.jsx("span",{children:"50%"}),e.jsx("span",{children:"100%"})]})]}),y.availableDevices&&y.availableDevices.length>0&&e.jsxs("div",{className:"space-y-2","data-testid":`section-device-filter-${$}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Filter by Device"}),e.jsxs(os,{value:C,onValueChange:z=>I(z),children:[e.jsx(ds,{className:"w-[160px] h-8 text-xs","data-testid":`dropdown-device-filter-${$}`,children:e.jsx("div",{className:"flex items-center gap-2",children:C==="all"?e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-3 w-3"}),e.jsx("span",{children:"All Devices"})]}):e.jsxs(e.Fragment,{children:[re(C),e.jsx("span",{className:"capitalize",children:C})]})})}
78),e.jsxs(ms,{children:[e.jsx(me,{value:"all","data-testid":`option-device-all-${$}`,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-3 w-3"}),e.jsx("span",{children:"All Devices"})]})}),y.availableDevices.map(z=>e.jsx(me,{value:z,"data-testid":`option-device-${z}-${$}`,children:e.jsxs("div",{className:"flex items-center gap-2",children:[re(z),e.jsx("span",{className:"capitalize",children:z})]})},z))]})]})]}),C!=="all"&&y.allDevicesBreakdown&&e.jsxs("div",{className:"flex items-center gap-2 bg-primary/10 border border-primary/20 rounded px-3 py-2","data-testid":`display-selected-device-${$}`,children:[re(C),e.jsx("span",{className:"text-xs capitalize flex-1 font-medium",children:C}),e.jsxs("span",{className:`text-sm font-bold ${O(y.avgScrollDepth)}`,children:[y.avgScrollDepth,"%"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",y.sessionsWithScroll," sessions)"]})]}),y.allDevicesBreakdown&&y.allDevicesBreakdown.length>0&&e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:y.allDevicesBreakdown.map((z,K)=>e.jsxs("div",{className:`flex items-center gap-2 rounded px-3 py-2 cursor-pointer transition-colors ${C===z.device?"bg-primary/10 border border-primary/20":"bg-muted/30 hover:bg-muted/50"}`,onClick:()=>I(z.device===C?"all":z.device),"data-testid":`row-device-scroll-${$}-${K}`,children:[re(z.device),e.jsx("span",{className:"text-xs capitalize flex-1",children:z.device}),e.jsxs("span",{className:`text-sm font-medium ${O(z.avgScrollDepth)}`,children:[z.avgScrollDepth,"%"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",z.sessions,")"]})]},z.device))})]}),y.pageBreakdown&&y.pageBreakdown.length>0&&e.jsx(Ta,{type:"single",collapsible:!0,className:"w-full","data-testid":`accordion-page-breakdown-${$}`,children:e.jsxs(Da,{value:"pages",className:"border-none",children:[e.jsxs(Pa,{className:"py-2 text-xs font-medium text-muted-foreground hover:no-underline","data-testid":`button-toggle-page-breakdown-${$}`,children:["Page-Level Scroll Breakdown (",y.pageBreakdown.length," pages)"]}),e.jsx(Ma,{children:e.jsx("div",{className:"space-y-2 mt-2",children:y.pageBreakdown.slice(0,5).map((z,K)=>e.jsxs("div",{className:"border rounded-lg p-2","data-testid":`row-page-scroll-${$}-${K}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium truncate flex-1",title:z.page,children:H(z.page)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Y,{variant:"outline",className:"text-xs",children:[z.sessions," sessions"]}),e.jsxs("span",{className:`text-sm font-bold ${O(z.avgScrollDepth)}`,children:[z.avgScrollDepth,"%"]})]})]}),e.jsx(mt,{value:z.avgScrollDepth,className:"h-1 mt-2"})]},z.page))})})]})}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground pt-2 border-t","data-testid":`section-percentiles-${$}`,children:[e.jsx("span",{children:"Percentiles:"}),e.jsxs("span",{"data-testid":`text-percentile-p25-${$}`,children:["P25: ",((Ie=y.percentiles)==null?void 0:Ie.p25)||0,"%"]}),e.jsxs("span",{"data-testid":`text-percentile-p75-${$}`,children:["P75: ",((ve=y.percentiles)==null?void 0:ve.p75)||0,"%"]}),e.jsxs("span",{"data-testid":`text-percentile-p95-${$}`,children:["P95: ",((B=y.percentiles)==null?void 0:B.p95)||0,"%"]})]})]}):e.jsxs("div",{className:"text-center py-4 text-muted-foreground text-sm","data-testid":`empty-scroll-depth-${$}`,children:[e.jsx(Hs,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scroll data available"}),e.jsx("p",{className:"text-xs",children:"Scroll data will appear once visitors scroll on pages after landing here"}),(y==null?void 0:y.totalSessions)>0&&e.jsxs("p",{className:"text-xs mt-1 text-amber-600",children:[y.totalSessions," sessions found, but none have scroll events recorded"]})]})})]})};function F({entryPointRange:D}){var L,Re,Ge,$e,Qe,js,ze,Ns,He,Gs;const{highlightedPath:$,highlightedNode:se,setHighlightedPath:J,setHighlightedNode:le}=p.useContext(Xr),[C,I]=p.useState(null),[y,f]=p.useState(null),[R,O]=p.useState(15),[N,re]=p.useState(30),[H,pe]=p.useState("sankey"),[ye,Ie]=p.useState("visits"),[ve,B]=p.useState(!1),[z,K]=p.useState(!1),[P,ue]=p.useState("all"),[V,U]=p.useState(0),[j,Q]=p.useState(!0),[je,ce]=p.useState(500),[be,ss]=p.useState(!1),[oe,Ne]=p.useState(!1),[Le,ae]=p.useState(null),[xe,Fe]=p.useState(!0),[X,Be]=p.useState([]),[ns,nt]=p.useState("exclude"),[ks,Rt]=p.useState(""),[wt,jt]=p.useState(!1),{data:rs}=_e({queryKey:["/api/admin/users"]}),ea=p.useMemo(()=>
78{if(!rs)return[];const ne=ks.toLowerCase();return rs.filter(ke=>{var Xe,ls,As,Ds;return((Xe=ke.username)==null?void 0:Xe.toLowerCase().includes(ne))||((ls=ke.email)==null?void 0:ls.toLowerCase().includes(ne))||((As=ke.firstName)==null?void 0:As.toLowerCase().includes(ne))||((Ds=ke.lastName)==null?void 0:Ds.toLowerCase().includes(ne))})},[rs,ks]),{data:Je,isLoading:da,error:qt}=_e({queryKey:["/api/analytics/site-sankey",D.startDate.toISOString(),D.endDate.toISOString(),xe,X,ns],queryFn:async()=>{const ne=new URLSearchParams({startDate:D.startDate.toISOString(),endDate:D.endDate.toISOString()});xe&&ne.append("excludeAdmins","true"),X.length>0&&(ns==="include_only"?ne.append("includeOnlyUserIds",X.join(",")):ne.append("excludeUserIds",X.join(",")));const ke=await fetch(`/api/analytics/site-sankey?${ne.toString()}`);if(!ke.ok)throw new Error("Failed to fetch Sankey data");return ke.json()}}),{nivoData:Js,nodeColorMap:qs,nodeDataMap:ie,stats:te}=p.useMemo(()=>{if(!(Je!=null&&Je.nodes)||!(Je!=null&&Je.links)||Je.nodes.length===0)return{nivoData:null,nodeColorMap:new Map,nodeDataMap:new Map,stats:null};let ne=[...Je.nodes].filter(Te=>Te.visits>=V).filter(Te=>!ve||parseFloat(Te.exitRate)>50);ye==="visits"?ne.sort((Te,ts)=>ts.visits-Te.visits):ye==="exitRate"?ne.sort((Te,ts)=>parseFloat(ts.exitRate)-parseFloat(Te.exitRate)):ne.sort((Te,ts)=>Te.name.localeCompare(ts.name));const ke=R===0?ne:ne.slice(0,R),Xe=new Set(ke.map(Te=>Te.name)),ls=new Map,As=new Map,Ds=ke.map(Te=>{const ts=Te.name.toLowerCase(),ua=parseFloat(Te.exitRate)||0;let wa="#94a3b8",ka="other";return ts.includes("/auth")||ts.includes("/signup")||ts.includes("/login")||ts.includes("/register")?(wa="#3b82f6",ka="conversion"):ua>50?(wa="#f97316",ka="highExit"):(ts==="/"||ts.includes("/pricing")||ts.includes("/learn"))&&(wa="#22c55e",ka="entry"),ls.set(Te.name,wa),As.set(Te.name,Te),{id:Te.name,nodeColor:wa,nodeType:ka,visits:Te.visits,exitRate:Te.exitRate,avgScrollDepth:Te.avgScrollDepth}}),_s=Je.links.filter(Te=>Xe.has(Te.source)&&Xe.has(Te.target)&&Te.source!==Te.target).sort((Te,ts)=>ts.value-Te.value),h=new Map,Z=[],E=[],Pe=(Te,ts)=>{const ua=new Set,wa=[{node:ts,path:[ts]}];for(;wa.length>0;){const{node:ka,path:jo}=wa.shift();if(ka===Te)return[...jo,Te];if(ua.has(ka))continue;ua.add(ka);const bo=h.get(ka);if(bo){const kx=Array.from(bo);for(const wl of kx)ua.has(wl)||wa.push({node:wl,path:[...jo,wl]})}}return null},Ze=N===0?_s.length:N;for(const Te of _s){if(Z.length>=Ze)break;const ts=Pe(Te.source,Te.target);ts?E.push({source:Te.source,target:Te.target,value:Te.value,cycleChain:[Te.source,...ts]}):(Z.push(Te),h.has(Te.source)||h.set(Te.source,new Set),h.get(Te.source).add(Te.target))}const ps=Z.map(Te=>({source:Te.source,target:Te.target,value:Te.value})),bt=ke.reduce((Te,ts)=>Te+ts.visits,0),ma=ke.length>0?ke.reduce((Te,ts)=>Te+parseFloat(ts.exitRate),0)/ke.length:0,yn=ps.reduce((Te,ts)=>Te+ts.value,0),Nn=ke.filter(Te=>Te.name==="/"||Te.name.includes("/pricing")||Te.name.includes("/learn")).length,wn=ke.filter(Te=>parseFloat(Te.exitRate)>50).length,sa=E.reduce((Te,ts)=>Te+ts.value,0),Wn=ps.reduce((Te,ts)=>Te+ts.value,0),Nl=new Map;for(const Te of E){const ts=Te.cycleChain.slice(0,-1).sort().join(" â "),ua=Nl.get(ts);ua?(ua.totalTraffic+=Te.value,ua.occurrences+=1,ua.paths.push(Te)):Nl.set(ts,{pages:Te.cycleChain.slice(0,-1),totalTraffic:Te.value,occurrences:1,paths:[Te]})}const wx=Array.from(Nl.entries()).map(([Te,ts])=>({key:Te,pages:ts.pages,totalTraffic:ts.totalTraffic,occurrences:ts.occurrences,percentage:sa>0?ts.totalTraffic/sa*100:0,paths:ts.paths})).sort((Te,ts)=>ts.totalTraffic-Te.totalTraffic);return{nivoData:{nodes:Ds,links:ps},nodeColorMap:ls,nodeDataMap:As,stats:{totalPages:Je.nodes.length,displayedPages:ke.length,totalLinks:Je.links.length,displayedLinks:ps.length,totalVisits:bt,avgExitRate:ma.toFixed(1),totalNavigations:yn,entryPages:Nn,highExitPages:wn,circularLinksRemoved:E.length,circularPaths:E,circularPathsGrouped:wx,totalCircularTraffic:sa,totalLinearTraffic:Wn,circularTrafficPercentage:sa+Wn>0?(sa/(sa+Wn)*100).toFixed(1):"0"}}},[Je,R,N,ye,ve,V]),fe=ne=>qs.get(ne.id)||"#94a3b8",ge=ne=>{if(ne==null)return{light:"#e2e8f0",dark:"#94a3b8",isOutOfRange:!1};const ke=Math.max(0,Math.min(100,ne)),Xe=()=>{switch(P){case"0-25":return{min:0,max:25};case"25-50":return{min:25,max:50};case"50-75":return{min:50,max:75};case"75-100":return{min:75,max:100};default:return{min:0,max:100}}},{min:ls,max:As}=Xe();if(As<=ls)return{light:"#93c5fd",dark:"#3b82f6",isOutOfRange:!1};if(P!=="all"&&(ke<ls||ke>As))return{light:"#e2e8f0",dark:"#cbd5e1",isOutOfRange:!0};const _s=Math.max(0,Math.min(1,(ke-ls)/(As-ls))),h=200+_s*70,Z=70+_s*15,E=85-_s*25,Pe=60-_s*25,Ze=`hsl(${h}, ${Z}%, ${E}%)`,ps=`hsl(${h}, ${Z}%, ${Pe}%)`;return{light:Ze,dark:ps,isOutOfRange:!1}},We=({nodes:ne})=>z?e.jsxs("g",{className:"scroll-depth-layer",children:[e.jsx("defs",{children:ne.map(ke=>
78{const Xe=ie.get(ke.id),ls=ge(Xe==null?void 0:Xe.avgScrollDepth);return e.jsxs("linearGradient",{id:`scroll-gradient-${ke.id.replace(/[^a-zA-Z0-9]/g,"_")}`,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:ls.light}),e.jsx("stop",{offset:"100%",stopColor:ls.dark})]},`gradient-${ke.id}`)})}),ne.map(ke=>e.jsx("rect",{x:ke.x,y:ke.y,width:ke.width,height:ke.height,rx:3,fill:`url(#scroll-gradient-${ke.id.replace(/[^a-zA-Z0-9]/g,"_")})`,opacity:.85,style:{pointerEvents:"none"}},`scroll-${ke.id}`))]}):null;if(da)return e.jsx("div",{className:"h-[500px] flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin w-8 h-8 border-4 border-primary border-t-transparent rounded-full mx-auto mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading navigation flow..."})]})});if(qt)return e.jsx("div",{className:"h-64 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Fs,{className:"h-12 w-12 mx-auto mb-4 text-amber-500"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"Unable to load navigation flow"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Please try again later"})]})});if(!Js||Js.nodes.length===0||Js.links.length===0)return e.jsx("div",{className:"h-64 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Wt,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"No navigation flow data yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Flow data will appear once visitors navigate through multiple pages"})]})});const we=()=>e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"font-medium text-sm mb-3",children:["Pages by ",ye==="visits"?"Visits":ye==="exitRate"?"Exit Rate":"Name"]}),Js.nodes.map((ne,ke)=>{var Xe,ls,As;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded border transition-colors cursor-pointer 79 ${se===ne.id?"bg-info-surface dark:bg-blue-950 border-blue-300":"hover:bg-muted/50"} 80 `,onMouseEnter:()=>le(ne.id),onMouseLeave:()=>le(null),onClick:()=>I(ne),children:[e.jsx("div",{className:"w-3 h-3 rounded flex-shrink-0",style:{backgroundColor:qs.get(ne.id)||"#94a3b8"}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:ne.id}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[((ls=(Xe=ie.get(ne.id))==null?void 0:Xe.visits)==null?void 0:ls.toLocaleString())||0," visits",e.jsxs("span",{className:"ml-2",children:["⢠",((As=ie.get(ne.id))==null?void 0:As.exitRate)||"0","% exit"]})]})]}),e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground"})]},ne.id)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium text-sm mb-3",children:"Top Navigation Paths"}),Js.links.slice(0,15).map((ne,ke)=>e.jsx("div",{className:`p-2 rounded border transition-colors cursor-pointer ${$===`${ne.source} â ${ne.target}`?"bg-info-surface dark:bg-blue-950 border-blue-300":"hover:bg-muted/50"}`,onMouseEnter:()=>J(`${ne.source} â ${ne.target}`),onMouseLeave:()=>J(null),children:e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("div",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:qs.get(ne.source)||"#94a3b8"}}),e.jsx("span",{className:"truncate max-w-[100px]",children:ne.source}),e.jsx(Va,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("div",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:qs.get(ne.target)||"#94a3b8"}}),e.jsx("span",{className:"truncate max-w-[100px]",children:ne.target}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground flex-shrink-0",children:ne.value.toLocaleString()})]})},`${ne.source}-${ne.target}-${ke}`))]})]}),gs=()=>e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-3 font-medium",children:"Page"}),e.jsx("th",{className:"text-right p-3 font-medium",children:"Visits"}),e.jsx("th",{className:"text-right p-3 font-medium",children:"Exit Rate"}),e.jsx("th",{className:"text-right p-3 font-medium",children:"Avg Scroll"}),e.jsx("th",{className:"text-left p-3 font-medium",children:"Type"})]})}),e.jsx("tbody",{children:Js.nodes.map((ne,ke)=>{const Xe=ie.get(ne.id);return e.jsxs("tr",{className:`border-t hover:bg-muted/30 cursor-pointer ${se===ne.id?"bg-info-surface dark:bg-blue-950":""}`,onMouseEnter:()=>le(ne.id),onMouseLeave:()=>le(null),onClick:()=>I(ne),children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded",style:{backgroundColor:qs.get(ne.id)||"#94a3b8"}}),e.jsx("span",{className:"truncate max-w-[250px]",children:ne.id})]})}),e.jsx("td",{className:"p-3 text-right font-medium",children:((Xe==null?void 0:Xe.visits)||0).toLocaleStr
80ing()}),e.jsx("td",{className:"p-3 text-right",children:e.jsxs("span",{className:parseFloat((Xe==null?void 0:Xe.exitRate)||"0")>50?"text-orange-600":"",children:[(Xe==null?void 0:Xe.exitRate)||"0","%"]})}),e.jsxs("td",{className:"p-3 text-right",children:[(Xe==null?void 0:Xe.avgScrollDepth)??"N/A","%"]}),e.jsx("td",{className:"p-3",children:e.jsx(Y,{variant:"outline",className:"text-xs",children:ne.nodeType==="entry"?"Entry":ne.nodeType==="conversion"?"Conversion":ne.nodeType==="highExit"?"High Exit":"Other"})})]},ne.id)})})]})}),Ss=e.jsxs("div",{"data-testid":"sankey-diagram",className:`w-full space-y-4 ${be?"h-full flex flex-col":""}`,children:[e.jsxs("div",{className:`p-4 bg-muted/30 border rounded-lg space-y-4 ${be?"flex-shrink-0":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"View:"}),e.jsxs("div",{className:"flex border rounded-lg overflow-hidden",children:[e.jsxs(ee,{variant:H==="sankey"?"default":"ghost",size:"sm",className:"rounded-none",onClick:()=>pe("sankey"),children:[e.jsx(Wt,{className:"h-4 w-4 mr-1"})," Sankey"]}),e.jsxs(ee,{variant:H==="list"?"default":"ghost",size:"sm",className:"rounded-none border-x",onClick:()=>pe("list"),children:[e.jsx(Zs,{className:"h-4 w-4 mr-1"})," List"]}),e.jsxs(ee,{variant:H==="table"?"default":"ghost",size:"sm",className:"rounded-none",onClick:()=>pe("table"),children:[e.jsx(fa,{className:"h-4 w-4 mr-1"})," Table"]})]})]}),e.jsx("div",{className:"flex items-center gap-4 flex-wrap",children:e.jsxs(xs,{delayDuration:300,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs(Ue,{className:"text-xs whitespace-nowrap cursor-help flex items-center gap-1",children:["Pages ",e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{side:"bottom",className:"max-w-[250px]",children:e.jsx("p",{className:"text-xs",children:'Number of pages (nodes) to display. Shows the top N pages by traffic. Use "All" to see every page.'})})]}),e.jsxs(os,{value:R.toString(),onValueChange:ne=>O(parseInt(ne)),children:[e.jsx(ds,{className:"w-24 h-8 text-xs",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"5",children:"5"}),e.jsx(me,{value:"10",children:"10"}),e.jsx(me,{value:"15",children:"15"}),e.jsx(me,{value:"25",children:"25"}),e.jsx(me,{value:"50",children:"50"}),e.jsxs(me,{value:"0",children:["All (",((L=Je==null?void 0:Je.nodes)==null?void 0:L.length)||0,")"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs(Ue,{className:"text-xs whitespace-nowrap cursor-help flex items-center gap-1",children:["Links ",e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{side:"bottom",className:"max-w-[250px]",children:e.jsx("p",{className:"text-xs",children:"Number of navigation paths (connections between pages) to display. Shows the top N paths by traffic volume."})})]}),e.jsxs(os,{value:N.toString(),onValueChange:ne=>re(parseInt(ne)),children:[e.jsx(ds,{className:"w-24 h-8 text-xs",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"15",children:"15"}),e.jsx(me,{value:"30",children:"30"}),e.jsx(me,{value:"50",children:"50"}),e.jsx(me,{value:"100",children:"100"}),e.jsx(me,{value:"0",children:"All"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs(Ue,{className:"text-xs whitespace-nowrap cursor-help flex items-center gap-1",children:["Sort ",e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{side:"bottom",className:"max-w-[250px]",children:e.jsx("p",{className:"text-xs",children:"How to order pages in the diagram: by visit count (most traffic first), exit rate (highest bounce first), or alphabetically."})})]}),e.jsxs(os,{value:ye,onValueChange:ne=>Ie(ne),children:[e.jsx(ds,{className:"w-28 h-8 text-xs",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"visits",children:"By Visits"}),e.jsx(me,{value:"exitRate",children:"By Exit Rate"}),e.jsx(me,{value:"name",children:"By Name"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs(Ue,{className:"text-xs whitespace-nowrap cursor-help flex items-center gap-1",children:["Min visits ",e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{side:"bottom",className:"max-w-[250px]",children:e.jsx("p",{className:"text-xs",children:"Hide pages with fewer than this many visits. Useful for focusing on high-traffic pages only."})})]}),e.jsx(Me,{type:"number",min:0,value:V,onChange:ne=>U(parseInt(ne.target.value)||0),className:"w-20 h-8 text-xs"})]}),e.jsxs("div",{className:"flex items-center gap-2 pl-2 border-l",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs(Ue,{className:"text-xs whitespace-nowrap cursor-help flex items-center gap-1",children:[e.jsx(Al,{className:"h-3 w-3 text-muted-foreground"}
80),"Exclude Admins",e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(Ae,{side:"bottom",className:"max-w-[280px]",children:[e.jsx("p",{className:"text-xs font-medium mb-1",children:"Exclude Admin Traffic"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When enabled, filters out navigation data from admin users, system admins, and test accounts. This gives a cleaner view of actual user behavior."}),(Je==null?void 0:Je.excludedUserCount)&&Je.excludedUserCount>0&&e.jsxs("p",{className:"text-xs text-amber-600 mt-1",children:["Currently excluding ",Je.excludedUserCount," user(s)"]})]})]}),e.jsx("button",{onClick:()=>Fe(!xe),"data-testid":"toggle-exclude-admins",className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${xe?"bg-primary":"bg-muted"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-surface-card shadow-sm transition-transform ${xe?"translate-x-4":"translate-x-0.5"}`})}),(Je==null?void 0:Je.excludedUserCount)&&Je.excludedUserCount>0&&xe&&e.jsxs(Y,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:["-",Je.excludedUserCount]})]}),e.jsx("div",{className:"flex items-center gap-2 pl-2 border-l",children:e.jsxs(Ic,{open:wt,onOpenChange:jt,children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(ee,{variant:"outline",size:"sm",className:`h-8 text-xs gap-1 ${ns==="include_only"&&X.length>0?"border-primary bg-primary/5":""}`,"data-testid":"button-filter-users",children:[ns==="include_only"?e.jsx(Za,{className:"h-3 w-3"}):e.jsx(Al,{className:"h-3 w-3"}),ns==="include_only"?"Show Only":"Exclude",X.length>0&&e.jsx(Y,{variant:ns==="include_only"?"default":"secondary",className:"ml-1 text-[10px] px-1.5 py-0",children:X.length})]})}),e.jsxs(Ec,{className:"w-96 p-0",align:"start",children:[e.jsxs("div",{className:"p-3 border-b space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(ee,{variant:ns==="exclude"?"secondary":"ghost",size:"sm",className:"flex-1 h-7 text-xs",onClick:()=>nt("exclude"),"data-testid":"mode-exclude",children:[e.jsx(Al,{className:"h-3 w-3 mr-1"}),"Exclude"]}),e.jsxs(ee,{variant:ns==="include_only"?"secondary":"ghost",size:"sm",className:"flex-1 h-7 text-xs",onClick:()=>nt("include_only"),"data-testid":"mode-include-only",children:[e.jsx(Za,{className:"h-3 w-3 mr-1"}),"Show Only"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Me,{placeholder:"Search by name, email, username...",value:ks,onChange:ne=>Rt(ne.target.value),className:"h-8 text-sm","data-testid":"input-user-search"})]}),X.length>0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[X.length," user(s) ",ns==="include_only"?"included":"excluded"]}),e.jsx(ee,{variant:"ghost",size:"sm",className:"h-6 text-xs text-destructive hover:text-destructive",onClick:()=>Be([]),"data-testid":"button-clear-selected",children:"Clear all"})]})]}),e.jsx(kt,{className:"h-[250px]",children:e.jsx("div",{className:"p-2 space-y-1",children:ea.length===0?e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:ks?"No users match your search":"No users found"}):ea.map(ne=>{const ke=X.includes(ne.id),Xe=()=>{Be(ls=>ls.includes(ne.id)?ls.filter(As=>As!==ne.id):[...ls,ne.id])};return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded cursor-pointer transition-colors ${ke?ns==="include_only"?"bg-primary/10":"bg-destructive/10":"hover:bg-muted"}`,onClick:Xe,"data-testid":`user-row-${ne.id}`,children:[e.jsx(lm,{checked:ke,onCheckedChange:()=>Xe()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[ne.firstName," ",ne.lastName]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[ne.email," ⢠",ne.role]})]}),ke&&e.jsx(Y,{variant:ns==="include_only"?"default":"destructive",className:"text-[10px]",children:ns==="include_only"?"Included":"Excluded"})]},ne.id)})})})]})]})})]})})]}),H==="sankey"&&e.jsx("div",{className:"flex items-center gap-4 flex-wrap pt-2 border-t",children:e.jsxs(xs,{delayDuration:300,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs(Ue,{className:"text-xs whitespace-nowrap cursor-help flex items-center gap-1",children:["Height ",e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsx(Ae,{side:"bottom",className:"max-w-[200px]",children:e.jsx("p",{className:"text-xs",children:"The vertical size of the diagram in pixels. Increase for more breathing room between nodes."})})]}),e.jsxs(os,{value:je.toString(),onValueChange:ne=>ce(parseInt(ne)),children:[e.jsx(ds,{className:"w-24 h-8 text-xs",children:e.jsx(hs,{})}
80),e.jsxs(ms,{children:[e.jsx(me,{value:"400",children:"400px"}),e.jsx(me,{value:"500",children:"500px"}),e.jsx(me,{value:"600",children:"600px"}),e.jsx(me,{value:"800",children:"800px"}),e.jsx(me,{value:"1000",children:"1000px"}),e.jsx(me,{value:"1200",children:"1200px"})]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 cursor-help",children:[e.jsx("input",{type:"checkbox",id:"showLabels",checked:j,onChange:ne=>Q(ne.target.checked),className:"rounded"}),e.jsxs(Ue,{htmlFor:"showLabels",className:"text-xs cursor-pointer flex items-center gap-1",children:["Labels ",e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"})]})]})}),e.jsx(Ae,{side:"bottom",className:"max-w-[200px]",children:e.jsx("p",{className:"text-xs",children:"Show or hide page names on the diagram nodes."})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 cursor-help",children:[e.jsx("input",{type:"checkbox",id:"showScrollDepth",checked:z,onChange:ne=>K(ne.target.checked),className:"rounded","data-testid":"checkbox-scroll-depth-overlay"}),e.jsxs(Ue,{htmlFor:"showScrollDepth",className:"text-xs cursor-pointer flex items-center gap-1",children:["Scroll Depth ",e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"})]})]})}),e.jsx(Ae,{side:"bottom",className:"max-w-[250px]",children:e.jsx("p",{className:"text-xs",children:"Overlay vertical gradients on nodes showing scroll depth. Darker colors = deeper scrolling = more engagement."})})]}),z&&e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("select",{value:P,onChange:ne=>ue(ne.target.value),className:"h-6 px-2 text-xs border rounded bg-background cursor-pointer","data-testid":"select-scroll-depth-range",children:[e.jsx("option",{value:"all",children:"All (0-100%)"}),e.jsx("option",{value:"0-25",children:"Focus: 0-25%"}),e.jsx("option",{value:"25-50",children:"Focus: 25-50%"}),e.jsx("option",{value:"50-75",children:"Focus: 50-75%"}),e.jsx("option",{value:"75-100",children:"Focus: 75-100%"})]})}),e.jsx(Ae,{side:"bottom",className:"max-w-[280px]",children:e.jsx("p",{className:"text-xs",children:"Focus on a specific range for maximum color differentiation. Nodes outside the range appear gray."})})]})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2 border-l pl-4 relative z-30",children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs(ee,{variant:be?"default":"outline",size:"sm",className:"h-7 gap-1",onClick:()=>ss(!be),"data-testid":"button-popout-diagram","aria-label":be?"Close pop-out":"Pop out to full screen",children:[be?e.jsx(_x,{className:"h-4 w-4"}):e.jsx(vo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:be?"Close":"Pop Out"})]})}),e.jsx(Ae,{side:"top",children:e.jsx("p",{className:"text-xs",children:be?"Return to inline view":"Pop out the entire section to fill your screen"})})]})})]})})]}),te&&e.jsxs(xs,{delayDuration:200,children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("button",{onClick:()=>ae(Le==="pages"?null:"pages"),className:`px-3 py-1.5 bg-card border rounded-full flex items-center gap-1.5 hover:bg-muted/50 transition-colors cursor-pointer ${Le==="pages"?"ring-2 ring-primary":""}`,children:[e.jsx(fa,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"font-semibold",children:te.displayedPages}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",te.totalPages]}),e.jsx("span",{className:"text-muted-foreground",children:"pages"}),e.jsx(Tt,{className:`h-3 w-3 text-muted-foreground transition-transform ${Le==="pages"?"rotate-180":""}`})]})}),e.jsxs(Ae,{side:"bottom",className:"max-w-[280px]",children:[e.jsx("p",{className:"font-medium",children:"Pages Displayed"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Shows ",te.displayedPages," of ",te.totalPages,' total unique pages tracked. Adjust the "Pages" dropdown above to show more or fewer pages in the diagram.']})]})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("button",{onClick:()=>ae(Le==="paths"?null:"paths"),className:`px-3 py-1.5 bg-card border rounded-full flex items-center gap-1.5 hover:bg-muted/50 transition-colors cursor-pointer ${Le==="paths"?"ring-2 ring-primary":""}`,children:[e.jsx(Va,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"font-semibold",children:te.displayedLinks}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",te.totalLinks]}),e.jsx("span",{className:"text-muted-foreground",children:"paths"}),e.jsx(Tt,{className:`h-3 w-3 text-muted-foreground transition-transform ${Le==="paths"?"rotate-180":""}`})]})}),e.jsxs(Ae,{side:"bottom",className:"max-w-[280px]",children:[e.jsx("p",{className:"font-medium",children:"Navigation Paths"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Shows ",te.displayedLinks," of ",te.totalLinks," unique page-to-page navigation paths. A path is created when a visitor clicks from one page to another. Click to see top paths."]})]})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("button",{onClick:()=>ae(Le==="navigations"?null:"navigations"),className:`px-3 py-1.5 bg-card border rounded-full flex items-center gap-1.5 hover:bg-muted/50 transition-colors cursor-pointer ${Le==="navigations"?"ring-2 ring-primary":""}`,children:[e.jsx(Is,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"font-semibold",children:te.totalNavigations.toLocaleStr
80ing()}),e.jsx("span",{className:"text-muted-foreground",children:"navigations"}),e.jsx(Tt,{className:`h-3 w-3 text-muted-foreground transition-transform ${Le==="navigations"?"rotate-180":""}`})]})}),e.jsxs(Ae,{side:"bottom",className:"max-w-[280px]",children:[e.jsx("p",{className:"font-medium",children:"Total Navigations"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"The total number of page-to-page navigation events shown in the diagram. Higher numbers = thicker lines in the Sankey chart. Click for breakdown."})]})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("button",{onClick:()=>ae(Le==="exitRate"?null:"exitRate"),className:`px-3 py-1.5 bg-card border rounded-full flex items-center gap-1.5 hover:bg-muted/50 transition-colors cursor-pointer ${Le==="exitRate"?"ring-2 ring-primary":""}`,children:[e.jsx(Tx,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:"font-semibold",children:[te.avgExitRate,"%"]}),e.jsx("span",{className:"text-muted-foreground",children:"avg exit"}),e.jsx(Tt,{className:`h-3 w-3 text-muted-foreground transition-transform ${Le==="exitRate"?"rotate-180":""}`})]})}),e.jsxs(Ae,{side:"bottom",className:"max-w-[280px]",children:[e.jsx("p",{className:"font-medium",children:"Average Exit Rate"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"The average percentage of visitors who leave your site from these pages. Lower is generally better (means visitors continue exploring). Click to see which pages have highest exits."})]})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("button",{onClick:()=>ae(Le==="highExit"?null:"highExit"),className:`px-3 py-1.5 bg-orange-50 dark:bg-orange-950/30 border border-orange-200 dark:border-orange-800 rounded-full flex items-center gap-1.5 hover:bg-orange-100 dark:hover:bg-orange-900/40 transition-colors cursor-pointer ${Le==="highExit"?"ring-2 ring-orange-400":""}`,children:[e.jsx(Fs,{className:"h-3 w-3 text-orange-600"}),e.jsx("span",{className:"font-semibold text-orange-600",children:te.highExitPages}),e.jsx("span",{className:"text-orange-600/70",children:"high exit"}),e.jsx(Tt,{className:`h-3 w-3 text-orange-600/70 transition-transform ${Le==="highExit"?"rotate-180":""}`})]})}),e.jsxs(Ae,{side:"bottom",className:"max-w-[280px]",children:[e.jsx("p",{className:"font-medium text-orange-600",children:"High Exit Pages"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[te.highExitPages," pages have exit rates above 50%. These are pages where visitors frequently leave. Consider improving content or adding clearer calls-to-action on these pages. Click to see the list."]})]})]}),te.circularLinksRemoved>0&&e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("button",{onClick:()=>Ne(!oe),className:`px-3 py-1.5 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-full flex items-center gap-1.5 hover:bg-amber-100 dark:hover:bg-amber-900/40 transition-colors cursor-pointer ${oe?"ring-2 ring-amber-400":""}`,children:[e.jsx(Pt,{className:"h-3 w-3 text-amber-600"}),e.jsx("span",{className:"font-semibold text-amber-600",children:te.circularLinksRemoved}),e.jsx("span",{className:"text-amber-600/70",children:"circular"}),e.jsx(Tt,{className:`h-3 w-3 text-amber-600/70 transition-transform ${oe?"rotate-180":""}`})]})}),e.jsxs(Ae,{side:"bottom",className:"max-w-[280px]",children:[e.jsx("p",{className:"font-medium text-amber-600",children:"Circular Navigation Paths"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[te.circularLinksRemoved," back-navigation patterns detected (e.g., A â B â A). Sankey diagrams can't show loops, so these are displayed separately below. Click to expand details."]})]})]})]}),Le&&e.jsxs("div",{className:"mt-3 p-3 bg-muted/30 border rounded-lg text-sm",children:[Le==="pages"&&e.jsxs("div",{children:[e.jsx("h5",{className:"font-medium mb-2",children:"Page Statistics"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-xs",children:[e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Total Tracked"}),e.jsxs("div",{className:"font-semibold",children:[te.totalPages," pages"]})]}),e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Currently Showing"}),e.jsxs("div",{className:"font-semibold",children:[te.displayedPages," pages"]})]}),e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Entry Pages"}),e.jsxs("div",{className:"font-semibold text-green-600",children:[te.entryPages," pages"]})]}),e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Hidden (filtered)"}),e.jsxs("div",{className:"font-semibold",children:[te.totalPages-te.displayedPages," pages"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:'Use the "Pages" dropdown above to adjust how many pages appear in the diagram.'})]}),Le==="paths"&&e.jsxs("div",{children:[e.jsx("h5",{className:"font-medium mb-2",children:"Navigation Path Statistics"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 text-xs",children:[e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Total Unique Paths"}),e.jsx("div",{className:"font-semibold",children:te.totalLinks})]}),e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Currently Showing"}),e.jsx("div",{className:"font-semibold",children:te.displayedLinks})]}),e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Circular (excluded)"}),e.jsx("div",{className:"font-semibold text-amber-600",children:te.circularLinksRemoved})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Paths show how visitors navigate between pages. Thicker lines = more traffic on that route."})]}),Le==="navigations"&&e.jsxs("div",{children:[e.jsx("h5",{className:"font-medium mb-2",children:"Navigation Volume"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 text-xs",children:[e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Linear Navigations"}),e.jsx("div",{className:"font-semibold",children:((Re=te.totalLinearTraffic)==null?void 0:Re.toLocaleStr
80ing())||te.totalNavigations.toLocaleString()})]}),e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Circular Navigations"}),e.jsx("div",{className:"font-semibold text-amber-600",children:((Ge=te.totalCircularTraffic)==null?void 0:Ge.toLocaleString())||0})]}),e.jsxs("div",{className:"p-2 bg-card rounded border",children:[e.jsx("div",{className:"text-muted-foreground",children:"Total Sessions"}),e.jsx("div",{className:"font-semibold",children:(($e=Je==null?void 0:Je.totalSessions)==null?void 0:$e.toLocaleString())||"N/A"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Each navigation event is when a visitor clicks from one page to another within a session."})]}),Le==="exitRate"&&e.jsxs("div",{children:[e.jsx("h5",{className:"font-medium mb-2",children:"Exit Rate Analysis"}),e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Average exit rate across displayed pages: ",e.jsxs("strong",{children:[te.avgExitRate,"%"]})]}),e.jsx("p",{className:"text-muted-foreground",children:"Exit rate shows what percentage of visitors leave your site from each page. Pages with high exit rates (shown in orange) may need better content or clearer next steps."}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-green-500"}),e.jsx("span",{children:"0-30% (Good)"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-yellow-500"}),e.jsx("span",{children:"30-50% (Average)"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-orange-500"}),e.jsx("span",{children:"50%+ (High)"})]})]})]})]}),Le==="highExit"&&e.jsxs("div",{children:[e.jsxs("h5",{className:"font-medium mb-2 text-orange-600",children:["High Exit Pages (",te.highExitPages,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"These pages have exit rates above 50%, meaning more than half of visitors leave from here. Consider reviewing these pages for potential improvements."}),e.jsx("div",{className:"space-y-1 max-h-32 overflow-y-auto",children:Js==null?void 0:Js.nodes.filter(ne=>{var ke;return parseFloat(((ke=ie.get(ne.id))==null?void 0:ke.exitRate)||"0")>50}).sort((ne,ke)=>{var Xe,ls;return parseFloat(((Xe=ie.get(ke.id))==null?void 0:Xe.exitRate)||"0")-parseFloat(((ls=ie.get(ne.id))==null?void 0:ls.exitRate)||"0")}).slice(0,10).map(ne=>{var ke;return e.jsxs("div",{className:"flex items-center justify-between text-xs p-1.5 bg-card rounded border",children:[e.jsx("span",{className:"truncate max-w-[200px]",children:ne.id}),e.jsxs("span",{className:"font-medium text-orange-600",children:[(ke=ie.get(ne.id))==null?void 0:ke.exitRate,"% exit"]})]},ne.id)})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs flex-wrap",children:[z?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:["Scroll Depth",P!=="all"&&` (${P}%)`,":"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:P==="all"?"0%":P.split("-")[0]+"%"}),e.jsx("div",{className:"w-32 h-4 rounded border",style:{background:"linear-gradient(to right, hsl(200, 70%, 85%), hsl(220, 75%, 70%), hsl(245, 80%, 55%), hsl(270, 85%, 45%))"}}),e.jsx("span",{className:"text-muted-foreground",children:P==="all"?"100%":P.split("-")[1]+"%"})]}),e.jsx("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:e.jsx("span",{children:"(Light = Low Scroll â Dark = Deep Scroll)"})}),P!=="all"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:"#e2e8f0"}}),e.jsx("span",{className:"text-muted-foreground",children:"Outside range"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:"#94a3b8"}}),e.jsx("span",{children:"No Data"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:"#22c55e"}}),e.jsxs("span",{children:["Entry Pages (",(te==null?void 0:te.entryPages)||0,")"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:"#3b82f6"}}),e.jsx("span",{children:"Conversion Pages"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:"#f97316"}}
80),e.jsx("span",{children:"High Exit Rate (>50%)"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:"#94a3b8"}}),e.jsx("span",{children:"Other Pages"})]})]}),e.jsxs("div",{className:"ml-auto text-muted-foreground",children:[((Qe=Je==null?void 0:Je.totalSessions)==null?void 0:Qe.toLocaleString())||0," total sessions"]})]}),H==="sankey"&&e.jsx("div",{className:`relative border rounded-lg bg-card transition-all duration-300 ${be?"flex-1 min-h-0":""}`,style:{height:be?"100%":`${je}px`},"data-testid":"nivo-sankey-container",children:e.jsx("div",{className:"w-full h-full overflow-visible",style:{position:"relative"},children:e.jsx("div",{className:"w-full h-full",style:{overflow:"visible"},children:e.jsx(e4,{data:Js,margin:{top:20,right:180,bottom:20,left:160},align:"justify",colors:ne=>z?"#e2e8f0":fe(ne),nodeOpacity:1,nodeHoverOpacity:1,nodeHoverOthersOpacity:.35,nodeThickness:18,nodeSpacing:24,nodeBorderWidth:0,nodeBorderRadius:3,linkOpacity:.5,linkHoverOpacity:.8,linkHoverOthersOpacity:.1,linkContract:3,enableLinkGradient:!0,labelPosition:"outside",labelOrientation:"horizontal",labelPadding:16,labelTextColor:{from:"color",modifiers:[["darker",1]]},layers:["links","nodes","labels","legends",We],nodeTooltip:({node:ne})=>{const ke=ie.get(ne.id);return e.jsxs("div",{className:"bg-popover border rounded shadow-lg p-3 text-sm",children:[e.jsx("div",{className:"font-semibold mb-1",children:ne.id}),e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("span",{children:"Visits:"}),e.jsx("span",{className:"font-medium text-foreground",children:((ke==null?void 0:ke.visits)||0).toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("span",{children:"Exit Rate:"}),e.jsxs("span",{className:"font-medium text-foreground",children:[(ke==null?void 0:ke.exitRate)||"0","%"]})]}),(ke==null?void 0:ke.avgScrollDepth)!==null&&(ke==null?void 0:ke.avgScrollDepth)!==void 0&&e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("span",{children:"Avg Scroll:"}),e.jsxs("span",{className:"font-medium text-foreground",children:[ke.avgScrollDepth,"%"]})]})]})]})},linkTooltip:({link:ne})=>e.jsxs("div",{className:"bg-popover border rounded shadow-lg p-3 text-sm",children:[e.jsx("div",{className:"font-semibold mb-1",children:"Navigation Flow"}),e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx("span",{children:ne.source.id}),e.jsx(Va,{className:"h-3 w-3"}),e.jsx("span",{children:ne.target.id})]}),e.jsxs("div",{className:"mt-1 font-medium text-foreground",children:[ne.value.toLocaleString()," navigations"]})]}),onClick:(ne,ke)=>{ne.id?(I(ne),le(ne.id)):ne.source&&ne.target&&(f(ne),J(`${ne.source.id} â ${ne.target.id}`))}})})})}),H==="list"&&e.jsx(we,{}),H==="table"&&e.jsx(gs,{}),(C||y)&&e.jsxs("div",{className:"mt-4 p-4 bg-card border rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"font-medium",children:C?"Page Details":"Navigation Path Details"}),e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>{I(null),f(null),le(null),J(null)},children:e.jsx(pt,{className:"h-4 w-4"})})]}),C&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Page"}),e.jsx("div",{className:"font-medium",children:C.id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Visits"}),e.jsx("div",{className:"font-medium",children:(((js=ie.get(C.id))==null?void 0:js.visits)||0).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Exit Rate"}),e.jsxs("div",{className:"font-medium",children:[((ze=ie.get(C.id))==null?void 0:ze.exitRate)||"0","%"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Avg Scroll Depth"}),e.jsxs("div",{className:"font-medium",children:[((Ns=ie.get(C.id
80))==null?void 0:Ns.avgScrollDepth)??"N/A","%"]})]})]}),y&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"From"}),e.jsx("div",{className:"font-medium",children:((He=y.source)==null?void 0:He.id)||y.source})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"To"}),e.jsx("div",{className:"font-medium",children:((Gs=y.target)==null?void 0:Gs.id)||y.target})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Navigations"}),e.jsx("div",{className:"font-medium",children:(y.value||0).toLocaleString()})]})]})]}),te&&te.circularLinksRemoved>0&&te.circularPathsGrouped&&te.circularPathsGrouped.length>0&&e.jsx(Ta,{type:"single",collapsible:!0,value:oe?"circular-paths":"",onValueChange:ne=>Ne(ne==="circular-paths"),className:"mt-4",children:e.jsxs(Da,{value:"circular-paths",className:"border border-amber-200 dark:border-amber-800 rounded-lg bg-gradient-to-br from-amber-50/50 to-orange-50/50 dark:from-amber-950/30 dark:to-orange-950/30 overflow-hidden","data-testid":"circular-paths-accordion",children:[e.jsx(Pa,{className:"px-4 py-3 hover:no-underline",children:e.jsxs("div",{className:"flex items-center justify-between w-full pr-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-amber-100 dark:bg-amber-900 rounded",children:e.jsx(Pt,{className:"h-4 w-4 text-amber-600 dark:text-amber-400"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("span",{className:"font-medium text-amber-900 dark:text-amber-100",children:"Circular Navigation Paths"}),e.jsxs("span",{className:"text-xs text-amber-700 dark:text-amber-300 ml-2",children:["(",te.circularLinksRemoved," back-navigation patterns)"]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Y,{variant:"outline",className:"bg-amber-100/50 border-amber-300 text-amber-700 text-xs",children:[te.circularTrafficPercentage,"% of traffic"]})})]})}),e.jsx(Ma,{className:"px-4 pb-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs bg-surface-card/50 dark:bg-black/20 rounded-lg p-3 border border-amber-200/50 dark:border-amber-700/50",children:[e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full bg-green-500"}),e.jsx("span",{className:"text-muted-foreground",children:"Linear:"}),e.jsx("span",{className:"font-semibold",children:te.totalLinearTraffic.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground",children:["(",(100-parseFloat(te.circularTrafficPercentage)).toFixed(1),"%)"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full bg-amber-500"}),e.jsx("span",{className:"text-muted-foreground",children:"Circular:"}),e.jsx("span",{className:"font-semibold",children:te.totalCircularTraffic.toLocaleString()}),e.jsxs("span",{className:"text-muted-foreground",children:["(",te.circularTrafficPercentage,"%)"]})]})]}),e.jsxs("div",{className:"text-muted-foreground",children:[te.circularPathsGrouped.length," unique loop patterns"]})]}),e.jsx("div",{className:"space-y-1.5",children:te.circularPathsGrouped.map((ne,ke)=>{var Ds;const Xe=((Ds=te.circularPathsGrouped[0])==null?void 0:Ds.totalTraffic)||1,ls=ne.totalTraffic/Xe*100,As=ne.pages.join(" â ");return e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"group relative flex items-center gap-3 py-2 px-3 rounded-lg hover:bg-amber-50/70 dark:hover:bg-amber-900/20 transition-all cursor-pointer border border-transparent hover:border-amber-200 dark:hover:border-amber-700","data-testid":`circular-bar-${ke}`,children:[e.jsx("div",{className:"w-5 text-xs font-medium text-amber-500 dark:text-amber-400 text-right flex-shrink-0",children:ke+1}),e.jsx("div",{className:"w-32 md:w-48 flex-shrink-0 truncate",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Pt,{className:"h-3 w-3 text-amber-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs font-medium truncate",title:As,children:ne.pages.length===2?`${ne.pages[0].replace(/^\//,"").split("/")[0]||"home"} â ${ne.pages[1].replace(/^\//,"").split("/")[0]||"home"}`:ne.pages.length===3?`${ne.pages[0].replace(/^\//,"").split("/")[0]||"home"} â ${ne.pages[1].replace(/^\//,"").split("/")[0]||"home"} â ...`:`${ne.pages.length}-page loop`})]})}),e.jsxs("div",{className:"flex-1 h-6 bg-amber-100/50 dark:bg-amber-900/30 rounded-md overflow-hidden relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 rounded-md transition-all duration-500 ease-out group-hover:brightness-110",style:{width:`${ls}%`,background:"linear-gradient(90deg, #f59e0b 0%, #fb923c 100%)"}}),e.jsx("div",{className:"absolute inset-0 flex items-center px-2",children:e.jsxs("span",{className:`text-xs font-medium ${ls>30?"text-white":"text-amber-700 dark:text-amber-300 ml-auto"}
80`,children:[ne.totalTraffic.toLocaleString()," (",ne.percentage.toFixed(1),"%)"]})})]})]})}),e.jsx(Ae,{side:"top",className:"max-w-sm p-3 bg-surface-card dark:bg-gray-900 border shadow-lg",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"font-semibold text-sm text-amber-700 dark:text-amber-300 flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4"}),"Circular Navigation Pattern"]}),e.jsxs("div",{className:"text-xs space-y-1.5",children:[e.jsx("div",{className:"font-medium",children:"Full Path:"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[ne.pages.map((_s,h)=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-medium",style:{backgroundColor:`${qs.get(_s)||"#94a3b8"}20`,color:qs.get(_s)||"#64748b"},children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:qs.get(_s)||"#94a3b8"}}),_s]}),h<ne.pages.length-1&&e.jsx(Va,{className:"h-3 w-3 text-muted-foreground"})]},`${_s}-${h}`)),e.jsx(Va,{className:"h-3 w-3 text-amber-500"}),e.jsx("span",{className:"text-amber-500 text-[11px] font-medium",children:"(back to start)"})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Traffic:"}),e.jsxs("span",{className:"font-semibold",children:[ne.totalTraffic.toLocaleString()," navigations"]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Share of circular:"}),e.jsxs("span",{className:"font-semibold",children:[ne.percentage.toFixed(1),"%"]})]})]})})]})},ne.key)})}),e.jsxs("div",{className:"text-xs text-muted-foreground bg-surface-card/30 dark:bg-black/10 rounded-lg p-2 border border-amber-200/30 dark:border-amber-800/30",children:[e.jsx("span",{className:"font-medium",children:"What this shows:"})," Users navigating back to pages they already visited (e.g., Dashboard â Settings â Dashboard). Hover over any bar to see the complete navigation path."]})]})})]})})]});return be?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 bg-black/60 z-50",onClick:()=>ss(!1),"data-testid":"popout-backdrop"}),e.jsxs("div",{className:"fixed inset-4 z-50 bg-background rounded-xl border shadow-2xl flex flex-col overflow-hidden","data-testid":"popout-container",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b bg-muted/30 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-5 w-5 text-blue-500"}),e.jsx("span",{className:"font-semibold",children:"Site Navigation Flow"}),e.jsx(Y,{variant:"outline",children:"Interactive"})]}),e.jsxs(ee,{variant:"ghost",size:"sm",onClick:()=>ss(!1),"data-testid":"button-close-popout",children:[e.jsx(pt,{className:"h-4 w-4 mr-1"}),"Close"]})]}),e.jsx("div",{className:"flex-1 overflow-auto p-4",children:Ss})]})]}):Ss}function de({pages:D,entryPointRange:$}){const{highlightedNode:se}=p.useContext(Xr),[J,le]=p.useState(null),[C,I]=p.useState(null),y=p.useMemo(()=>!D||!Array.isArray(D)?[]:D.filter(V=>V&&V.name&&V.name!=="exit").sort((V,U)=>(U.visits||0)-(V.visits||0)).slice(0,8),[D]),f=p.useMemo(()=>y.length===0?[]:y.map(V=>({queryKey:["/api/analytics/page-scroll",V.name,$.startDate.toISOString(),$.endDate.toISOString()],queryFn:async()=>{const U=await fetch(`/api/analytics/page-scroll?pageUrl=${encodeURIComponent(V.name)}&startDate=${$.startDate.toISOString()}&endDate=${$.endDate.toISOString()}`);if(!U.ok){const j=await U.text();throw console.error(`[SCROLL_DEPTH] API error for ${V.name}: ${U.status} - ${j}`),new Error(`Failed to fetch scroll data: ${U.status}`)}return U.json()},enabled:!0})),[y,$.startDate,$.endDate]),R=Oh({queries:f}),O=R.some(V=>V.isLoading),N=R.some(V=>V.error),re=R.filter(V=>V.error),H=p.useMemo(()=>{const V=new Map;return R.forEach((U,j)=>{U.data&&y[j]&&V.set(y[j].name||"",U.data)}),V},[R,y]),[pe,ye]=p.useState(null),Ie=V=>V>=80?"bg-green-500":V>=50?"bg-yellow-500":V>=25?"bg-orange-500":"bg-red-500",ve=V=>V>=80?"text-green-600 dark:text-green-400":V>=50?"text-yellow-600 dark:text-yellow-400":V>
80=25?"text-orange-600 dark:text-orange-400":"text-red-600 dark:text-red-400",B=V=>V>=60?"text-green-600 dark:text-green-400":V>=30?"text-yellow-600 dark:text-yellow-400":"text-red-600 dark:text-red-400",z=V=>{const U=V.toLowerCase();return U==="mobile"||U.includes("phone")?e.jsx(Ht,{className:"h-3 w-3"}):U==="tablet"?e.jsx(Ga,{className:"h-3 w-3"}):e.jsx(tt,{className:"h-3 w-3"})},K=(V,U)=>{var je;if(!((je=V==null?void 0:V.scrollDistribution)!=null&&je.length))return 0;let j=0;const Q=V.totalSessions||0;if(Q===0)return 0;for(const ce of V.scrollDistribution)ce.rangeStart>=U&&(j+=ce.count);return Math.round(j/Q*100)},P=V=>{var Q;const U=[],j=[0,10,20,30,40,50,60,70,80,90,100];if(!((Q=V==null?void 0:V.scrollDistribution)!=null&&Q.length)||V.totalSessions===0)return j.map(je=>({depth:je,reach:0,dropoff:0}));for(let je=0;je<j.length;je++){const ce=j[je],be=K(V,ce),ss=je>0?U[je-1].reach:be,oe=je>0?ss-be:0;U.push({depth:ce,reach:be,dropoff:oe})}return U},ue=V=>V==="/"?"Home":V.split("/").filter(Boolean).pop()||V;return y.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Hs,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"No pages to analyze"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Page scroll data will appear once you have visitor traffic"})]}):O?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[1,2,3,4].map(V=>e.jsx(_,{className:"animate-pulse",children:e.jsxs(T,{className:"pt-4",children:[e.jsx("div",{className:"h-4 bg-muted rounded w-3/4 mb-3"}),e.jsx("div",{className:"h-8 bg-muted rounded w-1/2 mb-2"}),e.jsx("div",{className:"h-2 bg-muted rounded w-full"})]})},V))})}):N&&H.size===0?e.jsxs("div",{className:"text-center py-8 text-red-600",children:[e.jsx(Fs,{className:"h-12 w-12 mx-auto mb-4"}),e.jsx("p",{className:"font-medium",children:"Failed to load scroll depth data"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[re.length," page(s) failed to load"]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:y.map(V=>{const U=H.get(V.name),j=(U==null?void 0:U.avgScrollDepth)||0,Q=se===V.name,je=J===V.name;return e.jsx(_,{className:`cursor-pointer transition-all hover:shadow-md ${Q?"ring-2 ring-blue-500 shadow-lg":""} ${je?"ring-2 ring-purple-500":""}`,onClick:()=>{le(J===V.name?null:V.name),I(C===V.name?null:V.name)},"data-testid":`scroll-page-${V.name.replace(/\//g,"-")}`,children:e.jsxs(T,{className:"pt-4",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx("span",{className:"text-sm font-medium truncate",title:V.name,children:ue(V.name)})}),e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:`text-2xl font-bold ${B(j)} cursor-help inline-block`,children:[j,"%"]})}),e.jsxs(Ae,{side:"top",className:"max-w-[250px]",children:[e.jsx("p",{className:"font-medium mb-1",children:"Average Scroll Depth"}),e.jsx("p",{className:"text-xs",children:"How far down the page users typically scroll. 100% means reaching the bottom."}),e.jsx("p",{className:"text-xs mt-1 text-muted-foreground",children:j>=60?"Excellent: Users are engaging well with content":j>=30?"Moderate: Consider moving key content higher":"Poor: Most users leave before scrolling much"})]})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"avg scroll depth"}),e.jsx(mt,{value:j,className:"h-2"}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:j>=60?"text-green-600":j>=30?"text-yellow-600":"text-red-600",children:j>=60?"â Excellent":j>=30?"â Moderate":"â Poor"}),e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"ml-auto cursor-help underline decoration-dotted",children:[((U==null?void 0:U.totalSessions)||0).toLocaleString()," sessions"]})}),e.jsxs(Ae,{side:"top",className:"max-w-[250px]",children:[e.jsx("p",{className:"font-medium mb-1",children:"Sessions Analyzed"}),e.jsx("p",{className:"text-xs",children:"Total sessions where we tracked scroll behavior on this page during this time period."})]})]})})]})]})},V.name)})}),C&&H.get(C)&&(()=>{const V=H.get(C),U=P(V),j=V.percentiles.p50,Q=V.percentiles.p75,je=V.percentiles.p90;return e.jsxs(_,{className:"border-purple-200 dark:border-purple-800","data-testid":"unified-scroll-map",children:[e.jsxs(q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(W,{className:"text-base flex items-center gap-2",children:[e.jsx(Hs,{className:"h-4 w-4 text-purple-500"}
80),"Scroll Reach Map"]}),e.jsx(Y,{variant:"outline",className:"text-xs",children:C})]}),e.jsx(ee,{variant:"ghost",size:"sm","data-testid":"button-close-scroll-map",onClick:()=>{I(null),le(null),ye(null)},children:e.jsx(pt,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 mt-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:V.totalSessions.toLocaleString()}),e.jsx("span",{className:"text-muted-foreground",children:"sessions"})]}),e.jsx(Sl,{orientation:"vertical",className:"h-4"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:`font-bold ${B(V.avgScrollDepth)}`,children:[V.avgScrollDepth,"%"]}),e.jsx("span",{className:"text-muted-foreground",children:"avg depth"})]}),e.jsx(Sl,{orientation:"vertical",className:"h-4"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:`font-bold ${B(j)}`,children:[j,"%"]}),e.jsx("span",{className:"text-muted-foreground",children:"median (P50)"})]}),e.jsx(Sl,{orientation:"vertical",className:"h-4"}),e.jsx("div",{className:"flex items-center gap-3",children:(V.deviceBreakdown||[]).map(ce=>e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 cursor-help",children:[z(ce.device),e.jsx("span",{className:"text-xs text-muted-foreground",children:ce.sessions})]})}),e.jsx(Ae,{children:e.jsxs("p",{className:"capitalize",children:[ce.device,": ",ce.avgScrollDepth,"% avg depth (",ce.sessions," sessions)"]})})]})},ce.device))})]})]}),e.jsx(T,{children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1fr_300px] gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Page Scroll Reach"}),e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsx(bs,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs(Ae,{className:"max-w-sm",children:[e.jsx("p",{className:"font-medium mb-1",children:"How to read this visualization:"}),e.jsx("p",{children:'Each bar shows what % of users scrolled to that depth. Green = most users saw this, Red = few users reached here. Hover over any bar to see exact reach %. Sharp drop-offs (red arrows) indicate potential "false bottoms" where users stop scrolling.'})]})]})})]}),e.jsxs("div",{className:"relative","data-testid":"scroll-reach-bands",children:[U.map((ce,be)=>{var Ne,Le,ae,xe,Fe,X;const ss=pe===ce.depth;ce.depth===j||ce.depth===Q||ce.depth===je||j>ce.depth&&j<(((Ne=U[be+1])==null?void 0:Ne.depth)||100)||Q>ce.depth&&Q<(((Le=U[be+1])==null?void 0:Le.depth)||100)||je>ce.depth&&je<(((ae=U[be+1])==null?void 0:ae.depth)||100);const oe=ce.dropoff>=15;return e.jsxs("div",{className:`flex items-center gap-3 py-1.5 px-2 rounded transition-all cursor-pointer ${ss?"bg-purple-100 dark:bg-purple-900/30":"hover:bg-muted/50"}`,onMouseEnter:()=>ye(ce.depth),onMouseLeave:()=>ye(null),"data-testid":`scroll-band-${ce.depth}`,children:[e.jsx("div",{className:"w-12 text-right",children:e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:[ce.depth,"%"]})}),e.jsxs("div",{className:"flex-1 h-6 bg-muted/30 rounded-sm overflow-hidden relative",children:[e.jsx("div",{className:`h-full transition-all duration-300 ${Ie(ce.reach)}`,style:{width:`${ce.reach}%`}}),ce.depth<=j&&(((xe=U[be+1])==null?void 0:xe.depth)||100)>j&&e.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-purple-600 dark:bg-purple-400",style:{left:`${j}%`},children:e.jsxs("span",{className:"absolute -top-5 -translate-x-1/2 text-[10px] bg-purple-600 text-white px-1 rounded whitespace-nowrap",children:["P50 (",j,"%)"]})}),ce.depth<=Q&&(((Fe=U[be+1])==null?void 0:Fe.depth)||100)>Q&&e.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-orange-500",style:{left:`${Q}%`},children:e.jsxs("span",{className:"absolute -top-5 -translate-x-1/2 text-[10px] bg-
80orange-500 text-white px-1 rounded whitespace-nowrap",children:["P75 (",Q,"%)"]})}),ce.depth<=je&&(((X=U[be+1])==null?void 0:X.depth)||100)>je&&e.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-red-500",style:{left:`${je}%`},children:e.jsxs("span",{className:"absolute -top-5 -translate-x-1/2 text-[10px] bg-red-500 text-white px-1 rounded whitespace-nowrap",children:["P90 (",je,"%)"]})})]}),e.jsx("div",{className:"w-16 text-right",children:e.jsxs("span",{className:`text-sm font-bold ${ve(ce.reach)}`,children:[ce.reach,"%"]})}),e.jsx("div",{className:"w-20 text-right",children:be>0&&ce.dropoff>0&&e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:`text-xs flex items-center justify-end gap-1 ${oe?"text-red-600 dark:text-red-400 font-medium":"text-muted-foreground"}`,children:[oe&&e.jsx(tc,{className:"h-3 w-3"}),"-",ce.dropoff,"%"]})}),e.jsxs(Ae,{children:[e.jsxs("p",{children:[ce.dropoff,"% of users stopped scrolling before reaching ",ce.depth,"% depth"]}),oe&&e.jsx("p",{className:"text-orange-400 mt-1",children:"â ï¸ Significant drop-off - check for false bottom"})]})]})})})]},ce.depth)}),pe!==null&&e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-48 pointer-events-none flex items-center justify-end",children:e.jsxs("div",{className:"bg-purple-600 text-white px-3 py-1.5 rounded-lg shadow-lg text-sm",children:[e.jsxs("span",{className:"font-bold",children:[K(V,pe),"%"]}),e.jsxs("span",{className:"ml-1",children:["of users scrolled to ",pe,"%"]})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-4 pt-4 border-t text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-green-500"}),e.jsx("span",{children:"Hot Zone (80%+ reach)"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-yellow-500"}),e.jsx("span",{children:"Warm (50-80%)"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-orange-500"}),e.jsx("span",{children:"Cool (25-50%)"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-red-500"}),e.jsx("span",{children:"Cold Zone (<25%)"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-4",children:[e.jsx(tc,{className:"h-3 w-3 text-red-500"}),e.jsx("span",{children:"Significant drop-off (15%+)"})]})]})]}),e.jsxs("div",{className:"space-y-4 lg:border-l lg:pl-6",children:[e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(lt,{className:"h-4 w-4"}),"Scroll Depth Percentiles"]}),e.jsx("div",{className:"space-y-2",children:[{label:"P50 (Median)",value:j,color:"purple",meaning:"Half of users scrolled at least this far"},{label:"P75",value:Q,color:"orange",meaning:"25% of users reached this depth"},{label:"P90",value:je,color:"red",meaning:"Top 10% of engaged users"}].map(({label:ce,value:be,color:ss,meaning:oe})=>e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"flex items-center justify-between p-2 bg-muted/50 rounded cursor-help",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full bg-${ss}-500`}),e.jsx("span",{className:"text-sm",children:ce})]}),e.jsxs("span",{className:"font-bold",children:[be,"%"]})]})}),e.jsx(Ae,{children:e.jsx("p",{children:oe})})]})},ce))})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(Zs,{className:"h-4 w-4"}),"Session Distribution",e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"How many sessions fell into each scroll depth bucket. Taller bars = more sessions stopped at that depth."})})]})})]}),e.jsx("div",{className:"space-y-1",children:(V.scrollDistribution||[]).map(ce=>{const be=Math.max(...(V.scrollDistribution||[]).map(Ne=>Ne.count)),ss=be>0?ce.count/be*100:0,oe=K(V,ce.rangeStart);return e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 cursor-help",children:[e.jsx("span",{className:"text-[10px] w-12 text-right text-muted-foreground",children:ce.range}),e.jsx("div",{className:"flex-1 h-4 bg-muted/30 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full transition-all ${Ie(oe)}`,style:{width:`${ss}%`}})}),e.jsx("span",{className:"text-[10px] w-8 text-muted-foreground",children:ce.count})]})}),e.jsx(Ae,{children:e.jsxs("p",{children:[ce.count," sessions (",ce.percentage,"%) stopped at ",ce.range," scroll depth"]})})]})},ce.range)})})]}),(V.deviceBreakdown||[]).length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4"}),"By Device"]}),e.jsx("div",{className:"space-y-2",children:(V.deviceBreakdown||[]).map(ce=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-muted/50 rounded",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[z(ce.device),e.jsx("span",{className:"text-sm capitalize",children:ce.device})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("span",{className:`font-bold ${B(ce.avgScrollDepth)}`,children:[ce.avgScrollDepth,"%"]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(",ce.sessions,")"]})]})]},ce.device))})]})]})]})})]})})(),y.every(V=>!H.get(V.name)||H.get(V.name).totalSessions===0)&&e.jsxs(Qs,{children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx(Xs,{children:"No scroll tracking data available for these pages. Scroll data will appear once visitors interact with your pages."})]})]})}function M({entryPointRange:D}){const[$,se]=p.useState(ai("30d")),{data:J,isLoading:le}=_e({queryKey:["/api/analytics/site-sankey",$.startDate.toISOString(),$.endDate.toISOString()],queryFn:async()=>{const I=await fetch(`/api/analytics/site-sankey?startDate=${$.startDate.toISOString()}&endDate=${$.endDate.toISOString()}`);if(!I.ok)throw new Error("Failed to fetch Sankey data");return I.json()}}),C=p.useMemo(()=>J!=null&&J.nodes?J.nodes.map(I=>({name:I.name,visits:I.visits})):[],[J]);return le?e.jsxs(_,{className:"mt-6","data-testid":"card-scroll-depth",children:[e.jsxs(q,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5 text-purple-500"}),"Page Scroll Depth Analysis"]}),e.jsx(Hr,{value:$,onChange:se,compact:!0})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Understand how far users scroll on each page (",De($.startDate,"MMM d")," - ",De($.endD
80ate,"MMM d, yyyy"),")"]})]}),e.jsx(T,{children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[1,2,3,4].map(I=>e.jsx(_,{className:"animate-pulse",children:e.jsxs(T,{className:"pt-4",children:[e.jsx("div",{className:"h-4 bg-muted rounded w-3/4 mb-3"}),e.jsx("div",{className:"h-8 bg-muted rounded w-1/2 mb-2"}),e.jsx("div",{className:"h-2 bg-muted rounded w-full"})]})},I))})})]}):e.jsxs(_,{className:"mt-6","data-testid":"card-scroll-depth",children:[e.jsxs(q,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5 text-purple-500"}),"Page Scroll Depth Analysis",e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(bs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsxs(Ae,{side:"right",className:"max-w-[300px]",children:[e.jsx("p",{className:"font-medium mb-2",children:"Understanding This Section"}),e.jsxs("ul",{className:"text-xs space-y-1.5",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Percentage"}),": Average scroll depth - how far down visitors scroll on this page (100% = reached bottom)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Sessions"}),": Total sessions where scroll behavior was tracked"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Color rating"}),": Green (60%+) = Excellent, Yellow (30-59%) = Moderate, Red (<30%) = Poor"]})]}),e.jsx("p",{className:"text-xs mt-2 text-muted-foreground",children:"Click any card to see detailed scroll distribution and device breakdown."})]})]})})]}),e.jsx(Hr,{value:$,onChange:se,compact:!0})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Understand how far users scroll on each page (",De($.startDate,"MMM d")," - ",De($.endDate,"MMM d, yyyy"),")"]})]}),e.jsx(T,{children:e.jsx(de,{pages:C,entryPointRange:$})})]})}const G=()=>{var nt,ks,Rt,wt,jt,rs,ea,Je,da,qt,Js,qs,ie,te,fe,ge,We,we,gs,Ss;const[D,$]=p.useState(ai("30d")),[se,J]=p.useState(ai("30d")),le=new Date("2025-12-03T12:00:00Z"),C=se.startDate<le?le:se.startDate,I=se.startDate<le,[y,f]=p.useState(null),[R,O]=p.useState(!1),[N,re]=p.useState(null),[H,pe]=p.useState(!1),[ye,Ie]=p.useState(null),[ve,B]=p.useState(null),[z,K]=p.useState(!1),{data:P,isLoading:ue}=_e({queryKey:["/api/analytics/entry-point-users",y==null?void 0:y.entry_page,y==null?void 0:y.sitelink,se.startDate.toISOString()],queryFn:async()=>y?(await fetch(`/api/analytics/entry-point-users?entryPage=${encodeURIComponent(y.entry_page)}&sitelink=${encodeURIComponent(y.sitelink)}&startDate=${se.startDate.toISOString()}&endDate=${se.endDate.toISOString()}`)).json():null,enabled:!!y&&R}),{data:V,isLoading:U}=_e({queryKey:["/api/analytics/funnel-stage-users",N==null?void 0:N.key,D.startDate.toISOString()],queryFn:async()=>N?(await fetch(`/api/analytics/funnel-stage-users?stage=${encodeURIComponent(N.key)}&startDate=${D.startDate.toISOString()}&endDate=${D.endDate.toISOString()}`)).json():null,enabled:!!N&&H}),{data:j}=_e({queryKey:["/api/analytics/user-journey",D.preset,D.startDate.toISOString(),D.endDate.toISOString()],queryFn:async()=>(await fetch(`/api/analytics/user-journey?startDate=${D.startDate.toISOString()}&endDate=${D.endDate.toISOString()}`)).json(),refetchInterval:5*60*1e3}),{data:Q}=_e({queryKey:["/api/analytics/user-journey","entrypoints",se.preset,se.startDate.toISOString(),se.endDate.toISOString()],queryFn:async()=>(await fetch(`/api/analytics/user-journey?startDate=${se.startDate.toISOString()}&endDate=${se.endDate.toISOString()}`)).json(),refetchInterval:5*60*1e3}),{data:je,isLoading:ce}=_e({queryKey:["/api/analytics/google-ads/sitelinks",se.startDate.toISOString(),se.endDate.toISOString()],queryFn:async()=>{const L=De(se.startDate,"yyyy-MM-dd"),Re=De(se.endDate,"yyyy-MM-dd");return(await fetch(`/api/analytics/google-ads/sitelinks?startDate=${L}&endDate=${Re}`)).json()},refetchInterval:10*60*1e3,staleTime:5*60*1e3});je!=null&&je.sitelinks&&console.log("[GOOGLE_ADS_SITELINKS] Loaded dynamic sitelink data:",{sitelinks:je.sitelinks.length,campaigns:((nt=je.campaigns)==null?void 0:nt.length)||0,adGroups:((ks=je.adGroups)==null?void 0:ks.length)||0,account:((Rt=je.accountInfo)==null?void 0:Rt.name)||"Unknown"});const be={Globe:ot,UserPlus:si,Mail:Ax,UserCheck:Za,Users:Ys,Activity:ja},ss=[{stage:"Website Visit",count:null,icon:ot},{stage:"Sign Up Started",count:null,icon:si},{stage:"Account Created",count:null,icon:Za},{stage:"First Patient Added",count:null,icon:Ys},{stage:"Active Subscriber",count:null,icon:ja}];j!=null&&j.stages||console.log("[ANALYTICS] User journey data is missing - displaying null state");const oe={"Website Visit":"website_visit","Sign Up Started":"signup_started","Account Created":"account_created","First Patient Added":"first_patient_added","Active Subscriber":"active_subscriber"},Ne=j!=null&&j.stages?j.stages.map(L=>({...L,icon:be[L.icon]||ot})):ss,Le=L=>({"/":"Homepage","/pricing":"Pricing Page","/learn":"Demo Videos","/auth":"Registration","/scribe":"AI Scribe Landing","/#features":"Features Section"})[L]||L,ae=L=>!L||L==="none"||L==="direct"?"Direct / Organic":L==="homepage_legacy"?"Legacy Tracking":L.split("_").map(Re=>Re.charAt(0).toUpperCase()+Re.slice(1)).join(" "),xe=(Q==null?void 0:Q.entryPoints)||[],Fe=Q==null?void 0:Q.dataInfo,X=[{entry_page:"/",sitelink:"direct",label:"Homepage",sublabel:"Direct / Organic",description:"Visitors who arrived at the homepage directly (typed URL, bookmark) or via organic search (Google, Bing). No paid ad attribution.",pageDescription:"Main landing page showcasing Clarafi EHR features, testimonials, and call-to-action.",googleAdsLink:null,isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:"https://www.clarafi.ai/"},{entry_page:"/",sitelink:"homepage",label:"Homepage",sublabel:"Google Ads Headline",description:"Visitors who clicked on a Google Ads headline or main ad link that directed to the homepage.",pageDescription:"Main landing page showcasing Clarafi EHR features, testimonials, and call-to-action.",googleAdsLink:"Leads-Search-1 Campaign",isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:"https://www.clarafi.ai/"},{entry_page:"/pricing",sitelink:"pricing_plans",label:"Pricing Page",sublabel:"Pricing Plans (Sitelink)",description:_t()?'Visitors who clicked the "Pricing Plans" sitelink extension in Google Ads.':'Visitors who clicked the "Pricing Plans" sitelink extension in Google Ads. High purchase intent signal.',pageDescription:"Displays Tier 1, Tier 2, and Enterprise pricing with feature comparison.",googleAdsLink:'Leads-Search-1 â Sitelink: "Pricing Plans"',isGoogleAdsSitelink:!0,sitelinkText:"Pricing Plans",descriptionLine1:_t()?"Learn more about our plans":"Trans
80parent pricing from $99/month",descriptionLine2:_t()?"Get started today":"No hidden fees, cancel anytime",finalUrl:"https://www.clarafi.ai/pricing"},{entry_page:"/pricing",sitelink:"direct",label:"Pricing Page",sublabel:"Direct / Organic",description:_t()?"Visitors who navigated to pricing directly or via organic search.":"Visitors who navigated to pricing directly or via organic search. May have compared pricing from multiple vendors.",pageDescription:"Displays Tier 1, Tier 2, and Enterprise pricing with feature comparison.",googleAdsLink:null,isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:"https://www.clarafi.ai/pricing"},{entry_page:"/learn",sitelink:"watch_demo_videos",label:"Demo Videos",sublabel:"Watch Demo Videos (Sitelink)",description:'Visitors who clicked "Watch Demo Videos" sitelink in Google Ads. These users want to see the product in action before signing up.',pageDescription:"Video tutorials and product demonstrations showing AI scribe, charting, and workflow features.",googleAdsLink:'Leads-Search-1 â Sitelink: "Watch Demo Videos"',isGoogleAdsSitelink:!0,sitelinkText:"Watch Demo Videos",descriptionLine1:"Learn how Clarafi works in action",descriptionLine2:"Step-by-step tutorials available",finalUrl:"https://www.clarafi.ai/learn"},{entry_page:"/learn",sitelink:"direct",label:"Demo Videos",sublabel:"Direct / Organic",description:"Visitors who found the demo videos page through direct navigation or organic search.",pageDescription:"Video tutorials and product demonstrations showing AI scribe, charting, and workflow features.",googleAdsLink:null,isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:"https://www.clarafi.ai/learn"},{entry_page:"/auth",sitelink:"start_free_trial",label:_t()?"Account Signup":"Free Trial Signup",sublabel:"Google Ads Sitelinks",description:_t()?'Visitors who clicked any "Get Started" or "Sign Up Now" sitelink in Google Ads. Highest intent signal - ready to try the product.':'Visitors who clicked any "Start Free Trial" or "Sign Up Now" sitelink in Google Ads. Highest intent signal - ready to try the product. Includes: "Start Free Trial" (Clarafi AI Scribe free for 30 days), "Start Free Trial" (Try Clarafi AI EHR free for 30 days), and "Sign Up Now" (Create your physician account today).',pageDescription:_t()?"Account registration page where users create their Clarafi account.":"Account registration page where users create their Clarafi account and start their 30-day trial.",googleAdsLink:"Leads-Search-1 â Multiple Sitelinks",isGoogleAdsSitelink:!0,sitelinkText:_t()?"Get Started / Sign Up Now":"Start Free Trial / Sign Up Now",descriptionLine1:_t()?"Get started with Clarafi AI Scribe ⢠Try Clarafi AI EHR ⢠Create your physician account today":"Clarafi AI Scribe free for 30 days ⢠Try Clarafi AI EHR free for 30 days ⢠Create your physician account today",descriptionLine2:_t()?"3-minute setup, start charting":"No credit card required ⢠3-minute setup, start charting",finalUrl:"https://www.clarafi.ai/auth?tab=register"},{entry_page:"/auth",sitelink:"sign_in",label:"Sign In Page",sublabel:"Returning Users",description:"Existing users returning to sign into their account. Not new acquisition traffic - these are returning visitors.",pageDescription:"Login page for existing Clarafi users.",googleAdsLink:null,isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:"https://www.clarafi.ai/auth"},{entry_page:"/auth",sitelink:"direct",label:"Registration",sublabel:"Direct / Organic",description:"Visitors who navigated directly to the registration page. May have been referred by colleague or found via search.",pageDescription:_t()?"Account registration page where users create their Clarafi account.":"Account registration page where users create their Clarafi account and start their trial.",googleAdsLink:null,isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:"https://www.clarafi.ai/auth"},{entry_page:"/scribe",sitelink:"direct",label:"AI Scribe Landing",sublabel:"Direct / Organic",description:"Visitors who landed on the AI Scribe feature page. Interested specifically in AI medical transcription.",pageDescription:"Dedicated landing page for the AI Scribe feature with live demo and feature highlights.",googleAdsLink:null,isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:"https://www.clarafi.ai/scribe"},{entry_page:"/scribe",sitelink:"ai_scribe_landing",label:"AI Scribe Landing",sublabel:"AI Scribe (Campaign Link)",description:"Visitors who clicked a Google Ads link specifically promoting the AI Scribe feature.",pageDescription:"Dedicated landing page for the AI Scribe feature with live demo and feature highlights.",googleAdsLink:"Leads-Search-1 â AI Scribe Ad",isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:"https://www.clarafi.ai/scribe"},{entry_page:"/#features",sitelink:"features_overview",label:"Features Section",sublabel:"Features Overview (Sitelink)",description:'Visitors who clicked "Features overview" sitelink and landed on the features section of the homepage.',pageDescription:"Features section on homepage highlighting AI capabilities, charting, billing, and integrations.",googleAdsLink:'Leads-Search-1 â Sitelink: "Features overview"',isGoogleAdsSitelink:!0,sitelinkText:"Features overview",descriptionLine1:"Discover AI-powered documentation",descriptionLine2:"See how Clarafi saves hours daily",finalUrl:"https://www.clarafi.ai/#features"}],Be=L=>{if(!L||!(je!=null&&je.sitelinks))return null;const Re=$e=>$e.replace(/^https?:\/\//,"").replace(/\/$/,"").toLowerCase(),Ge=Re(L);return je.sitelinks.find($e=>{var Qe;return(Qe=$e.finalUrls)==null?void 0:Qe.some(js=>Re(js)===Ge)})||null},ns=X.map(L=>{var Qe;const Re=xe.find(js=>js.entry_page===L.entry_page&&js.sitelink===L.sitelink),Ge=L.isGoogleAdsSitelink?Be(L.finalUrl):null,$e=Ge?{sitelinkText:Ge.linkText,descriptionLine1:Ge.description1,descriptionLine2:Ge.description2,finalUrl:((Qe=Ge.finalUrls)==null?void 0:Qe[0])||L.finalUrl,campaignAssociations:Ge.campaignAssociations,adGroupAssociations:Ge.adGroupAssociations,sitelinkMetrics:Ge.metrics,isDynamicData:!0,assetId:Ge.assetId,assetStatus:Ge.status,primaryStatus:Ge.primaryStatus,primaryStatusReasons:Ge.primaryStatusReasons}:{sitelinkText:L.sitelinkText,descriptionLine1:L.descriptionLine1,descriptionLine2:L.descriptionLine2,finalUrl:L.finalUrl,campaignAssociations:[],adGroupAssociations:[],sitelinkMetrics:null,isDynamicData:!1,assetId:null,assetStatus:null,primaryStatus:null,primaryStatusReasons:[]};return{entry_page:L.entry_page,sitelink:L.sitelink,display_label:L.label,display_sublabel:L.sublabel,description:L.description,pageDescription:L.pageDescription,googleAdsLink:L.googleAdsLink,isGoogleAdsSitelink:L.isGoogleAdsSitelink,...$e,unique_sessions:(Re==null?void 0:Re.unique_sessions)||0,raw_events:(Re==null?void 0:Re.raw_events)||0,is_legacy:(Re==null?void 0:Re.is_legacy)||!1}});return xe.forEach(L=>{if(!ns.some(Ge=>Ge.entry_page===L.entry_page&&Ge.sitelink===L.sitelink)){const Ge=L.is_legacy||L.sitelink==="homepage_legacy";ns.push({entry_page:L.entry_page||"/",sitelink:L.sitelink,display_label:Le(L.entry_page)||"Homepage",display_sublabel:Ge?"Legacy Tracking":ae(L.sitelink),description:Ge?"Historical visits tracked before December 2025 using the old tracking system. Entry point details (which page they landed on) were not captured. These represent all website visits before unified tracking was implemented.":`Visitors who arrived via ${ae(L.sitelink)}.`,pageDescription:Ge?"Unknown landing page - legacy tracking did n
80ot capture entry point details.":"Page details not available.",googleAdsLink:null,isGoogleAdsSitelink:!1,sitelinkText:null,descriptionLine1:null,descriptionLine2:null,finalUrl:null,campaignAssociations:[],adGroupAssociations:[],sitelinkMetrics:null,isDynamicData:!1,assetId:null,assetStatus:null,primaryStatus:null,primaryStatusReasons:[],unique_sessions:L.unique_sessions||0,raw_events:L.raw_events||0,is_legacy:Ge})}}),ns.sort((L,Re)=>Re.unique_sessions-L.unique_sessions),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx(W,{children:"User Acquisition Journey"}),e.jsx(Hr,{value:D,onChange:$,compact:!0})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Data from ",De(D.startDate,"MMM d, yyyy")," to ",De(D.endDate,"MMM d, yyyy")]})]}),e.jsx(T,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-2 font-medium",children:"Stage"}),e.jsx("th",{className:"text-right py-3 px-2 font-medium",children:"Count"}),e.jsx("th",{className:"text-right py-3 px-2 font-medium",children:"Drop-off"}),e.jsx("th",{className:"text-right py-3 px-2 font-medium",children:"Conversion Rate"}),e.jsx("th",{className:"text-right py-3 px-2 font-medium",children:"Actions"})]})}),e.jsx("tbody",{children:Ne.map((L,Re)=>{var Ns,He,Gs,ne;const Ge=L.icon,$e=L.count,Qe=Re>0?Ne[Re-1].count:null,js=Re>0&&Qe!==null&&$e!==null?Qe-$e:null,ze=Re>0&&Qe!==null&&$e!==null&&Qe>0?($e/Qe*100).toFixed(1):null;return e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-3 px-2",children:e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2 cursor-help",children:[e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:L.stage}),e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsx("p",{className:"font-medium",children:(Ns=Wr(oe[L.stage]))==null?void 0:Ns.description}),((He=Wr(oe[L.stage]))==null?void 0:He.formula)&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Formula: ",(Gs=Wr(oe[L.stage]))==null?void 0:Gs.formula]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Source: ",(ne=Wr(oe[L.stage]))==null?void 0:ne.source]})]})]})})}),e.jsx("td",{className:"text-right py-3 px-2 font-semibold",children:$e!==null?$e.toLocaleString():e.jsx("span",{className:"text-muted-foreground font-normal",children:"â"})}),e.jsx("td",{className:"text-right py-3 px-2",children:Re===0?e.jsx("span",{className:"text-muted-foreground",children:"â"}):js!==null?e.jsxs("span",{className:"text-red-500",children:["-",js.toLocaleString()]}):e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx("td",{className:"text-right py-3 px-2",children:Re===0?e.jsx("span",{className:"text-muted-foreground",children:"â"}):ze!==null?e.jsxs("span",{children:[ze,"%"]}):e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx("td",{className:"text-right py-3 px-2",children:e.jsxs(ee,{variant:"ghost",size:"sm",onClick:()=>{re({key:oe[L.stage],displayName:L.stage,count:$e||0}),pe(!0)},disabled:$e===null||$e===0,className:"text-xs","data-testid":`btn-view-stage-users-${Re}`,children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"}),"View Users"]})})]},L.stage)})})]})})})]}),e.jsxs(Xr.Provider,{value:{highlightedPath:ye,highlightedNode:ve,setHighlightedPath:Ie,setHighlightedNode:B},children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_,{"data-testid":"card-entry-point-breakdown",className:"lg:max-h-[800px] lg:overflow-y-auto",children:[e.jsx(q,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-5 w-5"}),"Entry Point Breakdown"]}),e.jsx(Hr,{value:se,onChange:J,compact:!0})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Which pages and Google Ads sitelinks are driving visitors (",De(C,"MMM d")," - ",De(se.endDate,"MMM d, yyyy"),")",I&&e.jsx("span",{className:"ml-1 text-amber-600 dar
80k:text-amber-400",children:"â Data available from Dec 3, 2025"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Fe&&e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"text-xs text-muted-foreground cursor-help flex items-center gap-1",children:[e.jsx(bs,{className:"h-3 w-3"}),"Info"]})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsx("p",{className:"font-medium",children:"Session Tracking"}),e.jsx("p",{className:"text-xs mt-1",children:Fe.note}),e.jsxs("p",{className:"text-xs mt-2",children:["Total: ",(Fe.totalSessions||0).toLocaleString()," unique sessions"]})]})]})}),e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>K(!0),"data-testid":"btn-expand-entry-points",className:"h-8 w-8 p-0",children:e.jsx(vo,{className:"h-4 w-4"})})}),e.jsx(Ae,{children:e.jsx("p",{children:"Expand to full view"})})]})})]})]})}),e.jsx(T,{children:ns.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-sm font-medium",children:[ns.length," entry points"]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Total: ",ns.reduce((L,Re)=>L+(Re.unique_sessions||0),0).toLocaleString()," sessions"]})]}),e.jsx(Ta,{type:"multiple",className:"space-y-2",children:ns.map((L,Re)=>{var Ns;const Ge=ns.reduce((He,Gs)=>He+(Gs.unique_sessions||0),0),$e=L.unique_sessions||0,Qe=Ge>0&&$e>0?($e/Ge*100).toFixed(1):"0.0",js=L.finalUrl?L.finalUrl:(Ns=L.entry_page)!=null&&Ns.startsWith("/")?`${window.location.origin}${L.entry_page}`:L.entry_page,ze=()=>{f({entry_page:L.entry_page,sitelink:L.sitelink,display_label:L.display_label,display_sublabel:L.display_sublabel}),O(!0)};return e.jsxs(Da,{value:`entry-${Re}`,className:"border rounded-lg overflow-hidden","data-testid":`accordion-entry-point-${Re}`,children:[e.jsx(Pa,{className:"hover:no-underline px-4 py-3 [&[data-state=open]>div>.chevron]:rotate-180",children:e.jsxs("div",{className:"flex items-center justify-between w-full gap-4 pr-2",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[L.isGoogleAdsSitelink?e.jsx("div",{className:"flex-shrink-0 flex items-center justify-center w-6 h-6 rounded bg-blue-100 dark:bg-blue-900",children:e.jsx("span",{className:"text-xs font-bold text-blue-600 dark:text-blue-400",children:"G"})}):L.is_legacy?e.jsx(Ua,{className:"flex-shrink-0 h-5 w-5 text-amber-500"}):e.jsx(ot,{className:"flex-shrink-0 h-5 w-5 text-muted-foreground"}),e.jsx("span",{className:"font-medium truncate",children:L.display_label||Le(L.entry_page)}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[L.is_legacy&&e.jsx(Y,{variant:"outline",className:"text-xs bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950 dark:text-amber-400 dark:border-amber-800",children:"Legacy"}),L.isGoogleAdsSitelink&&e.jsx(Y,{variant:"outline",className:"text-xs bg-info-surface text-info-ink-soft border-info-border dark:bg-blue-950 dark:text-blue-400 dark:border-blue-800",children:"Sitelink"})]}),e.jsx("span",{className:`text-sm hidden md:inline ${L.isGoogleAdsSitelink?"text-blue-600 dark:text-blue-400":"text-muted-foreground"}`,children:L.display_sublabel||ae(L.sitelink)})]}),e.jsxs("div",{className:"flex items-center gap-4 flex-shrink-0",children:[e.jsxs("div",{className:"text-right min-w-[60px]",children:[e.jsx("span",{className:`font-semibold ${$e===0?"text-muted-foreground":""}`,children:$e.toLocaleString()}),e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"sessions"})]}),e.jsxs("div",{className:"flex items-center gap-2 min-w-[100px]",children:[e.jsx(mt,{value:parseFloat(Qe),className:`h-2 w-16 ${L.isGoogleAdsSitelink?"[&>div]:bg-blue-500":"[&>div]:bg-gray-400"}`}),e.jsxs("span",{className:"text-sm font-medium w-12 text-right",children:[Qe,"%"]})]})]})]})}),e.jsx(Ma,{className:"px-4 pb-4",children:e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"text-sm text-muted-foreground border-b pb-3",children:[e.jsx("p",{children:L.description}),L.pageDescription&&e.jsx("p",{className:"mt-1 text-xs",children:L.pageDescription}),!L.is_legacy&&L.entry_page&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("code",{className:"text-xs bg-muted px-2 py-0.5 rounded",children:L.finalUrl||L.entry_page}),js&&e.jsxs("a",{href:js,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-info-ink-soft flex items-center gap-1 text-xs",onClick:He=>He.stopPropagation(),children:[e.jsx(yt,{className:"h-3 w-3"}),"Visit"]})]})]}),L.isGoogleAdsSitelink&&e.jsxs(_,{className:"border-info-border dark:border-blue-800 bg-info-surface/50 dark:bg-blue-950/30","data-testid":`section-google-ads-${Re}`,children:[e.jsx(q,{className:"py-3 px-4",children:e.jsxs(W,{className:"text-sm flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded bg-blue-100 dar
80k:bg-blue-900",children:e.jsx("span",{className:"text-[10px] font-bold text-blue-600 dark:text-blue-400",children:"G"})}),"Google Ads Sitelink Details",L.isDynamicData&&e.jsx(Y,{variant:"outline",className:"text-[10px] bg-green-100 text-green-700 border-green-300 dark:bg-green-950 dark:text-green-400 dark:border-green-800",children:"LIVE"})]})}),e.jsxs(T,{className:"py-3 px-4 space-y-4",children:[L.sitelinkText&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium text-blue-800 dark:text-blue-200",children:['"',L.sitelinkText,'"']}),L.descriptionLine1&&e.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-400 mt-1",children:L.descriptionLine1}),L.descriptionLine2&&e.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-400",children:L.descriptionLine2})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[L.campaignAssociations&&L.campaignAssociations.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-medium text-info-ink-soft dark:text-blue-300 mb-2",children:["Campaign Attribution (",L.campaignAssociations.length,")"]}),e.jsx("div",{className:"space-y-1",children:L.campaignAssociations.map((He,Gs)=>e.jsxs("div",{className:"text-xs bg-blue-100 dark:bg-blue-900 rounded px-2 py-1",children:[e.jsx("span",{className:"font-medium",children:He.campaignName}),e.jsxs("span",{className:"text-blue-500 ml-1",children:["(",He.status,")"]})]},Gs))})]}),L.adGroupAssociations&&L.adGroupAssociations.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-medium text-info-ink-soft dark:text-blue-300 mb-2",children:["Ad Group Attribution (",L.adGroupAssociations.length,")"]}),e.jsx("div",{className:"space-y-1",children:L.adGroupAssociations.map((He,Gs)=>e.jsxs("div",{className:"text-xs bg-blue-100 dark:bg-blue-900 rounded px-2 py-1",children:[e.jsx("span",{className:"font-medium",children:He.adGroupName}),He.campaignName&&e.jsxs("span",{className:"text-blue-500 ml-1",children:["in ",He.campaignName]})]},Gs))})]})]}),L.sitelinkMetrics&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-info-ink-soft dark:text-blue-300 mb-2",children:"Performance Metrics (Last 30 days)"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-xs",children:[e.jsxs("div",{className:"bg-blue-100 dark:bg-blue-900 rounded px-3 py-2",children:[e.jsx("span",{className:"text-blue-500 block",children:"Clicks"}),e.jsx("span",{className:"font-semibold text-sm",children:L.sitelinkMetrics.clicks.toLocaleString()})]}),e.jsxs("div",{className:"bg-blue-100 dark:bg-blue-900 rounded px-3 py-2",children:[e.jsx("span",{className:"text-blue-500 block",children:"Impressions"}),e.jsx("span",{className:"font-semibold text-sm",children:L.sitelinkMetrics.impressions.toLocaleString()})]}),e.jsxs("div",{className:"bg-blue-100 dark:bg-blue-900 rounded px-3 py-2",children:[e.jsx("span",{className:"text-blue-500 block",children:"CTR"}),e.jsxs("span",{className:"font-semibold text-sm",children:[L.sitelinkMetrics.ctr.toFixed(2),"%"]})]}),e.jsxs("div",{className:"bg-blue-100 dark:bg-blue-900 rounded px-3 py-2",children:[e.jsx("span",{className:"text-blue-500 block",children:"Cost"}),e.jsxs("span",{className:"font-semibold text-sm",children:["$",(L.sitelinkMetrics.costMicros/1e6).toFixed(2)]})]}),L.sitelinkMetrics.conversions>0&&e.jsxs("div",{className:"bg-green-100 dark:bg-green-900 rounded px-3 py-2 col-span-2",children:[e.jsx("span",{className:"text-green-600 dark:text-green-400 block",children:"Conversions"}),e.jsxs("span",{className:"font-semibold text-sm text-green-700 dark:text-green-300",children:[L.sitelinkMetrics.conversions.toFixed(1),L.sitelinkMetrics.conversionsValue>0&&e.jsxs("span",{className:"ml-2 font-normal text-green-600 dark:text-green-400",children:["($",L.sitelinkMetrics.conversionsValue.toFixed(2),")"]})]})]})]})]}),L.assetId&&e.jsxs("div",{className:"text-[10px] text-blue-400 pt-2 border-t border-info-border dark:border-blue-800",children:["Asset ID: ",L.assetId]})]})]}),e.jsx(b,{entry:L,index:Re,entryPointRange:se}),e.jsx(S,{entry:L,index:Re,entryPointRange:se}),e.jsx(A,{entry:L,index:Re,entryPointRange:se}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Explore individual user journeys from this entry point"}),e.jsxs(ee,{variant:"outline",size:"sm",onClick:ze,disabled:$e===0,className:"text-xs","data-testid":`btn-view-users-accordion-${Re}`,children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"}
80),"View Users (",$e.toLocaleString(),")"]})]})]})})]},`${L.entry_page}-${L.sitelink}-${Re}`)})}),e.jsxs("div",{className:"mt-4 pt-4 border-t flex flex-wrap gap-4 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"flex items-center justify-center w-4 h-4 rounded bg-blue-100 dark:bg-blue-900",children:e.jsx("span",{className:"text-[10px] font-bold text-blue-600 dark:text-blue-400",children:"G"})}),e.jsx("span",{children:"Google Ads Sitelink"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ot,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Direct / Organic Traffic"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ua,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{children:"Legacy Tracking (pre-Dec 2025)"})]})]})]}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx(sn,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"No entry point data yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Entry points will appear once visitors land on your marketing pages"})]})})]}),e.jsx(M,{entryPointRange:se})]}),e.jsxs(_,{"data-testid":"card-site-sankey",children:[e.jsxs(q,{className:"pb-2",children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(Wt,{className:"h-5 w-5 text-blue-500"}),"Site Navigation Flow",e.jsx(Y,{variant:"outline",className:"ml-2",children:"Interactive"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Hover on paths in Entry Point Breakdown above to highlight corresponding flows."})]}),e.jsx(T,{className:"p-4",children:e.jsx(F,{entryPointRange:se})})]})]}),e.jsx(Vs,{open:z,onOpenChange:K,children:e.jsxs(Us,{className:"max-w-5xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Bs,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-5 w-5"}),"Entry Point Breakdown"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Which pages and Google Ads sitelinks are driving visitors (",De(C,"MMM d")," - ",De(se.endDate,"MMM d, yyyy"),")"]})]})})}),e.jsx("div",{className:"flex-1 overflow-y-auto pr-2",children:ns.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-sm font-medium",children:[ns.length," entry points"]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Total: ",ns.reduce((L,Re)=>L+(Re.unique_sessions||0),0).toLocaleString()," sessions"]})]}),e.jsx(Ta,{type:"multiple",className:"space-y-2",children:ns.map((L,Re)=>{const Ge=ns.reduce((js,ze)=>js+(ze.unique_sessions||0),0),$e=L.unique_sessions||0,Qe=Ge>0&&$e>0?($e/Ge*100).toFixed(1):"0.0";return e.jsxs(Da,{value:`expanded-entry-${Re}`,className:"border rounded-lg overflow-hidden",children:[e.jsx(Pa,{className:"hover:no-underline px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between w-full gap-4 pr-2",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[L.isGoogleAdsSitelink?e.jsx("div",{className:"flex-shrink-0 flex items-center justify-center w-6 h-6 rounded bg-blue-100 dark:bg-blue-900",children:e.jsx("span",{className:"text-xs font-bold text-blue-600 dark:text-blue-400",children:"G"})}):L.is_legacy?e.jsx(Ua,{className:"flex-shrink-0 h-5 w-5 text-amber-500"}):e.jsx(ot,{className:"flex-shrink-0 h-5 w-5 text-muted-foreground"}),e.jsx("span",{className:"font-medium truncate",children:L.display_label||Le(L.entry_page)}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[L.is_legacy&&e.jsx(Y,{variant:"outline",className:"text-xs bg-amber-50 text-amber-700 border-amber-200",children:"Legacy"}),L.isGoogleAdsSitelink&&e.jsx(Y,{variant:"outline",className:"text-xs bg-info-surface text-info-ink-soft border-info-border",children:"Sitelink"})]}),e.jsx("span",{className:`text-sm ${L.isGoogleAdsSitelink?"text-blue-600":"text-muted-foreground"}`,children:L.display_sublabel||ae(L.sitelink)})]}),e.jsxs("div",{className:"flex items-center gap-4 flex-shrink-0",children:[e.jsxs("div",{className:"text-right min-w-[60px]",children:[e.jsx("span",{className:`font-semibold ${$e===0?"text-muted-foreground":""}
80`,children:$e.toLocaleString()}),e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"sessions"})]}),e.jsxs("div",{className:"flex items-center gap-2 min-w-[100px]",children:[e.jsx(mt,{value:parseFloat(Qe),className:`h-2 w-16 ${L.isGoogleAdsSitelink?"[&>div]:bg-blue-500":"[&>div]:bg-gray-400"}`}),e.jsxs("span",{className:"text-sm font-medium w-12 text-right",children:[Qe,"%"]})]})]})]})}),e.jsx(Ma,{className:"px-4 pb-4",children:e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"text-sm text-muted-foreground border-b pb-3",children:[e.jsx("p",{children:L.description}),L.pageDescription&&e.jsx("p",{className:"mt-1 text-xs",children:L.pageDescription})]}),L.deviceBreakdown&&L.deviceBreakdown.length>0&&e.jsxs("div",{className:"bg-muted/20 rounded-lg p-3",children:[e.jsxs("h5",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4"}),"Device Breakdown"]}),e.jsx("div",{className:"grid grid-cols-3 gap-2 text-xs",children:L.deviceBreakdown.map((js,ze)=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-background rounded",children:[e.jsx("span",{className:"capitalize",children:js.deviceType}),e.jsxs("span",{className:"font-medium",children:[js.sessions," (",js.percentage,"%)"]})]},ze))})]}),L.navigationPaths&&L.navigationPaths.length>0&&e.jsxs("div",{className:"bg-muted/20 rounded-lg p-3",children:[e.jsxs("h5",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(Va,{className:"h-4 w-4"}),"Top Navigation Paths"]}),e.jsx("div",{className:"space-y-1",children:L.navigationPaths.slice(0,5).map((js,ze)=>e.jsxs("div",{className:"flex items-center justify-between text-xs p-2 rounded hover:bg-muted/50 transition-colors",children:[e.jsx("code",{className:"text-muted-foreground bg-muted px-1 py-0.5 rounded flex-1 truncate mr-2",children:js.path}),e.jsxs("span",{className:"font-medium flex-shrink-0",children:[js.count," sessions"]})]},ze))})]})]})})]},`expanded-${L.entry_page}-${L.sitelink}-${Re}`)})}),e.jsxs("div",{className:"mt-4 pt-4 border-t flex flex-wrap gap-4 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"flex items-center justify-center w-4 h-4 rounded bg-blue-100 dark:bg-blue-900",children:e.jsx("span",{className:"text-[10px] font-bold text-blue-600 dark:text-blue-400",children:"G"})}),e.jsx("span",{children:"Google Ads Sitelink"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ot,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Direct / Organic Traffic"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ua,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{children:"Legacy Tracking (pre-Dec 2025)"})]})]})]}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx(sn,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"No entry point data yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Entry points will appear once visitors land on your marketing pages"})]})})]})}),e.jsx(Vs,{open:R,onOpenChange:O,children:e.jsxs(Us,{className:"max-w-4xl max-h-[80vh] overflow-y-auto",children:[e.jsx(Bs,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-5 w-5"}),"Users from: ",y==null?void 0:y.display_label,e.jsx(Y,{variant:"outline",className:"ml-2",children:y==null?void 0:y.display_sublabel})]})}),ue?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"animate-spin w-8 h-8 border-4 border-primary border-t-transparent rounded-full mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading user data..."})]}):P!=null&&P.error?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(Fs,{className:"h-12 w-12 mx-auto mb-4 text-amber-500"}),e.jsx("p",{className:"font-medium",children:"Access Restricted"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:P.error})]}):P?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_,{children:e.jsxs(T,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Sessions"}),e.jsx("p",{className:"text-2xl font-bold",children:(((wt=P.summary)==null?void 0:wt.totalSessions)||0).toLocaleStr
80ing()})]})}),e.jsx(_,{children:e.jsxs(T,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Logged-In Users"}),e.jsx("p",{className:"text-2xl font-bold",children:(((jt=P.summary)==null?void 0:jt.loggedInUsers)||0).toLocaleString()}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(((rs=P.summary)==null?void 0:rs.anonymousSessions)||0).toLocaleString()," anonymous"]})]})}),e.jsx(_,{children:e.jsxs(T,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Activated"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:(((ea=P.summary)==null?void 0:ea.convertedToActivation)||0).toLocaleString()}),e.jsxs("p",{className:"text-xs text-green-600",children:[((Je=P.summary)==null?void 0:Je.activationRate)||"0.0","% rate"]})]})}),e.jsx(_,{children:e.jsxs(T,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paid Subscribers"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:(((da=P.summary)==null?void 0:da.convertedToPaid)||0).toLocaleString()}),e.jsxs("p",{className:"text-xs text-blue-600",children:[((qt=P.summary)==null?void 0:qt.paidRate)||"0.0","% rate"]})]})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium",children:"Conversion Funnel for This Entry Point"})}),e.jsx(T,{children:e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ot,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[(((Js=P.summary)==null?void 0:Js.totalSessions)||0).toLocaleString()," visits"]})]}),e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(si,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[(((qs=P.summary)==null?void 0:qs.convertedToSignup)||0).toLocaleString()," signed up"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",((ie=P.summary)==null?void 0:ie.signupRate)||"0.0","%)"]})]}),e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Za,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:[(((te=P.summary)==null?void 0:te.convertedToActivation)||0).toLocaleString()," activated"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",((fe=P.summary)==null?void 0:fe.activationRate)||"0.0","%)"]})]}),e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ct,{className:"h-4 w-4 text-blue-600"}),e.jsxs("span",{children:[(((ge=P.summary)==null?void 0:ge.convertedToPaid)||0).toLocaleString()," paid"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",((We=P.summary)==null?void 0:We.paidRate)||"0.0","%)"]})]})]})})]}),P.users&&P.users.length>0?e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium flex items-center gap-2",children:["Registered Users (",P.users.length,")",e.jsx(xs,{children:e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsx(bs,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Users who were logged in when visiting this entry point. Anonymous visitors are not shown."})})]})})]})}),e.jsx(T,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Username"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Email"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Signed Up"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Status"})]})}),e.jsx("tbody",{children:P.users.map(L=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2 px-2 font-medium",children:L.username}),e.jsx("td",{className:"py-2 px-2 text-muted-foreground",children:L.email||"â"}),e.jsx("td",{className:"py-2 px-2 text-muted-foreground",children:L.signedUpAt?De(new Date(L.signedUpAt),"MMM d, yyyy"):"â"}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(Y,{variant:L.conversionStatus==="subscriber"||L.conversionStatus==="activated"?"default":L.conversionStatus==="signed_up"?"secondary":"outline",className:L.conversionStatus==="subscriber"?"bg-blue-500":L.conversionStatus==="activated"?"bg-green-500":"",children:L.conversionStatus==="subscriber"?"Paid Subscriber":L.conversionStatus==="activated"?"Activated":L.conversionStatus==="signed_up"?"Signed Up":"Visitor"})})]},L.id))})]})})})]}):e.jsx(_,{children:e.jsxs(T,{className:"py-8 text-center",children:[e.jsx(Ys,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No logged-in users found"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[(((we=P.summary)==null?void 0:we.anonymousSessions)||0).toLocaleStr
80ing()," anonymous sessions were recorded from this entry point.",e.jsx("br",{}),"User data is only available for visitors who were logged in."]})]})})]}):null]})}),e.jsx(Vs,{open:H,onOpenChange:pe,children:e.jsxs(Us,{className:"max-w-4xl max-h-[80vh] overflow-y-auto",children:[e.jsx(Bs,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-5 w-5"}),N==null?void 0:N.displayName,e.jsxs(Y,{variant:"outline",className:"ml-2",children:[N==null?void 0:N.count," users"]})]})}),U?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"animate-spin w-8 h-8 border-4 border-primary border-t-transparent rounded-full mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading user data..."})]}):V!=null&&V.error?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(Fs,{className:"h-12 w-12 mx-auto mb-4 text-amber-500"}),e.jsx("p",{className:"font-medium",children:"Access Restricted"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:V.error})]}):V?e.jsxs("div",{className:"space-y-6",children:[e.jsx(_,{children:e.jsx(T,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Users at This Stage"}),e.jsx("p",{className:"text-3xl font-bold",children:(V.totalCount||0).toLocaleString()})]}),e.jsxs("div",{className:"ml-auto text-right text-sm text-muted-foreground",children:[e.jsx("p",{children:"Date Range:"}),e.jsxs("p",{children:[(gs=V.dateRange)!=null&&gs.startDate?De(new Date(V.dateRange.startDate),"MMM d"):"â"," - ",(Ss=V.dateRange)!=null&&Ss.endDate?De(new Date(V.dateRange.endDate),"MMM d, yyyy"):"â"]})]})]})})}),V.users&&V.users.length>0?e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium",children:["Users (",V.users.length,")"]})}),e.jsx(T,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Username"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Email"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Health System"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Signed Up"}),e.jsx("th",{className:"text-left py-2 px-2 font-medium",children:"Funnel Progress"})]})}),e.jsx("tbody",{children:V.users.map(L=>{var js,ze,Ns;const Re=!!((js=L.conversions)!=null&&js.signup),Ge=!!((ze=L.conversions)!=null&&ze.first_patient),$e=!!((Ns=L.conversions)!=null&&Ns.trial_to_paid);let Qe=null;return $e?Qe=e.jsx(Y,{className:"bg-blue-500",children:"Paid Subscriber"}):Ge?Qe=e.jsx(Y,{className:"bg-green-500",children:"Activated"}):Re?Qe=e.jsx(Y,{variant:"secondary",children:"Signed Up"}):Qe=e.jsx(Y,{variant:"outline",children:"Visitor"}),e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2 px-2 font-medium",children:L.username}),e.jsx("td",{className:"py-2 px-2 text-muted-foreground",children:L.email||"â"}),e.jsx("td",{className:"py-2 px-2 text-muted-foreground",children:L.healthSystemName||"â"}),e.jsx("td",{className:"py-2 px-2 text-muted-foreground",children:L.signedUpAt?De(new Date(L.signedUpAt),"MMM d, yyyy"):"â"}),e.jsx("td",{className:"py-2 px-2",children:Qe})]},L.id)})})]})})})]}):e.jsx(_,{children:e.jsxs(T,{className:"py-8 text-center",children:[e.jsx(Ys,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No users found at this stage"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['No users have reached the "',N==null?void 0:N.displayName,'" stage in the selected date range.']})]})})]}):null]})})]})};return d?e.jsx("div",{children:"Loading advanced analytics..."}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex flex-wrap gap-4 items-center justify-between",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(os,{value:s,onValueChange:t,children:[e.jsx(ds,{className:"w-32",children:e.jsx(hs,{})}
80),e.jsxs(ms,{children:[e.jsx(me,{value:"7d",children:"Last 7 days"}),e.jsx(me,{value:"30d",children:"Last 30 days"}),e.jsx(me,{value:"90d",children:"Last 90 days"}),e.jsx(me,{value:"1y",children:"Last year"})]})]}),e.jsxs(os,{value:a,onValueChange:n,children:[e.jsx(ds,{className:"w-32",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"all",children:"All Channels"}),e.jsx(me,{value:"organic",children:"Organic"}),e.jsx(me,{value:"paid",children:"Paid Search"}),e.jsx(me,{value:"social",children:"Social Media"}),e.jsx(me,{value:"email",children:"Email"})]})]})]})}),(()=>{var le,C;const D=(le=u==null?void 0:u.channelAttribution)==null?void 0:le.paid,$=(C=u==null?void 0:u.channelAttribution)==null?void 0:C.youtube,se=D&&!D.noDataForRange,J=$&&!$.noDataForRange;return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4","data-testid":"real-metrics-grid",children:[e.jsx(_,{"data-testid":"card-ad-spend",className:"cursor-pointer hover:shadow-lg hover:border-blue-300 transition-all duration-200",onClick:()=>r(!0),children:e.jsxs(T,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:["Google Ads Spend",e.jsx(Ca,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:se&&D.cost!==null?`$${Number(D.cost).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`:e.jsx("span",{className:"text-muted-foreground",children:"â"})}),se&&D.impressions&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[D.impressions.toLocaleString()," impressions"]})]}),e.jsx(ct,{className:"h-8 w-8 text-blue-500"})]}),e.jsxs("p",{className:"text-xs text-blue-500 mt-2 flex items-center gap-1",children:["Click for deep dive ",e.jsx(yt,{className:"h-3 w-3"})]})]})}),e.jsx(_,{"data-testid":"card-ad-clicks",className:"cursor-pointer hover:shadow-lg hover:border-purple-300 transition-all duration-200",onClick:()=>r(!0),children:e.jsxs(T,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:["Ad Clicks",e.jsx(Ca,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-2xl font-bold",children:se&&D.clicks?D.clicks.toLocaleString():e.jsx("span",{className:"text-muted-foreground",children:"â"})}),se&&D.ctr&&e.jsxs("p",{className:"text-xs text-green-600 mt-1 flex items-center",children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),Pn(D.ctr)," CTR"]})]}),e.jsx(Nr,{className:"h-8 w-8 text-purple-500"})]}),e.jsxs("p",{className:"text-xs text-purple-500 mt-2 flex items-center gap-1",children:["Click for deep dive ",e.jsx(yt,{className:"h-3 w-3"})]})]})}),e.jsx(_,{"data-testid":"card-conversions",className:"cursor-pointer hover:shadow-lg hover:border-green-300 transition-all duration-200",onClick:()=>r(!0),children:e.jsxs(T,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:["Conversions",e.jsx(Ca,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:se&&D.conversions?D.conversions:e.jsx("span",{className:"text-muted-foreground",children:"â"})}),se&&D.costPerConversion&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[et(D.costPerConversion),"/conv"]})]}),e.jsx(lt,{className:"h-8 w-8 text-green-500"})]}),e.jsxs("p",{className:"text-xs text-green-500 mt-2 flex items-center gap-1",children:["Click for deep dive ",e.jsx(yt,{className:"h-3 w-3"})]})]})}),e.jsx(_,{"data-testid":"card-youtube-views",className:"cursor-pointer hover:shadow-lg hover:border-red-300 transition-all duration-200",onClick:()=>c(!0),children:e.jsxs(T,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:["YouTube Views",e.jsx(Ca,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-2xl font-bold text-red-600",children:J&&$.views?$.views.toLocaleStr
80ing():e.jsx("span",{className:"text-muted-foreground",children:"â"})}),J&&$.watchTimeMinutes&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[Math.round($.watchTimeMinutes/60).toLocaleString(),"h watched"]})]}),e.jsx(Hs,{className:"h-8 w-8 text-red-500"})]}),e.jsxs("p",{className:"text-xs text-red-500 mt-2 flex items-center gap-1",children:["Click for deep dive ",e.jsx(yt,{className:"h-3 w-3"})]})]})})]})})(),e.jsxs(la,{defaultValue:"journey",className:"space-y-4",children:[e.jsxs(ca,{className:"grid w-full grid-cols-4",children:[e.jsx(Ee,{value:"journey",children:"User Journey"}),e.jsx(Ee,{value:"attribution",children:"Channel Attribution"}),e.jsx(Ee,{value:"predictive",children:"Predictive Insights"}),e.jsx(Ee,{value:"campaigns",children:"Campaign ROI"})]}),e.jsx(Ve,{value:"journey",className:"space-y-4",children:e.jsx(G,{})}),e.jsx(Ve,{value:"attribution",className:"space-y-4",children:e.jsx(k,{})}),e.jsx(Ve,{value:"predictive",className:"space-y-4",children:e.jsx(w,{})}),e.jsx(Ve,{value:"campaigns",className:"space-y-4",children:e.jsxs(_,{"data-testid":"card-campaign-roi",children:[e.jsx(q,{children:e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"h-5 w-5"}),"Campaign ROI Analysis"]})}),e.jsxs(T,{className:"p-8 text-center",children:[e.jsx(Zs,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"Coming Soon"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Campaign ROI tracking will analyze the return on investment for your marketing campaigns:"}),e.jsxs("ul",{className:"text-sm text-muted-foreground mt-3 space-y-1",children:[e.jsx("li",{children:"⢠Return on Ad Spend (ROAS) per campaign"}),e.jsx("li",{children:"⢠Cost Per Acquisition (CPA) breakdown"}),e.jsx("li",{children:"⢠Conversion value tracking"}),e.jsx("li",{children:"⢠Campaign performance comparison"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-4",children:"Data source: Google Ads integration (connected)"})]})]})})]}),e.jsx(t4,{open:i,onClose:()=>r(!1),timeRange:s}),e.jsx(l4,{open:l,onClose:()=>c(!1),timeRange:s})]})}function o4(){const[s,t]=p.useState("overview"),{data:a,isLoading:n}=_e({queryKey:["/api/analytics/seo-metrics"]});a||console.log("[SEO_DASHBOARD] No SEO data available from /api/analytics/seo-metrics");const i=a==null?void 0:a.technicalScore,r=a==null?void 0:a.pageSpeed,l=a==null?void 0:a.mobileScore,c=a==null?void 0:a.schemaScore,o=a==null?void 0:a.metaTags,d=a==null?void 0:a.crawl,u=a==null?void 0:a.keywords,x=a==null?void 0:a.organicTraffic,m=a==null?void 0:a.coreWebVitals,v=a==null?void 0:a.technicalChecks,g=({title:w,score:k,icon:b})=>{const S=F=>F>=90?"text-green-600":F>=70?"text-yellow-600":"text-red-600",A=F=>F>=90?"Excellent":F>=70?"Good":"Needs Work";return k==null?e.jsx(_,{children:e.jsxs(T,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx(b,{className:"h-8 w-8 text-muted-foreground"}),e.jsx(Y,{variant:"outline",children:"No Data"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:w}),e.jsx("p",{className:"text-xl text-muted-foreground",children:"Awaiting data"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Connect Google Search Console or run a site audit"})]})}):e.jsx(_,{children:e.jsxs(T,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx(b,{className:"h-8 w-8 text-muted-foreground"}),e.jsx(Y,{variant:k>=90?"default":k>=70?"secondary":"destructive",children:A(k)})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:w}),e.jsxs("p",{className:`text-3xl font-bold ${S(k)}`,children:[k,"/100"]}),e.jsx(mt,{value:k,className:"mt-2"})]})})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(g,{title:"Technical SEO",score:i,icon:mi}),e.jsx(g,{title:"Page Speed",score:r,icon:oa}),e.jsx(g,{title:"Mobile Optimization",score:l,icon:Ht}),e.jsx(g,{title:"Schema Markup",score:c,icon:Kh})]}),e.jsxs(la,{value:s,onValueChange:t,children:[e.jsxs(ca,{className:"grid grid-cols-4 w-full max-w-2xl",children:[e.jsx(Ee,{value:"overview",children:"Overview"}),e.jsx(Ee,{value:"technical",children:"Technical"}),e.jsx(Ee,{value:"content",children:"Content"}),e.jsx(Ee,{value:"rankings",children:"Rankings"})]}),e.jsxs(Ve,{value:"overview",className:"space-y-6",children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Organic Traffic Growth"}),e.jsx(Oe,{children:"Monthly organic search visitors and growth rate"})]}),e.jsx(T,{children:x&&x.length>0?e.jsx(ft,{width:"100%",height:300,children:e.jsxs(Vc,{data:x,children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"month"}),e.jsx(at,{yAxisId:"left"}),e.jsx(at,{yAxisId:"right",orientation:"right"}),e.jsx(gt,{}),e.jsx(On,{}),e.jsx(Vt,{yAxisId:"left",type:"monotone",dataKey:"visitors",stroke:"#3b82f6",name:"Visitors",strokeWidth:2}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"growth",stroke:"#10b981",name:"Growth %",strokeWidth:2})]})}):e.jsxs("div",{className:"h-[300px] flex flex-col items-center justify-center text-muted-foreground",children:[e.jsx(ot,{className:"h-12 w-12 mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No organic traffic data available"}),e.jsx("p",{className:"text-sm mt-1",children:"Connect Google Search Console to view traffic trends"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"SEO Quick Actions"}),e.jsx(Oe,{children:"Immediate optimization opportunities"})]}),e.jsxs(T,{className:"space-y-3",children:[o!=null&&o.missing&&o.missing>0?e.jsxs(Qs,{children:[e.jsx(Dt,{className:"h-4 w-4"}),e.jsxs(Xs,{children:[e.jsxs("strong",{children:[o.missing," pages missing meta descriptions"]}),e.jsx("p",{className:"text-sm mt-1",children:"Fix these to improve click-through rates from search results"}),e.jsx(ee,{size:"sm",variant:"outline",className:"mt-2",children:"View & Fix Pages"})]})]}):null,d!=null&&d.lastCrawl?e.jsxs(Qs,{className:"border-green-200 bg-green-50",children:[e.jsx(Ft,{className:"h-4 w-4 text-green-600"}),e.jsxs(Xs,{children:[e.jsx("strong",{children:"Sitemap is up to date"}),e.jsxs("p",{className:"text-sm mt-1",children:["Last submitted: ",new Date(d.lastCrawl).toLocaleDateString()]})]})]}):null,!o&&!d&&e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx("p",{children:"No SEO actions available yet."}),e.jsx("p",{className:"text-sm mt-1",children:"Run a technical audit to identify optimization opportunities."})]})]})]})]}),e.jsx(Ve,{value:"technical",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Technical SEO Audit"}),e.jsx(Oe,{children:"Core Web Vitals and technical implementation status"})]}),e.jsxs(T,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"Core Web Vitals"}),m?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Largest Contentful Paint (LCP)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:m.lcp}),m.lcpStatus==="good"?e.jsx(Ft,{className:"h-4 w-4 text-green-600"}):m.lcpStatus==="needs-improvement"?e.jsx(Dt,{className:"h-4 w-4 text-yellow-600"}):e.jsx(tn,{className:"h-4 w-4 text-red-600"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"First Input Delay (FID)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:m.fid}),m.fidStatus==="good"?e.jsx(Ft,{className:"h-4 w-4 text-green-600"}):m.fidStatus==="needs-improvement"?e.jsx(Dt,{className:"h-4 w-4 text-yellow-600"}):e.jsx(tn,{className:"h-4 w-4 text-red-600"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Cumulative Layout Shift (CLS)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:m.cls}),m.clsStatus==="good"?e.jsx(Ft,{className:"h-4 w-4 text-green-600"}):m.clsStatus==="needs-improvement"?e.jsx(Dt,{className:"h-4 w-4 text-yellow-600"}):e.jsx(tn,{className:"h-4 w-4 text-red-600"})]})]})]}):e.jsxs("div",{className:"text-center py-4 text-muted-foreground bg-surface-page rounded-lg",children:[e.jsx(ja,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No Core Web Vitals data available"}),e.jsx("p",{className:"text-xs mt-1",children:"Run a PageSpeed Insights audit or connect Google Search Console"})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"Technical Implementation"}),v&&v.length>0?e.jsx("div",{className:"space-y-2",children:v.map((w,k)=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-surface-page rounded",children:[e.jsx("span",{className:"text-sm",children:w.name}),w.status==="pass"?e.jsx(Ft,{className:"h-4 w-4 text-green-600"}):w.status==="warning"?e.jsx(Dt,{className:"h-4 w-4 text-yellow-600"}):e.jsx(tn,{className:"h-4 w-4 text-red-600"})]},k))}):e.jsxs("div",{className:"text-center py-4 text-muted-foreground bg-surface-page rounded-lg",children:[e.jsx(mi,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No technical audit data available"}),e.jsx("p",{className:"text-xs mt-1",children:'Click "Run Full Technical Audit" to analyze your site'})]})]}),e.jsx(ee,{className:"w-full",children:"Run Full Technical Audit"})]})]})}),e.jsx(Ve,{value:"content",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Content Optimization Status"}),e.jsx(Oe,{children:"Meta tags, headings, and content quality metrics"})]}),e.jsx(T,{children:o?e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h4",{className:"font-medium",children:"Meta Tags Optimization"}),e.jsxs(Y,{variant:"secondary",children:[o.optimized,"/",o.totalPages," Optimized"]})]}),e.jsx(mt,{value:o.totalPages>0?o.optimized/o.totalPages*100:0,className:"mb-4"}),o.issues&&o.issues.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-red-600",children:"Issues Found:"}),o.issues.map((w,k)=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-red-50 rounded",children:[e.jsx("span",{className:"text-sm",children:w.page}),e.jsx("span",{className:"text-sm text-red-600",children:w.issue})]},k))]})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(fa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No content optimization data available"}),e.jsx("p",{className:"text-sm mt-1",children:"Run a content audit to analyze meta tags and page optimization"})]})})]})}),e.jsx(Ve,{value:"rankings",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Keyword Rankings"}),e.jsx(Oe,{children:"Track your search engine rankings for target keywords"})]}),e.jsx(T,{children:u&&u.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2",children:"Keyword"}),e.jsx("th",{className:"text-center py-2",children:"Position"}),e.jsx("th",{className:"text-center py-2",children:"Change"}),e.jsx("th",{className:"text-right py-2",children:"Search Volume"})]})}),e.jsx("tbody",{children:u.map((w,k)=>e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-3",children:w.keyword}),e.jsx("td",{className:"text-center",children:e.jsxs(Y,{variant:w.position<=3?"default":"secondary",children:["#",w.position]})}
80),e.jsx("td",{className:"text-center",children:w.change>0?e.jsxs("span",{className:"text-green-600 flex items-center justify-center gap-1",children:[e.jsx(Is,{className:"h-3 w-3"}),"+",w.change]}):w.change<0?e.jsx("span",{className:"text-red-600",children:w.change}):e.jsx("span",{className:"text-ink-faint",children:"â"})}),e.jsxs("td",{className:"text-right",children:[w.volume.toLocaleString(),"/mo"]})]},k))})]})}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ga,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No keyword ranking data available"}),e.jsx("p",{className:"text-sm mt-1",children:"Connect Google Search Console to track keyword positions"})]})})]})})]})]})}function d4(){const{toast:s}=ya(),t=Ya(),[a,n]=p.useState(!1),[i,r]=p.useState(null),[l,c]=p.useState(null),[o,d]=p.useState(null),{data:u,isLoading:x}=_e({queryKey:["/api/system-config/landing-variant/status"]}),{data:m,isLoading:v}=_e({queryKey:["/api/system-config/scribe-variant/status"]}),g=ws({mutationFn:async M=>(await vs("PUT","/api/system-config/landing-variant",M)).json(),onSuccess:M=>{t.invalidateQueries({queryKey:["/api/system-config/landing-variant/status"]}),t.invalidateQueries({queryKey:["/api/system-config/public/landing-variant"]}),s({title:"Landing page variant updated",description:M.message||`Now showing ${M.activeVariant==="a"?"Dark":"Light"} theme to visitors`}),c(null)},onError:()=>{s({title:"Failed to update landing variant",variant:"destructive"})}}),w=ws({mutationFn:async M=>(await vs("PUT","/api/system-config/scribe-variant",M)).json(),onSuccess:M=>{t.invalidateQueries({queryKey:["/api/system-config/scribe-variant/status"]}),t.invalidateQueries({queryKey:["/api/system-config/public/scribe-variant"]}),s({title:"Scribe landing page variant updated",description:M.message||`Now showing ${M.activeVariant==="a"?"Dark":"Light"} theme to scribe page visitors`}),d(null)},onError:()=>{s({title:"Failed to update scribe variant",variant:"destructive"})}}),{data:k=[],isLoading:b}=_e({queryKey:["/api/advanced-marketing/ab-tests"]}),S=ws({mutationFn:M=>vs("/api/advanced-marketing/ab-tests","POST",M),onSuccess:()=>{t.invalidateQueries({queryKey:["/api/advanced-marketing/ab-tests"]}),s({title:"A/B test created successfully"}),n(!1)},onError:()=>{s({title:"Failed to create A/B test",variant:"destructive"})}}),A=ws({mutationFn:({id:M,status:G})=>vs(`/api/advanced-marketing/ab-tests/${M}/status`,"PUT",{status:G}),onSuccess:()=>{t.invalidateQueries({queryKey:["/api/advanced-marketing/ab-tests"]}),s({title:"Test status updated"})}}),F=M=>{switch(M){case"running":return"bg-green-500";case"paused":return"bg-yellow-500";case"completed":return"bg-blue-500";default:return"bg-gray-500"}},de=(M,G)=>M===0?0:((G-M)/M*100).toFixed(1);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"A/B Testing"}),e.jsx("p",{className:"text-muted-foreground",children:"Run experiments to optimize your healthcare platform"})]}),e.jsxs(Vs,{open:a,onOpenChange:n,children:[e.jsx(zn,{asChild:!0,children:e.jsxs(ee,{children:[e.jsx(fi,{className:"mr-2 h-4 w-4"}),"Create Test"]})}),e.jsxs(Us,{className:"sm:max-w-[600px]",children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Create A/B Test"}),e.jsx(Ct,{children:"Set up a new experiment to test variations of your platform features"})]}),e.jsxs("form",{onSubmit:M=>{M.preventDefault();const G=new FormData(M.currentTarget);S.mutate({name:G.get("name"),description:G.get("description"),featureKey:G.get("featureKey"),variants:{control:G.get("control"),treatment:G.get("treatment")}})},children:[e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"name",children:"Test Name"}),e.jsx(Me,{id:"name",name:"name",placeholder:"e.g., Homepage CTA Button Color",required:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"description",children:"Description"}),e.jsx(La,{id:"description",name:"description",placeholder:"Describe what you're testing and why"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"featureKey",children:"Feature Key"}),e.jsxs(os,{name:"featureKey",required:!0,children:[e.jsx(ds,{children:e.jsx(hs,{placeholder:"Select feature to test"})}
80),e.jsxs(ms,{children:[e.jsx(me,{value:"homepage_cta",children:"Homepage CTA"}),e.jsx(me,{value:"signup_flow",children:"Signup Flow"}),e.jsx(me,{value:"pricing_page",children:"Pricing Page"}),e.jsx(me,{value:"onboarding",children:"Onboarding Process"}),e.jsx(me,{value:"dashboard_layout",children:"Dashboard Layout"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"control",children:"Control (Original)"}),e.jsx(Me,{id:"control",name:"control",placeholder:"e.g., Blue Button",required:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"treatment",children:"Treatment (Variation)"}),e.jsx(Me,{id:"treatment",name:"treatment",placeholder:"e.g., Green Button",required:!0})]})]})]}),e.jsx(Ut,{children:e.jsx(ee,{type:"submit",disabled:S.isPending,children:"Create Test"})})]})]})]})]}),e.jsxs(_,{className:"border-2 border-primary/20 bg-gradient-to-r from-primary/5 to-transparent","data-testid":"card-landing-ab-test",children:[e.jsx(q,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Po,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:["Landing Page A/B Test",e.jsx(Y,{variant:(u==null?void 0:u.activeVariant)==="b"?"default":"secondary",children:(u==null?void 0:u.activeVariant)==="b"?"Light Theme (B)":"Dark Theme (A)"})]}),e.jsx(Oe,{children:"Control which landing page variant visitors see"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("a",{href:"/landing-a",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary flex items-center gap-1",children:[e.jsx(tt,{className:"h-3 w-3"}),"Preview A",e.jsx(yt,{className:"h-3 w-3"})]}),e.jsx("span",{className:"text-muted-foreground",children:"|"}),e.jsxs("a",{href:"/landing-b",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary flex items-center gap-1",children:[e.jsx(tt,{className:"h-3 w-3"}),"Preview B",e.jsx(yt,{className:"h-3 w-3"})]})]})]})}),e.jsx(T,{children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-card",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:"Active Variant"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(u==null?void 0:u.activeVariant)==="a"?"Dark theme with gradient background (original)":"Light theme with navy/gold branding (new)"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`text-sm font-medium ${(u==null?void 0:u.activeVariant)==="a"?"text-primary":"text-muted-foreground"}`,children:"A (Dark)"}),e.jsx(vr,{checked:(u==null?void 0:u.activeVariant)==="b",disabled:g.isPending||x,onCheckedChange:M=>{g.mutate({variant:M?"b":"a",trafficSplit:l??(u==null?void 0:u.trafficSplit)??100})},"data-testid":"switch-landing-variant"}),e.jsx("span",{className:`text-sm font-medium ${(u==null?void 0:u.activeVariant)==="b"?"text-primary":"text-muted-foreground"}`,children:"B (Light)"})]})]}),(u==null?void 0:u.updatedAt)&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Last changed: ",De(new Date(u.updatedAt),"MMM d, yyyy h:mm a"),(u==null?void 0:u.updatedBy)&&e.jsxs("span",{className:"ml-1",children:["by ",e.jsx("strong",{children:u.updatedBy})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Traffic Split"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Percentage of visitors who see the active variant"})]}),e.jsxs(Y,{variant:"outline",className:"text-lg font-bold",children:[l??(u==null?void 0:u.trafficSplit)??100,"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Do,{value:[l??(u==null?void 0:u.trafficSplit)??100],min:0,max:100,step:5,onValueChange:([M])=>c(M),disabled:g.isPending,"data-testid":"slider-traffic-split"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"0% (all get opposite)"}),e.jsx("span",{children:"50% (split test)"}),e.jsx("span",{children:"100% (all active)"})]})]}),l!==null&&l!==(u==null?void 0:u.trafficSplit)&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(ee,{size:"sm",onClick:()=>{g.mutate({variant:(u==null?void 0:u.activeVariant)??"a",trafficSplit:l})},disabled:g.isPending,"data-testid":"button-apply-split",children:"Apply Split"}),e.jsx(ee,{size:"sm",variant:"outline",onClick:()=>c(null),"data-testid":"button-cancel-split",children:"Cancel"})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground p-2 rounded bg-muted/50",children:[e.jsx("strong",{children:"Tip:"})," Set to 50% for a true A/B split test. Analytics will track which variant each visitor sees."]})]})]})})]}),e.jsxs(_,{className:"border-2 border-amber-500/20 bg-gradient-to-r from-amber-500/5 to-transparent","data-testid":"card-scribe-ab-test",children:[e.jsx(q,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-amber-500/10",children:e.jsx(Po,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:["Scribe Landing Page A/B Test",e.jsx(Y,{variant:(m==null?void 0:m.activeVariant)==="b"?"default":"secondary",children:(m==null?void 0:m.activeVariant)==="b"?"Light Theme (B)":"Dark Theme (A)"})]}),e.jsx(Oe,{children:"Control which AI scribe landing page variant visitors see at /scribe"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("a",{href:"/scribe-a",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-amber-600 flex items-center gap-1",children:[e.jsx(tt,{className:"h-3 w-3"}),"Preview A",e.jsx(yt,{className:"h-3 w-3"})]}),e.jsx("span",{className:"text-muted-foreground",children:"|"}),e.jsxs("a",{href:"/scribe-b",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-amber-600 flex items-center gap-1",children:[e.jsx(tt,{className:"h-3 w-3"}),"Preview B",e.jsx(yt,{className:"h-3 w-3"})]})]})]})}),e.jsx(T,{children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-card",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:"Active Variant"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(m==null?void 0:m.activeVariant)==="a"?"Dark theme with gradient background (original)":"Light theme with navy/gold branding (new)"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`text-sm font-medium ${(m==null?void 0:m.activeVariant)==="a"?"text-amber-600":"text-muted-foreground"}`,children:"A (Dark)"}),e.jsx(vr,{checked:(m==null?void 0:m.activeVariant)==="b",disabled:w.isPending||v,onCheckedChange:M=>{w.mutate({variant:M?"b":"a",trafficSplit:o??(m==null?void 0:m.trafficSplit)??100})},"data-testid":"switch-scribe-variant"}),e.jsx("span",{className:`text-sm font-medium ${(m==null?void 0:m.activeVariant)==="b"?"text-amber-600":"text-muted-foreground"}`,children:"B (Light)"})]})]}),(m==null?void 0:m.updatedAt)&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Last changed: ",De(new Date(m.updatedAt),"MMM d, yyyy h:mm a"),(m==null?void 0:m.updatedBy)&&e.jsxs("span",{className:"ml-1",children:["by ",e.jsx("strong",{children:m.updatedBy})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Traffic Split"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Percentage of visitors who see the active variant"})]}),e.jsxs(Y,{variant:"outline",className:"text-lg font-bold",children:[o??(m==null?void 0:m.trafficSplit)??100,"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Do,{value:[o??(m==null?void 0:m.trafficSplit)??100],min:0,max:100,step:5,onValueChange:([M])=>d(M),disabled:w.isPending,"data-testid":"slider-scribe-traffic-split"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"0% (all get opposite)"}),e.jsx("span",{children:"50% (split test)"}),e.jsx("span",{children:"100% (all active)"})]})]}),o!==null&&o!==(m==null?void 0:m.trafficSplit)&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(ee,{size:"sm",onClick:()=>{w.mutate({variant:(m==null?void 0:m.activeVariant)??"a",trafficSplit:o})},disabled:w.isPending,"data-testid":"button-apply-scribe-split",children:"Apply Split"}),e.jsx(ee,{size:"sm",variant:"outline",onClick:()=>d(null),"data-testid":"button-cancel-scribe-split",children:"Cancel"})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground p-2 rounded bg-muted/50",children:[e.jsx("strong",{children:"Tip:"})," Set to 50% for a true A/B split test. Analytics will track which variant each visitor sees."]})]})]})})]}),e.jsx("div",{className:"grid gap-4",children:b?e.jsx(_,{children:e.jsx(T,{className:"py-8 text-center text-muted-foreground",children:"Loading A/B tests..."})}):k.length===0?e.jsx(_,{children:e.jsxs(T,{className:"py-8 text-center",children:[e.jsx(fi,{className:"mx-auto h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No A/B tests yet. Create your first experiment!"})]})}):k.map(M=>e.jsxs(_,{className:"overflow-hidden",children:[e.jsx(q,{children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{children:[e.jsxs(W,{className:"flex items-center gap-2",children:[M.name,e.jsx(Y,{className:F(M.status),children:M.status})]}),e.jsx(Oe,{children:M.description||`Testing ${M.featureKey}`})]}),e.jsxs("div",{className:"flex gap-2",children:[M.status==="draft"&&e.jsx(ee,{size:"sm",onClick:()=>A.mutate({id:M.id,status:"running"}),children:e.jsx(pa,{className:"h-4 w-4"})}),M.status==="running"&&e.jsx(ee,{size:"sm",variant:"secondary",onClick:()=>A.mutate({id:M.id,status:"paused"}),children:e.jsx(ac,{className:"h-4 w-4"})}),M.status==="paused"&&e.jsx(ee,{size:"sm",onClick:()=>A.mutate({id:M.id,status:"running"}),children:e.jsx(pa,{className:"h-4 w-4"})})]})]})}),e.jsxs(T,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm font-medium",children:"Control"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:M.variants.control})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Users"}),e.jsx("span",{children:M.metrics.control.users})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Conversions"}),e.jsx("span",{children:M.metrics.control.conversions})]}),e.jsxs("div",{className:"flex justify-between text-sm font-medium",children:[e.jsx("span",{children:"Conversion Rate"}),e.jsxs("span",{children:[M.metrics.control.conversionRate,"%"]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm font-medium",children:"Treatment"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:M.variants.treatment})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Users"}),e.jsx("span",{children:M.metrics.treatment.users})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Conversions"}),e.jsx("span",{children:M.metrics.treatment.conversions})]}),e.jsxs("div",{className:"flex justify-between text-sm font-medium",children:[e.jsx("span",{children:"Conversion Rate"}),e.jsxs("span",{className:"flex items-center gap-1",children:[M.metrics.treatment.conversionRate,"%",M.metrics.treatment.conversionRate>M.metrics.control.conversionRate&&e.jsx(Is,{className:"h-3 w-3 text-green-500"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{children:"Statistical Significance"}),e.jsxs("span",{className:"font-medium",children:[M.metrics.confidence,"% confidence"]})]}),e.jsx(mt,{value:M.metrics.confidence,className:"h-2"}),M.metrics.confidence>=95&&e.jsxs("p",{className:"text-sm text-green-600 flex items-center gap-1",children:[e.jsx(ui,{className:"h-4 w-4"}),"Test has reached statistical significance"]})]}),M.metrics.treatment.conversionRate!==M.metrics.control.conversionRate&&e.jsx("div",{className:"bg-muted/50 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-center",children:[e.jsx("span",{className:"font-medium",children:"Lift: "}),e.jsxs("span",{className:`font-bold ${M.metrics.treatment.conversionRate>M.metrics.control.conversionRate?"text-green-600":"text-red-600"}`,children:[M.metrics.treatment.conversionRate>M.metrics.control.conversionRate?"+":"",de(M.metrics.control.conversionRate,M.metrics.treatment.conversionRate),"%"]})]})}),M.startedAt&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:["Running since ",De(new Date(M.startedAt),"MMM d, yyyy")]})]})]},M.id))})]})}function m4(){console.log("[DASHBOARD] Component mounting/updating");const{toast:s}=ya(),[t,a]=p.useState(!1),[n,i]=p.useState("google_ads"),[r,l]=p.useState({preset:"30d",custom:{from:"",to:""}}),[c,o]=p.useState(null),[d,u]=p.useState(""),[x,m]=p.useState(0),[v,g]=p.useState("overview"),[w,k]=p.useState(!1),[b,S]=p.useState(!1),[A,F]=p.useState(!1),[de,M]=p.useState(!1),[G,D]=p.useState(!1),[$,se]=p.useState(null),[J,le]=p.useState(null),[C,I]=p.useState(null),[y,f]=p.useState(null);p.useEffect(()=>{console.log("[DASHBOARD] Date range changed:",r)},[r]),p.useEffect(()=>{if(x>0){console.log("[DASHBOARD] Setting up auto-refresh interval:",x,"seconds");const ae=setInterval(()=>{console.log("[DASHBOARD] Auto-refresh triggered"),Ts.invalidateQueries({queryKey:["/api/advanced-marketing"]})},x*1e3);return()=>{console.log("[DASHBOARD] Clearing auto-refresh interval"),clearInterval(ae)}}},[x]);const R=()=>r.preset==="custom"&&r.custom.from&&r.custom.to?`?startDate=${r.custom.from}
80&endDate=${r.custom.to}`:`?preset=${r.preset}`,{data:O=[],isLoading:N,error:re,refetch:H}=_e({queryKey:["/api/advanced-marketing/ad-accounts"],queryFn:async()=>{console.log("[DASHBOARD] Fetching ad accounts...");const xe=await(await fetch("/api/advanced-marketing/ad-accounts",{credentials:"include"})).json();return console.log("[DASHBOARD] Ad accounts received:",xe.length),xe}}),{data:pe,isLoading:ye,error:Ie}=_e({queryKey:["/api/advanced-marketing/ad-metrics/aggregate",r],queryFn:async()=>{console.log("[DASHBOARD] Fetching aggregated metrics with params:",R());const xe=await(await fetch(`/api/advanced-marketing/ad-metrics/aggregate${R()}`,{credentials:"include"})).json();return console.log("[DASHBOARD] Metrics received:",xe),xe}}),{data:ve,isLoading:B}=_e({queryKey:["/api/advanced-marketing/performance-history",r,c],queryFn:async()=>{var X;console.log("[DASHBOARD] Fetching performance history...");const ae=new URLSearchParams;c&&ae.append("campaignId",c.toString()),r.preset==="custom"&&r.custom.from&&r.custom.to&&(ae.append("startDate",r.custom.from),ae.append("endDate",r.custom.to));const Fe=await(await fetch(`/api/advanced-marketing/performance-history?${ae}`,{credentials:"include"})).json();return console.log("[DASHBOARD] Performance history received:",((X=Fe.data)==null?void 0:X.length)||0,"records"),Fe},enabled:v==="detailed"&&O.length>0}),{data:z,isLoading:K,error:P}=_e({queryKey:["/api/advanced-marketing/keyword-performance",c],queryFn:async()=>{var X;console.log("[DASHBOARD] Fetching keyword performance for campaign:",c);const ae=c?`?campaignId=${c}`:"",xe=await fetch(`/api/advanced-marketing/keyword-performance${ae}`,{credentials:"include"});if(!xe.ok)throw console.error("[DASHBOARD] Keyword fetch failed:",xe.status),new Error(`Failed to fetch keywords: ${xe.status}`);const Fe=await xe.json();return console.log("[DASHBOARD] Keywords received:",((X=Fe==null?void 0:Fe.keywords)==null?void 0:X.length)||0),{keywords:(Fe==null?void 0:Fe.keywords)||[],summary:(Fe==null?void 0:Fe.summary)||{total:0,avgQualityScore:0,totalImpressions:0,totalClicks:0,totalCost:0}}},enabled:v==="keywords"&&O.length>0}),{data:ue,isLoading:V}=_e({queryKey:["/api/advanced-marketing/campaigns",c,"budget-pacing"],queryFn:async()=>{console.log("[DASHBOARD] Fetching budget pacing for campaign:",c);const xe=await(await fetch(`/api/advanced-marketing/campaigns/${c}/budget-pacing`,{credentials:"include"})).json();return console.log("[DASHBOARD] Budget pacing received:",xe),xe},enabled:v==="budget"&&c!==null}),U=ws({mutationFn:async ae=>(console.log("[DASHBOARD] Connecting ad account:",ae),vs("POST","/api/advanced-marketing/ad-accounts/connect",ae)),onSuccess:ae=>{console.log("[DASHBOARD] Account connected successfully:",ae),Ts.invalidateQueries({queryKey:["/api/advanced-marketing/ad-accounts"]}),s({title:"Ad account connected successfully"}),a(!1)},onError:ae=>{console.error("[DASHBOARD] Failed to connect account:",ae),s({title:"Failed to connect ad account",variant:"destructive"})}}),j=ws({mutationFn:ae=>(console.log("[DASHBOARD] Syncing account with historical backfill:",ae),vs("POST",`/api/advanced-marketing/ad-accounts/${ae}/sync`,{syncHistory:!0,daysBack:60})),onSuccess:()=>{console.log("[DASHBOARD] Account sync initiated with historical data"),setTimeout(()=>{Ts.invalidateQueries({queryKey:["/api/advanced-marketing/ad-accounts"]}),Ts.invalidateQueries({queryKey:["/api/advanced-marketing/ad-metrics/aggregate"]}),H()},5e3),s({title:"Syncing account with 60-day historical data - will refresh shortly"})},onError:ae=>{console.error("[DASHBOARD] Sync failed:",ae),s({title:"Sync failed",variant:"destructive"})}}),Q=ws({mutationFn:({campaignId:ae,status:xe,budget:Fe})=>(console.log("[DASHBOARD] Updating campaign:",ae,"to status:",xe,"budget:",Fe),vs("PATCH",`/api/advanced-marketing/campaigns/${ae}`,{status:xe,budget:Fe})),onSuccess:()=>{console.log("[DASHBOARD] Campaign updated successfully"),Ts.invalidateQueries({queryKey:["/api/advanced-marketing/ad-accounts"]}),Ts.invalidateQueries({queryKey:["/api/advanced-marketing/ad-metrics/aggregate"]}),Ts.invalidateQueries({queryKey:["/api/advanced-marketing"]}),H(),s({title:"Campaign updated successfully"}),k(!1)},onError:ae=>{console.error("[DASHBOARD] Campaign update failed:",ae),s({title:"Failed to update campaign",variant:"destructive"})}}),je=ws({mutationFn:ae=>(console.log("[DASHBOARD] Deleting campaign:",ae),vs("DELETE",`/api/advanced-marketing/campaigns/${ae}`)),onSuccess:()=>{console.log("[DASHBOARD] Campaign deleted successfully"),s({title:"Campaign deleted",description:"Campaign has been removed from Google Ads"}),Ts.invalidateQueries({queryKey:["/api/advanced-marketing"]})},onError:ae=>{console.error("[DASHBOARD] Campaign delete error:",ae),s({title:"Delete failed",variant:"destructive"})}}),ce=ws({mutationFn:ae=>{var Fe;console.log("[DASHBOARD] Creating campaign:",ae);const xe=(Fe=O.find(X=>X.platform==="google_ads"))==null?void 0:Fe.id;if(!xe)throw new Error("No Google Ads account found");return vs("POST",`/api/advanced-marketing/ad-accounts/${xe}/campaigns`,ae)},onSuccess:()=>{console.log("[DASHBOARD] Campaign created successfully"),s({title:"Campaign created",description:"New campaign has been created in Google Ads"}),Ts.invalidateQueries({queryKey:["/api/advanced-marketing"]}),D(!1)},onError:ae=>{console.error("[DASHBOARD] Campaign create error:",ae),s({title:"Create failed",variant:"destructive"})}}),be=ae=>{const xe=ae??0;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:xe<1?2:0,maximumFractionDigits:xe<1?2:0}).format(xe)},ss=ae=>{if(ae==null||isNaN(Number(ae)))return"0";const xe=Number(ae);return xe>=1e6?(xe/1e6).toFixed(1)+"M":xe>=1e3?(xe/1e3).toFixed(1)+"K":xe.toString()},oe=ae=>ae==null||isNaN(Number(ae))?"0.00%":`${Number(ae).toFixed(2)}%`,Ne=ae=>{switch(ae){case"google_ads":return e.jsx("div",{className:"w-5 h-5 bg-blue-500 rounded-sm flex items-center justify-center text-white text-xs font-bold",children:"G"});case"facebook_ads":return e.jsx("div",{className:"w-5 h-5 bg-blue-600 rounded-sm flex items-center justify-center text-white text-xs font-bold",children:"F"});case"microsoft_ads":return e.jsx("div",{className:"w-5 h-5 bg-green-600 rounded-sm flex items-center justify-center text-white text-xs font-bold",children:"M"});default:return e.jsx(yr,{className:"h-5 w-5"})}},Le=ae=>{switch(ae){case"active":return e.jsx(ui,{className:"h-4 w-4 text-green-500"});case"paused":return e.jsx(ac,{className:"h-4 w-4 text-yellow-500"});case"ended":return e.jsx(tn,{className:"h-4 w-4 text-red-500"});default:return e.jsx(Dt,{className:"h-4 w-4 text-ink-soft"})}};return console.log("[DASHBOARD] Rendering with state:",{accountsCount:O.length,metricsLoaded:!!pe,viewM
80ode:v,selectedCampaign:c,dateRange:r}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:["Marketing Analytics",N&&e.jsx(Es,{className:"h-5 w-5 animate-spin"})]}),e.jsx("p",{className:"text-muted-foreground",children:"Real-time data from connected advertising platforms"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Vs,{open:t,onOpenChange:a,children:[e.jsx(zn,{asChild:!0,children:e.jsxs(ee,{children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),"Connect Account"]})}),e.jsxs(Us,{children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Connect Ad Account"}),e.jsx(Ct,{children:"Connect your advertising account to track real performance data"})]}),e.jsxs("form",{onSubmit:ae=>{ae.preventDefault();const xe=new FormData(ae.currentTarget),Fe=xe.get("accountId"),X=xe.get("accountName");console.log("[DASHBOARD] Form submitted:",{accountId:Fe,accountName:X,selectedPlatform:n}),Fe&&X&&n&&U.mutate({platform:n,accountId:Fe,accountName:X})},children:[e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"platform",children:"Platform"}),e.jsxs(os,{name:"platform",defaultValue:"google_ads",onValueChange:i,children:[e.jsx(ds,{children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"google_ads",children:"Google Ads"}),e.jsx(me,{value:"facebook_ads",children:"Facebook Ads"}),e.jsx(me,{value:"microsoft_ads",children:"Microsoft Ads"})]})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"accountId",children:"Account ID"}),e.jsx(Me,{id:"accountId",name:"accountId",placeholder:n==="google_ads"?"123-456-7890":"act_123456789",required:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"accountName",children:"Account Name"}),e.jsx(Me,{id:"accountName",name:"accountName",placeholder:"e.g., Main Healthcare Account",required:!0})]})]}),e.jsx(Ut,{children:e.jsx(ee,{type:"submit",disabled:U.isPending,children:U.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"mr-2 h-4 w-4 animate-spin"}),"Connecting..."]}):"Connect Account"})})]})]})]}),e.jsxs(gr,{children:[e.jsx(jr,{asChild:!0,children:e.jsx(ee,{variant:"outline",size:"icon",children:e.jsx(yo,{className:"h-4 w-4"})})}),e.jsxs(br,{align:"end",className:"w-56",children:[e.jsx(oi,{children:"Dashboard Settings"}),e.jsx(en,{}),e.jsxs(Dx,{children:[e.jsxs(xt,{onClick:()=>m(x===0?30:0),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),"Auto-refresh: ",x>0?`${x}s`:"Off"]}),e.jsxs(xt,{onClick:()=>{console.log("[DASHBOARD] Manual refresh triggered"),Ts.invalidateQueries({queryKey:["/api/advanced-marketing"]})},children:[e.jsx(Pt,{className:"mr-2 h-4 w-4"}),"Refresh Now"]})]}),e.jsx(en,{}),e.jsxs(xt,{onClick:()=>{console.log("[DASHBOARD] Export triggered"),s({title:"Export functionality coming soon"})},children:[e.jsx(di,{className:"mr-2 h-4 w-4"}),"Export Data"]})]})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(ee,{variant:r.preset==="7d"?"default":"outline",size:"sm",onClick:()=>{console.log("[DASHBOARD] Date range changed to 7d"),l({preset:"7d",custom:{from:"",to:""}})},children:"Last 7 Days"}),e.jsx(ee,{variant:r.preset==="30d"?"default":"outline",size:"sm",onClick:()=>{console.log("[DASHBOARD] Date range changed to 30d"),l({preset:"30d",custom:{from:"",to:""}})},children:"Last 30 Days"}),e.jsx(ee,{variant:r.preset==="90d"?"default":"outline",size:"sm",onClick:()=>{console.log("[DASHBOARD] Date range changed to 90d"),l({preset:"90d",custom:{from:"",to:""}})},children:"Last 90 Days"}),e.jsx(ee,{variant:r.preset==="ytd"?"default":"outline",size:"sm",onClick:()=>{console.log("[DASHBOARD] Date range changed to YTD"),l({preset:"ytd",custom:{from:"",to:""}})},children:"Year to Date"})]}),e.jsxs(Ic,{children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(ee,{variant:"outline",size:"sm",children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),r.preset==="custom"&&r.custom.from&&r.custom.to?`${r.custom.from} to ${r.custom.to}`:"Custom Range"]})}),e.jsx(Ec,{className:"w-auto p-4",align:"end",children:e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{children:"From"}),e.jsx(Me,{type:"date",value:r.custom.from,onChange:ae=>{console.log("[DASHBOARD] Custom date from:",ae.target.value),l({preset:"custom",custom:{...r.custom,from:ae.target.value}})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{children:"To"}),e.jsx(Me,{type:"date",value:r.custom.to,onChange:ae=>{console.log("[DASHBOARD] Custom date to:",ae.target.value),l({preset:"custom",custom:{...r.custom,to:ae.target.value}})}})]})]})})})]}),O.length>0&&O[0].lastSync&&e.jsxs("div",{className:"ml-auto flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ra,{className:"h-3 w-3"}),"Last sync: ",De(new Date(O[0].lastSync),"h:mm a")]})]})]}),re&&e.jsxs(Qs,{variant:"destructive",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx(Mn,{children:"Error loading accounts"}),e.jsx(Xs,{children:re.message})]}),Ie&&e.jsxs(Qs,{variant:"destructive",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx(Mn,{children:"Error loading metrics"}),e.jsx(Xs,{children:Ie.message})]}),e.jsxs(la,{value:v,onValueChange:ae=>g(ae),className:"mt-4",children:[e.jsxs(ca,{children:[e.jsx(Ee,{value:"overview",children:"Overview"}),e.jsx(Ee,{value:"detailed",children:"Performance Trends"}),e.jsx(Ee,{value:"keywords",children:"Keyword Analysis"}),e.jsx(Ee,{value:"budget",children:"Budget Pacing"})]}
80),e.jsxs(Ve,{value:"overview",className:"space-y-4 mt-4",children:[pe?e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"Total Spend"}),e.jsx(ct,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:be(pe.totalSpend)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[pe.recordCount," records"]})]})]}),e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"Impressions"}),e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:ss(pe.totalImpressions)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["CPM: ",pe.totalImpressions>0?be(pe.totalSpend/pe.totalImpressions*1e3):"N/A"]})]})]}),e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"Clicks"}),e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:ss(pe.totalClicks)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["CTR: ",pe.totalImpressions>0?oe(pe.totalClicks/pe.totalImpressions*100):"N/A"]})]})]}),e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"Conversions"}),e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:ss(pe.totalConversions)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Value: ",be(pe.totalConversionValue)]})]})]}),e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"ROAS"}),e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(pe.averageRoas??0).toFixed(2),"x"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Return on ad spend"})]})]})]}):ye?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[...Array(5)].map((ae,xe)=>e.jsxs(_,{children:[e.jsx(q,{className:"space-y-0 pb-2",children:e.jsx(cs,{className:"h-4 w-[100px]"})}),e.jsxs(T,{children:[e.jsx(cs,{className:"h-8 w-[120px]"}),e.jsx(cs,{className:"h-3 w-[80px] mt-2"})]})]},xe))}):null,e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(W,{children:"Active Campaigns"}),e.jsxs(os,{value:(c==null?void 0:c.toString())||"all",onValueChange:ae=>o(ae==="all"?null:parseInt(ae)),children:[e.jsx(ds,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Select campaign"})}),e.jsxs(ms,{children:[e.jsx(me,{value:"all",children:"All Campaigns"}),O&&Array.isArray(O)&&O.flatMap(ae=>{var xe;return((xe=ae.campaigns)==null?void 0:xe.map(Fe=>e.jsx(me,{value:Fe.id.toString(),children:Fe.name},Fe.id)))||[]})]})]})]})}),e.jsx(T,{children:N?e.jsx("div",{className:"space-y-3",children:[...Array(3)].map((ae,xe)=>e.jsx(cs,{className:"h-20 w-full"},xe))}):O.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(Yh,{className:"mx-auto h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No ad accounts connected yet."})]}):e.jsx("div",{className:"space-y-4",children:O.map(ae=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[Ne(ae.platform),e.jsx("span",{children:ae.accountName}),e.jsx(Y,{variant:ae.connected?"default":"secondary",children:ae.connected?"Connected":"Disconnected"}),e.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>j.mutate(ae.id),disabled:j.isPending,className:"ml-auto",children:e.jsx(Pt,{className:_a("h-4 w-4",j.isPending&&"animate-spin")})})]}),ae.campaigns&&ae.campaigns.length>0?e.jsx("div",{className:"space-y-2",children:ae.campaigns.map(xe=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[Le(xe.status),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:xe.name}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Budget: ",be(xe.dailyBudget),"/day"]}),e.jsxs("span",{children:["Spent: ",be(xe.totalSpend)]}),e.jsxs("span",{children:["ROAS: ",(xe.roas??0).toFixed(2),"x"]})]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(gr,{children:[e.jsx(jr,{asChild:!0,children:e.jsxs(ee,{size:"sm",variant:"outline",children:[e.jsx(yo,{className:"h-4 w-4 mr-2"}),"Manage"]})}),e.jsxs(br,{align:"end",className:"w-56",children:[e.jsx(oi,{children:"Campaign Controls"}),e.jsx(en,{}),e.jsx(xt,{onClick:()=>{const Fe=xe.status==="active"?"paused":"active";Q.mutate({campaignId:xe.id,status:Fe})},children:xe.status==="active"?e.jsxs(e.Fragment,{children:[e.jsx(ac,{className:"h-4 w-4 mr-2"}),"Pause Campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(pa,{className:"h-4 w-4 mr-2"}),"Resume Campaign"]})}),e.jsxs(xt,{onClick:()=>{se(xe),k(!0)},children:[e.jsx(ct,{className:"h-4 w-4 mr-2"}),"Modify Budget"]}
80),e.jsxs(xt,{onClick:()=>{le(xe),S(!0)},children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Manage Keywords"]}),e.jsxs(xt,{onClick:()=>{I(xe),F(!0)},children:[e.jsx(fa,{className:"h-4 w-4 mr-2"}),"Create Ads"]}),e.jsxs(xt,{onClick:()=>{f(xe),M(!0)},children:[e.jsx(lt,{className:"h-4 w-4 mr-2"}),"Adjust Targeting"]}),e.jsx(en,{}),e.jsxs(xt,{className:"text-red-600",onClick:()=>{confirm(`Are you sure you want to delete campaign "${xe.name}"?`)&&je.mutate(xe.id)},children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Delete Campaign"]})]})]})})]},xe.id))}):e.jsx("p",{className:"text-sm text-muted-foreground pl-7",children:"No campaigns found"})]},ae.id))})})]})]}),e.jsx(Ve,{value:"detailed",className:"space-y-4 mt-0",children:ve&&ve.data.length>0?e.jsxs(e.Fragment,{children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Performance Trends"}),e.jsxs(Oe,{children:["Daily performance metrics for ",ve.summary.dateRange.start," to ",ve.summary.dateRange.end]})]}),e.jsx(T,{children:e.jsx(ft,{width:"100%",height:300,children:e.jsxs(Mm,{data:ve.data,children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"date"}),e.jsx(at,{}),e.jsx(gt,{}),e.jsx(On,{}),e.jsx(In,{type:"monotone",dataKey:"cost",stroke:"#8884d8",fill:"#8884d8",name:"Cost ($)"}),e.jsx(In,{type:"monotone",dataKey:"conversions",stroke:"#82ca9d",fill:"#82ca9d",name:"Conversions"})]})})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm",children:"Average CTR"})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold",children:ve.summary.totals.impressions>0?oe(ve.summary.totals.clicks/ve.summary.totals.impressions*100):"N/A"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm",children:"Average CPC"})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold",children:ve.summary.totals.clicks>0?be(ve.summary.totals.cost/ve.summary.totals.clicks):"N/A"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm",children:"Conversion Rate"})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold",children:ve.summary.totals.clicks>0?oe(ve.summary.totals.conversions/ve.summary.totals.clicks*100):"N/A"})})]})]})]}):B?e.jsx(_,{children:e.jsxs(T,{className:"py-8",children:[e.jsx(Es,{className:"h-8 w-8 animate-spin mx-auto"}),e.jsx("p",{className:"text-center text-muted-foreground mt-2",children:"Loading performance data..."})]})}):e.jsx(_,{children:e.jsxs(T,{className:"py-8 text-center",children:[e.jsx(Zs,{className:"mx-auto h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No performance data available for the selected period."})]})})}),e.jsx(Ve,{value:"keywords",className:"space-y-4 mt-0",children:P?e.jsxs(Qs,{variant:"destructive",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx(Mn,{children:"Error loading keywords"}),e.jsx(Xs,{children:"Unable to fetch keyword data. Please try again later."})]}):z&&z.keywords&&z.keywords.length>0?e.jsxs(e.Fragment,{children:[e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(W,{children:"Keyword Performance"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Me,{placeholder:"Search keywords...",value:d,onChange:ae=>u(ae.target.value),className:"w-[200px]"})})]})}),e.jsx(T,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2",children:"Keyword"}),e.jsx("th",{className:"text-right py-2",children:"Impressions"}),e.jsx("th",{className:"text-right py-2",children:"Clicks"}),e.jsx("th",{className:"text-right py-2",children:"CTR"}),e.jsx("th",{className:"text-right py-2",children:"Avg. CPC"}),e.jsx("th",{className:"text-right py-2",children:"Cost"}),e.jsx("th",{className:"text-right py-2",children:"Quality Score"})]})}),e.jsx("tbody",{children:z.keywords.filter(ae=>!d||ae.keyword.toLowerCase().includes(d.toLowerCase())).slice(0,10).map(ae=>e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ae.keyword}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ae.matchType})]})}),e.jsx("td",{className:"text-right py-2",children:ss(ae.impressions)}),e.jsx("td",{className:"text-right py-2",children:ss(ae.clicks)}),e.jsx("td",{className:"text-right py-2",children:oe(ae.ctr)}),e.jsx("td",{className:"text-right py-2",children:be(ae.costPerClick)}),e.jsx("td",{className:"text-right py-2",children:be(parseFloat(ae.cost))}),e.jsx("td",{className:"text-right py-2",children:e.jsxs(Y,{variant:ae.qualityScore>=7?"default":ae.qualityScore>=4?"secondary":"destructive",children:[ae.qualityScore,"/10"]})})]},ae.id))})]})})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm",children:"Total Keywords"})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold",children:z.summary.total})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm",children:"Avg Quality Score"})}),e.jsx(T,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[(z.summary.avgQualityScore??0).toFixed(1),"/10"]})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm",children:"Total Cost"})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold",children:be(z.summary.totalCost)})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm",children:"Avg CTR"})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold",children:z.summary.totalImpressions>0?oe(z.summary.totalClicks/z.summary.totalImpressions*100):"N/A"})})]})]})]}):K?e.jsx(_,{children:e.jsxs(T,{className:"py-8",children:[e.jsx(Es,{className:"h-8 w-8 animate-spin mx-auto"}),e.jsx("p",{className:"text-center text-muted-foreground mt-2",children:"Loading keyword data..."})]})}):e.jsx(_,{children:e.jsxs(T,{className:"py-8 text-center",children:[e.jsx(Px,{className:"mx-auto h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No keyword data available. Select a campaign to view keywords."})]})})}
80),e.jsx(Ve,{value:"budget",className:"space-y-4 mt-0",children:c&&ue?e.jsx(e.Fragment,{children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:ue.campaign.name}),e.jsx(Oe,{children:"Budget utilization over the last 30 days"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Daily Budget"}),e.jsx("p",{className:"text-2xl font-bold",children:be(ue.campaign.dailyBudget)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Avg Daily Spend"}),e.jsx("p",{className:"text-2xl font-bold",children:be(ue.pacing.avgDailySpend)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Avg Utilization"}),e.jsx("p",{className:"text-2xl font-bold",children:oe(ue.pacing.avgUtilization)})]})]}),ue.pacing.dailySpend.length>0&&e.jsx(ft,{width:"100%",height:200,children:e.jsxs(Lr,{data:ue.pacing.dailySpend,children:[e.jsx(Jt,{strokeDasharray:"3 3"}),e.jsx(Bt,{dataKey:"date"}),e.jsx(at,{}),e.jsx(gt,{}),e.jsx(Zt,{dataKey:"spent",fill:"#8884d8",name:"Spent ($)"}),e.jsx(Zt,{dataKey:"budget",fill:"#82ca9d",name:"Budget ($)"})]})}),e.jsxs(Qs,{children:[e.jsx(bs,{className:"h-4 w-4"}),e.jsx(Mn,{children:"Recommendation"}),e.jsx(Xs,{children:ue.pacing.recommendation})]})]})})]})}):V?e.jsx(_,{children:e.jsxs(T,{className:"py-8",children:[e.jsx(Es,{className:"h-8 w-8 animate-spin mx-auto"}),e.jsx("p",{className:"text-center text-muted-foreground mt-2",children:"Loading budget pacing data..."})]})}):e.jsx(_,{children:e.jsxs(T,{className:"py-8 text-center",children:[e.jsx(Rm,{className:"mx-auto h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Select a campaign to view budget pacing analysis."})]})})})]}),e.jsx(Vs,{open:w,onOpenChange:k,children:e.jsxs(Us,{children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Modify Campaign Budget"}),e.jsxs(Ct,{children:["Update the daily budget for ",$==null?void 0:$.name]})]}),e.jsxs("form",{onSubmit:ae=>{ae.preventDefault();const xe=new FormData(ae.currentTarget),Fe=parseFloat(xe.get("budget"));$&&Fe&&Q.mutate({campaignId:$.id,budget:Fe})},children:[e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"budget",children:"Daily Budget ($)"}),e.jsx(Me,{id:"budget",name:"budget",type:"number",step:"0.01",min:"1",defaultValue:$==null?void 0:$.dailyBudget,required:!0}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Current budget: ",$&&be($.dailyBudget),"/day"]})]})}),e.jsxs(Ut,{children:[e.jsx(ee,{type:"button",variant:"outline",onClick:()=>k(!1),children:"Cancel"}),e.jsx(ee,{type:"submit",disabled:Q.isPending,children:Q.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):"Update Budget"})]})]})]})}),e.jsx(Vs,{open:G,onOpenChange:D,children:e.jsxs(Us,{className:"max-w-2xl",children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Create New Campaign"}),e.jsx(Ct,{children:"Create a new Google Ads campaign with full control"})]}),e.jsxs("form",{onSubmit:ae=>{ae.preventDefault();const xe=new FormData(ae.currentTarget),Fe={name:xe.get("name"),dailyBudget:parseFloat(xe.get("dailyBudget")),type:xe.get("type"),biddingStrategy:xe.get("biddingStrategy"),startDate:xe.get("startDate"),endDate:xe.get("endDate")};console.log("[DASHBOARD] Creating campaign with data:",Fe),ce.mutate(Fe)},children:[e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"name",children:"Campaign Name"}),e.jsx(Me,{id:"name",name:"name",placeholder:"e.g., Summer Healthcare Campaign",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"type",children:"Campaign Type"}),e.jsxs("select",{name:"type",defaultValue:"SEARCH",className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm r
80ing-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("option",{value:"SEARCH",children:"Search"}),e.jsx("option",{value:"DISPLAY",children:"Display"}),e.jsx("option",{value:"VIDEO",children:"Video"}),e.jsx("option",{value:"SHOPPING",children:"Shopping"}),e.jsx("option",{value:"PERFORMANCE_MAX",children:"Performance Max"})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"dailyBudget",children:"Daily Budget ($)"}),e.jsx(Me,{id:"dailyBudget",name:"dailyBudget",type:"number",step:"0.01",min:"1",placeholder:"50.00",required:!0})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"biddingStrategy",children:"Bidding Strategy"}),e.jsxs("select",{name:"biddingStrategy",defaultValue:"MANUAL_CPC",className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("option",{value:"MANUAL_CPC",children:"Manual CPC (Recommended)"}),e.jsx("option",{value:"MAXIMIZE_CLICKS",children:"Maximize Clicks"}),e.jsx("option",{value:"TARGET_CPA",children:"Target CPA"}),e.jsx("option",{value:"MAXIMIZE_CONVERSIONS",children:"Maximize Conversions"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"startDate",children:"Start Date"}),e.jsx(Me,{id:"startDate",name:"startDate",type:"date",defaultValue:new Date().toISOString().split("T")[0]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"endDate",children:"End Date (Optional)"}),e.jsx(Me,{id:"endDate",name:"endDate",type:"date"})]})]})]}),e.jsxs(Ut,{children:[e.jsx(ee,{type:"button",variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(ee,{type:"submit",disabled:ce.isPending,children:ce.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Campaign"})]})]})]})}),e.jsxs(ee,{className:"fixed bottom-6 right-6 shadow-lg",size:"lg",onClick:()=>D(!0),children:[e.jsx(on,{className:"mr-2 h-5 w-5"}),"Create Campaign"]})]})}function u4(){const{toast:s}=ya(),t=Ya(),[a,n]=p.useState(!1),[i,r]=p.useState("6months"),{data:l=[],isLoading:c}=_e({queryKey:["/api/advanced-marketing/cohorts"]}),{data:o}=_e({queryKey:["/api/advanced-marketing/cohorts/retention-matrix",i]}),d=ws({mutationFn:g=>vs("/api/advanced-marketing/cohorts","POST",g),onSuccess:()=>{t.invalidateQueries({queryKey:["/api/advanced-marketing/cohorts"]}),s({title:"Cohort created successfully"}),n(!1)},onError:()=>{s({title:"Failed to create cohort",variant:"destructive"})}}),u=g=>`${(g*100).toFixed(1)}%`,x=g=>g>=.8?"text-green-600":g>=.6?"text-yellow-600":"text-red-600",m=g=>g<=.05?"text-green-600":g<=.15?"text-yellow-600":"text-red-600",v=()=>{const g=["Month 0"];for(let w=1;w<=12;w++)g.push(`Month ${w}`);return g};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Cohort Analysis"}),e.jsx("p",{className:"text-muted-foreground",children:"Track user behavior and retention across different cohorts"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(os,{value:i,onValueChange:r,children:[e.jsx(ds,{className:"w-[150px]",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"3months",children:"Last 3 months"}),e.jsx(me,{value:"6months",children:"Last 6 months"}),e.jsx(me,{value:"12months",children:"Last 12 months"}),e.jsx(me,{value:"24months",children:"Last 24 months"})]})]}),e.jsxs(Vs,{open:a,onOpenChange:n,children:[e.jsx(zn,{asChild:!0,children:e.jsxs(ee,{children:[e.jsx(mc,{className:"mr-2 h-4 w-4"}),"Create Cohort"]})}),e.jsxs(Us,{children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Create New Cohort"}),e.jsx(Ct,{children:"Define a cohort based on user signup date or specific criteria"})]}),e.jsxs("form",{onSubmit:g=>{g.preventDefault();const w=new FormData(g.currentTarget);d.mutate({name:w.get("name"),definition:w.get("definition"),type:w.get("type")})},children:[e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"name",children:"Cohort Name"}),e.jsx(Me,{id:"name",name:"name",placeholder:"e.g., January 2025 Signups",required:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"type",children:"Cohort Type"}),e.jsxs(os,{name:"type",defaultValue:"monthly",children:[e.jsx(ds,{children:e.jsx(hs,{})}
80),e.jsxs(ms,{children:[e.jsx(me,{value:"monthly",children:"Monthly Signups"}),e.jsx(me,{value:"weekly",children:"Weekly Signups"}),e.jsx(me,{value:"custom",children:"Custom Definition"})]})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"definition",children:"Definition"}),e.jsx(La,{id:"definition",name:"definition",placeholder:"Users who signed up in January 2025",required:!0})]})]}),e.jsx(Ut,{children:e.jsx(ee,{type:"submit",disabled:d.isPending,children:"Create Cohort"})})]})]})]})]})]}),o&&e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(Zs,{className:"h-5 w-5"}),"Retention Matrix"]}),e.jsx(Oe,{children:"User retention by cohort over time"})]}),e.jsx(T,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2 border-b",children:"Cohort"}),e.jsx("th",{className:"text-center p-2 border-b",children:"Users"}),v().map(g=>e.jsx("th",{className:"text-center p-2 border-b text-sm",children:g},g))]})}),e.jsx("tbody",{children:o.cohorts.map(g=>e.jsxs("tr",{className:"hover:bg-muted/50",children:[e.jsx("td",{className:"p-2 border-b font-medium",children:g.month}),e.jsx("td",{className:"text-center p-2 border-b",children:g.users}),g.retention.map((w,k)=>e.jsx("td",{className:`text-center p-2 border-b text-sm ${x(w)}`,children:u(w)},k))]},g.month))})]})})})]}),e.jsxs(la,{defaultValue:"overview",className:"space-y-4",children:[e.jsxs(ca,{children:[e.jsx(Ee,{value:"overview",children:"Overview"}),e.jsx(Ee,{value:"revenue",children:"Revenue Analysis"}),e.jsx(Ee,{value:"features",children:"Feature Adoption"}),e.jsx(Ee,{value:"churn",children:"Churn Analysis"})]}),e.jsx(Ve,{value:"overview",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c?e.jsx(_,{className:"col-span-full",children:e.jsx(T,{className:"py-8 text-center text-muted-foreground",children:"Loading cohorts..."})}):l.length===0?e.jsx(_,{className:"col-span-full",children:e.jsxs(T,{className:"py-8 text-center",children:[e.jsx(mc,{className:"mx-auto h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No cohorts created yet. Create your first cohort to start tracking!"})]})}):l.map(g=>e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{children:[e.jsx(W,{className:"text-lg",children:g.name}),e.jsx(Oe,{className:"text-xs",children:De(new Date(g.createdAt),"MMM yyyy")})]}),e.jsxs(Y,{variant:"secondary",children:[g.metrics.totalUsers," users"]})]})}),e.jsxs(T,{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Users"}),e.jsxs("span",{className:"text-sm font-medium",children:[g.metrics.activeUsers," (",u(g.metrics.activeUsers/g.metrics.totalUsers),")"]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Month 1 Retention"}),e.jsx("span",{className:`text-sm font-medium ${x(g.metrics.retentionRate[1]||0)}`,children:u(g.metrics.retentionRate[1]||0)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Revenue/User"}),e.jsxs("span",{className:"text-sm font-medium",children:["$",g.metrics.revenuePerUser.toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Churn Rate"}),e.jsx("span",{className:`text-sm font-medium ${m(g.metrics.churnRate)}`,children:u(g.metrics.churnRate)})]})]})]},g.id))})}),e.jsx(Ve,{value:"revenue",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Revenue by Cohort"}),e.jsx(Oe,{children:"Compare lifetime value and revenue metrics across cohorts"})]}),e.jsx(T,{children:e.jsx("div",{className:"space-y-4",children:l.map(g=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:g.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.metrics.totalUsers," users"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"font-medium",children:["$",g.metrics.totalRevenue.toLocaleStr
80ing()]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["LTV: $",g.metrics.lifetimeValue.toFixed(2)]})]})]}),e.jsx(mt,{value:g.metrics.lifetimeValue/2e3*100,className:"h-2"})]},g.id))})})]})}),e.jsx(Ve,{value:"features",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Feature Adoption by Cohort"}),e.jsx(Oe,{children:"Track how different cohorts adopt key platform features"})]}),e.jsx(T,{children:e.jsx("div",{className:"space-y-4",children:l.length>0&&e.jsx("div",{className:"grid gap-4",children:Object.keys(l[0].metrics.featureAdoption).map(g=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium capitalize",children:g.replace(/_/g," ")}),e.jsx("div",{className:"space-y-1",children:l.map(w=>e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm",children:w.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{value:w.metrics.featureAdoption[g]||0,className:"w-24 h-2"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-10 text-right",children:[w.metrics.featureAdoption[g]||0,"%"]})]})]},w.id))})]},g))})})})]})}),e.jsx(Ve,{value:"churn",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Churn Analysis"}),e.jsx(Oe,{children:"Identify at-risk cohorts and churn patterns"})]}),e.jsx(T,{children:e.jsx("div",{className:"grid gap-4",children:l.sort((g,w)=>w.metrics.churnRate-g.metrics.churnRate).map(g=>e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`p-2 rounded-full ${g.metrics.churnRate>.15?"bg-red-100":g.metrics.churnRate>.05?"bg-yellow-100":"bg-green-100"}`,children:g.metrics.churnRate>.15?e.jsx(Et,{className:"h-4 w-4 text-red-600"}):g.metrics.churnRate>.05?e.jsx(ja,{className:"h-4 w-4 text-yellow-600"}):e.jsx(Is,{className:"h-4 w-4 text-green-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:g.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.metrics.totalUsers-g.metrics.activeUsers," churned users"]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:`text-lg font-bold ${m(g.metrics.churnRate)}`,children:u(g.metrics.churnRate)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"churn rate"})]})]},g.id))})})]})})]})]})}function x4(){const{toast:s}=ya(),t=Ya(),[a,n]=p.useState(!1),[i,r]=p.useState("30days"),{data:l,isLoading:c}=_e({queryKey:["/api/advanced-marketing/healthcare-metrics",i]}),{data:o=[]}=_e({queryKey:["/api/advanced-marketing/healthcare-campaigns"]}),d=ws({mutationFn:v=>vs("/api/advanced-marketing/healthcare-campaigns","POST",v),onSuccess:()=>{t.invalidateQueries({queryKey:["/api/advanced-marketing/healthcare-campaigns"]}),s({title:"Healthcare campaign created successfully"}),n(!1)},onError:()=>{s({title:"Failed to create campaign",variant:"destructive"})}}),u=v=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0}).format(v),x=v=>v?"text-green-600":"text-red-600",m=v=>v>=3?"text-green-600":v>=1.5?"text-yellow-600":"text-red-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Healthcare Marketing Intelligence"}),e.jsx("p",{className:"text-muted-foreground",children:"Healthcare-specific marketing insights and compliance tracking"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(os,{value:i,onValueChange:r,children:[e.jsx(ds,{className:"w-[150px]",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"7days",children:"Last 7 days"}),e.jsx(me,{value:"30days",children:"Last 30 days"}),e.jsx(me,{value:"90days",children:"Last 90 days"}),e.jsx(me,{value:"1year",children:"Last year"})]})]}),e.jsxs(Vs,{open:a,onOpenChange:n,children:[e.jsx(zn,{asChild:!0,children:e.jsxs(ee,{children:[e.jsx(nc,{className:"mr-2 h-4 w-4"}),"New Healthcare Campaign"]})}),e.jsxs(Us,{children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Create Healthcare Campaign"}),e.jsx(Ct,{children:"Launch a targeted campaign for patient acquisition or provider outreach"})]}),e.jsxs("form",{onSubmit:v=>{v.preventDefault();const g=new FormData(v.currentTarget);d.mutate({name:g.get("name"),type:g.get("type"),budget:Number(g.get("budget")),target:g.get("target"),compliance:g.get("compliance")==="on"})},children:[e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"name",children:"Campaign Name"}),e.jsx(Me,{id:"name",name:"name",placeholder:"e.g., Cardiology Awareness Month",required:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"type",children:"Campaign Type"}),e.jsxs(os,{name:"type",defaultValue:"patient_acquisition",children:[e.jsx(ds,{children:e.jsx(hs,{})}
80),e.jsxs(ms,{children:[e.jsx(me,{value:"patient_acquisition",children:"Patient Acquisition"}),e.jsx(me,{value:"provider_outreach",children:"Provider Outreach"}),e.jsx(me,{value:"wellness",children:"Wellness Program"}),e.jsx(me,{value:"specialty",children:"Specialty Service"})]})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"budget",children:"Budget"}),e.jsx(Me,{id:"budget",name:"budget",type:"number",placeholder:"10000",required:!0})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(Ue,{htmlFor:"target",children:"Target Audience"}),e.jsx(La,{id:"target",name:"target",placeholder:"Adults 45-65 with cardiovascular risk factors",required:!0})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("input",{id:"compliance",name:"compliance",type:"checkbox",className:"h-4 w-4",defaultChecked:!0}),e.jsx(Ue,{htmlFor:"compliance",children:"HIPAA compliant campaign"})]})]}),e.jsx(Ut,{children:e.jsx(ee,{type:"submit",disabled:d.isPending,children:"Create Campaign"})})]})]})]})]})]}),c?e.jsx("div",{className:"text-center py-8",children:"Loading healthcare metrics..."}):l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"New Patients"}),e.jsx(si,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:l.patientAcquisition.totalNewPatients}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Cost per acquisition: ",u(l.patientAcquisition.acquisitionCost)]})]})]}),e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"Provider Referrals"}),e.jsx(Qh,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:l.providerMetrics.referralVolume}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["From ",l.providerMetrics.referringProviders," providers"]})]})]}),e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"Patient Satisfaction"}),e.jsx(nc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(l.outcomeMarketing.patientSatisfaction*100).toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.outcomeMarketing.testimonials," testimonials"]})]})]}),e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(W,{className:"text-sm font-medium",children:"Compliance Score"}),e.jsx(mi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(T,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-2xl font-bold ${x(l.complianceScore.hipaaCompliant)}`,children:l.complianceScore.hipaaCompliant?"â":"â"}),e.jsx("span",{className:"text-sm",children:"HIPAA Compliant"})]}),l.complianceScore.issues.length>0&&e.jsxs(Y,{variant:"destructive",className:"mt-1",children:[l.complianceScore.issues.length," issues"]})]})]})]}),e.jsxs(la,{defaultValue:"acquisition",className:"space-y-4",children:[e.jsxs(ca,{children:[e.jsx(Ee,{value:"acquisition",children:"Patient Acquisition"}),e.jsx(Ee,{value:"referrals",children:"Provider Network"}),e.jsx(Ee,{value:"payer",children:"Payer Mix"}),e.jsx(Ee,{value:"campaigns",children:"Campaigns"}),e.jsx(Ee,{value:"compliance",children:"Compliance"})]}),e.jsx(Ve,{value:"acquisition",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Patient Acquisition Sources"}),e.jsx(Oe,{children:"Breakdown of how new patients find your practice"})]}),e.jsxs(T,{children:[e.jsx("div",{className:"space-y-4",children:Object.entries(l.patientAcquisition.sourcesBreakdown).map(([v,g])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[v==="referrals"&&e.jsx(Ys,{className:"h-4 w-4"}),v==="directSearch"&&e.jsx(ga,{className:"h-4 w-4"}),v==="insurance"&&e.jsx(Rm,{className:"h-4 w-4"}),v==="campaigns"&&e.jsx(lt,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:v.replace(/([A-Z])/g," $1").trim()})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{value:g/l.patientAcquisition.totalNewPatients
80*100,className:"w-24"}),e.jsx("span",{className:"text-sm w-12 text-right",children:g})]})]},v))}),e.jsx("div",{className:"mt-4 pt-4 border-t",children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Conversion Rate"}),e.jsxs("span",{className:"font-medium",children:[(l.patientAcquisition.conversionRate*100).toFixed(1),"%"]})]})})]})]})}),e.jsx(Ve,{value:"referrals",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Top Referring Providers"}),e.jsx(Oe,{children:"Your most valuable referral partners"})]}),e.jsx(T,{children:e.jsx("div",{className:"space-y-4",children:l.providerMetrics.topReferrers.map((v,g)=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.specialty})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"font-medium",children:[v.referrals," referrals"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[u(v.revenue)," revenue"]})]})]},g))})})]})}),e.jsx(Ve,{value:"payer",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Insurance Payer Mix"}),e.jsx(Oe,{children:"Distribution of payment sources"})]}),e.jsx(T,{children:e.jsx("div",{className:"space-y-4",children:Object.entries(l.payerMix).map(([v,g])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"capitalize",children:v}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[g,"%"]})]}),e.jsx(mt,{value:g,className:"h-2"})]},v))})})]})}),e.jsx(Ve,{value:"campaigns",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:o.map(v=>e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{children:[e.jsx(W,{className:"text-lg",children:v.name}),e.jsx(Oe,{className:"capitalize",children:v.type.replace(/_/g," ")})]}),e.jsx(Y,{variant:v.status==="active"?"default":"secondary",children:v.status})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Budget"}),e.jsx("p",{className:"font-medium",children:u(v.budget)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Spent"}),e.jsx("p",{className:"font-medium",children:u(v.spent)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"New Patients"}),e.jsx("p",{className:"font-medium",children:v.results.newPatients})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"ROI"}),e.jsxs("p",{className:`font-medium ${m(v.results.roi)}`,children:[v.results.roi.toFixed(1),"x"]})]})]}),e.jsx(mt,{value:v.spent/v.budget*100,className:"mt-4"})]})]},v.id))})}),e.jsx(Ve,{value:"compliance",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Marketing Compliance Status"}),e.jsx(Oe,{children:"Healthcare marketing regulatory compliance"})]}),e.jsxs(T,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mi,{className:"h-4 w-4"}),e.jsx("span",{children:"HIPAA Compliance"})]}),e.jsx(Y,{variant:l.complianceScore.hipaaCompliant?"default":"destructive",children:l.complianceScore.hipaaCompliant?"Compliant":"Non-Compliant"})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-4 w-4"}),e.jsx("span",{children:"Marketing Guidelines"})]}),e.jsx(Y,{variant:l.complianceScore.marketingCompliant?"default":"destructive",children:l.complianceScore.marketingCompliant?"Compliant":"Non-Compliant"})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4"}),e.jsx("span",{children:"Data Privacy Score"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{value:l.complianceScore.dataPrivacy,className:"w-24"}),e.jsxs("span",{className:"text-sm",children:[l.complianceScore.dataPrivacy,"%"]})]})]})]}),l.complianceScore.issues.length>0&&e.jsxs("div",{className:"mt-4 p-4 bg-red-50 rounded-lg",children:[e.jsx("h4",{className:"font-medium text-red-900 mb-2",children:"Compliance Issues"}),e.jsx("ul",{className:"space-y-1",children:l.complianceScore.issues.map((v,g)=>e.jsxs("li",{className:"text-sm text-red-700 flex items-start gap-2",children:[e.jsx(Dt,{className:"h-3 w-3 mt-0.5 flex-shrink-0"}),v]},g))})]})]})]})})]})]})]})}function h4(){if(_t())return null;const s=Ya(),[t,a]=p.useState(!1),[n,i]=p.useState("30d"),{data:r,isLoading:l}=_e({queryKey:[`/api/marketing/campaigns?range=${n}`]}),{data:c}=_e({queryKey:[`/api/marketing/roi-metrics?range=${n}`]}),o=ws({mutationFn:async b=>{const S=await fetch("/api/marketing/campaigns",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!S.ok)throw new Error("Failed to create campaign");return S.json()},onSuccess:()=>{s.invalidateQueries({queryKey:["/api/marketing/campaigns"]}),a(!1),ta({title:"Campaign created",description:"Your campaign has been created successfully."})}}),d=b=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(b),u=b=>new Intl.NumberFormat("en-US").format(b);if(l)return e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((b,S)=>e.jsx(cs,{className:"h-48"},S))});const x=(r==null?void 0:r.reduce((b,S)=>b+S.spent,0))||0,m=(r==null?void 0:r.reduce((b,S)=>b+S.revenue,0))||0,v=(r==null?void 0:r.reduce((b,S)=>b+S.conversions,0))||0,g=x>0?(m-x)/x*100:0,w=v>0?x/v:0,k=r||[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Campaign Performance & ROI"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(os,{value:n,onValueChange:i,children:[e.jsx(ds,{className:"w-32",children:e.jsx(hs,{})}
80),e.jsxs(ms,{children:[e.jsx(me,{value:"7d",children:"Last 7 days"}),e.jsx(me,{value:"30d",children:"Last 30 days"}),e.jsx(me,{value:"90d",children:"Last 90 days"}),e.jsx(me,{value:"ytd",children:"Year to date"})]})]}),e.jsxs(Vs,{open:t,onOpenChange:a,children:[e.jsx(zn,{asChild:!0,children:e.jsxs(ee,{children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"New Campaign"]})}),e.jsxs(Us,{children:[e.jsx(Bs,{children:e.jsx(zs,{children:"Create New Campaign"})}),e.jsx("form",{onSubmit:b=>{b.preventDefault();const S=new FormData(b.currentTarget);o.mutate({name:S.get("name"),channel:S.get("channel"),budget:Number(S.get("budget")),startDate:S.get("startDate"),status:"active",spent:0,impressions:0,clicks:0,conversions:0,revenue:0,roi:0,cpa:0})},children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Ue,{htmlFor:"name",children:"Campaign Name"}),e.jsx(Me,{id:"name",name:"name",required:!0})]}),e.jsxs("div",{children:[e.jsx(Ue,{htmlFor:"channel",children:"Channel"}),e.jsxs(os,{name:"channel",required:!0,children:[e.jsx(ds,{children:e.jsx(hs,{placeholder:"Select channel"})}),e.jsxs(ms,{children:[e.jsx(me,{value:"Google Ads",children:"Google Ads"}),e.jsx(me,{value:"Facebook",children:"Facebook"}),e.jsx(me,{value:"LinkedIn",children:"LinkedIn"}),e.jsx(me,{value:"Email",children:"Email"}),e.jsx(me,{value:"Organic",children:"Organic"})]})]})]}),e.jsxs("div",{children:[e.jsx(Ue,{htmlFor:"budget",children:"Budget"}),e.jsx(Me,{id:"budget",name:"budget",type:"number",min:"0",step:"100",required:!0})]}),e.jsxs("div",{children:[e.jsx(Ue,{htmlFor:"startDate",children:"Start Date"}),e.jsx(Me,{id:"startDate",name:"startDate",type:"date",required:!0})]}),e.jsx(ee,{type:"submit",className:"w-full",children:"Create Campaign"})]})})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium",children:"Total Spend"})}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d(x)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all campaigns"})]})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium",children:"Total Revenue"})}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d(m)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Generated revenue"})]})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium",children:"Overall ROI"})}),e.jsxs(T,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"text-2xl font-bold",children:[g.toFixed(0),"%"]}),g>0?e.jsx(dc,{className:"h-4 w-4 text-green-600"}):e.jsx(hp,{className:"h-4 w-4 text-red-600"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Return on investment"})]})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium",children:"Conversions"})}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"New subscriptions"})]})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium",children:"Avg. CPA"})}),e.jsxs(T,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d(w)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cost per acquisition"})]})]})]}),e.jsx("div",{className:"space-y-4",children:k.map(b=>e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(W,{className:"text-lg",children:b.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Y,{variant:"outline",children:b.channel}),e.jsx(Y,{variant:b.status==="active"?"default":b.status==="paused"?"secondary":"outline",children:b.status}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.jsx(ia,{className:"h-3 w-3 inline mr-1"}),new Date(b.startDate).toLocaleDateString(),b.endDate&&` - ${new Date(b.endD
80ate).toLocaleDateString()}`]})]})]}),e.jsx("div",{className:"text-right",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-2xl font-bold text-green-600",children:[b.roi,"% ROI"]}),b.roi>200?e.jsx(Is,{className:"h-5 w-5 text-green-600"}):e.jsx(Et,{className:"h-5 w-5 text-yellow-600"})]})})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[e.jsxs("span",{children:["Budget: ",d(b.spent)," / ",d(b.budget)]}),e.jsxs("span",{children:[(b.spent/b.budget*100).toFixed(0),"%"]})]}),e.jsx(mt,{value:b.spent/b.budget*100,className:"h-2"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Impressions"}),e.jsx("p",{className:"text-lg font-semibold",children:u(b.impressions)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Clicks"}),e.jsx("p",{className:"text-lg font-semibold",children:u(b.clicks)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(b.clicks/b.impressions*100).toFixed(2),"% CTR"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Conversions"}),e.jsx("p",{className:"text-lg font-semibold",children:b.conversions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(b.conversions/b.clicks*100).toFixed(1),"% CVR"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Revenue"}),e.jsx("p",{className:"text-lg font-semibold text-green-600",children:d(b.revenue)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"CPA"}),e.jsx("p",{className:"text-lg font-semibold",children:d(b.cpa)})]})]}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsxs(ee,{variant:"outline",size:"sm",children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"View Details"]}),b.status==="active"&&e.jsx(ee,{variant:"outline",size:"sm",children:"Pause Campaign"}),b.status==="paused"&&e.jsx(ee,{variant:"outline",size:"sm",children:"Resume Campaign"})]})]})]},b.id))}),(!k||k.length===0)&&e.jsx(_,{children:e.jsxs(T,{className:"p-12 text-center",children:[e.jsx(lt,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No campaigns found. Create your first campaign to start tracking ROI."})]})})]})}const Ea={competitive_positioning:{name:"Competitive Positioning",icon:lt,description:"Analyzes your competitive landscape across SEO, YouTube, and paid media",mission:"Identify competitive gaps and opportunities to differentiate Clarafi in the market",color:"text-blue-600",bgColor:"bg-info-surface dark:bg-blue-950"},acquisition_funnel:{name:"Acquisition Funnel",icon:Is,description:"Tracks user journey from first touch to activation",mission:"Optimize conversion rates at each funnel stage to maximize signups",color:"text-green-600",bgColor:"bg-green-50 dark:bg-green-950"},youtube_performance:{name:"YouTube Performance",icon:Ra,description:"Analyzes video performance, retention, and content strategy",mission:"Maximize YouTube as a growth channel through data-driven content decisions",color:"text-red-600",bgColor:"bg-red-50 dark:bg-red-950"},seo_opportunity:{name:"SEO Opportunity",icon:ga,description:"Identifies keyword opportunities and content gaps",mission:"Build organic traffic through strategic SEO improvements",color:"text-purple-600",bgColor:"bg-purple-50 dark:bg-purple-950"},paid_media:{name:"Paid Media",icon:ct,description:"Optimizes Google Ads campaigns and budget allocation",mission:"Maximize ROI from paid advertising while maintaining target CAC",color:"text-amber-600",bgColor:"bg-amber-50 dark:bg-amber-950"},messaging_positioning:{name:"Messaging & Positioning",icon:rc,description:"Refines value propositions and marketing copy",mission:"Craft compelling messaging that resonates with target physicians",color:"text-pink-600",bgColor:"bg-pink-50 dark:bg-pink-950"},experiment_planner:{name:"Experiment Planner",icon:fi,description:"Prioritizes and tracks marketing experiments",mission:"Systematically test and learn to drive continuous improvement",color:"text-cyan-600",bgColor:"bg-cyan-50 dark:bg-cyan-950"}},Xl=[{value:"gpt-4.1-nano",label:"GPT-4.1 Nano",description:"Fastest processing, lowest cost",badge:"Fast",color:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},{value:"gpt-4.1-mini",label:"GPT-4.1 Mini",description:"Balanced speed and accuracy",badge:"Balanced",color:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"},{value:"gpt-4.1",label:"GPT-4.1",description:"Highest accuracy, most thorough analysis",badge:"Best",color:"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"},{value:"o3",label:"o3 (Reasoning)",description:"Advanced reasoning for complex analysis",badge:"Premium",color:"bg-
80amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200"}];function p4(){if(_t())return null;const[s,t]=p.useState(null),[a,n]=p.useState("gpt-4.1-mini"),[i,r]=p.useState({start:De(vt(new Date,30),"yyyy-MM-dd"),end:De(new Date,"yyyy-MM-dd")}),[l,c]=p.useState(""),[o,d]=p.useState([]),[u,x]=p.useState("agents"),[m,v]=p.useState(!1),[g,w]=p.useState(null),[k,b]=p.useState(!0),[S,A]=p.useState(null),[F,de]=p.useState(!1),[M,G]=p.useState(!1),[D,$]=p.useState(null),[se,J]=p.useState(null),[le,C]=p.useState(""),[I,y]=p.useState(!1),[f,R]=p.useState(null),O=p.useRef(null),{toast:N}=ya(),re=Ya(),{data:H,isLoading:pe}=_e({queryKey:["/api/marketing/agents"]}),{data:ye,isLoading:Ie,refetch:ve}=_e({queryKey:["/api/marketing/agent-runs"]}),{data:B,isLoading:z,refetch:K}=_e({queryKey:["/api/marketing/human-data-requests"]}),{data:P}=_e({queryKey:["/api/marketing/documents"]});p.useEffect(()=>{P&&d(ie=>{const te=ie.filter(ge=>ge.status==="uploading"||ge.status==="processing"),fe=P.map(ge=>({...ge,status:"parsed"}));return[...te,...fe]})},[P]);const{data:ue,isLoading:V,refetch:U}=_e({queryKey:["/api/marketing/threads",{agentId:D}],queryFn:async()=>{const ie=await fetch(`/api/marketing/threads?agentId=${D}`,{credentials:"include"});if(!ie.ok)throw new Error("Failed to fetch threads");return ie.json()},enabled:!!D&&M}),{data:j,isLoading:Q,refetch:je}=_e({queryKey:["/api/marketing/threads",se],queryFn:async()=>{const ie=await fetch(`/api/marketing/threads/${se}`,{credentials:"include"});if(!ie.ok)throw new Error("Failed to fetch thread");return ie.json()},enabled:!!se}),ce=j==null?void 0:j.messages;p.useEffect(()=>{ce&&O.current&&O.current.scrollIntoView({behavior:"smooth"})},[ce]);const be=ws({mutationFn:async({agentId:ie,initialMessage:te})=>{const fe=await vs("POST","/api/marketing/threads",{agentId:ie,model:a,initialMessage:te});if(!fe.ok){const ge=await fe.json();throw new Error(ge.error||"Failed to create thread")}return fe.json()},onSuccess:ie=>{J(ie.thread.threadId),re.invalidateQueries({queryKey:["/api/marketing/threads",{agentId:D}]})},onError:ie=>{N({title:"Failed to create conversation",description:ie.message,variant:"destructive"})}}),ss=ws({mutationFn:async({threadId:ie,content:te,includeDebug:fe})=>{const ge=await vs("POST",`/api/marketing/threads/${ie}/messages`,{content:te,includeDebug:fe});if(!ge.ok){const We=await ge.json();throw new Error(We.error||"Failed to send message")}return ge.json()},onSuccess:()=>{C(""),re.invalidateQueries({queryKey:["/api/marketing/threads",se]}),re.invalidateQueries({queryKey:["/api/marketing/threads",{agentId:D}]})},onError:ie=>{N({title:"Failed to send message",description:ie.message,variant:"destructive"})}}),oe=ie=>{$(ie),J(null),G(!0)},Ne=ie=>{J(ie)},Le=()=>{D&&J(null)},ae=()=>{le.trim()&&(!se&&D?be.mutate({agentId:D,initialMessage:le.trim()},{onSuccess:()=>{C("")}}):se&&ss.mutate({threadId:se,content:le.trim(),includeDebug:k}))},xe=ws({mutationFn:async({agentId:ie,dateRange:te,model:fe,context:ge,documents:We,includeDebug:we})=>{const gs=await vs("POST",`/api/marketing/agents/${ie}/run`,{dateRange:{start:te.start,end:te.end},model:fe,additionalContext:ge,uploadedDocuments:We,includeDebug:we});if(!gs.ok){const Ss=await gs.json();throw new Error(Ss.error||"Failed to run agent")}return gs.json()},onSuccess:ie=>{var te;N({title:"Agent Run Completed",description:`${((te=Ea[ie.agentId])==null?void 0:te.name)||ie.agentId} analysis is complete.`}),re.invalidateQueries({queryKey:["/api/marketing/agent-runs"]}),v(!1),ie.debug&&k&&(A(ie.debug),de(!0))},onError:ie=>{N({title:"Agent Run Failed",description:ie.message,variant:"destructive"})}}),Fe=ws({mutationFn:async({id:ie,status:te,responseData:fe,responseNotes:ge})=>{const We=await vs("PATCH",`/api/marketing/human-data-requests/${ie}`,{status:te,responseData:fe,responseNotes:ge});if(!We.ok)throw new Error("Failed to update data request");return We.json()},onSuccess:()=>{N({title:"Data Request Updated",description:"The data request status has been updated."}),re.invalidateQueries({queryKey:["/api/marketing/human-data-requests"]})}}),X=p.useCallback(async ie=>{for(const te of ie){const fe=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;d(ge=>[...ge,{id:fe,fileName:te.name,fileType:te.type,fileSize:te.size,uploadedAt:new Date().toISOString(),status:"uploading"}]);try{const ge=new FormData;ge.append("file",te),ge.append("type","marketing_data");const We=await fetch("/api/marketing/documents/upload",{method:"POST",body:ge,credentials:"include"});if(!We.ok)throw new Error("Upload failed");const we=await We.json();d(gs=>gs.map(Ss=>Ss.id===fe?{...Ss,status:"parsed",extractedContent:we.extractedContent,parsedData:we.parsedData}
80:Ss)),N({title:"Document Processed",description:`${te.name} has been parsed successfully.`})}catch{d(We=>We.map(we=>we.id===fe?{...we,status:"error",error:"Failed to process document"}:we)),N({title:"Upload Failed",description:`Failed to process ${te.name}`,variant:"destructive"})}}},[N]),{getRootProps:Be,getInputProps:ns,isDragActive:nt}=Xh({onDrop:X,accept:{"text/csv":[".csv"],"application/pdf":[".pdf"],"application/vnd.ms-excel":[".xls"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xlsx"],"text/plain":[".txt"]},maxSize:10*1024*1024}),ks=async ie=>{try{d(fe=>fe.filter(ge=>ge.id!==ie)),(await vs("DELETE",`/api/marketing/documents/${ie}`)).ok||console.error("Failed to delete document from server"),re.invalidateQueries({queryKey:["/api/marketing/documents"]})}catch(te){console.error("Error deleting document:",te)}},Rt=()=>{s&&xe.mutate({agentId:s,dateRange:i,model:a,context:l,documents:o.filter(ie=>ie.status==="parsed").map(ie=>ie.id),includeDebug:k})},wt=ie=>{const te={high:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",medium:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",low:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"};return e.jsxs(Y,{className:te[ie],children:[ie," confidence"]})},jt=ie=>{const te={running:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",completed:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",failed:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",pending:"bg-surface-sunken text-ink-heading dark:bg-gray-900 dark:text-gray-200",fulfilled:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",cannot_fulfill:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"};return e.jsx(Y,{className:te[ie]||te.pending,children:ie})},rs=()=>{const ie=(H==null?void 0:H.agents)||[];return pe?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6,7].map(te=>e.jsxs(_,{className:"animate-pulse",children:[e.jsxs(q,{children:[e.jsx(cs,{className:"h-6 w-3/4"}),e.jsx(cs,{className:"h-4 w-full mt-2"})]}),e.jsx(T,{children:e.jsx(cs,{className:"h-4 w-2/3"})})]},te))}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:ie.map(te=>{var we;const fe=Ea[te];if(!fe)return null;const ge=fe.icon,We=(we=ye==null?void 0:ye.filter(gs=>gs.agentId===te))==null?void 0:we[0];return e.jsxs(_,{className:`cursor-pointer transition-all hover:shadow-lg hover:scale-[1.02] ${s===te?"ring-2 ring-primary":""}`,onClick:()=>t(te),"data-testid":`agent-card-${te}`,children:[e.jsxs(q,{children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:`p-2 rounded-lg ${fe.bgColor}`,children:e.jsx(ge,{className:`h-6 w-6 ${fe.color}`})}),We&&e.jsxs(Y,{variant:"outline",className:"text-xs",children:[We.status==="completed"?e.jsx(Ft,{className:"h-3 w-3 mr-1 text-green-500"}):We.status==="running"?e.jsx(Es,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(Dt,{className:"h-3 w-3 mr-1 text-red-500"}),We.status]})]}),e.jsx(W,{className:"text-lg mt-2",children:fe.name}),e.jsx(Oe,{children:fe.description})]}),e.jsxs(T,{children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx(sc,{className:"h-4 w-4 inline mr-1"}),fe.mission]}),We&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[e.jsx(ra,{className:"h-3 w-3 inline mr-1"}),"Last run: ",De(new Date(We.startedAt),"MMM d, h:mm a")]})]}),e.jsxs(Ix,{className:"flex gap-2",children:[e.jsxs(ee,{variant:"outline",className:"flex-1",onClick:gs=>{gs.stopPropagation(),oe(te)},"data-testid":`chat-agent-${te}`,children:[e.jsx(jp,{className:"h-4 w-4 mr-2"}),"Chat"]}),e.jsxs(ee,{className:"flex-1",onClick:gs=>{gs.stopPropagation(),t(te),v(!0)},"data-testid":`run-agent-${te}`,children:[e.jsx(pa,{className:"h-4 w-4 mr-2"}),"Analyze"]})]})]},te)})})},ea=()=>{if(Ie)return e.jsx("div",{className:"space-y-4",children:[1,2,3].map(te=>e.jsx(_,{className:"animate-pulse",children:e.jsx(T,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(cs,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(cs,{className:"h-4 w-1/3"}),e.jsx(cs,{className:"h-3 w-1/4 mt-2"})]}),e.jsx(cs,{className:"h-8 w-20"})]})})},te))});const ie=ye||[];return ie.length===0?e.jsx(_,{children:e.jsxs(T,{className:"p-8 text-center",children:[e.jsx(Ua,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium",children:"No Run History"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Run an agent to see the analysis history here."})]})}):e.jsx("div",{className:"space-y-4",children:ie.map(te=>{var We;const fe=Ea[te.agentId],ge=(fe==null?void 0:fe.icon)||Xa;return e.jsx(_,{"data-testid":`run-history-${te.id}`,children:e.jsxs(T,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`p-2 rounded-lg ${(fe==null?void 0:fe.bgColor)||"bg-surface-sunken"}`,children:e.jsx(ge,{className:`h-5 w-5 ${(fe==null?void 0:fe.color)||"text-ink-muted"}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium truncate",children:(fe==null?void 0:fe.name)||te.agentId}),jt(te.status)]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[De(new Date(te.startedAt),"MMM d, yyyy h:mm a"),te.durationMs&&e.jsxs("span",{className:"ml-2",children:["· ",(te.durationMs/1e3).toFixed(1),"s"]}),te.tokensUsed&&e.jsxs("span",{className:"ml-2",children:["· ",te.tokensUsed.toLocaleStr
80ing()," tokens"]})]})]}),e.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>w(te.id),disabled:te.status!=="completed","data-testid":`view-run-${te.id}`,children:[e.jsx(Hs,{className:"h-4 w-4 mr-1"}),"View"]})]}),te.status==="completed"&&((We=te.output)==null?void 0:We.summary)&&e.jsx("div",{className:"mt-4 p-3 bg-muted/50 rounded-lg",children:e.jsx("p",{className:"text-sm line-clamp-2",children:te.output.summary})}),te.status==="failed"&&te.errorMessage&&e.jsxs(Qs,{variant:"destructive",className:"mt-4",children:[e.jsx(Dt,{className:"h-4 w-4"}),e.jsx(Xs,{children:te.errorMessage})]})]})},te.id)})})},Je=()=>{if(z)return e.jsx("div",{className:"space-y-4",children:[1,2].map(fe=>e.jsx(_,{className:"animate-pulse",children:e.jsxs(T,{className:"p-4",children:[e.jsx(cs,{className:"h-4 w-1/2"}),e.jsx(cs,{className:"h-3 w-3/4 mt-2"})]})},fe))});const ie=B||[],te=ie.filter(fe=>fe.status==="pending");return ie.length===0?e.jsx(_,{children:e.jsxs(T,{className:"p-8 text-center",children:[e.jsx(No,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium",children:"No Data Requests"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"When agents need data that's only available through manual export, requests will appear here with step-by-step instructions."})]})}):e.jsxs("div",{className:"space-y-4",children:[te.length>0&&e.jsxs(Qs,{children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx(Mn,{children:"Action Required"}),e.jsxs(Xs,{children:[te.length," data request",te.length>1?"s":""," need your attention. These contain data that agents can't retrieve automatically."]})]}),e.jsx(Ta,{type:"single",collapsible:!0,className:"space-y-2",children:ie.map((fe,ge)=>{var We,we;return e.jsxs(Da,{value:`request-${fe.id||ge}`,className:"border rounded-lg","data-testid":`data-request-${fe.id||ge}`,children:[e.jsx(Pa,{className:"px-4 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left",children:[e.jsx("div",{className:`p-2 rounded-lg ${fe.status==="pending"?"bg-yellow-50":"bg-green-50"}`,children:e.jsx(fa,{className:`h-4 w-4 ${fe.status==="pending"?"text-yellow-600":"text-green-600"}`})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:fe.dataType||fe.data_type}),jt(fe.status),fe.urgency==="required"&&e.jsx(Y,{variant:"destructive",className:"text-xs",children:"Required"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",((We=Ea[fe.agentId])==null?void 0:We.name)||fe.agentId]})]})]})}),e.jsx(Ma,{className:"px-4 pb-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Ue,{className:"text-sm font-medium",children:"Description"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:fe.description})]}),fe.instructions&&e.jsxs("div",{children:[e.jsxs(Ue,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(yt,{className:"h-4 w-4"}),"How to Export This Data"]}),e.jsxs("div",{className:"mt-2 p-3 bg-muted rounded-lg",children:[e.jsxs("p",{className:"text-sm font-medium mb-2",children:["Platform: ",fe.instructions.platform]}),e.jsx("ol",{className:"text-sm space-y-2",children:(we=fe.instructions.navigation_path)==null?void 0:we.map((gs,Ss)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-primary text-primary-foreground text-xs flex items-center justify-center",children:Ss+1}),e.jsx("span",{children:gs})]},Ss))}),fe.instructions.export_format&&e.jsxs("p",{className:"text-sm mt-2",children:[e.jsx("strong",{children:"Export format:"})," ",fe.instructions.export_format]})]})]}),fe.status==="pending"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ee,{onClick:()=>Fe.mutate({id:fe.id,status:"fulfilled"}),disabled:Fe.isPending,"data-testid":`fulfill-request-${fe.id}`,children:[e.jsx(Ft,{className:"h-4 w-4 mr-2"}),"Mark as Fulfilled"]}),e.jsx(ee,{variant:"outline",onClick:()=>Fe.mutate({id:fe.id,status:"cannot_fulfill"}),disabled:Fe.isPending,"data-testid":`button-cannot-fulfill-${fe.id}`,children:"Cannot Provide"})]})]})})]},fe.id||ge)})})]})},da=()=>{var fe;const ie=s?Ea[s]:null,te=(ie==null?void 0:ie.icon)||Xa;return e.jsx(Vs,{open:m,onOpenChange:v,children:e.jsxs(Us,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-3",children:[ie&&e.jsx("div",{className:`p-2 rounded-lg ${ie.bgColor}`,children:e.jsx(te,{className:`h-5 w-5 ${ie.color}`})}),"Run ",(ie==null?void 0:ie.name)||"Agent"]}),e.jsx(Ct,{children:"Configure the analysis parameters and run the agent."})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ue,{htmlFor:"model-select",className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4"}),"GPT Model"]}),e.jsxs(os,{value:a,onValueChange:n,children:[e.jsx(ds,{id:"model-select","data-testid":"model-select",children:e.jsx(hs,{placeholder:"Select a model"})}),e.jsx(ms,{children:Xl.map(ge=>e.jsx(me,{value:ge.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:ge.label}),e.jsx(Y,{className:ge.color,variant:"secondary",children:ge.badge})]})},ge.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(fe=Xl.find(ge=>ge.value===a))==null?void 0:fe.description})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ue,{htmlFor:"date-start",children:[e.jsx(ia,{className:"h-4 w-4 inline mr-2"}),"Start Date"]}
80),e.jsx(Me,{id:"date-start",type:"date",value:i.start,onChange:ge=>r(We=>({...We,start:ge.target.value})),"data-testid":"date-start"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{htmlFor:"date-end",children:"End Date"}),e.jsx(Me,{id:"date-end",type:"date",value:i.end,onChange:ge=>r(We=>({...We,end:ge.target.value})),"data-testid":"date-end"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ue,{className:"flex items-center gap-2",children:[e.jsx(sp,{className:"h-4 w-4"}),"Upload Data Documents (Optional)"]}),e.jsxs("div",{...Be(),className:`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors ${nt?"border-primary bg-primary/5":"border-muted-foreground/25 hover:border-primary/50"}`,"data-testid":"document-dropzone",children:[e.jsx("input",{...ns()}),e.jsx(ic,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:nt?"Drop files here...":"Drag & drop CSV, PDF, or Excel files, or click to select"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Max 10MB per file"})]}),o.length>0&&e.jsx("div",{className:"space-y-2 mt-3",children:o.map(ge=>e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted rounded-lg",children:[e.jsx(fa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:ge.fileName}),ge.status==="uploading"&&e.jsx(Es,{className:"h-4 w-4 animate-spin"}),ge.status==="processing"&&e.jsx(Y,{variant:"secondary",children:"Processing..."}),ge.status==="parsed"&&e.jsx(Ft,{className:"h-4 w-4 text-green-500"}),ge.status==="error"&&e.jsx(Dt,{className:"h-4 w-4 text-red-500"}),e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>ks(ge.id),"data-testid":`button-remove-doc-${ge.id}`,children:e.jsx(pt,{className:"h-4 w-4"})})]},ge.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ue,{htmlFor:"context",children:[e.jsx(rc,{className:"h-4 w-4 inline mr-2"}),"Additional Context (Optional)"]}),e.jsx(La,{id:"context",placeholder:"Add any specific questions or focus areas for the analysis...",value:l,onChange:ge=>c(ge.target.value),rows:3,"data-testid":"additional-context"})]})]}),e.jsxs(Ut,{children:[e.jsx(ee,{variant:"outline",onClick:()=>v(!1),"data-testid":"button-cancel-run",children:"Cancel"}),e.jsx(ee,{onClick:Rt,disabled:xe.isPending,"data-testid":"button-confirm-run-agent",children:xe.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-4 w-4 mr-2 animate-spin"}),"Running..."]}):e.jsxs(e.Fragment,{children:[e.jsx(pa,{className:"h-4 w-4 mr-2"}),"Run Analysis"]})})]})]})})},qt=()=>{var We,we,gs,Ss;const ie=ye==null?void 0:ye.find(L=>L.id===g);if(!ie)return null;const te=Ea[ie.agentId],fe=(te==null?void 0:te.icon)||Xa,ge=ie.output;return e.jsx(Vs,{open:g!==null,onOpenChange:()=>w(null),children:e.jsxs(Us,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-3",children:[te&&e.jsx("div",{className:`p-2 rounded-lg ${te.bgColor}`,children:e.jsx(fe,{className:`h-5 w-5 ${te.color}`})}),(te==null?void 0:te.name)||ie.agentId," Analysis Results"]}),e.jsxs(Ct,{children:["Run completed on ",De(new Date(ie.startedAt),"MMMM d, yyyy at h:mm a")]})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[(ge==null?void 0:ge.summary)&&e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(Mx,{className:"h-5 w-5 text-primary"}),"Summary"]})}),e.jsx(T,{children:e.jsx("p",{className:"text-sm leading-relaxed",children:ge.summary})})]}),(ge==null?void 0:ge.data_gaps)&&e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(bs,{className:"h-5 w-5 text-amber-500"}),"Data Quality"]})}),e.jsxs(T,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Analysis Confidence:"}),wt(ge.data_gaps.analysis_confidence)]}),((We=ge.data_gaps.api_unavailable_data_used)==null?void 0:We.length)>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Data Limitations:"}),e.jsx("ul",{className:"text-sm text-muted-foreground list-disc list-inside",children:ge.data_gaps.api_unavailable_data_used.map((L,Re)=>e.jsx("li",{children:L},Re))})]}),((we=ge.data_gaps.pending_human_requests)==null?void 0:we.length)>0&&e.jsxs(Qs,{children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsxs(Xs,{children:[ge.data_gaps.pending_human_requests.length," data requests pending. Check the Data Requests tab to provide missing data."]})]})]})]}),((gs=ge==null?void 0:ge.recommendations)==null?void 0:gs.length)>0&&e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(sc,{className:"h-5 w-5 text-yellow-500"}),"Recommendations"]})}),e.jsx(T,{children:e.jsx("div",{className:"space-y-3",children:ge.recommendations.map((L,Re)=>e.jsx("div",{className:"p-3 bg-muted rounded-lg",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Va,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:L.description}),L.expected_impact&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Expected impact: ",L.expected_impact.direction," ",L.expected_impact.metric,"(",L.expected_impact.confidence," confidence)"]})]})]})},Re))})})]}),((Ss=ge==null?void 0:ge.human_review)==null?void 0:Ss.required)&&e.jsxs(Qs,{children:[e.jsx(Dt,{className:"h-4 w-4"}),e.jsx(Mn,{children:"Review Required"}),e.jsxs(Xs,{children:[e.jsx("p",{children:"Please review these areas before taking action:"}),e.jsx("ul",{className:"list-disc list-inside mt-2",children:ge.human_review.areas_to_focus.map((L,Re)=>e.jsx("li",{children:L},Re))})]})]}),e.jsx(Ta,{type:"single",collapsible:!0,children:e.jsxs(Da,{value:"raw-output",children:[e.jsx(Pa,{className:"text-sm",children:"View Raw Output"}),e.jsx(Ma,{children:e.jsx("pre",{className:"text-xs bg-muted p-4 rounded-lg overflow-x-auto",children:JSON.stringify(ge,null,2)})})]})})]}),e.jsx(Ut,{children:e.jsx(ee,{variant:"outline",onClick:()=>w(null),"data-testid":"button-close-run-details",children:"Close"})})]})})},Js=()=>{var Ge;if(!S)return null;const{dataSources:ie,prompt:te,response:fe,reasoningSteps:ge,timing:We,agentId:we,executedAt:gs}=S,Ss=Ea[we],L=async($e,Qe)=>{try{await navigator.clipboard.writeText($e),N({title:"Copied",description:`${Qe} copied to clipboard`})}catch(js){console.error("Failed to copy:",js)}},Re=$e=>$e<1024?`${$e} chars`:`${($e/1024).toFixed(1)}K chars`;
80return e.jsx(Mo,{open:F,onOpenChange:de,children:e.jsxs(Ro,{className:"w-full sm:max-w-2xl overflow-y-auto","data-testid":"transparency-drawer",children:[e.jsxs(Zh,{children:[e.jsxs(Jh,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5 text-primary"}),"Agent Transparency View"]}),e.jsxs(ep,{children:["Full visibility into how ",(Ss==null?void 0:Ss.name)||we," processed your data and drew conclusions"]})]}),e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsxs(W,{className:"text-sm flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4"}),"Execution Timeline"]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-center",children:[e.jsxs("div",{className:"p-2 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Data Collection"}),e.jsxs("p",{className:"text-lg font-semibold",children:[We.dataCollectionMs,"ms"]})]}),e.jsxs("div",{className:"p-2 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"LLM Call"}),e.jsxs("p",{className:"text-lg font-semibold",children:[We.llmCallMs,"ms"]})]}),e.jsxs("div",{className:"p-2 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Parsing"}),e.jsxs("p",{className:"text-lg font-semibold",children:[We.parsingMs,"ms"]})]}),e.jsxs("div",{className:"p-2 bg-primary/10 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total"}),e.jsxs("p",{className:"text-lg font-semibold text-primary",children:[We.totalMs,"ms"]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center mt-2",children:["Executed at ",De(new Date(gs),"h:mm:ss a")]})]})]}),e.jsxs(la,{defaultValue:"data",className:"w-full",children:[e.jsxs(ca,{className:"grid w-full grid-cols-4",children:[e.jsxs(Ee,{value:"data","data-testid":"tab-debug-data",children:[e.jsx(fa,{className:"h-4 w-4 mr-1"}),"Data"]}),e.jsxs(Ee,{value:"prompt","data-testid":"tab-debug-prompt",children:[e.jsx(rc,{className:"h-4 w-4 mr-1"}),"Prompt"]}),e.jsxs(Ee,{value:"response","data-testid":"tab-debug-response",children:[e.jsx(oa,{className:"h-4 w-4 mr-1"}),"Response"]}),e.jsxs(Ee,{value:"reasoning","data-testid":"tab-debug-reasoning",children:[e.jsx(Qt,{className:"h-4 w-4 mr-1"}),"Reasoning"]})]}),e.jsx(Ve,{value:"data",className:"mt-4 space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{className:"pb-3",children:[e.jsx(W,{className:"text-sm",children:"Data Sources Used"}),e.jsxs(Oe,{children:[ie.length," data source",ie.length!==1?"s":""," collected for analysis"]})]}),e.jsx(T,{children:ie.length===0?e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No specific data sources recorded for this run."}):e.jsx("div",{className:"space-y-3",children:ie.map(($e,Qe)=>e.jsxs("div",{className:"p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"text-xs capitalize",children:$e.type.replace("_"," ")}),e.jsx("span",{className:"font-medium text-sm",children:$e.name})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[$e.recordCount," record",$e.recordCount!==1?"s":""]})]}),$e.apiEndpoint&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Endpoint: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:$e.apiEndpoint})]}),$e.dateRange&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Period: ",$e.dateRange.start," to ",$e.dateRange.end]}),$e.sampleData&&e.jsx(Ta,{type:"single",collapsible:!0,children:e.jsxs(Da,{value:`sample-${Qe}`,className:"border-0",children:[e.jsx(Pa,{className:"text-xs py-1",children:"View Sample Data"}),e.jsx(Ma,{children:e.jsx("pre",{className:"text-xs bg-muted p-2 rounded overflow-x-auto max-h-32",children:JSON.stringify($e.sampleData,null,2)})})]})})]},Qe))})})]})}),e.jsxs(Ve,{value:"prompt",className:"mt-4 space-y-4",children:[e.jsx(_,{children:e.jsxs(q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(W,{className:"text-sm",children:"LLM Configuration"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Y,{variant:"secondary",children:te.model}),e.jsxs(Y,{variant:"outline",children:["temp: ",te.temperature]})]})]}),e.jsx(Oe,{children:te.tokenEstimate&&e.jsxs("span",{children:["~",te.tokenEstimate.promptTokens.toLocaleStr
80ing()," input tokens, ~",te.tokenEstimate.completionTokens.toLocaleString()," output tokens"]})})]})}),e.jsxs(_,{children:[e.jsxs(q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(W,{className:"text-sm",children:"System Prompt"}),e.jsxs(ee,{variant:"ghost",size:"sm",onClick:()=>L(te.systemPrompt,"System prompt"),"data-testid":"button-copy-system-prompt",children:[e.jsx(_l,{className:"h-4 w-4 mr-1"}),"Copy"]})]}),e.jsx(Oe,{children:Re(te.systemPrompt.length)})]}),e.jsx(T,{children:e.jsx(kt,{className:"h-64 rounded-md border",children:e.jsx("pre",{className:"text-xs p-4 whitespace-pre-wrap break-words",children:te.systemPrompt})})})]}),e.jsxs(_,{children:[e.jsxs(q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(W,{className:"text-sm",children:"User Prompt"}),e.jsxs(ee,{variant:"ghost",size:"sm",onClick:()=>L(te.userPrompt,"User prompt"),"data-testid":"button-copy-user-prompt",children:[e.jsx(_l,{className:"h-4 w-4 mr-1"}),"Copy"]})]}),e.jsx(Oe,{children:Re(te.userPrompt.length)})]}),e.jsx(T,{children:e.jsx(kt,{className:"h-64 rounded-md border",children:e.jsx("pre",{className:"text-xs p-4 whitespace-pre-wrap break-words",children:te.userPrompt})})})]})]}),e.jsxs(Ve,{value:"response",className:"mt-4 space-y-4",children:[e.jsxs(_,{children:[e.jsxs(q,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(W,{className:"text-sm",children:"Raw LLM Response"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Y,{variant:"outline",children:[fe.responseTimeMs,"ms"]}),fe.finishReason&&e.jsx(Y,{variant:"secondary",children:fe.finishReason}),e.jsxs(ee,{variant:"ghost",size:"sm",onClick:()=>L(fe.rawResponse,"Raw response"),"data-testid":"button-copy-raw-response",children:[e.jsx(_l,{className:"h-4 w-4 mr-1"}),"Copy"]})]})]}),e.jsxs(Oe,{children:[Re(fe.rawResponse.length)," of JSON output"]})]}),e.jsx(T,{children:e.jsx(kt,{className:"h-96 rounded-md border",children:e.jsx("pre",{className:"text-xs p-4 whitespace-pre-wrap break-words",children:fe.rawResponse})})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsx(W,{className:"text-sm",children:"Parsed Output (Structured)"})}),e.jsx(T,{children:e.jsx(kt,{className:"h-64 rounded-md border",children:e.jsx("pre",{className:"text-xs p-4 whitespace-pre-wrap",children:JSON.stringify(fe.parsedOutput,null,2)})})})]})]}),e.jsxs(Ve,{value:"reasoning",className:"mt-4 space-y-4",children:[e.jsxs(_,{children:[e.jsxs(q,{className:"pb-3",children:[e.jsxs(W,{className:"text-sm flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4"}),"Agent Reasoning Steps"]}),e.jsx(Oe,{children:"How the agent processed data and arrived at conclusions"})]}),e.jsx(T,{children:!ge||ge.length===0?e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No explicit reasoning steps recorded. Review the parsed output for the agent's conclusions."}):e.jsx("div",{className:"space-y-2",children:ge.map(($e,Qe)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-muted rounded-lg",children:[e.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-full bg-primary/10 flex items-center justify-center text-xs font-medium text-primary",children:Qe+1}),e.jsx("p",{className:"text-sm",children:$e})]},Qe))})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-3",children:e.jsx(W,{className:"text-sm",children:"Conclusions Summary"})}),e.jsx(T,{children:(Ge=fe.parsedOutput)!=null&&Ge.summary?e.jsx("p",{className:"text-sm leading-relaxed",children:fe.parsedOutput.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No summary available in the parsed output."})})]})]})]}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsx(ee,{onClick:()=>de(!1),"data-testid":"button-close-transparency",children:"Close Transparency View"})})]})]})})},qs=()=>{var ge,We;if(!D)return null;const ie=Ea[D],te=(ie==null?void 0:ie.icon)||Xa,fe=ss.isPending||be.isPending;return e.jsx(Mo,{open:M,onOpenChange:G,children:e.jsxs(Ro,{side:"right",className:"w-full sm:max-w-3xl p-0 flex flex-col",children:[e.jsx("div",{className:`px-6 py-4 border-b ${(ie==null?void 0:ie.bgColor)||"bg-muted"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-background rounded-lg shadow-sm",children:e.jsx(te,{className:`h-5 w-5 ${(ie==null?void 0:ie.color)||"text-primary"}`})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:(ie==null?void 0:ie.name)||D}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ie==null?void 0:ie.mission)||"AI Marketing Agent"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(os,{value:a,onValueChange:n,children:[e.jsx(ds,{className:"w-[130px] h-8 text-xs","data-testid":"select-chat-model",children:e.jsx(hs,{})}),e.jsx(ms,{children:Xl.map(we=>e.jsx(me,{value:we.value,children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{children:we.label})})},we.value))})]}),e.jsx(ee,{variant:I?"secondary":"ghost",size:"sm",onClick:()=>y(!I),"data-testid":"button-toggle-chat-debug",children:e.jsx(Hs,{className:`h-4 w-4 ${I?"text-primary":""}`})})]})]})}),e.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[e.jsxs("div",{className:"w-56 border-r bg-muted/30 flex flex-col",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsxs(ee,{className:"w-full",size:"sm",onClick:Le,disabled:be.isPending,"data-testid":"button-new-conversation",children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"New Chat"]})}),e.jsx(kt,{className:"flex-1",children:e.jsx("div",{className:"p-2 space-y-1",children:V?e.jsx("div",{className:"p-4 text-center",children:e.jsx(Es,{className:"h-4 w-4 animate-spin mx-auto"})}):!ue||ue.length===0?e.jsx("p",{className:"p-4 text-xs text-muted-foreground text-center",children:"No conversations yet. Start a new chat to begin."}):ue.map(we=>e.jsxs("button",{onClick:()=>Ne(we.threadId),className:`w-full text-left p-2 rounded-lg text-sm transition-colors ${se===we.threadId?"bg-primary/10 text-primary":"hover:bg-muted"}`,"data-testid":`button-select-thread-${we.threadId}`,children:[e.jsx("div",{className:"font-medium truncate",children:we.title||"New Conversation"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Sm(new Date(we.updatedAt),{addSuffix:!0})})]},we.threadId))})})]}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(kt,{className:"flex-1 p-4",children:e.jsxs("div",{className:"space-y-4 max-w-2xl mx-auto",children:[se?Q?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Es,{className:"h-6 w-6 animate-spin"})}):!ce||ce.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Start the conversation by sending a message below."}):ce.map((we,gs)=>e.jsxs("div",{className:`flex gap-3 ${we.role==="user"?"flex-row-reverse":""}`,children:[e.jsx("div",{className:`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${we.role==="user"?"bg-primary text-primary-foreground":(ie==null?void 0:ie.bgColor)||"bg-muted"}`,children:we.role==="user"?e.jsx(Rx,{className:"h-4 w-4"}):e.jsx(te,{className:`h-4 w-4 ${(ie==null?void 0:ie.color)||""}`})}),e.jsxs("div",{className:`flex-1 min-w-0 ${we.role==="user"?"text-right":""}`,children:[e.jsx("div",{className:`inline-block max-w-full text-left ${we.role==="user"?"bg-primary text-primary-foreground rounded-2xl rounded-tr-sm px-4 py-2":"bg-muted rounded-2xl rounded-tl-sm px-4 py-3"}`,children:we.status==="pending"?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Thinking..."})]}):e.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:we.content})}),e.jsxs("div",{className:`flex items-center gap-2 mt-1 text-xs text-muted-foreground ${we.role==="user"?"justify-end":""}`,children:[e.jsx("span",{children:De(new Date(we.createdAt),"h:mm a")}),we.tokensUsed&&e.jsxs("span",{children:["· ",we.tokensUsed," tokens"]}),we.role==="assistant"&&we.debugMetadata&&I&&e.jsxs(ee,{variant:"ghost",size:"sm",className:"h-5 px-1",onClick:()=>R(we.debugMetadata),"data-testid":`button-view-debug-${we.messageId}`,children:[e.jsx(Hs,{className:"h-3 w-3 mr-1"}),"Debug"]})]})]})]},we.id)):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-12 text-center",children:[e.jsx("div",{className:`p-4 rounded-full ${(ie==null?void 0:ie.bgColor)||"bg-muted"}
80 mb-4`,children:e.jsx(te,{className:`h-8 w-8 ${(ie==null?void 0:ie.color)||"text-primary"}`})}),e.jsx("h4",{className:"text-lg font-semibold mb-2",children:"Start a Conversation"}),e.jsxs("p",{className:"text-sm text-muted-foreground max-w-md mb-4",children:["Ask questions, request analyses, or discuss strategies with ",(ie==null?void 0:ie.name)||"this agent",". The agent will respond based on your marketing data and can ask clarifying questions."]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"text-xs",children:'"What are our top performing channels?"'}),e.jsx(Y,{variant:"outline",className:"text-xs",children:'"Analyze our conversion funnel"'}),e.jsx(Y,{variant:"outline",className:"text-xs",children:'"Help me plan an A/B test"'})]})]}),e.jsx("div",{ref:O})]})}),e.jsxs("div",{className:"border-t p-4 bg-background",children:[e.jsxs("div",{className:"flex gap-2 max-w-2xl mx-auto",children:[e.jsx(Me,{placeholder:"Ask a question or request an analysis...",value:le,onChange:we=>C(we.target.value),onKeyDown:we=>{we.key==="Enter"&&!we.shiftKey&&(we.preventDefault(),ae())},disabled:fe,className:"flex-1","data-testid":"input-chat-message"}),e.jsx(ee,{onClick:ae,disabled:fe||!le.trim(),"data-testid":"button-send-message",children:fe?e.jsx(Es,{className:"h-4 w-4 animate-spin"}):e.jsx(Lx,{className:"h-4 w-4"})})]}),k&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center mt-2",children:[e.jsx(Hs,{className:"h-3 w-3 inline mr-1"}),"Transparency mode is on - debug info will be captured"]})]})]}),I&&f&&e.jsxs("div",{className:"w-80 border-l bg-muted/30 flex flex-col",children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Debug Info"}),e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>R(null),"data-testid":"button-close-message-debug",children:e.jsx(pt,{className:"h-4 w-4"})})]}),e.jsx(kt,{className:"flex-1",children:e.jsxs("div",{className:"p-3 space-y-4",children:[f.timing&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-medium mb-2",children:"Timing"}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Data Collection"}),e.jsxs("span",{children:[f.timing.dataCollectionMs,"ms"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"LLM Call"}),e.jsxs("span",{children:[f.timing.llmCallMs,"ms"]})]}),e.jsxs("div",{className:"flex justify-between font-medium",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:[f.timing.totalMs,"ms"]})]})]})]}),((ge=f.dataSources)==null?void 0:ge.length)>0&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-medium mb-2",children:"Data Sources"}),e.jsx("div",{className:"space-y-1",children:f.dataSources.map((we,gs)=>e.jsxs("div",{className:"text-xs p-2 bg-background rounded",children:[e.jsx("div",{className:"font-medium",children:we.name}),we.recordCount&&e.jsxs("div",{className:"text-muted-foreground",children:[we.recordCount," records"]})]},gs))})]}),f.prompt&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-medium mb-2",children:"Prompt"}),e.jsx("div",{className:"text-xs bg-background p-2 rounded max-h-32 overflow-auto",children:e.jsxs("p",{className:"text-muted-foreground truncate",children:[(We=f.prompt.systemPrompt)==null?void 0:We.substring(0,200),"..."]})})]})]})})]})]})]})})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Xa,{className:"h-7 w-7 text-primary"}),"GPT Marketing Agents"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"AI-powered agents that analyze your marketing data and provide actionable insights"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vr,{id:"transparency-mode",checked:k,onCheckedChange:b,"data-testid":"switch-transparency-mode"}),e.jsxs(Ue,{htmlFor:"transparency-mode",className:"text-sm cursor-pointer flex items-center gap-1",children:[e.jsx(Hs,{className:"h-4 w-4"}),"Transparency Mode"]})]}),e.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>{ve(),K()},"data-testid":"button-refresh-agents",children:[e.jsx(Pt,{className:"h-4 w-4 mr-2"}),"Refresh"]})]})]}),e.jsxs(la,{value:u,onValueChange:x,children:[e.jsxs(ca,{className:"grid w-full grid-cols-3",children:[e.jsxs(Ee,{value:"agents","data-testid":"tab-agents",children:[e.jsx(Xa,{className:"h-4 w-4 mr-2"}),"Agents"]}),e.jsxs(Ee,{value:"history","data-testid":"tab-history",children:[e.jsx(Ua,{className:"h-4 w-4 mr-2"}),"Run History",ye&&ye.length>0&&e.jsx(Y,{variant:"secondary",className:"ml-2",children:ye.length})]}),e.jsxs(Ee,{value:"requests","data-testid":"tab-requests",children:[e.jsx(No,{className:"h-4 w-4 mr-2"}),"Data Requests",B&&B.filter(ie=>ie.status==="pending").length>0&&e.jsx(Y,{variant:"destructive",className:"ml-2",children:B.filter(ie=>ie.status==="pending").length})]})]}),e.jsx(Ve,{value:"agents",className:"mt-6",children:rs()}),e.jsx(Ve,{value:"history",className:"mt-6",children:ea()}),e.jsx(Ve,{value:"requests",className:"mt-6",children:Je()})]}),da(),qt(),Js(),qs()]})}const Zl=[{code:"US",name:"United States"},{code:"IN",name:"India"},{code:"GB",name:"United Kingdom"},{code:"CA",name:"Canada"},{code:"AU",name:"Australia"},{code:"DE",name:"Germany"},{code:"FR",name:"France"},{code:"BR",name:"Brazil"},{code:"MX",name:"Mexico"},{code:"JP",name:"Japan"},{code:"KR",name:"South Korea"},{code:"ES",name:"Spain"},{code:"IT",name:"Italy"},{code:"NL",name:"Netherlands"},{code:"PH",name:"Philippines"},{code:"ID",name:"Indonesia"},{code:"PK",name:"Pakistan"},{code:"NG",name:"Nigeria"},{code:"ZA",name:"South Africa"},{code:"WORLDWIDE",name:"All Countries (Worldwide)"}],f4=Uc({videoId:st().min(1,"Video ID is required"),videoTitle:st().min(1,"Video title is required"),videoUrl:st().optional(),promotionLandingUrl:st().optional(),descriptionUrl:st().optional(),targetCountries:Kn(st()).optional(),startDate:st().optional(),endDate:st().optional(),dailyBudget:st().optional(),totalBudget:st().optional(),targetGenders:Kn(st()).optional(),targetAgeRanges:Kn(st()).optional(),targetInterests:Kn(st()).optional(),targetLanguages:Kn(st()).optional(),goal:st().default("website_visits"),status:up(["active","paused","completed","draft"]).default("active")}
80),g4=Uc({snapshotDate:st().min(1,"Snapshot date is required"),cost:st().min(1,"Cost is required"),impressions:zr.number().min(0).default(0),views:zr.number().min(0).default(0),subscribers:zr.number().min(0).default(0),websiteVisits:zr.number().min(0).default(0),notes:st().optional()});function Sa(s){const t=typeof s=="string"?parseFloat(s):s;return isNaN(t)?"$0.00":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(t)}function j4(s,t){const a=new Date(s),n=t||"America/Chicago";return a.toLocaleString("en-US",{timeZone:n,month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function Mc(s,t=!1){if(s===0)return"-";const a=s>0?"+":"";return t?`${a}${Sa(s)}`:`${a}${s.toLocaleString()}`}function Jl(s){switch(s){case"active":return"default";case"paused":return"secondary";case"completed":return"outline";default:return"outline"}}function _n({value:s,isCurrency:t=!1}){if(s===0)return e.jsx("span",{className:"text-muted-foreground",children:"-"});const a=s>0?Is:Et,n=s>0?"text-green-600":"text-red-600";return e.jsxs("span",{className:`flex items-center gap-1 ${n}`,children:[e.jsx(a,{className:"h-3 w-3"}),Mc(s,t)]})}function b4(){var Ds,_s;const{user:s}=$x(),t=s==null?void 0:s.healthSystemTimezone,[a,n]=p.useState(null),[i,r]=p.useState(!1),[l,c]=p.useState(!1),[o,d]=p.useState(!1),[u,x]=p.useState("all"),[m,v]=p.useState("all"),[g,w]=p.useState("all"),[k,b]=p.useState("all"),[S,A]=p.useState(()=>typeof window<"u"&&localStorage.getItem("youtube-campaigns-view")||"cards"),[F,de]=p.useState(!1),M=h=>{A(h),localStorage.setItem("youtube-campaigns-view",h)},[G,D]=p.useState([]),[$,se]=p.useState(null),[J,le]=p.useState(!1),C=p.useRef(null),{toast:I}=ya(),[y,f]=p.useState(!1),[R,O]=p.useState([]),[N,re]=p.useState(!1),[H,pe]=p.useState(null),[ye,Ie]=p.useState(De(new Date,"yyyy-MM-dd")),[ve,B]=p.useState([]),[z,K]=p.useState(!1),P=p.useRef(null),[ue,V]=p.useState(null),[U,j]=p.useState(null),[Q,je]=p.useState(!1),[ce,be]=p.useState(null),[ss,oe]=p.useState(null),Ne=p.useCallback(h=>{h&&Array.from(h).forEach(Z=>{if(!Z.type.startsWith("image/")){I({title:"Invalid file",description:"Please upload an image file",variant:"destructive"});return}const E=new FileReader;E.onload=Pe=>{var bt;const Ze=(bt=Pe.target)==null?void 0:bt.result,ps=Ze.split(",")[1];D(ma=>[...ma,{data:ps,mimeType:Z.type,preview:Ze}])},E.readAsDataURL(Z)})},[I]),Le=p.useCallback(h=>{var Pe;const Z=(Pe=h.clipboardData)==null?void 0:Pe.items;if(!Z)return;const E=Array.from(Z);for(let Ze=0;Ze<E.length;Ze++){const ps=E[Ze];if(ps.type.startsWith("image/")){h.preventDefault();const bt=ps.getAsFile();if(bt){const ma=new FileReader;ma.onload=yn=>{var sa;const Nn=(sa=yn.target)==null?void 0:sa.result,wn=Nn.split(",")[1];D(Wn=>[...Wn,{data:wn,mimeType:bt.type,preview:Nn}])},ma.readAsDataURL(bt)}break}}},[]),ae=p.useCallback(h=>{h.preventDefault(),h.stopPropagation()},[]),xe=p.useCallback(h=>{h.preventDefault(),h.stopPropagation(),le(!0)},[]),Fe=p.useCallback(h=>{h.preventDefault(),h.stopPropagation();const Z=h.currentTarget.getBoundingClientRect(),E=h.clientX,Pe=h.clientY;(E<Z.left||E>Z.right||Pe<Z.top||Pe>Z.bottom)&&le(!1)},[]),X=p.useCallback(h=>{var E;h.preventDefault(),h.stopPropagation(),le(!1);const Z=(E=h.dataTransfer)==null?void 0:E.files;Z&&Z.length>0&&Ne(Z)},[Ne]),Be=h=>{D(Z=>Z.filter((E,Pe)=>Pe!==h)),se(null)},ns=async()=>{var h;if(G.length===0){I({title:"No images",description:"Please upload or paste a screenshot first",variant:"destructive"});return}d(!0),se(null);try{const E=await(await fetch("/api/analytics/youtube-promotion-parse",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({images:G.map(Pe=>({data:Pe.data,mimeType:Pe.mimeType}))})})).json();if(se(E),E.success&&E.data){if(E.data.videoTitle&&ze.setValue("videoTitle",E.data.videoTitle),E.data.videoId&&ze.setValue("videoId",E.data.videoId),E.data.videoUrl&&ze.setValue("videoUrl",E.data.videoUrl),E.data.promotionLandingUrl&&ze.setValue("promotionLandingUrl",E.data.promotionLandingUrl),E.data.descriptionUrl&&ze.setValue("descriptionUrl",E.data.descriptionUrl),E.data.targetCountries&&E.data.targetCountries.length>0&&ze.setValue("targetCountries",E.data.targetCountries),E.data.goal&&ze.setValue("goal",E.data.goal),E.data.campaignStatus){const Pe=E.data.campaignStatus;["active","paused","completed"].includes(Pe)&&ze.setValue("status",Pe)}E.data.campaignStartDate&&ze.setValue("startDate",E.data.campaignStartDate),E.data.campaignEndDate&&ze.setValue("endDate",E.data.campaignEndDate),E.data.dailyBudget&&ze.setValue("dailyBudget",E.data.dailyBudget),E.data.totalBudget&&ze.setValue("totalBudget",E.data.totalBudget),E.data.targetGenders&&E.data.targetGenders.length>0&&ze.setValue("targetGenders",E.data.targetGenders),E.data.targetAgeRanges&&E.data.targetAgeRanges.length>0&&ze.setValue("targetAgeRanges",E.data.targetAgeRanges),E.data.targetInterests&&E.data.targetInterests.length>
800&&ze.setValue("targetInterests",E.data.targetInterests),E.data.targetLanguages&&E.data.targetLanguages.length>0&&ze.setValue("targetLanguages",E.data.targetLanguages),E.data.snapshotDate&&Ns.setValue("snapshotDate",E.data.snapshotDate),E.data.cost&&Ns.setValue("cost",E.data.cost),E.data.impressions!==void 0&&Ns.setValue("impressions",E.data.impressions),E.data.views!==void 0&&Ns.setValue("views",E.data.views),E.data.subscribers!==void 0&&Ns.setValue("subscribers",E.data.subscribers),E.data.websiteVisits!==void 0&&Ns.setValue("websiteVisits",E.data.websiteVisits),I({title:"Screenshot parsed!",description:`Extracted data with ${Math.round(E.confidence*100)}% confidence. Please verify and edit as needed.`})}else I({title:"Parsing failed",description:((h=E.errors)==null?void 0:h.join(", "))||"Could not extract data from screenshot",variant:"destructive"})}catch(Z){console.error("Parse error:",Z),I({title:"Error",description:"Failed to parse screenshot. Please try again.",variant:"destructive"})}finally{d(!1)}},nt=()=>{D([]),se(null)},{data:ks,isLoading:Rt}=_e({queryKey:["/api/analytics/youtube-promotion-campaigns-with-stats"]}),{data:wt,isLoading:jt}=_e({queryKey:["/api/analytics/youtube-promotion-campaigns",a,"snapshots"],enabled:!!a}),{data:rs,isLoading:ea}=_e({queryKey:["/api/analytics/youtube-promotion-campaigns",a,"correlation"],enabled:!!a}),{data:Je,isLoading:da}=_e({queryKey:["/api/analytics/youtube-snapshots/history"],enabled:F}),qt=ws({mutationFn:h=>vs("POST","/api/analytics/youtube-promotion-campaigns",h),onSuccess:()=>{Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns-with-stats"]}),r(!1),ze.reset(),I({title:"Campaign created",description:"Now add your first snapshot from YouTube Studio."})},onError:()=>{I({title:"Error",description:"Failed to create campaign.",variant:"destructive"})}}),Js=ws({mutationFn:h=>{const Z={...h,impressions:Number(h.impressions),views:Number(h.views),subscribers:Number(h.subscribers),websiteVisits:Number(h.websiteVisits)};return vs("POST",`/api/analytics/youtube-promotion-campaigns/${a}/snapshots`,Z)},onSuccess:()=>{Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns-with-stats"]}),Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns",a,"snapshots"]}),c(!1),Ns.reset(),I({title:"Snapshot added",description:"ROI metrics have been updated."})},onError:()=>{I({title:"Error",description:"Failed to add snapshot.",variant:"destructive"})}}),qs=ws({mutationFn:h=>vs("POST","/api/analytics/youtube-snapshots/bulk",{snapshots:h}),onSuccess:h=>{Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns-with-stats"]}),a&&Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns",a,"snapshots"]}),f(!1),Re(),I({title:"Bulk snapshots saved",description:`Created ${h.totalCreated} snapshot(s) for ${ye}`})},onError:()=>{I({title:"Error",description:"Failed to save bulk snapshots.",variant:"destructive"})}}),ie=ws({mutationFn:({snapshotId:h,data:Z})=>vs("PATCH",`/api/analytics/youtube-promotion-snapshots/${h}`,Z),onSuccess:()=>{Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns-with-stats"]}),Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns",a,"snapshots"]}),V(null),j(null),I({title:"Snapshot updated",description:"Changes saved successfully."})},onError:()=>{I({title:"Error",description:"Failed to update snapshot.",variant:"destructive"})}}),te=ws({mutationFn:h=>vs("DELETE",`/api/analytics/youtube-promotion-snapshots/${h}`),onSuccess:()=>{Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns-with-stats"]}),Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns",a,"snapshots"]}),oe(null),I({title:"Snapshot deleted",description:"Snapshot has been removed."})},onError:()=>{I({title:"Error",description:"Failed to delete snapshot.",variant:"destructive"})}}),fe=ws({mutationFn:h=>vs("PATCH",`/api/analytics/youtube-promotion-campaigns/${a}`,h),onSuccess:()=>{Ts.invalidateQueries({queryKey:["/api/analytics/youtube-promotion-campaigns-with-stats"]}),je(!1),be(null),I({title:"Campaign updated",description:"Changes saved successfully."})},onError:()=>{I({title:"Error",description:"Failed to update campaign.",variant:"destructive"})}}),ge=p.useCallback(h=>
80{h&&Array.from(h).forEach(Z=>{if(!Z.type.startsWith("image/")){I({title:"Invalid file",description:"Please upload an image file",variant:"destructive"});return}const E=new FileReader;E.onload=Pe=>{var bt;const Ze=(bt=Pe.target)==null?void 0:bt.result,ps=Ze.split(",")[1];O(ma=>[...ma,{data:ps,mimeType:Z.type,preview:Ze}])},E.readAsDataURL(Z)})},[I]),We=p.useCallback(h=>{var E;const Z=(E=h.clipboardData)==null?void 0:E.items;if(Z)for(let Pe=0;Pe<Z.length;Pe++){const Ze=Z[Pe];if(Ze.type.startsWith("image/")){h.preventDefault();const ps=Ze.getAsFile();if(ps){const bt=new FileReader;bt.onload=ma=>{var wn;const yn=(wn=ma.target)==null?void 0:wn.result,Nn=yn.split(",")[1];O(sa=>[...sa,{data:Nn,mimeType:ps.type,preview:yn}])},bt.readAsDataURL(ps)}break}}},[]),we=p.useCallback(h=>{h.preventDefault(),h.stopPropagation(),K(!0)},[]),gs=p.useCallback(h=>{h.preventDefault(),h.stopPropagation(),K(!1)},[]),Ss=p.useCallback(h=>{var E;h.preventDefault(),h.stopPropagation(),K(!1);const Z=(E=h.dataTransfer)==null?void 0:E.files;Z&&Z.length>0&&ge(Z)},[ge]),L=async()=>{var h;if(R.length===0){I({title:"No image",description:"Please upload a screenshot first",variant:"destructive"});return}re(!0);try{const E=await(await vs("POST","/api/analytics/youtube-promotion-bulk-parse",{images:R.map(Pe=>({data:Pe.data,mimeType:Pe.mimeType}))})).json();pe(E),E.success&&E.promotions.length>0?(B(E.promotions.map(Pe=>({...Pe,selected:!!Pe.matchedCampaignId}))),I({title:"Screenshot parsed",description:`Found ${E.totalRowsExtracted} promotions, ${E.matchedCount} matched to campaigns`})):I({title:"Parsing failed",description:((h=E.warnings)==null?void 0:h.join(", "))||"Could not extract data from screenshot",variant:"destructive"})}catch(Z){console.error("Bulk parse error:",Z),I({title:"Error",description:"Failed to parse bulk screenshot. Please try again.",variant:"destructive"})}finally{re(!1)}},Re=()=>{O([]),pe(null),B([]),Ie(De(new Date,"yyyy-MM-dd"))},Ge=h=>{B(Z=>Z.map((E,Pe)=>Pe===h?{...E,selected:!E.selected}:E))},$e=(h,Z,E)=>{B(Pe=>Pe.map((Ze,ps)=>ps===h?{...Ze,[Z]:E,edited:!0}:Ze))},Qe=(h,Z)=>{if(!Z){B(Pe=>Pe.map((Ze,ps)=>ps===h?{...Ze,matchedCampaignId:void 0,matchedCampaignTitle:void 0,matchConfidence:void 0,matchReasoning:void 0,matchError:"No match",selected:!1}:Ze));return}const E=ks==null?void 0:ks.find(Pe=>Pe.id===Z);E&&B(Pe=>Pe.map((Ze,ps)=>ps===h?{...Ze,matchedCampaignId:Z,matchedCampaignTitle:E.videoTitle,matchConfidence:1,matchReasoning:"Manually assigned",matchError:void 0,selected:!0}:Ze))},js=()=>{const h=ve.filter(E=>E.selected&&E.matchedCampaignId);if(h.length===0){I({title:"No snapshots selected",description:"Select at least one matched campaign",variant:"destructive"});return}const Z=h.map(E=>({campaignId:E.matchedCampaignId,snapshotDate:ye,cost:E.cost||"0",impressions:E.impressions||0,views:E.views||0,subscribers:E.subscribers||0,websiteVisits:E.websiteVisits||0}));qs.mutate(Z)},ze=lc({resolver:cc(f4),defaultValues:{videoId:"",videoTitle:"",videoUrl:"",promotionLandingUrl:"",descriptionUrl:"",targetCountries:[],startDate:"",endDate:"",dailyBudget:"",totalBudget:"",targetGenders:[],targetAgeRanges:[],targetInterests:[],targetLanguages:[],goal:"website_visits",status:"active"}}
80),Ns=lc({resolver:cc(g4),defaultValues:{snapshotDate:De(new Date,"yyyy-MM-dd"),cost:"0",impressions:0,views:0,subscribers:0,websiteVisits:0,notes:""}}),He=ks==null?void 0:ks.find(h=>h.id===a),Gs=(ks==null?void 0:ks.filter(h=>{var Z,E,Pe,Ze;return!(u!=="all"&&!((Z=h.targetCountries)!=null&&Z.includes(u))||m!=="all"&&!((E=h.targetLanguages)!=null&&E.includes(m))||g!=="all"&&!((Pe=h.targetGenders)!=null&&Pe.includes(g))||k!=="all"&&!((Ze=h.targetAgeRanges)!=null&&Ze.includes(k)))}))||[],ne=Gs.length,ke=Gs.reduce((h,Z)=>{var E;return h+parseFloat(((E=Z.latestSnapshot)==null?void 0:E.cost)||"0")},0),Xe=Gs.reduce((h,Z)=>{var E;return h+(((E=Z.latestSnapshot)==null?void 0:E.websiteVisits)||0)},0),ls=Xe>0?ke/Xe:0,As=wt==null?void 0:wt.map((h,Z,E)=>{const Pe=E[Z+1];return Pe?{...h,delta:{cost:parseFloat(h.cost||"0")-parseFloat(Pe.cost||"0"),impressions:(h.impressions||0)-(Pe.impressions||0),views:(h.views||0)-(Pe.views||0),subscribers:(h.subscribers||0)-(Pe.subscribers||0),websiteVisits:(h.websiteVisits||0)-(Pe.websiteVisits||0)}}:{...h,delta:null}});return He?e.jsx(xs,{children:e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>n(null),"data-testid":"button-back-to-campaigns",children:e.jsx(Ox,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"h-5 w-5"}),He.videoTitle]}),e.jsxs(Oe,{className:"flex items-center gap-2 mt-1",children:[e.jsx(Y,{variant:Jl(He.status),children:He.status}),He.videoUrl&&e.jsxs("a",{href:He.videoUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline flex items-center gap-1",children:["View on YouTube ",e.jsx(yt,{className:"h-3 w-3"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ee,{variant:"outline",onClick:()=>{je(!0),be({videoTitle:He.videoTitle,videoId:He.videoId||"",videoUrl:He.videoUrl||"",promotionLandingUrl:He.promotionLandingUrl||"",status:He.status,startDate:He.startDate||"",endDate:He.endDate||"",dailyBudget:He.dailyBudget||"",totalBudget:He.totalBudget||"",notes:He.notes||""})},"data-testid":"button-edit-campaign",children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Edit Campaign"]}),e.jsxs(ee,{onClick:()=>c(!0),"data-testid":"button-add-snapshot",children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Add Snapshot"]})]})]})}),e.jsxs(T,{children:[e.jsx("div",{className:"mb-4 p-3 rounded-lg bg-info-surface dark:bg-blue-950 border border-info-border dark:border-blue-800",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(bs,{className:"h-4 w-4 text-blue-600 mt-0.5"}),e.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:[e.jsx("strong",{children:"Enter cumulative values"})," from YouTube Studio. We'll calculate the week-over-week changes automatically."]})]})}),He.latestSnapshot&&e.jsxs("div",{className:"grid grid-cols-4 gap-4 mb-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Spend"}),e.jsx("p",{className:"text-xl font-bold",children:Sa(He.latestSnapshot.cost)}),He.delta&&e.jsx(_n,{value:He.delta.cost,isCurrency:!0})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Views"}),e.jsx("p",{className:"text-xl font-bold",children:(He.latestSnapshot.views||0).toLocaleString()}),He.delta&&e.jsx(_n,{value:He.delta.views})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Website Visits"}),e.jsx("p",{className:"text-xl font-bold",children:(He.latestSnapshot.websiteVisits||0).toLocaleString()}),He.delta&&e.jsx(_n,{value:He.delta.websiteVisits})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cost per Visit"}),e.jsx("p",{className:"text-xl font-bold",children:He.latestSnapshot.websiteVisits>0?Sa(parseFloat(He.latestSnapshot.cost)/He.latestSnapshot.websiteVisits):"-"})]})]}),e.jsxs("div",{className:"mb-6 p-4 rounded-lg border",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Analytics Correlation"]}),ea?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Es,{className:"h-4 w-4 animate-spin"}),"Loading correlation data..."]}):rs?e.jsxs("div",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"UTM Parameters (from Promotion Landing URL)"}
80),rs.utmParams.source||rs.utmParams.medium||rs.utmParams.campaign||rs.utmParams.content?e.jsxs("div",{className:"flex flex-wrap gap-2",children:[rs.utmParams.source&&e.jsxs(Y,{variant:"outline","data-testid":"badge-utm-source",children:["source: ",rs.utmParams.source]}),rs.utmParams.medium&&e.jsxs(Y,{variant:"outline","data-testid":"badge-utm-medium",children:["medium: ",rs.utmParams.medium]}),rs.utmParams.campaign&&e.jsxs(Y,{variant:"outline","data-testid":"badge-utm-campaign",children:["campaign: ",rs.utmParams.campaign]}),rs.utmParams.content&&e.jsxs(Y,{variant:"outline","data-testid":"badge-utm-content",children:["content: ",rs.utmParams.content]})]}):e.jsx(Qs,{variant:"destructive",className:"mt-2",children:e.jsx(Xs,{children:"No UTM parameters found. Add UTM parameters to your Promotion Landing URL to track visits from this campaign."})})]}),(rs.utmParams.source||rs.utmParams.medium||rs.utmParams.campaign||rs.utmParams.content)&&e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tracked Visits"}),e.jsx("p",{className:"text-lg font-bold","data-testid":"text-correlation-visits",children:rs.visits.toLocaleString()})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversions"}),e.jsx("p",{className:"text-lg font-bold","data-testid":"text-correlation-conversions",children:rs.conversions.toLocaleString()})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last Seen"}),e.jsx("p",{className:"text-lg font-bold","data-testid":"text-correlation-lastseen",children:rs.lastSeen?De($o(rs.lastSeen),"MMM d, yyyy"):"Never"})]})]}
80),(rs.utmParams.source||rs.utmParams.medium||rs.utmParams.campaign||rs.utmParams.content)&&rs.visits===0&&e.jsxs(Qs,{className:"mt-3",children:[e.jsx(bs,{className:"h-4 w-4"}),e.jsx(Xs,{children:"No matching analytics events found yet. Make sure your landing page has analytics tracking enabled."})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Unable to load correlation data."})]}),e.jsx("h3",{className:"font-semibold mb-3",children:"Snapshot History"}),jt?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading snapshots..."}):!As||As.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Br,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No snapshots yet."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add your first snapshot from YouTube Studio."})]}):e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs(nn,{children:[e.jsx(rn,{children:e.jsxs(ht,{children:[e.jsx(fs,{children:"Date"}),e.jsx(fs,{className:"text-right",children:"Cost"}),e.jsx(fs,{className:"text-right",children:"Î Cost"}),e.jsx(fs,{className:"text-right",children:"Views"}),e.jsx(fs,{className:"text-right",children:"Î Views"}),e.jsx(fs,{className:"text-right",children:"Visits"}),e.jsx(fs,{className:"text-right",children:"Î Visits"}),e.jsx(fs,{children:"Notes"}),e.jsx(fs,{className:"text-right",children:"Actions"})]})}),e.jsx(ln,{children:As.map(h=>e.jsx(ht,{"data-testid":`snapshot-row-${h.id}`,children:ue===h.id&&U?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"font-medium",children:e.jsx(Me,{type:"date",value:U.snapshotDate,onChange:Z=>j(E=>E?{...E,snapshotDate:Z.target.value}:null),className:"w-32","data-testid":`input-edit-date-${h.id}`})}),e.jsx(Ke,{className:"text-right",children:e.jsx(Me,{type:"text",value:U.cost,onChange:Z=>j(E=>E?{...E,cost:Z.target.value}:null),className:"w-24 text-right","data-testid":`input-edit-cost-${h.id}`})}),e.jsx(Ke,{className:"text-right text-muted-foreground",children:"-"}),e.jsx(Ke,{className:"text-right",children:e.jsx(Me,{type:"number",value:U.views,onChange:Z=>j(E=>E?{...E,views:parseInt(Z.target.value)||0}:null),className:"w-24 text-right","data-testid":`input-edit-views-${h.id}`})}),e.jsx(Ke,{className:"text-right text-muted-foreground",children:"-"}),e.jsx(Ke,{className:"text-right",children:e.jsx(Me,{type:"number",value:U.websiteVisits,onChange:Z=>j(E=>E?{...E,websiteVisits:parseInt(Z.target.value)||0}:null),className:"w-24 text-right","data-testid":`input-edit-visits-${h.id}`})}),e.jsx(Ke,{className:"text-right text-muted-foreground",children:"-"}),e.jsx(Ke,{children:e.jsx(Me,{type:"text",value:U.notes,onChange:Z=>j(E=>E?{...E,notes:Z.target.value}:null),className:"w-32",placeholder:"Notes...","data-testid":`input-edit-notes-${h.id}`})}),e.jsx(Ke,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>{ie.mutate({snapshotId:h.id,data:U})},disabled:ie.isPending,"data-testid":`button-save-snapshot-${h.id}`,children:e.jsx(ec,{className:"h-4 w-4"})}),e.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>{V(null),j(null)},"data-testid":`button-cancel-edit-${h.id}`,children:e.jsx(pt,{className:"h-4 w-4"})})]})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ke,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[De($o(h.snapshotDate),"MMM d, yyyy"),h.isBaseline&&e.jsx(Y,{variant:"outline",className:"text-xs",children:"Baseline"})]})}),e.jsx(Ke,{className:"text-right",children:Sa(h.cost)}),e.jsx(Ke,{className:"text-right",children:h.delta?e.jsx(_n,{value:h.delta.
80cost,isCurrency:!0}):"-"}),e.jsx(Ke,{className:"text-right",children:(h.views||0).toLocaleString()}),e.jsx(Ke,{className:"text-right",children:h.delta?e.jsx(_n,{value:h.delta.views}):"-"}),e.jsx(Ke,{className:"text-right",children:(h.websiteVisits||0).toLocaleString()}),e.jsx(Ke,{className:"text-right",children:h.delta?e.jsx(_n,{value:h.delta.websiteVisits}):"-"}),e.jsx(Ke,{className:"max-w-[200px] truncate text-muted-foreground",children:h.notes||"-"}),e.jsx(Ke,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>{V(h.id),j({snapshotDate:h.snapshotDate,cost:h.cost,views:h.views||0,websiteVisits:h.websiteVisits||0,notes:h.notes||""})},"data-testid":`button-edit-snapshot-${h.id}`,children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>oe(h.id),className:"text-destructive hover:text-destructive","data-testid":`button-delete-snapshot-${h.id}`,children:e.jsx(xi,{className:"h-4 w-4"})})]})})]})},h.id))})]}),e.jsx(tp,{open:ss!==null,onOpenChange:h=>!h&&oe(null),children:e.jsxs(ap,{children:[e.jsxs(np,{children:[e.jsx(rp,{children:"Delete Snapshot?"}),e.jsx(ip,{children:"This action cannot be undone. This will permanently delete this snapshot and recalculate the deltas."})]}),e.jsxs(lp,{children:[e.jsx(cp,{children:"Cancel"}),e.jsx(op,{onClick:()=>{ss&&te.mutate(ss)},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90","data-testid":"button-confirm-delete-snapshot",children:te.isPending?"Deleting...":"Delete"})]})]})})]}),e.jsx(Vs,{open:l,onOpenChange:c,children:e.jsxs(Us,{className:"max-w-lg",children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Add Snapshot"}),e.jsx(Ct,{children:"Enter current cumulative values from YouTube Studio"})]}),e.jsx(oc,{...Ns,children:e.jsxs("form",{onSubmit:Ns.handleSubmit(h=>Js.mutate(h)),className:"space-y-4",children:[e.jsx(Ms,{control:Ns.control,name:"snapshotDate",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Snapshot Date"}),e.jsx(Ks,{children:e.jsx(Me,{type:"date",...h,"data-testid":"input-snapshot-date"})}),e.jsx($s,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ms,{control:Ns.control,name:"cost",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Total Cost ($)"}),e.jsx(Ks,{children:e.jsx(Me,{type:"number",step:"0.01",placeholder:"0.00",...h,"data-testid":"input-snapshot-cost"})}),e.jsx(kn,{children:"Cumulative spend to date"}),e.jsx($s,{})]})}),e.jsx(Ms,{control:Ns.control,name:"impressions",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Impressions"}),e.jsx(Ks,{children:e.jsx(Me,{type:"number",...h,onChange:Z=>h.onChange(parseInt(Z.target.value)||0),"data-testid":"input-snapshot-impressions"})}),e.jsx($s,{})]})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(Ms,{control:Ns.control,name:"views",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Views"}),e.jsx(Ks,{children:e.jsx(Me,{type:"number",...h,onChange:Z=>h.onChange(parseInt(Z.target.value)||0),"data-testid":"input-snapshot-views"})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:Ns.control,name:"subscribers",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Subscribers"}),e.jsx(Ks,{children:e.jsx(Me,{type:"number",...h,onChange:Z=>h.onChange(parseInt(Z.target.value)||0),"data-testid":"input-snapshot-subscribers"})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:Ns.control,name:"websiteVisits",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Website Visits"}),e.jsx(Ks,{children:e.jsx(Me,{type:"number",...h,onChange:Z=>h.onChange(parseInt(Z.target.value)||0),"data-testid":"input-snapshot-website-visits"})}),e.jsx($s,{})]})})]}),e.jsx(Ms,{control:Ns.control,name:"notes",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Notes (optional)"}),e.jsx(Ks,{children:e.jsx(La,{placeholder:"Any observations or context...",...h,"data-testid":"input-snapshot-notes"})}),e.jsx($s,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(ee,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(ee,{type:"submit",disabled:Js.isPending,"data-testid":"button-submit-snapsh
80ot",children:Js.isPending?"Saving...":"Save Snapshot"})]})]})})]})}),e.jsx(Vs,{open:Q,onOpenChange:h=>{h||(je(!1),be(null))},children:e.jsxs(Us,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Bs,{children:[e.jsx(zs,{children:"Edit Campaign"}),e.jsx(Ct,{children:"Update campaign details and targeting information"})]}),ce&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Video Title"}),e.jsx(Me,{value:ce.videoTitle,onChange:h=>be({...ce,videoTitle:h.target.value}),"data-testid":"input-edit-campaign-title"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Video ID"}),e.jsx(Me,{value:ce.videoId,onChange:h=>be({...ce,videoId:h.target.value}),placeholder:"YouTube Video ID","data-testid":"input-edit-campaign-video-id"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Status"}),e.jsxs(os,{value:ce.status,onValueChange:h=>be({...ce,status:h}),children:[e.jsx(ds,{"data-testid":"select-edit-campaign-status",children:e.jsx(hs,{})}),e.jsxs(ms,{children:[e.jsx(me,{value:"active",children:"Active"}),e.jsx(me,{value:"paused",children:"Paused"}),e.jsx(me,{value:"completed",children:"Completed"}),e.jsx(me,{value:"draft",children:"Draft"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"YouTube Video URL"}),e.jsx(Me,{value:ce.videoUrl,onChange:h=>be({...ce,videoUrl:h.target.value}),placeholder:"https://youtube.com/watch?v=...","data-testid":"input-edit-campaign-video-url"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Promotion Landing URL"}),e.jsx(Me,{value:ce.promotionLandingUrl,onChange:h=>be({...ce,promotionLandingUrl:h.target.value}),placeholder:"https://clarafi.com/...","data-testid":"input-edit-campaign-promotion-url"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Start Date"}),e.jsx(Me,{type:"date",value:ce.startDate,onChange:h=>be({...ce,startDate:h.target.value}),"data-testid":"input-edit-campaign-start-date"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"End Date"}),e.jsx(Me,{type:"date",value:ce.endDate,onChange:h=>be({...ce,endDate:h.target.value}),"data-testid":"input-edit-campaign-end-date"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Daily Budget ($)"}),e.jsx(Me,{type:"number",step:"0.01",value:ce.dailyBudget,onChange:h=>be({...ce,dailyBudget:h.target.value}),placeholder:"0.00","data-testid":"input-edit-campaign-daily-budget"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Total Budget ($)"}),e.jsx(Me,{type:"number",step:"0.01",value:ce.totalBudget,onChange:h=>be({...ce,totalBudget:h.target.value}),placeholder:"0.00","data-testid":"input-edit-campaign-total-budget"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Notes"}),e.jsx(La,{value:ce.notes,onChange:h=>be({...ce,notes:h.target.value}),placeholder:"Campaign notes...","data-testid":"input-edit-campaign-notes"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(ee,{type:"button",variant:"outline",onClick:()=>{je(!1),be(null)},children:"Cancel"}),e.jsx(ee,{onClick:()=>{ce&&fe.mutate(ce)},disabled:fe.isPending,"data-testid":"button-save-campaign",children:fe.isPending?"Saving...":"Save Changes"})]})]})]})})]})]})}):e.jsx(xs,{children:e.jsxs(_,{children:[e.jsx(q,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"h-5 w-5"}),"YouTube Promotion Campaigns",e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Track ROI for your YouTube paid promotions. Create a campaign for each video, then add weekly snapshots to calculate accurate week-over-week performance."})})]})]}),e.jsx(Oe,{children:"Track week-over-week ROI with snapshot-based metrics"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center border rounded-md",children:[e.jsx(ee,{variant:S==="cards"?"secondary":"ghost",size:"sm",onClick:()=>M("cards"),className:"rounded-r-none","data-testid":"button-view-cards",children:e.jsx(Lm,{className:"h-4 w-4"})}),e.jsx(ee,{variant:S==="table"?"secondary":"ghost",size:"sm",onClick:()=>M("table"),className:"rounded-l-none","data-testid":"button-view-table",children:e.jsx($m,{className:"h-4 w-4"})})]}),e.jsxs(ee,{variant:F?"secondary":"outline",onClick:()=>de(!F),"data-testid":"button-snapshot-history",children:[e.jsx(Ua,{className:"h-4 w-4 mr-2"}),"History"]}),e.jsxs(ee,{variant:"outline",onClick:()=>f(!0),"data-testid":"button-bulk-snapshot",children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Bulk Snapshot"]}),e.jsxs(ee,{onClick:()=>r(!0),"data-testid":"button-new-campaign",children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"New Campaign"]})]})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 mb-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Campaigns"}),e.jsx("p",{className:"text-xl font-bold",children:ne.toLocaleStr
80ing()})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Spend"}),e.jsx("p",{className:"text-xl font-bold",children:Sa(ke)})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Cost per Visit"}),e.jsx("p",{className:"text-xl font-bold",children:Sa(ls)})]})]}),e.jsx("div",{className:"mb-4 p-3 rounded-lg bg-muted/50 border",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"How it works:"})," Create a campaign for each video you promote â Add a snapshot each time you check YouTube Studio (weekly recommended) â The system calculates week-over-week ROI from your snapshots."]})}),e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Country:"}),e.jsxs(os,{value:u,onValueChange:x,children:[e.jsx(ds,{className:"w-[150px]","data-testid":"select-country-filter",children:e.jsx(hs,{placeholder:"All"})}),e.jsxs(ms,{children:[e.jsx(me,{value:"all","data-testid":"filter-country-all",children:"All"}),e.jsx(me,{value:"WORLDWIDE","data-testid":"filter-country-WORLDWIDE",children:"Worldwide"}),Zl.map(h=>e.jsx(me,{value:h.code,"data-testid":`filter-country-${h.code}`,children:h.name},h.code))]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Language:"}),e.jsxs(os,{value:m,onValueChange:v,children:[e.jsx(ds,{className:"w-[130px]","data-testid":"select-language-filter",children:e.jsx(hs,{placeholder:"All"})}),e.jsxs(ms,{children:[e.jsx(me,{value:"all",children:"All"}),e.jsx(me,{value:"English",children:"English"}),e.jsx(me,{value:"Spanish",children:"Spanish"}),e.jsx(me,{value:"Hindi",children:"Hindi"}),e.jsx(me,{value:"Portuguese",children:"Portuguese"}),e.jsx(me,{value:"French",children:"French"}),e.jsx(me,{value:"German",children:"German"}),e.jsx(me,{value:"Japanese",children:"Japanese"}),e.jsx(me,{value:"Korean",children:"Korean"}),e.jsx(me,{value:"Chinese",children:"Chinese"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Gender:"}),e.jsxs(os,{value:g,onValueChange:w,children:[e.jsx(ds,{className:"w-[110px]","data-testid":"select-gender-filter",children:e.jsx(hs,{placeholder:"All"})}),e.jsxs(ms,{children:[e.jsx(me,{value:"all",children:"All"}),e.jsx(me,{value:"Female",children:"Female"}),e.jsx(me,{value:"Male",children:"Male"}),e.jsx(me,{value:"Unknown",children:"Unknown"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Age:"}),e.jsxs(os,{value:k,onValueChange:b,children:[e.jsx(ds,{className:"w-[100px]","data-testid":"select-age-filter",children:e.jsx(hs,{placeholder:"All"})}),e.jsxs(ms,{children:[e.jsx(me,{value:"all",children:"All"}),e.jsx(me,{value:"18-24",children:"18-24"}),e.jsx(me,{value:"25-34",children:"25-34"}),e.jsx(me,{value:"35-44",children:"35-44"}),e.jsx(me,{value:"45-54",children:"45-54"}),e.jsx(me,{value:"55-64",children:"55-64"}),e.jsx(me,{value:"65+",children:"65+"})]})]})]}),(u!=="all"||m!=="all"||g!=="all"||k!=="all")&&e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>{x("all"),v("all"),w("all"),b("all")},className:"text-xs","data-testid":"clear-filters",children:"Clear filters"})]}),F&&e.jsxs("div",{className:"mb-6 p-4 rounded-lg border bg-muted/30","data-testid":"snapshot-history-section",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"font-medium flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4"}),"Recent Snapshot Uploads"]}),e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>de(!1),"data-testid":"close-history",children:e.jsx(pt,{className:"h-4 w-4"})})]}),da?e.jsx("div",{className:"text-center py-4 text-muted-foreground",children:"Loading history..."}):!(Je!=null&&Je.groups)||Je.groups.length===0?e.jsx("div",{className:"text-center py-4 text-muted-foreground",children:'No snapshot uploads yet. Use "Bulk Snapshot" to upload campaign data.'}):e.jsx(Ta,{type:"single",collapsible:!0,className:"space-y-2",children:Je.groups.map((h,Z)=>e.jsxs(Da,{value:`upload-${Z}`,className:"border rounded-lg px-4",children:[e.jsx(Pa,{className:"hover:no-underline py-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Lo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:j4(h.capturedAt,t)}),e.jsxs(Y,{variant:"secondary",className:"text-xs",children:[h.snapshots.length," snapshot",h.snapshots.length!==1?"s":""]})]})}),e.jsx(Ma,{children:e.jsx("div",{className:"space-y-2 pt-1 pb-2",children:h.snapshots.map(E=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded bg-muted/50 cursor-pointer hover:bg-muted transition-colors",onClick:()=>n(E.campaignId),"data-testid":`history-snapshot-${E.id}`,children:[e.jsx("span",{className:"font-medium truncate max-w-[250px]",children:E.campaignTitle}),e.jsxs("div",{className:"flex items-center gap-4 text-muted-foreground text-xs",children:[e.jsx("span",{className:"font-mono",children:Sa(E.cost)}
80),e.jsxs("span",{children:[(E.views||0).toLocaleString()," views"]}),e.jsxs("span",{children:[(E.websiteVisits||0).toLocaleString()," visits"]})]})]},E.id))})})]},h.capturedAt))})]}),Rt?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading campaigns..."}):!Gs||Gs.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Ra,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:u!=="all"||m!=="all"||g!=="all"||k!=="all"?"No campaigns match the selected filters.":"No campaigns yet."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:u!=="all"||m!=="all"||g!=="all"||k!=="all"?"Try adjusting the filters above or clear them to see all campaigns.":"Create your first campaign to start tracking ROI."})]}):S==="table"?e.jsx("div",{className:"rounded-md border",children:e.jsxs(nn,{children:[e.jsx(rn,{children:e.jsxs(ht,{children:[e.jsx(fs,{children:"Title"}),e.jsx(fs,{className:"w-[100px]",children:"Status"}),e.jsx(fs,{className:"w-[100px] text-right",children:"Cost"}),e.jsx(fs,{className:"w-[100px] text-right",children:"Visits"}),e.jsx(fs,{className:"w-[130px]",children:"Last Snapshot"})]})}),e.jsx(ln,{children:Gs.map(h=>e.jsxs(ht,{onClick:()=>n(h.id),className:"cursor-pointer hover:bg-muted/50","data-testid":`campaign-row-${h.id}`,children:[e.jsxs(Ke,{children:[e.jsx("div",{className:"font-medium",children:h.videoTitle}),h.targetCountries&&h.targetCountries.length>0&&e.jsxs("div",{className:"flex gap-1 mt-1",children:[h.targetCountries.slice(0,3).map(Z=>e.jsx(Y,{variant:"outline",className:"text-xs px-1 py-0",children:Z},Z)),h.targetCountries.length>3&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",h.targetCountries.length-3]})]})]}),e.jsx(Ke,{children:e.jsx(Y,{variant:Jl(h.status),className:"text-xs",children:h.status})}),e.jsx(Ke,{className:"text-right",children:h.latestSnapshot?Sa(h.latestSnapshot.cost):"-"}),e.jsx(Ke,{className:"text-right",children:h.latestSnapshot?(h.latestSnapshot.websiteVisits||0).toLocaleString():"-"}),e.jsx(Ke,{children:h.latestSnapshot?De(new Date(h.latestSnapshot.snapshotDate),"MMM d, yyyy"):e.jsx("span",{className:"text-amber-600 text-xs",children:"No snapshots"})})]},h.id))})]})}):e.jsx("div",{className:"grid gap-3",children:Gs.map(h=>e.jsxs("div",{onClick:()=>n(h.id),className:"p-4 rounded-lg border hover:border-primary cursor-pointer transition-colors","data-testid":`campaign-card-${h.id}`,children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-medium",children:h.videoTitle}),e.jsx(Y,{variant:Jl(h.status),className:"text-xs",children:h.status})]}),h.videoUrl&&e.jsxs("a",{href:h.videoUrl,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-blue-600 hover:underline flex items-center gap-1",onClick:Z=>Z.stopPropagation(),children:[e.jsx(yt,{className:"h-3 w-3"}),"youtube.com"]}),h.targetCountries&&h.targetCountries.length>0&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Targets:"}),h.targetCountries.map(Z=>{var E;return e.jsx(Y,{variant:"outline",className:"text-xs px-1 py-0","data-testid":`campaign-${h.id}-country-${Z}`,children:((E=Zl.find(Pe=>Pe.code===Z))==null?void 0:E.code)||Z},Z)})]}),(h.startDate||h.endDate)&&e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[e.jsx(Lo,{className:"h-3 w-3"}),e.jsxs("span",{children:[h.startDate?De(new Date(h.startDate),"MMM d, yyyy"):"?"," â ",h.endDate?De(new Date(h.endDate),"MMM d, yyyy"):"Ongoing"]})]}),(h.dailyBudget||h.totalBudget)&&e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[e.jsx(ct,{className:"h-3 w-3"}),e.jsxs("span",{children:[h.dailyBudget&&`$${h.dailyBudget}/day`,h.dailyBudget&&h.totalBudget&&" ⢠",h.totalBudget&&`$${h.totalBudget} total`]})]}),h.targetLanguages&&h.targetLanguages.length>0&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(dp,{className:"h-3 w-3 text-muted-foreground"}),h.targetLanguages.slice(0,3).map(Z=>e.jsx(Y,{variant:"secondary",className:"text-xs px-1 py-0",children:Z},Z)),h.targetLanguages.length>3&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",h.targetLanguages.length-3]})]}),h.targetGenders&&h.targetGenders.length>0&&h.targetGenders.length<3&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"}),h.targetGenders.map(Z=>e.jsx(Y,{variant:"secondary",className:"text-xs px-1 py-0",children:Z},Z))]}),h.targetAgeRanges&&h.targetAgeRanges.length>0&&h.targetAgeRanges.length<7&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Ages:"}),h.targetAgeRanges.slice(0,3).map(Z=>e.jsx(Y,{variant:"secondary",className:"text-xs px-1 py-0",children:Z},Z)),h.targetAgeRanges.length>3&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",h.targetAgeRanges.length-3]})]})]}),h.latestSnapshot&&e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm font-medium",children:Sa(h.latestSnapshot.cost)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(h.latestSnapshot.websiteVisits||0).toLocaleStr
80ing()," visits"]})]})]}),h.delta&&h.delta.daysBetween>0&&e.jsxs("div",{className:"mt-3 pt-3 border-t flex items-center gap-4 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Last ",h.delta.daysBetween," days:"]}),e.jsxs("span",{className:h.delta.cost>0?"text-red-600":"text-muted-foreground",children:[Mc(h.delta.cost,!0)," spend"]}),e.jsx("span",{className:"text-muted-foreground",children:"â"}),e.jsxs("span",{className:h.delta.websiteVisits>0?"text-green-600":"text-muted-foreground",children:[Mc(h.delta.websiteVisits)," visits"]})]}),h.snapshotCount===0&&e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx("p",{className:"text-xs text-amber-600",children:"No snapshots yet - add your first snapshot to start tracking"})})]},h.id))}),e.jsx(Vs,{open:i,onOpenChange:h=>{r(h),h||nt()},children:e.jsxs(Us,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Tl,{className:"h-5 w-5 text-purple-600"}),"Create Campaign from Screenshot"]}),e.jsx(Ct,{children:"Paste or upload a screenshot from YouTube Studio and we'll extract all the data automatically"})]}),e.jsxs(Qs,{className:"mb-4",children:[e.jsx(bs,{className:"h-4 w-4"}),e.jsxs(Xs,{children:[e.jsx("strong",{children:"What the AI extracts:"})," Video title, Video ID, Video URL, Promotion landing URL, Description URL, Target countries, Campaign dates, Budget (daily/total), Target genders, Age ranges, Interests, Languages, Goal, Status, and performance metrics (cost, views, visits).",e.jsx("br",{}),e.jsx("span",{className:"text-muted-foreground text-xs mt-1 block",children:"Tip: For best results, screenshot the full promotion settings page showing targeting options."})]})]}),e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-4 text-center transition-colors focus-within:border-primary hover:border-primary/50 ${J?"border-primary bg-primary/5":""}`,onPaste:Le,onDragOver:ae,onDragEnter:xe,onDragLeave:Fe,onDrop:X,tabIndex:0,"data-testid":"drop-zone-screenshot",children:[e.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:h=>Ne(h.target.files),"data-testid":"input-screenshot-upload"}),G.length===0?e.jsxs("div",{className:"py-6",children:[e.jsx(ic,{className:`h-10 w-10 mx-auto mb-3 transition-colors ${J?"text-primary":"text-muted-foreground"}`}),e.jsx("p",{className:"text-sm font-medium mb-1",children:J?"Drop screenshot here":"Drag & drop, paste (Ctrl/Cmd+V), or click to upload"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Works with YouTube Studio promotion dashboards and video analytics"}),e.jsxs(ee,{type:"button",variant:"outline",size:"sm",onClick:()=>{var h;return(h=C.current)==null?void 0:h.click()},"data-testid":"button-browse-files",children:[e.jsx(mp,{className:"h-4 w-4 mr-2"}),"Browse Files"]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2 justify-center",children:G.map((h,Z)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:h.preview,alt:`Screenshot ${Z+1}`,className:"h-24 w-auto rounded border object-cover"}),e.jsx("button",{type:"button",onClick:()=>Be(Z),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(pt,{className:"h-3 w-3"})})]},Z))}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsxs(ee,{type:"button",variant:"outline",size:"sm",onClick:()=>{var h;return(h=C.current)==null?void 0:h.click()},children:[e.jsx(on,{className:"h-4 w-4 mr-1"}),"Add More"]}),e.jsx(ee,{type:"button",onClick:ns,disabled:o,size:"sm","data-testid":"button-parse-screenshots",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-4 w-4 mr-2 animate-spin"}),"Analyzing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Tl,{className:"h-4 w-4 mr-2"}),"Extract Data"]})}),e.jsx(ee,{type:"button",variant:"ghost",size:"sm",onClick:nt,children:"Clear"})]})]})]}),$&&e.jsx(Qs,{variant:$.success?"default":"destructive",className:"mt-2",children:e.jsx(Xs,{className:"flex items-center gap-2",children:$.success?e.jsxs(e.Fragment,{children:[e.jsx(Ft,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:["Extracted data with ",Math.round($.confidence*100),"% confidence.",((Ds=$.data)==null?void 0:Ds.warnings)&&$.data.warnings.length>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["Warnings: ",$.data.warnings.join(", ")
80]})]})]}):e.jsx("span",{children:((_s=$.errors)==null?void 0:_s.join(", "))||"Failed to parse"})})}),e.jsx(oc,{...ze,children:e.jsxs("form",{onSubmit:ze.handleSubmit(h=>qt.mutate(h)),className:"space-y-4",children:[e.jsx(Ms,{control:ze.control,name:"videoTitle",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Video Title"}),e.jsx(Ks,{children:e.jsx(Me,{placeholder:"e.g., Clarafi AI Problem List Demo",...h,"data-testid":"input-campaign-video-title"})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:ze.control,name:"videoId",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Video ID"}),e.jsx(Ks,{children:e.jsx(Me,{placeholder:"e.g., dQw4w9WgXcQ",...h,"data-testid":"input-campaign-video-id"})}),e.jsxs(kn,{children:["The ID from the YouTube URL (youtube.com/watch?v=",e.jsx("strong",{children:"VIDEO_ID"}),")"]}),e.jsx($s,{})]})}),e.jsx(Ms,{control:ze.control,name:"videoUrl",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Video URL (optional)"}),e.jsx(Ks,{children:e.jsx(Me,{placeholder:"https://youtube.com/watch?v=...",...h,"data-testid":"input-campaign-video-url"})}),e.jsx($s,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ms,{control:ze.control,name:"promotionLandingUrl",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Promotion Landing URL"}),e.jsx(Ks,{children:e.jsx(Me,{placeholder:"e.g., clarafi.ai/scribe",...h,"data-testid":"input-promotion-landing-url"})}),e.jsx(kn,{className:"text-xs",children:'Where YouTube sends viewers ("send viewers to")'}),e.jsx($s,{})]})}),e.jsx(Ms,{control:ze.control,name:"descriptionUrl",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Description URL"}),e.jsx(Ks,{children:e.jsx(Me,{placeholder:"e.g., clarafi.ai",...h,"data-testid":"input-description-url"})}),e.jsx(kn,{className:"text-xs",children:"URL in your video description"}),e.jsx($s,{})]})})]}),e.jsx(Ms,{control:ze.control,name:"targetCountries",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Target Countries"}),e.jsx(kn,{className:"text-xs mb-2",children:"Select the countries you're showing this promotion to"}),e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border rounded-md max-h-32 overflow-y-auto","data-testid":"input-target-countries",children:Zl.map(Z=>{var Pe;const E=(Pe=h.value)==null?void 0:Pe.includes(Z.code);return e.jsx("button",{type:"button",onClick:()=>{const Ze=h.value||[];E?h.onChange(Ze.filter(ps=>ps!==Z.code)):h.onChange([...Ze,Z.code])},className:`px-2 py-1 text-xs rounded-full border transition-colors ${E?"bg-primary text-primary-foreground border-primary":"bg-background hover:bg-muted border-input"}`,"data-testid":`country-${Z.code}`,children:Z.name},Z.code)})}),h.value&&h.value.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Selected: ",h.value.join(", ")]}),e.jsx($s,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ms,{control:ze.control,name:"startDate",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Start Date"}),e.jsx(Ks,{children:e.jsx(Me,{type:"date",...h,"data-testid":"input-start-date"})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:ze.control,name:"endDate",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"End Date"}),e.jsx(Ks,{children:e.jsx(Me,{type:"date",...h,"data-testid":"input-end-date"})}),e.jsx($s,{})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ms,{control:ze.control,name:"dailyBudget",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Daily Budget ($)"}),e.jsx(Ks,{children:e.jsx(Me,{type:"text",placeholder:"10.00",...h,"data-testid":"input-daily-budget"})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:ze.control,name:"totalBudget",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Total Budget ($)"}),e.jsx(Ks,{children:e.jsx(Me,{type:"text",placeholder:"100.00",...h,"data-testid":"input-total-budget"})}),e.jsx($s,{})]})})]}),e.jsx(Ms,{control:ze.control,name:"targetGenders",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Target Genders"}),e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border rounded-md","data-testid":"input-target-genders",children:["Female","Male","Unknown"].map(Z=>{var Pe;const E=(Pe=h.value)==null?void 0:Pe.includes(Z);return e.jsx("button",{type:"button",onClick:()=>{const Ze=h.value||[];E?h.onChange(Ze.filter(ps=>ps!==Z)):h.onChange([...Ze,Z])},className:`px-3 py-1 text-sm rounded-full border transition-colors ${E?"bg-primary text-primary-foreground border-primary":"bg-background hover:bg-muted border-input"}`,"data-testid":`gender-${Z.toLowerCase()}`,children:Z},Z)})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:ze.control,name:"targetAgeRanges",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Target Age Ranges"}),e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border rounded-md","data-testid":"input-target-age-ranges",children:["18-24","25-34","35-44","45-54","55-64","65+","Unknown"].map(Z=>{var Pe;const E=(Pe=h.value)==null?void 0:Pe.includes(Z);return e.jsx("button",{type:"button",onClick:()=>{const Ze=h.value||[];E?h.onChange(Ze.filter(ps=>ps!==Z)):h.onChange([...Ze,Z])},className:`px-3 py-1 text-sm rounded-full border transition-colors ${E?"bg-primary text-primary-foreground border-primary":"bg-background hover:bg-muted border-input"}`,"data-testid":`age-${Z.replace("+","plus")}`,children:Z},Z)})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:ze.control,name:"targetInterests",render:({field:h})=>{var Z;return e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Target Interests"}),e.jsx(kn,{className:"text-xs",children:"Click common interests below or enter custom ones separated by commas"}),e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border rounded-md mb-2","data-testid":"input-target-interests-buttons",children:["Health Care Education","Business & Productivity Software","Health & Medical Jobs"].map(E=>{var Ze;const Pe=(Ze=h.value)==null?void 0:Ze.includes(E);return e.jsx("button",{type:"button",onClick:()=>{const ps=h.value||[];Pe?h.onChange(ps.filter(bt=>bt!==E)):h.onChange([...ps,E])},className:`px-3 py-1 text-sm rounded-full border transition-colors ${Pe?"bg-primary text-primary-foreground border-primary":"bg-background hover:bg-muted border-input"}`,"data-testid":`interest-${E.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,children:E},E)})}),e.jsx(Ks,{children:e.jsx(Me,{type:"text",placeholder:"Or type custom interests...",value:((Z=h.value)==null?void 0:Z.join(", "))||"",onChange:E=>{const Pe=E.target.value.split(",").map(Ze=>
80Ze.trim()).filter(Boolean);h.onChange(Pe)},"data-testid":"input-target-interests"})}),e.jsx($s,{})]})}}),e.jsx(Ms,{control:ze.control,name:"targetLanguages",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Target Languages"}),e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border rounded-md","data-testid":"input-target-languages",children:["English","Spanish","Hindi","Portuguese","French","German","Japanese","Korean","Chinese"].map(Z=>{var Pe;const E=(Pe=h.value)==null?void 0:Pe.includes(Z);return e.jsx("button",{type:"button",onClick:()=>{const Ze=h.value||[];E?h.onChange(Ze.filter(ps=>ps!==Z)):h.onChange([...Ze,Z])},className:`px-3 py-1 text-sm rounded-full border transition-colors ${E?"bg-primary text-primary-foreground border-primary":"bg-background hover:bg-muted border-input"}`,"data-testid":`language-${Z.toLowerCase()}`,children:Z},Z)})}),e.jsx($s,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ms,{control:ze.control,name:"goal",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Goal"}),e.jsxs(os,{onValueChange:h.onChange,defaultValue:h.value,children:[e.jsx(Ks,{children:e.jsx(ds,{"data-testid":"select-campaign-goal",children:e.jsx(hs,{placeholder:"Select goal"})})}),e.jsxs(ms,{children:[e.jsx(me,{value:"website_visits",children:"Website Visits"}),e.jsx(me,{value:"views",children:"Views"}),e.jsx(me,{value:"subscribers",children:"Subscribers"})]})]}),e.jsx($s,{})]})}),e.jsx(Ms,{control:ze.control,name:"status",render:({field:h})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Status"}),e.jsxs(os,{onValueChange:h.onChange,defaultValue:h.value,children:[e.jsx(Ks,{children:e.jsx(ds,{"data-testid":"select-campaign-status",children:e.jsx(hs,{placeholder:"Select status"})})}),e.jsxs(ms,{children:[e.jsx(me,{value:"active",children:"Active"}),e.jsx(me,{value:"paused",children:"Paused"}),e.jsx(me,{value:"completed",children:"Completed"})]})]}),e.jsx($s,{})]})})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(ee,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(ee,{type:"submit",disabled:qt.isPending,"data-testid":"button-submit-campaign",children:qt.isPending?"Creating...":"Create Campaign"})]})]})})]})}),e.jsx(Vs,{open:y,onOpenChange:h=>{f(h),h||Re()},children:e.jsxs(Us,{className:"max-w-4xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Br,{className:"h-5 w-5"}),"Bulk Snapshot from Promotions List"]}),e.jsx(Ct,{children:'Screenshot the "Channel Content â Promotions" page in YouTube Studio to update all campaigns at once'})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("label",{className:"text-sm font-medium",children:"Snapshot Date:"}),e.jsx(Me,{type:"date",value:ye,onChange:h=>Ie(h.target.value),className:"w-40","data-testid":"input-bulk-snapshot-date"})]}),R.length===0&&e.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${z?"border-primary bg-primary/5":"hover:border-primary/50"}`,onClick:()=>{var h;return(h=P.current)==null?void 0:h.click()},onPaste:We,onDragOver:we,onDragEnter:we,onDragLeave:gs,onDrop:Ss,tabIndex:0,"data-testid":"bulk-screenshot-dropzone",children:[e.jsx(ic,{className:`h-8 w-8 mx-auto mb-2 ${z?"text-primary":"text-muted-foreground"}`}),e.jsx("p",{className:`text-sm mb-2 ${z?"text-primary font-medium":"text-muted-foreground"}`,children:z?"Drop image here":"Drag & drop, click to upload, or paste (Ctrl/Cmd+V)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Go to YouTube Studio â Content â Promotions â Screenshot the list of all promotions"}),e.jsx("input",{ref:P,type:"file",accept:"image/*",className:"hidden",onChange:h=>ge(h.target.files),"data-testid":"input-bulk-screenshot"})]}),R.length>0&&!H&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Uploaded Screenshot"}),e.jsxs(ee,{variant:"ghost",size:"sm",onClick:()=>O([]),"data-testid":"button-clear-bulk-image",children:[e.jsx(pt,{className:"h-4 w-4 mr-1"}),"Clear"]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden max-h-48",children:e.jsx("img",{src:R[0].preview,alt:"Bulk screenshot preview",className:"w-full object-contain"})}),e.jsx(ee,{onClick:L,disabled:N,className:"w-full","data-testid":"button-parse-bulk-screenshot",children:N?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-4 w-4 mr-2 animate-spin"}),"Parsing screenshot..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Tl,{className:"h-4 w-4 mr-2"}),"Parse Screenshot with AI"]})})]}),H&&ve.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{className:"text-sm font-medium",children:["Found ",H.totalRowsExtracted," promotions"]}),e.jsxs(Y,{variant:"outline",className:"text-xs",children:[H.matchedCount," matched"]}),H.unmatchedCount>0&&e.jsxs(Y,{variant:"destructive",className:"text-xs",children:[H.unmatchedCount," unmatched"]})]}),e.jsxs(ee,{variant:"ghost",size:"sm",onClick:Re,"data-testid":"button-clear-bulk-parse",children:[e.jsx(pt,{className:"h-4 w-4 mr-1"}),"Start Over"]})]}),H.warnings&&H.warnings.length>0&&e.jsxs(Qs,{children:[e.jsx(bs,{className:"h-4 w-4"}),e.jsx(Xs,{children:H.warnings.join(", ")})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(nn,{children:[e.jsx(rn,{children:e.jsxs(ht,{children:[e.jsx(fs,{className:"w-10",children:"Use"}),e.jsx(fs,{children:"Video Title"}),e.jsx(fs,{children:"Match"}),e.jsx(fs,{className:"text-right",children:"Cost"}),e.jsx(fs,{className:"text-right",children:"Impressions"}),e.jsx(fs,{className:"text-right",children:"Views"}),e.jsx(fs,{className:"text-right",children:"Subs"}),e.jsx(fs,{className:"text-right",children:"Visits"})]})}),e.jsx(ln,{children:ve.map((h,Z)=>e.jsxs(ht,{className:h.matchedCampaignId?"":"bg-red-50 dark:bg-red-950/20",children:[e.jsx(Ke,{children:e.jsx("input",{type:"checkbox",checked:h.selected||!1,disabled:!h.matchedCampaignId,onChange:()=>Ge(Z),className:"h-4 w-4","data-testid":`checkbox-bulk-${Z}`})}),e.jsx(Ke,{className:"font-medium max-w-[200px] truncate",title:h.videoTitle||"",children:h.videoTitle||"Unknown"}),e.jsx(Ke,{children:h.matchedCampaignId?e.jsxs(Ce,{children:[e.jsx(Se,{children:e.jsxs(Y,{variant:"outline",className:`text-xs cursor-pointer ${h.matchReasoning==="Manually assigned"?"text-blue-600 border-blue-300":"text-green-600"}`,onClick:()=>Qe(Z,null),children:[h.matchReasoning==="Manually assigned"?"Manual":`${Math.round((h.matchConfidence||0)*100)}%`," â"]})}),e.jsxs(Ae,{children:[e.jsx("p",{className:"text-xs font-medium",children:h.matchedCampaignTitle}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click to unmatch"})]})]}):e.jsxs(os,{onValueChange:E=>Qe(Z,parseInt(E)),children:[e.jsx(ds,{className:"h-7 w-28 text-xs","data-testid":`select-campaign-${Z}`,children:e.jsx(hs,{placeholder:"Select..."})}),e.jsx(ms,{children:ks==null?void 0:ks.map(E=>e.jsx(me,{value:E.id.toString(),className:"text-xs",children:E.videoTitle.length>25?E.videoTitle.slice(0,25)+"...":E.videoTitle},E.id))})]})}),e.jsx(Ke,{className:"text-right",children:e.jsx(Me,{type:"text",value:h.cost||"",onChange:E=>$e(Z,"cost",E.target.value),className:"w-20 h-7 text-right text-xs",disabled:!h.matchedCampaignId,"data-testid":`input-bulk-cost-${Z}`})}),e.jsx(Ke,{className:"text-right",children:e.jsx(Me,{type:"number",value:h.impressions||0,onChange:E=>$e(Z,"impressions",parseInt(E.target.value)||0),className:"w-20 h-7 text-right text-xs",disabled:!h.matchedCampaignId,"data-testid":`input-bulk-impressions-${Z}`})}),e.jsx(Ke,{className:"text-right",children:e.jsx(Me,{type:"number",value:h.views||0,onChange:E=>$e(Z,"views",parseInt(E.target.value)||0),className:"w-20 h-7 text-right text-xs",disabled:!h.matchedCampaignId,"data-testid":`input-bulk-views-${Z}`})}),e.jsx(Ke,{className:"text-right",children:e.jsx(Me,{type:"number",value:h.subscribers||0,onChange:E=>$e(Z,"subscribers",parseInt(E.target.value)||0),className:"w-20 h-7 text-right text-xs",disabled:!h.matchedCampaignId,"data-testid":`input-bulk-subs-${Z}`})}),e.jsx(Ke,{className:"text-right",children:e.jsx(Me,{type:"number",value:h.websiteVisits||0,onChange:E=>$e(Z,"websiteVisits",parseInt(E.target.value)||0),className:"w-20 h-7 text-right text-xs",disabled:!h.matchedCampaignId,"data-testid":`input-bulk-visits-${Z}`})})]},Z))})]})}),e.jsxs("div",{className:"flex justify-between items-center pt-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ve.filter(h=>h.selected).length," of ",ve.filter(h=>h.matchedCampaignId).length," matched campaigns selected"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ee,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(ee,{onClick:js,disabled:qs.isPending||ve.filter(h=>h.selected).length===0,"data-testid":"button-save-bulk-snapshots",children:qs.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ft,{className:"h-4 w-4 mr-2"}),"Save ",ve.filter(h=>h.selected).length," Snapshots"]})})]})]})]})]})]})})]})]})})}function v4({value:s,onChange:t}){const a=[{label:"Last 7 days",days:7},{label:"Last 30 days",days:30},{label:"Last 90 days",days:90},{label:"Last 6 months",days:180},{label:"Last year",days:365}];return e.jsxs(os,{value:String(s),onValueChange:n=>t(Number(n)),children:[e.jsx(ds,{className:"w-[180px]","data-testid":"select-time-range",children:e.jsx(hs,{placeholder:"Select time range"})}),e.jsx(ms,{children:a.map(n=>e.jsx(me,{value:String(n.days),"data-testid":`option-${n.days}d`,children:n.label},n.days))})]})}
80function rt(s){return s.toLocaleString()}function Tn(s){return s>=.5?"text-green-600":s>=.3?"text-yellow-600":"text-red-600"}function y4(s){return s>=.5?{label:"Strong",variant:"default"}:s>=.3?{label:"Moderate",variant:"secondary"}:{label:"Weak",variant:"destructive"}}function N4(s){switch(s){case"trendingUp":return e.jsx(Is,{className:"h-5 w-5 text-green-600"});case"target":return e.jsx(lt,{className:"h-5 w-5 text-blue-600"});case"video":return e.jsx(ji,{className:"h-5 w-5 text-purple-600"});case"spend":return e.jsx(ct,{className:"h-5 w-5 text-amber-600"});case"zap":return e.jsx(oa,{className:"h-5 w-5 text-yellow-600"});default:return e.jsx(Zs,{className:"h-5 w-5 text-ink-muted"})}}function w4(s){switch(s.toLowerCase()){case"high":return{variant:"default",className:"bg-green-600"};case"medium":return{variant:"secondary",className:"bg-yellow-600 text-white"};case"low":return{variant:"outline",className:"text-ink-muted"};default:return{variant:"outline",className:""}}}const nm={views:1,visits:1,signups:1,spend:1,googleAdsSpend:1,googleAdsClicks:1},k4=[{value:.001,label:"÷1000"},{value:.01,label:"÷100"},{value:.1,label:"÷10"},{value:1,label:"1x"},{value:10,label:"Ã10"},{value:100,label:"Ã100"},{value:1e3,label:"Ã1000"}];function C4(){var y;if(_t())return null;const[s,t]=p.useState(30),[a,n]=p.useState(null),[i,r]=p.useState("absolute"),[l,c]=p.useState(!1),[o,d]=p.useState(nm),u=()=>d(nm),x=Object.values(o).some(f=>f!==1),m=De(new Date,"yyyy-MM-dd"),v=De(vt(new Date,s),"yyyy-MM-dd"),{data:g,isLoading:w,isError:k}=_e({queryKey:["/api/marketing/youtube-correlation/daily",{startDate:v,endDate:m}]}),{data:b,isLoading:S,isError:A}=_e({queryKey:["/api/marketing/youtube-correlation/summary",{startDate:v,endDate:m}]}),{data:F,isLoading:de,isError:M}=_e({queryKey:["/api/marketing/youtube-correlation/videos",{startDate:v,endDate:m}]}),G=w||S||de,D=k||A||M,$=g&&g.length>0,se=(g==null?void 0:g.map(f=>{var R,O;return{date:De(new Date(f.date+"T12:00:00"),"MMM d"),fullDate:f.date,views:f.youtube.totalViews,visits:f.site.websiteVisits,signups:f.site.signupsCompleted,spend:f.spend.youtubePromotion,googleAdsSpend:((R=f.googleAds)==null?void 0:R.spend)||0,googleAdsClicks:((O=f.googleAds)==null?void 0:O.clicks)||0,totalSpend:f.spend.totalSpend,newVideo:f.newVideoPublished}}))||[],J=se.reduce((f,R)=>({views:Math.max(f.views,R.views||0),visits:Math.max(f.visits,R.visits||0),signups:Math.max(f.signups,R.signups||0),spend:Math.max(f.spend,R.spend||0),googleAdsSpend:Math.max(f.googleAdsSpend,R.googleAdsSpend||0),googleAdsClicks:Math.max(f.googleAdsClicks,R.googleAdsClicks||0)}),{views:0,visits:0,signups:0,spend:0,googleAdsSpend:0,googleAdsClicks:0}),le=(f,R)=>R>0?f/R*100:0,C=se.map(f=>{let R=i==="relative"?le(f.views,J.views):f.views,O=i==="relative"?le(f.visits,J.visits):f.visits,N=i==="relative"?le(f.signups,J.signups):f.signups,re=i==="relative"?le(f.spend,J.spend):f.spend,H=i==="relative"?le(f.googleAdsSpend,J.googleAdsSpend):f.googleAdsSpend,pe=i==="relative"?le(f.googleAdsClicks,J.googleAdsClicks):f.googleAdsClicks;return i==="absolute"&&(R*=o.views,O*=o.visits,N*=o.signups,re*=o.spend,H*=o.googleAdsSpend,pe*=o.googleAdsClicks),{...f,rawViews:f.views,rawVisits:f.visits,rawSignups:f.signups,rawSpend:f.spend,rawGoogleAdsSpend:f.googleAdsSpend,rawGoogleAdsClicks:f.googleAdsClicks,views:R,visits:O,signups:N,spend:re,googleAdsSpend:H,googleAdsClicks:pe}}),I=C.filter(f=>f.newVideo).map(f=>{var R;return{date:f.date,title:((R=f.newVideo)==null?void 0:R.videoTitle)||"New Video"}});return D?e.jsx("div",{className:"space-y-6",children:e.jsxs(_,{"data-testid":"error-youtube-unavailable",children:[e.jsxs(q,{children:[e.jsxs(W,{className:"flex items-center gap-2 text-red-600",children:[e.jsx(Dt,{className:"h-5 w-5"}),"YouTube Analytics Unavailable"]}),e.jsx(Oe,{children:"We're unable to fetch YouTube analytics data at this time. This could be due to a service outage or configuration issue. Please try again later."})]}),e.jsx(T,{children:e.jsx(ee,{onClick:()=>{Ts.invalidateQueries({queryKey:["/api/marketing/youtube-correlation/daily"]}),Ts.invalidateQueries({queryKey:["/api/marketing/youtube-correlation/summary"]}),Ts.invalidateQueries({queryKey:["/api/marketing/youtube-correlation/videos"]})},variant:"outline",children:"Retry"})})]})}):e.jsxs(xs,{children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2","data-testid":"heading-youtube-impact",children:[e.jsx(Ra,{className:"h-6 w-6 text-red-600"}),"YouTube Impact Dashboard"]}),e.jsx("p",{className:"text-muted-foreground",children:"Analyze how YouTube content and promotions drive website conversions"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:[e.jsx(bs,{className:"h-3 w-3"}),"YouTube Analytics API has a 2-3 day data delay. Recent days may not show data yet."]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(v4,{value:s,onChange:t})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:G?e.jsx(e.Fragment,{children:[1,2,3,4].map(f=>e.jsxs(_,{"data-testid":"skeleton-loading",children:[e.jsx(q,{className:"pb-2",children:e.jsx(cs,{className:"h-4 w-32"})}),e.jsx(T,{children:e.jsx(cs,{className:"h-8 w-20"})})]},f))}):e.jsxs(e.Fragment,{children:[e.jsxs(_,{"data-testid":"card-correlation-views-visits",children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Hs,{className:"h-4 w-4"}),"Views to Visits",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Measures statistical correlation between daily YouTube views and website visits. Data sources: YouTube Analytics API (views) and our site analytics database (visits). A correlation of 70%+ indicates YouTube activity strongly drives site traffic."})})]})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-2xl font-bold ${Tn((b==null?void 0:b.correlations.viewsToVisits)||0)}`,children:[(((b==null?void 0:b.correlations.viewsToVisits)||0)*100).toFixed(0),"%"]}),((b==null?void 0:b.correlations.viewsToVisits)||0)>=.3?e.jsx(Is,{className:"h-5 w-5 text-green-600"}):e.jsx(Et,{className:"h-5 w-5 text-red-600"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Correlation coefficient"})]})]}),e.jsxs(_,{"data-testid":"card-correlation-views-signups",children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Views to Signups",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Correlation between YouTube views and signup completions. Higher values suggest your videos effectively convert viewers to users."})})]})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-2xl font-bold ${Tn((b==null?void 0:b.correlations.viewsToSignups)||0)}`,children:[(((b==null?void 0:b.correlations.viewsToSignups)||0)*100).toFixed(0),"%"]}),((b==null?void 0:b.correlations.viewsToSignups)||0)>=.3?e.jsx(Is,{className:"h-5 w-5 text-green-600"}):e.jsx(Et,{className:"h-5 w-5 text-red-600"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Correlation coefficient"})]})]}),e.jsxs(_,{"data-testid":"card-correlation-spend-visits",children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ct,{className:"h-4 w-4"}),"Spend to Visits",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Correlation between YouTube promotion spend and website visits. Spend data comes from manual promotion tracking. Strong correlation indicates paid promotion drives traffic."})})]})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-2xl font-bold ${Tn((b==null?void 0:b.correlations.spendToVisits)||0)}`,children:[(((b==null?void 0:b.correlations.spendToVisits)||0)*100).toFixed(0),"%"]}),((b==null?void 0:b.correlations.spendToVisits)||0)>=.3?e.jsx(Is,{className:"h-5 w-5 text-green-600"}):e.jsx(Et,{className:"h-5 w-5 text-red-600"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Correlation coefficient"})]})]}),e.jsxs(_,{"data-testid":"card-correlation-spend-conversions",children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(lt,{className:"h-4 w-4"}),"Spend to Conversions",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Correlation between promotion spend and signup conversions. Key ROI indicator for your YouTube ad budget."})})]})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`text-2xl font-bold ${Tn((b==null?void 0:b.correlations.spendToConversions)||0)}`,children:[(((b==null?void 0:b.correlations.spendToConversions)||0)*100).toFixed(0),"%"]}),((b==null?void 0:b.correlations.spendToConversions)||0)>=.3?e.jsx(Is,{className:"h-5 w-5 text-green-600"}):e.jsx(Et,{className:"h-5 w-5 text-red-600"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Correlation coefficient"})]})]})]})}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(Zs,{className:"h-5 w-5"}),"YouTube & Website Activity Timeline"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Absolute:"})," Shows actual values (views, visits, dollars)"]}),e.jsxs("p",{className:"mt-1",children:[e.jsx("strong",{children:"Relative:"})," Shows each metric as 0-100% of its maximum, making trends easier to compare across different scales"]})]})]}),e.jsxs("div",{className:"flex rounded-lg border overflow-hidden",children:[e.jsx(ee,{variant:i==="absolute"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-3",onClick:()=>r("absolute"),"data-testid":"btn-chart-absolute",children:"Absolute"}),e.jsx(ee,{variant:i==="relative"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-3",onClick:()=>r("relative"),"data-testid":"btn-chart-relative",children:"Relative"})]})]})]}),e.jsxs(Oe,{className:"flex items-center gap-4",children:[e.jsx("span",{children:"Track how YouTube views, promotion spend, and website activity correlate over time"}),i==="absolute"?e.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-1 cursor-help text-blue-600",children:[e.jsx(bs,{className:"h-3 w-3"}),"Left axis"]})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"YouTube views from your channel analytics, updated daily via YouTube Analytics API"})})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-1 cursor-help text-green-600",children:[e.jsx(bs,{className:"h-3 w-3"}),"Right axis"]})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Website metrics from our analytics: visits (all traffic), signups (completed registrations), and promotion spend (manually tracked)"})})]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"All metrics shown as % of their maximum value (hover for actual numbers)"})]}),i==="absolute"&&e.jsxs(Ri,{open:l,onOpenChange:c,className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Li,{asChild:!0,children:e.jsxs(ee,{variant:"ghost",size:"sm",className:"gap-1 h-7 px-2",children:[e.jsx(Om,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs",children:"Scale Controls"}),l?e.jsx(Mr,{className:"h-3 w-3"}):e.jsx(Tt,{className:"h-3 w-3"})]})}),x&&e.jsxs(ee,{variant:"ghost",size:"sm",onClick:u,className:"gap-1 h-7 px-2 text-muted-foreground hover:text-foreground",children:[e.jsx(hi,{className:"h-3 w-3"}),e.jsx("span",{className:"text-xs",children:"Reset"})]}),x&&e.jsxs("span",{className:"text-xs text-amber-600 flex items-center gap-1",children:[e.jsx(bs,{className:"h-3 w-3"}),"Custom scales applied - hover chart for actual values"]})]}),e.jsx($i,{children:e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-3 mt-2 p-3 bg-muted/50 rounded-lg",children:[{key:"views",label:"YouTube Views (L)",color:"text-red-600"},{key:"visits",label:"Website Visits (R)",color:"text-green-600"},{key:"signups",label:"Signups (R)",color:"text-purple-600"}
80,{key:"spend",label:"YT Spend (R)",color:"text-orange-500"},{key:"googleAdsSpend",label:"Google Ads $ (R)",color:"text-blue-600"},{key:"googleAdsClicks",label:"Ad Clicks (R)",color:"text-cyan-600"}].map(({key:f,label:R,color:O})=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:`text-xs font-medium ${O}`,children:R}),e.jsxs(os,{value:String(o[f]),onValueChange:N=>d(re=>({...re,[f]:parseFloat(N)})),children:[e.jsx(ds,{className:"h-7 text-xs",children:e.jsx(hs,{})}),e.jsx(ms,{children:k4.map(N=>e.jsx(me,{value:String(N.value),children:N.label},N.value))})]})]},f))})})]})]}),e.jsx(T,{children:G?e.jsx(cs,{className:"h-[400px] w-full","data-testid":"skeleton-loading"}):$?e.jsx("div",{className:"h-[400px]","data-testid":"chart-container-correlation",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(nu,{data:C,children:[e.jsx(Jt,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Bt,{dataKey:"date",tick:{fontSize:12},tickLine:!1}),i==="absolute"?e.jsxs(e.Fragment,{children:[e.jsx(at,{yAxisId:"left",orientation:"left",tick:{fontSize:12},tickFormatter:f=>rt(f),label:{value:"Views",angle:-90,position:"insideLeft"}}),e.jsx(at,{yAxisId:"right",orientation:"right",tick:{fontSize:12},tickFormatter:f=>rt(f),label:{value:"Visits/Signups/Spend/Clicks",angle:90,position:"insideRight"}})]}):e.jsxs(e.Fragment,{children:[e.jsx(at,{yAxisId:"left",orientation:"left",tick:{fontSize:12},domain:[0,100],tickFormatter:f=>`${f}%`,label:{value:"% of Max",angle:-90,position:"insideLeft"}}),e.jsx(at,{yAxisId:"right",orientation:"right",tick:{fontSize:12},domain:[0,100],tickFormatter:f=>`${f}%`,label:{value:"% of Max",angle:90,position:"insideRight"}})]}),e.jsx(gt,{content:({active:f,payload:R,label:O})=>{var re;if(!f||!(R!=null&&R.length))return null;const N=(re=R[0])==null?void 0:re.payload;return e.jsxs("div",{className:"bg-background border rounded-lg shadow-lg p-3 space-y-1",children:[e.jsx("p",{className:"font-medium",children:O}),i==="relative"?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-red-600",children:["Views (L): ",rt((N==null?void 0:N.rawViews)||0)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((N==null?void 0:N.views)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-green-600",children:["Visits (R): ",rt((N==null?void 0:N.rawVisits)||0)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((N==null?void 0:N.visits)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-purple-600",children:["Signups (R): ",((N==null?void 0:N.rawSignups)||0).toLocaleString()," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((N==null?void 0:N.signups)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-orange-500",children:["YouTube Spend (R): $",((N==null?void 0:N.rawSpend)||0).toFixed(2)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((N==null?void 0:N.spend)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-blue-600",children:["Google Ads (R): $",((N==null?void 0:N.rawGoogleAdsSpend)||0).toFixed(2)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((N==null?void 0:N.googleAdsSpend)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-cyan-600",children:["Ad Clicks (R): ",rt((N==null?void 0:N.rawGoogleAdsClicks)||0)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((N==null?void 0:N.googleAdsClicks)||0).toFixed(0),"%)"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-red-600",children:["Views (L): ",rt((N==null?void 0:N.rawViews)||(N==null?void 0:N.views)||0)]}),e.jsxs("p",{className:"text-green-600",children:["Visits (R): ",rt((N==null?void 0:N.rawVisits)||(N==null?void 0:N.visits)||0)]}),e.jsxs("p",{className:"text-purple-600",children:["Signups (R): ",((N==null?void 0:N.rawSignups)||(N==null?void 0:N.signups)||0).toLocaleString()]}),e.jsxs("p",{className:"text-orange-500",children:["YouTube Spend (R): $",((N==null?void 0:N.rawSpend)||(N==null?void 0:N.spend)||0).toFixed(2)]}),e.jsxs("p",{className:"text-blue-600",children:["Google Ads (R): $",((N==null?void 0:N.rawGoogleAdsSpend)||(N==null?void 0:N.googleAdsSpend)||0).toFixed(2)]}),e.jsxs("p",{className:"text-cyan-600",children:["Ad Clicks (R): ",rt((N==null?void 0:N.rawGoogleAdsClicks)||(N==null?void 0:N.googleAdsClicks)||0)]})]}),(N==null?void 0:N.newVideo)&&e.jsxs("p",{className:"text-red-600 font-medium mt
80-2",children:["ð¹ New: ",N.newVideo.videoTitle]})]})}}),e.jsx(On,{}),e.jsx(In,{yAxisId:"left",type:"monotone",dataKey:"views",fill:"#dc2626",fillOpacity:.3,stroke:"#dc2626",strokeWidth:2,name:"YouTube Views (L)"}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"visits",stroke:"#22c55e",strokeWidth:2,dot:!1,name:"Website Visits (R)"}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"signups",stroke:"#a855f7",strokeWidth:2,dot:!1,name:"Signups (R)"}),e.jsx(Zt,{yAxisId:"right",dataKey:"spend",fill:"#f97316",opacity:.8,name:"YouTube Spend $ (R)",stackId:"spend"}),e.jsx(Zt,{yAxisId:"right",dataKey:"googleAdsSpend",fill:"#2563eb",opacity:.8,name:"Google Ads $ (R)",stackId:"spend"}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"googleAdsClicks",stroke:"#06b6d4",strokeWidth:2,strokeDasharray:"5 5",dot:!1,name:"Ad Clicks (R)"}),I.map((f,R)=>e.jsx(ir,{x:f.date,yAxisId:"left",stroke:"#ef4444",strokeDasharray:"5 5",label:{value:"ð¹",position:"top",fontSize:14}},R))]},`chart-${i}`)})}):e.jsx("div",{className:"h-[400px] flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ji,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No YouTube correlation data available for this time range."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Connect your YouTube channel and start tracking performance."})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-5 w-5"}),"Video Performance Rankings",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Videos ranked by their Views-to-Visits correlation score. Higher correlation means the video is more effective at driving traffic. Data: YouTube Analytics API (video metrics) + site analytics (attribution window: 7 days after video publish)"})})]})]}),e.jsx(Oe,{children:"Videos ranked by conversion impact"})]}),e.jsx(T,{children:G?e.jsx("div",{className:"space-y-3","data-testid":"skeleton-loading",children:[1,2,3,4,5].map(f=>e.jsx(cs,{className:"h-16 w-full"},f))}):!F||F.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Ra,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No video data available."})]}):e.jsx("div",{className:"space-y-3","data-testid":"list-video-leaderboard",children:F.slice(0,10).map((f,R)=>{const O=y4(f.correlation.viewsToVisitsCorr);return e.jsxs("div",{onClick:()=>n(f),className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors cursor-pointer","data-testid":`video-item-${R}`,children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",R+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("a",{href:`https://www.youtube.com/watch?v=${f.videoId}`,target:"_blank",rel:"noopener noreferrer",className:"font-medium truncate hover:text-blue-600 hover:underline flex items-center gap-1",title:f.videoTitle,children:[f.videoTitle,e.jsx(yt,{className:"h-3 w-3 flex-shrink-0"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"}),f.daysOnline,"d"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"}),rt(f.metrics.views)]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-1 cursor-help",children:[e.jsx(dc,{className:"h-3 w-3"}),"~",(f.siteImpact.websiteVisits||0).toLocaleString()," est."]})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Estimated visits based on time correlation (all site visits within 7 days of publish). Add UTM links for direct tracking."})})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-1 cursor-help",children:[e.jsx(Ys,{className:"h-3 w-3"}
80),"~",(f.siteImpact.signups||0).toLocaleString()," signups"]})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Estimated signups based on time correlation. Add UTM links for direct tracking."})})]}),e.jsxs("a",{href:`https://studio.youtube.com/video/${f.videoId}/analytics`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-blue-600 flex items-center gap-1","data-testid":`link-video-analytics-${R}`,children:[e.jsx(Zs,{className:"h-3 w-3"}),"Studio"]})]})]}),e.jsx(Y,{variant:O.variant,children:O.label})]},f.videoId)})})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(oa,{className:"h-5 w-5"}),"Attribution Insights",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"AI-generated insights analyzing patterns in your YouTube-to-website attribution data. Updated when the dashboard loads with fresh data."})})]})]}),e.jsx(Oe,{children:"AI-powered analysis of your YouTube marketing"})]}),e.jsx(T,{children:G?e.jsx("div",{className:"space-y-4","data-testid":"skeleton-loading",children:[1,2,3].map(f=>e.jsx(cs,{className:"h-24 w-full"},f))}):!(b!=null&&b.insights)||b.insights.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(oa,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No insights available yet."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Insights will appear as more data is collected."})]}):e.jsx("div",{className:"space-y-4","data-testid":"list-insights",children:b.insights.map((f,R)=>{const O=w4(f.significance);return e.jsx("div",{className:"p-4 rounded-lg border bg-card","data-testid":`insight-item-${R}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[N4(f.type),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h4",{className:"font-semibold",children:f.title}),e.jsx(Y,{variant:O.variant,className:O.className,children:f.significance})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:f.description}),e.jsxs("p",{className:"text-xs text-muted-foreground italic",children:["ð¡ ",f.recommendation]})]})]})},R)})})})]})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(Zs,{className:"h-5 w-5"}),"Period Totals",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Aggregated totals for the selected time period. YouTube metrics from YouTube Analytics API; site metrics from our analytics database."})})]})]}),e.jsx(Oe,{children:"Aggregated metrics for the selected time range"})]}),e.jsx(T,{children:G?e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4","data-testid":"skeleton-loading",children:[1,2,3,4,5].map(f=>e.jsx(cs,{className:"h-20"},f))}):b!=null&&b.totals?e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4","data-testid":"section-totals-summary",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"text-center p-4 rounded-lg bg-info-surface dark:bg-blue-950 cursor-help",children:[e.jsx(Hs,{className:"h-6 w-6 text-blue-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:rt(b.totals.views)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Views"})]})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsx("p",{className:"font-medium",children:"YouTube Channel Views"}),e.jsx("p",{className:"text-xs mt-1",children:"Source: YouTube Analytics API. Total views across all videos on your channel during the selected period."})]})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"text-center p-4 rounded-lg bg-amber-50 dark:bg-amber-950 cursor-help",children:[e.jsx(ct,{className:"h-6 w-6 text-amber-600 mx-auto mb-2"}),e.jsxs("p",{className:"text-2xl font-bold text-amber-600",children:["$",rt(b.totals.totalSpend)]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Spend"}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 space-y-0.5",children:[e.jsxs("p",{children:["YT Promo: $",(b.totals.youtubePromotionSpend||0).toLocaleStr
80ing(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("p",{children:["Google Ads: $",(b.totals.googleAdsSpend||0).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]})]})]})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsx("p",{className:"font-medium",children:"Combined Ad Spend"}),e.jsxs("p",{className:"text-xs mt-1",children:[e.jsx("strong",{children:"YT Promo:"})," Manual snapshot data from your YouTube promotion campaigns."]}),e.jsxs("p",{className:"text-xs mt-1",children:[e.jsx("strong",{children:"Google Ads:"})," PMax and other campaigns via Google Ads API."]})]})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"text-center p-4 rounded-lg bg-green-50 dark:bg-green-950 cursor-help",children:[e.jsx(dc,{className:"h-6 w-6 text-green-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:rt(b.totals.websiteVisits)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Website Visits"})]})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsx("p",{className:"font-medium",children:"All Website Visits"}),e.jsx("p",{className:"text-xs mt-1",children:"Source: Site analytics database. Total visits from all sources (not just YouTube)."}),e.jsx("p",{className:"text-xs mt-1 text-amber-600",children:"â ï¸ To attribute visits to specific campaigns, add UTM parameters to your video description links."})]})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"text-center p-4 rounded-lg bg-purple-50 dark:bg-purple-950 cursor-help",children:[e.jsx(Ys,{className:"h-6 w-6 text-purple-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-purple-600",children:rt(b.totals.signups)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Signups"})]})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsx("p",{className:"font-medium",children:"Completed Signups"}),e.jsx("p",{className:"text-xs mt-1",children:"Source: Conversion events database. Users who completed registration."}),e.jsx("p",{className:"text-xs mt-1 text-amber-600",children:"â ï¸ To attribute signups to YouTube vs PMax, use distinct UTM params for each channel."})]})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("div",{className:"text-center p-4 rounded-lg bg-red-50 dark:bg-red-950 cursor-help",children:[e.jsx(lt,{className:"h-6 w-6 text-red-600 mx-auto mb-2"}),e.jsx("p",{className:"text-2xl font-bold text-red-600",children:rt(b.totals.conversions)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Conversions"})]})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsx("p",{className:"font-medium",children:"Signup Conversions"}),e.jsx("p",{className:"text-xs mt-1",children:"Source: Conversion events database. Currently equals signups."}),e.jsx("p",{className:"text-xs mt-1",children:"Future: Can track activations, paid subscriptions, etc."})]})]})]}):e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-muted-foreground",children:"No totals available."})})})]}),e.jsx(b4,{})]}),e.jsx(Vs,{open:!!a,onOpenChange:f=>!f&&n(null),children:e.jsxs(Us,{className:"max-w-2xl","data-testid":"dialog-video-detail",children:[e.jsxs(Bs,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"h-5 w-5 text-red-600"}),a==null?void 0:a.videoTitle]}),e.jsx(Ct,{children:"Detailed performance analysis for this video"})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("a",{href:`https://www.youtube.com/watch?v=${a==null?void 0:a.videoId}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm","data-testid":"link-watch-youtube",children:["Watch on YouTube ",e.jsx(yt,{className:"h-4 w-4"})]}),e.jsxs("a",{href:`https://studio.youtube.com/video/${a==null?void 0:a.videoId}/analytics`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-900 transition-colors text-sm","data-testid":"link-youtube-studio",children:["View in YouTube Studio ",e.jsx(yt,{className:"h-4 w-4"})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold mb-3",children:"YouTube Metrics"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Views"}),e.jsx("p",{className:"text-2xl font-bold",children:a?rt(a.metrics.views):"-"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Likes"}),e.jsx("p",{className:"text-2xl font-bold",children:a?rt(a.metrics.likes):"-"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Watch Time"}),e.jsxs("p",{className:"text-2xl font-bold",children:[a?rt(a.metrics.estimatedMinutesWatched):"-","m"]})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Subscribers Gained"}),e.jsx("p",{className:"text-2xl font-bold",children:a?rt(a.metrics.subscribersGained):"-"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Comments"}),e.jsx("p",{className:"text-2xl font-bold",children:a?rt(a.metrics.comments):"-"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shares"}),e.jsx("p",{className:"text-2xl font-bold",children:a?rt(a.metrics.shares):"-"})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("h4",{className:"font-semibold",children:"Direct
80Clicks (UTM Tracked)"}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Actual clicks from your video's description links with UTM tracking. Add ?utm_source=youtube&utm_content=video-slug to your description links to track."})})]})]}),a!=null&&a.utmTracking?e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-info-surface dark:bg-blue-950",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link Clicks"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:a.utmTracking.clicks.toLocaleString()}),a.utmTracking.utmContent&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["utm_content: ",a.utmTracking.utmContent]})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-info-surface dark:bg-blue-950",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signups from Clicks"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:a.utmTracking.signups.toLocaleString()})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-info-surface dark:bg-blue-950 border-2 border-dashed border-info-border dark:border-blue-800",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link Clicks"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:"â"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Add UTM links to track"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-info-surface dark:bg-blue-950 border-2 border-dashed border-info-border dark:border-blue-800",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signups from Clicks"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:"â"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Add UTM links to track"})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("h4",{className:"font-semibold",children:"Estimated Website Impact"}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Time-based estimate: ALL website visits during the 7 days after this video was published. Not actual tracked clicks from this video."})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-green-50/50 dark:bg-green-950/50 border border-dashed",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"~Website Visits (7-day window)"}),e.jsxs("p",{className:"text-2xl font-bold text-green-600/70",children:["~",((y=a==null?void 0:a.siteImpact.websiteVisits)==null?void 0:y.toLocaleString())??"-"]})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-purple-50/50 dark:bg-purple-950/50 border border-dashed",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"~Signups (7-day window)"}),e.jsxs("p",{className:"text-2xl font-bold text-purple-600/70",children:["~",(a==null?void 0:a.siteImpact.signups)??"-"]})]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold mb-3",children:"Correlation Analysis"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 rounded-lg border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Views â Visits Correlation"}),e.jsxs("p",{className:`text-2xl font-bold ${a?Tn(a.correlation.viewsToVisitsCorr):""}`,children:[a?(a.correlation.viewsToVisitsCorr*100).toFixed(0):"-","%"]})]}),e.jsxs("div",{className:"p-4 rounded-lg border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Views â Signups Correlation"}),e.jsxs("p",{className:`text-2xl font-bold ${a?Tn(a.correlation.viewsToSignupsCorr):""}`,children:[a?(a.correlation.viewsToSignupsCorr*100).toFixed(0):"-","%"]})]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Published ",(a==null?void 0:a.daysOnline)??"-"," days ago"]})]})]})})]})}const S4=Uc({title:st().min(1,"Title required").max(120,"Title must be 120 characters or less"),occurredAt:st().min(1,"Date required"),description:st().optional()});function A4({onSuccess:s}){const[t,a]=p.useState(!1),{toast:n}=ya(),i=lc({resolver:cc(S4),defaultValues:{title:"",occurredAt:De(ne
80w Date,"yyyy-MM-dd'T'HH:mm"),description:""}}),r=ws({mutationFn:async c=>{const o={title:c.title,occurredAt:new Date(c.occurredAt).toISOString(),description:c.description||void 0};return vs("POST","/api/marketing/annotations",o)},onSuccess:()=>{n({title:"Annotation added",description:"Your timeline annotation has been created successfully."}),i.reset({title:"",occurredAt:De(new Date,"yyyy-MM-dd'T'HH:mm"),description:""}),Ts.invalidateQueries({queryKey:["/api/marketing/annotations"]}),s==null||s()},onError:c=>{n({title:"Failed to add annotation",description:c.message||"An error occurred while creating the annotation.",variant:"destructive"})}}),l=c=>{r.mutate(c)};return e.jsx(Ri,{open:t,onOpenChange:a,children:e.jsxs(_,{className:"border-amber-200 bg-amber-50/50 dark:bg-amber-950/20 dark:border-amber-800","data-testid":"card-annotation-form",children:[e.jsx(Li,{asChild:!0,children:e.jsx(q,{className:"cursor-pointer hover:bg-amber-100/50 dark:hover:bg-amber-900/30 transition-colors py-3",children:e.jsxs(W,{className:"flex items-center justify-between text-base",children:[e.jsxs("span",{className:"flex items-center gap-2 text-amber-800 dark:text-amber-200",children:[e.jsx(cm,{className:"h-4 w-4"}),"ð Add Timeline Annotation"]}),t?e.jsx(Mr,{className:"h-4 w-4 text-amber-600"}):e.jsx(Tt,{className:"h-4 w-4 text-amber-600"})]})})}),e.jsx($i,{children:e.jsx(T,{className:"pt-0",children:e.jsx(oc,{...i,children:e.jsxs("form",{onSubmit:i.handleSubmit(l),className:"space-y-4",children:[e.jsx(Ms,{control:i.control,name:"title",render:({field:c})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Title *"}),e.jsx(Ks,{children:e.jsx(Me,{placeholder:"e.g., New video published, Campaign launched",maxLength:120,"data-testid":"input-annotation-title",...c})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:i.control,name:"occurredAt",render:({field:c})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Date & Time *"}),e.jsx(Ks,{children:e.jsx(Me,{type:"datetime-local","data-testid":"input-annotation-datetime",...c})}),e.jsx($s,{})]})}),e.jsx(Ms,{control:i.control,name:"description",render:({field:c})=>e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Description (optional)"}),e.jsx(Ks,{children:e.jsx(La,{placeholder:"Additional notes about this event...",rows:3,"data-testid":"input-annotation-description",...c})}),e.jsx($s,{})]})}),e.jsx(ee,{type:"submit",disabled:r.isPending,className:"w-full bg-amber-600 hover:bg-amber-700 text-white","data-testid":"btn-add-annotation",children:r.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):"Add Annotation"})]})})})})]})})}function rm({value:s,onChange:t}){const a=[{label:"Last 7 days",days:7},{label:"Last 30 days",days:30},{label:"Last 90 days",days:90},{label:"Last 6 months",days:180},{label:"Last year",days:365}];return e.jsxs(os,{value:String(s),onValueChange:n=>t(Number(n)),children:[e.jsx(ds,{className:"w-[180px]","data-testid":"select-timeline-range",children:e.jsx(hs,{placeholder:"Select time range"})}),e.jsx(ms,{children:a.map(n=>e.jsx(me,{value:String(n.days),"data-testid":`timeline-option-${n.days}d`,children:n.label},n.days))})]})}function xa(s){return s.toLocaleString()}function _4({annotations:s,startDate:t,endDate:a,highlightedAnnotationDate:n,onAnnotationHover:i}){const[r,l]=p.useState("cards"),[c,o]=p.useState(!1),[d,u]=p.useState(null),[x,m]=p.useState(""),[v,g]=p.useState(""),[w,k]=p.useState(""),b=Ya(),{toast:S}=ya(),A=ws({mutationFn:async G=>vs("DELETE",`/api/marketing/annotations/${G}`),onSuccess:()=>{S({title:"Annotation deleted",description:"The annotation has been removed."}),b.invalidateQueries({queryKey:["/api/marketing/annotations"]})},onError:G=>{S({title:"Failed to delete",description:G.message,variant:"destructive"})}}),F=ws({mutationFn:async({id:G,data:D})=>vs("PATCH",`/api/marketing/annotations/${G}`,D),onSuccess:()=>{S({title:"Annotation updated",description:"Your changes have been saved."}),b.invalidateQueries({queryKey:["/api/marketing/annotations"]}),u(null)},onError:G=>{S({title:"Failed to update",description:G.message,variant:"destructive"})}}),de=G=>{u(G),m(G.title),g(G.description||""),k(De(new Date(G.occurredAt),"yyyy-MM-dd'T'HH:mm"))},M=()=>{d&&F.mutate({id:d.id,data:{title:x,description:v||null,occurredAt:new Date(w).toISOString()}})};return!s||s.length===0?null:e.jsxs(Ri,{open:c,onOpenChange:o,children:[e.jsxs(_,{className:"border-amber-200 dark:border-amber-800",children:[e.jsx(Li,{asChild:!0,children:e.jsx(q,{className:"cursor-pointer hover:bg-amber-50/50 dark:hover:bg-amber-900/20 transition-colors py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cm,{className:"h-4 w-4 text-amber-600"}),e.jsxs(W,{className:"text-base text-amber-700 dark:text-amber-400",children:["Timeline Annotations (",s.length,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsxs("div",{className:"flex border rounded overflow-hidden mr-2",onClick:G=>G.stopPropagation(),children:[e.jsx(ee,{variant:r==="cards"?"default":"ghost",size:"sm",className:"rounded-none h-7 px-2",onClick:()=>l("cards"),"data-testid":"btn-annotation-cards-view",children:e.jsx(Lm,{className:"h-3 w-3"})}),e.jsx(ee,{variant:r==="table"?"default":"ghost",size:"sm",className:"rounded-none h-7 px-2",onClick:()=>l("table"),"data-testid":"btn-annotation-table-view",children:e.jsx($m,{className:"h-3 w-3"})})]}),c?e.jsx(Mr,{className:"h-4 w-4"}):e.jsx(Tt,{className:"h-4 w-4"})]})]})})}),e.jsx($i,{children:e.jsx(T,{className:"pt-0",children:r==="cards"?e.jsx(Ta,{type:"multiple",className:"space-y-2",children:s.map(G=>{const D=De(new Date(G.occurredAt),"yyyy-MM-dd"),$=n===D;return e.jsxs(Da,{value:String(G.id),className:`border rounded-lg px-3 transition-all duration-200 ${$?"bg-amber-200/70 dark:bg-amber-700/40 border-amber-400 dark:border-amber-500 ring-2 ring-amber-400/50 shadow-md":"bg-amber-50/30 dark:bg-amber-900/10"}`,"data-testid":`annotation-card-${G.id}`,onMouseEnter:()=>i(D),onMouseLeave:()=>i(null),children:[e.jsx(Pa,{className:"hover:no-underline py-2",children:e.jsxs("div",{className:"flex items-center gap-3 text-left",children:[e.jsx("span",{className:"text-amber-600",children:"ð"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:G.title}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"}),De(new Date(G.occurredAt),"MMM d, yyyy 'at' h:mm a")]})]})]})}),e.jsx(Ma,{children:e.jsxs("div",{className:"pb-2 pl-8",children:[G.description?e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:G.description}):e.jsx("p",{className:"text-sm text-muted-foreground italic mb-3",children:"No description"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ee,{variant:"ghost",size:"sm",className:"text-blue-600 hover:text-info-ink-soft hover:bg-info-surface h-7 px-2",onClick:()=>de(G),"data-testid":`btn-edit-annotation-${G.id}`,children:[e.jsx(gi,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(ee,{variant:"ghost",size:"sm",className:"text-red-600 hover:text-red-700 hover:bg-red-50 h-7 px-2",onClick:()=>A.mutate(G.id),disabled:A.isPending,"data-testid":`btn-delete-annotation-${G.id}`,children:[e.jsx(xi,{className:"h-3 w-3 mr-1"}),"Delete"]})]})]})})]},G.id)})}):e.jsxs(nn,{children:[e.jsx(rn,{children:e.jsxs(ht,{children:[e.jsx(fs,{className:"w-[200px]",children:"Date"}),e.jsx(fs,{children:"Title"}),e.jsx(fs,{className:"hidden md:table-cell",children:"Description"}),e.jsx(fs,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(ln,{children:s.map(G=>{const D=De(new Date(G.occurredAt),"yyyy-MM-dd"),$=n===D;return e.jsxs(ht,{"data-testid":`annotation-row-${G.id}`,className:`transition-all duration-200 ${$?"bg-amber-200/70 dark:bg-amber-700/40":""}`,onMouseEnter:()=>i(D),onMouseLeave:()=>i(null),children:[e.jsx(Ke,{className:"text-sm",children:De(new Date(G.occurredAt),"MMM d, yyyy h:mm a")}),e.jsxs(Ke,{className:"font-medium",children:[e.jsx("span",{className:"mr-1",children:"ð"}),G.title]}),e.jsx(Ke,{className:"hidden md:table-cell text-muted-foreground text-sm",children:G.description||e.jsx("span",{className:"italic",children:"-"})}),e.jsx(Ke,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(ee,{variant:"ghost",size:"sm",className:"text-blue-600 hover:text-info-ink-soft hover:bg-info-surface h-7 w-7 p-0",onClick:()=>de(G),"data-testid":`btn-edit-annotation-table-${G.id}`,children:e.jsx(gi,{className:"h-3 w-3"})}),e.jsx(ee,{variant:"ghost",size:"sm",className:"text-red-600 hover:text-red-700 hover:bg-red-50 h-7 w-7 p-0",onClick:()=>A.mutate(G.id),disabled:A.isPending,"data-testid":`btn-delete-annotation-table-${G.id}`,children:e.jsx(xi,{className:"h-3 w-3"})})]})})]},G.id)})})]})})})]}),e.jsx(Vs,{open:!!d,onOpenChange:G=>!G&&u(null),children:e.jsxs(Us,{className:"sm:max-w-[425px]",children:[e.jsx(Bs,{children:e.jsx(zs,{children:"Edit Annotation"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{htmlFor:"edit-title",children:"Title *"}),e.jsx(Me,{id:"edit-title",value:x,onChange:G=>m(G.target.value),placeholder:"Annotation title",maxLength:200,"data-testid":"input-edit-annotation-title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{htmlFor:"edit-datetime",children:"Date & Time *"}),e.jsx(Me,{id:"edit-datetime",type:"datetime-local",value:w,onChange:G=>k(G.target.value),"data-testid":"input-edit-annotation-datetime"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ue,{htmlFor:"edit-description",children:"Description (optional)"}
80),e.jsx(La,{id:"edit-description",value:v,onChange:G=>g(G.target.value),placeholder:"Additional notes...",rows:3,"data-testid":"input-edit-annotation-description"})]})]}),e.jsxs(Ut,{children:[e.jsx(ee,{variant:"outline",onClick:()=>u(null),"data-testid":"btn-cancel-edit-annotation",children:"Cancel"}),e.jsx(ee,{onClick:M,disabled:F.isPending||!x.trim(),className:"bg-amber-600 hover:bg-amber-700","data-testid":"btn-save-edit-annotation",children:F.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})}const im={views:1,visits:1,signups:1,spend:1,googleAdsSpend:1,googleAdsClicks:1,blogViews:1},T4=[{value:.001,label:"÷1000"},{value:.01,label:"÷100"},{value:.1,label:"÷10"},{value:1,label:"1x"},{value:10,label:"Ã10"},{value:100,label:"Ã100"},{value:1e3,label:"Ã1000"}];function D4({showHeader:s=!0,defaultTimeRange:t=30}){const[a,n]=p.useState(t),[i,r]=p.useState("absolute"),[l,c]=p.useState(!1),[o,d]=p.useState(im),[u,x]=p.useState(null),m=()=>d(im),v=Object.values(o).some(C=>C!==1),g=De(new Date,"yyyy-MM-dd"),w=De(vt(new Date,a),"yyyy-MM-dd"),{data:k,isLoading:b,isError:S}=_e({queryKey:["/api/marketing/youtube-correlation/daily",{startDate:w,endDate:g}]}),{data:A}=_e({queryKey:["/api/marketing/annotations",{startDate:w,endDate:g}]}),F=b,de=S,M=k&&k.length>0,G=(k==null?void 0:k.map(C=>{var I,y,f;return{date:De(new Date(C.date+"T12:00:00"),"MMM d"),fullDate:C.date,views:C.youtube.totalViews,visits:C.site.websiteVisits,signups:C.site.signupsCompleted,spend:C.spend.youtubePromotion,googleAdsSpend:((I=C.googleAds)==null?void 0:I.spend)||0,googleAdsClicks:((y=C.googleAds)==null?void 0:y.clicks)||0,blogViews:((f=C.blog)==null?void 0:f.totalPageViews)||0,totalSpend:C.spend.totalSpend,newVideo:C.newVideoPublished,newBlog:C.newBlogPublished}}))||[],D=G.reduce((C,I)=>({views:Math.max(C.views,I.views||0),visits:Math.max(C.visits,I.visits||0),signups:Math.max(C.signups,I.signups||0),spend:Math.max(C.spend,I.spend||0),googleAdsSpend:Math.max(C.googleAdsSpend,I.googleAdsSpend||0),googleAdsClicks:Math.max(C.googleAdsClicks,I.googleAdsClicks||0),blogViews:Math.max(C.blogViews,I.blogViews||0)}),{views:0,visits:0,signups:0,spend:0,googleAdsSpend:0,googleAdsClicks:0,blogViews:0}),$=(C,I)=>I>0?C/I*100:0,se=G.map(C=>{let I=i==="relative"?$(C.views,D.views):C.views,y=i==="relative"?$(C.visits,D.visits):C.visits,f=i==="relative"?$(C.signups,D.signups):C.signups,R=i==="relative"?$(C.spend,D.spend):C.spend,O=i==="relative"?$(C.googleAdsSpend,D.googleAdsSpend):C.googleAdsSpend,N=i==="relative"?$(C.googleAdsClicks,D.googleAdsClicks):C.googleAdsClicks,re=i==="relative"?$(C.blogViews,D.blogViews):C.blogViews;i==="absolute"&&(I*=o.views,y*=o.visits,f*=o.signups,R*=o.spend,O*=o.googleAdsSpend,N*=o.googleAdsClicks,re*=o.blogViews);const H=(A==null?void 0:A.filter(pe=>De(new Date(pe.occurredAt),"yyyy-MM-dd")===C.fullDate))||[];return{...C,rawViews:C.views,rawVisits:C.visits,rawSignups:C.signups,rawSpend:C.spend,rawGoogleAdsSpend:C.googleAdsSpend,rawGoogleAdsClicks:C.googleAdsClicks,rawBlogViews:C.blogViews,views:I,visits:y,signups:f,spend:R,googleAdsSpend:O,googleAdsClicks:N,blogViews:re,annotations:H}}),J=se.filter(C=>C.newVideo).map(C=>{var I;return{date:C.date,title:((I=C.newVideo)==null?void 0:I.videoTitle)||"New Video"}}),le=se.filter(C=>C.newBlog).map(C=>{var I;return{date:C.date,title:((I=C.newBlog)==null?void 0:I.title)||"New Article"}});return de?e.jsx(_,{"data-testid":"error-timeline-unavailable",children:e.jsxs(q,{children:[e.jsx(W,{className:"text-red-600",children:"Timeline Data Unavailable"}),e.jsx(Oe,{children:"Unable to fetch activity timeline data. Please try again later."})]})}):e.jsx(xs,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(A4,{}),e.jsx(_4,{annotations:A,startDate:w,endDate:g,highlightedAnnotationDate:u,onAnnotationHover:x}),e.jsxs(_,{children:[s&&e.jsxs("div",{className:"flex items-center justify-between px-6 pt-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2","data-testid":"heading-activity-timeline",children:[e.jsx(Zs,{className:"h-5 w-5"}),"YouTube & Website Activity Timeline"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Track how YouTube views, promotion spend, and website activity correlate over time"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:[e.jsx(bs,{className:"h-3 w-3"}),"YouTube Analytics API has a 2-3 day data delay. Recent days may not show data yet."]})]}),e.jsx(rm,{value:a,onChange:n})]}),e.jsxs(q,{className:s?"pt-4":"",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[!s&&e.jsxs(W,{className:"flex items-center gap-2",children:[e.jsx(Zs,{className:"h-5 w-5"}),"YouTube & Website Activity Timeline"]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-4 w-4 text-muted-foreground cursor-help"})}),e.jsxs(Ae,{className:"max-w-xs",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Absolute:"})," Shows actual values (views, visits, dollars)"]}),e.jsxs("p",{className:"mt-1",children:[e.jsx("strong",{children:"Relative:"})," Shows each metric as 0-100% of its maximum, making trends easier to compare across different scales"]})]})]}),e.jsxs("div",{className:"flex rounded-lg border overflow-hidden",children:[e.jsx(ee,{variant:i==="absolute"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-3",onClick:()=>r("absolute"),"data-testid":"btn-timeline-absolute",children:"Absolute"}),e.jsx(ee,{variant:i==="relative"?"default":"ghost",size:"sm",className:"rounded-none h-8 px-3",onClick:()=>r("relative"),"data-testid":"btn-timeline-relative",children:"Relative"})]}),!s&&e.jsx(rm,{value:a,onChange:n})]})]}),!s&&e.jsxs(Oe,{className:"flex items-center gap-4",children:[e.jsx("span",{children:"Track how YouTube views, promotion spend, and website activity correlate over time"}),i==="absolute"?e.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-1 cursor-help text-blue-600",children:[e.jsx(bs,{className:"h-3 w-3"}),"Left axis"]})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"YouTube views from your channel analytics, updated daily via YouTube Analytics API"})})]}),e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-1 cursor-help text-green-600",children:[e.jsx(bs,{className:"h-3 w-3"}),"Right axis"]})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Website metrics from our analytics: visits (all traffic), signups (completed registrations), and promotion spend (manually tracked)"})})]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"All metrics shown as % of their maximum value (hover for actual numbers)"})]}),i==="absolute"&&e.jsxs(Ri,{open:l,onOpenChange:c,className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Li,{asChild:!0,children:e.jsxs(ee,{variant:"ghost",size:"sm",className:"gap-1 h-7 px-2",children:[e.jsx(Om,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs",children:"Scale Controls"}),l?e.jsx(Mr,{className:"h-3 w-3"}):e.jsx(Tt,{className:"h-3 w-3"})]})}),v&&e.jsxs(ee,{variant:"ghost",size:"sm",onClick:m,className:"gap-1 h-7 px-2 text-muted-foreground hover:text-foreground",children:[e.jsx(hi,{className:"h-3 w-3"}),e.jsx("span",{className:"text-xs",children:"Reset"})]}),v&&e.jsxs("span",{className:"text-xs text-amber-600 flex items-center gap-1",children:[e.jsx(bs,{className:"h-3 w-3"}),"Custom scales applied - hover chart for actual values"]})]}),e.jsx($i,{children:e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-3 mt-2 p-3 bg-muted/50 rounded-lg",children:[{key:"views",label:"YouTube Views (L)",color:"text-red-600"},{key:"visits",label:"Website Visits (R)",color:"text-green-600"},{key:"signups",label:"Signups (R)",color:"text-purple-600"}
80,{key:"spend",label:"YT Spend (R)",color:"text-orange-500"},{key:"googleAdsSpend",label:"Google Ads $ (R)",color:"text-blue-600"},{key:"googleAdsClicks",label:"Ad Clicks (R)",color:"text-cyan-600"},{key:"blogViews",label:"Blog Views (R)",color:"text-teal-600"}].map(({key:C,label:I,color:y})=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:`text-xs font-medium ${y}`,children:I}),e.jsxs(os,{value:String(o[C]),onValueChange:f=>d(R=>({...R,[C]:parseFloat(f)})),children:[e.jsx(ds,{className:"h-7 text-xs",children:e.jsx(hs,{})}),e.jsx(ms,{children:T4.map(f=>e.jsx(me,{value:String(f.value),children:f.label},f.value))})]})]},C))})})]})]}),e.jsx(T,{children:F?e.jsx(cs,{className:"h-[400px] w-full","data-testid":"skeleton-timeline-loading"}):M?e.jsx("div",{className:"h-[400px]","data-testid":"chart-container-timeline",children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(nu,{data:se,onMouseMove:C=>{if(C&&C.activePayload&&C.activePayload[0]){const I=C.activePayload[0].payload;I.annotations&&I.annotations.length>0?x(I.fullDate):x(null)}},onMouseLeave:()=>x(null),children:[e.jsx(Jt,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Bt,{dataKey:"date",tick:{fontSize:12},tickLine:!1}),i==="absolute"?e.jsxs(e.Fragment,{children:[e.jsx(at,{yAxisId:"left",orientation:"left",tick:{fontSize:12},tickFormatter:C=>xa(C),label:{value:"Views",angle:-90,position:"insideLeft"}}),e.jsx(at,{yAxisId:"right",orientation:"right",tick:{fontSize:12},tickFormatter:C=>xa(C),label:{value:"Visits/Signups/Spend/Clicks",angle:90,position:"insideRight"}})]}):e.jsxs(e.Fragment,{children:[e.jsx(at,{yAxisId:"left",orientation:"left",tick:{fontSize:12},domain:[0,100],tickFormatter:C=>`${C}%`,label:{value:"% of Max",angle:-90,position:"insideLeft"}}),e.jsx(at,{yAxisId:"right",orientation:"right",tick:{fontSize:12},domain:[0,100],tickFormatter:C=>`${C}%`,label:{value:"% of Max",angle:90,position:"insideRight"}})]}),e.jsx(gt,{content:({active:C,payload:I,label:y})=>{var R,O;if(!C||!(I!=null&&I.length))return null;const f=(R=I[0])==null?void 0:R.payload;return e.jsxs("div",{className:"bg-background border rounded-lg shadow-lg p-3 space-y-1",children:[e.jsx("p",{className:"font-medium",children:y}),i==="relative"?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-red-600",children:["Views (L): ",xa((f==null?void 0:f.rawViews)||0)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((f==null?void 0:f.views)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-green-600",children:["Visits (R): ",xa((f==null?void 0:f.rawVisits)||0)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((f==null?void 0:f.visits)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-purple-600",children:["Signups (R): ",((f==null?void 0:f.rawSignups)||0).toLocaleString()," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((f==null?void 0:f.signups)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-orange-500",children:["YouTube Spend (R): $",((f==null?void 0:f.rawSpend)||0).toFixed(2)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((f==null?void 0:f.spend)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-blue-600",children:["Google Ads (R): $",((f==null?void 0:f.rawGoogleAdsSpend)||0).toFixed(2)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((f==null?void 0:f.googleAdsSpend)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-cyan-600",children:["Ad Clicks (R): ",xa((f==null?void 0:f.rawGoogleAdsClicks)||0)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((f==null?void 0:f.googleAdsClicks)||0).toFixed(0),"%)"]})]}),e.jsxs("p",{className:"text-teal-600",children:["Blog Views (R): ",xa((f==null?void 0:f.rawBlogViews)||0)," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",((f==null?void 0:f.blogViews)||0).toFixed(0),"%)"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-red-600",children:["Views (L): ",xa((f==null?void 0:f.rawViews)||(f==null?void 0:f.views)||0)]}),e.jsxs("p",{className:"text-green-600",children:["Visits (R): ",xa((f==null?void 0:f.rawVisits)||(f==null?void 0:f.visits)||0)]}),e.jsxs("p",{className:"text-purple-600",children:["Signups (R): ",((f==null?void 0:f.rawSignups)||(f==null?void 0:f.signups)||0).toLocaleStr
80ing()]}),e.jsxs("p",{className:"text-orange-500",children:["YouTube Spend (R): $",((f==null?void 0:f.rawSpend)||(f==null?void 0:f.spend)||0).toFixed(2)]}),e.jsxs("p",{className:"text-blue-600",children:["Google Ads (R): $",((f==null?void 0:f.rawGoogleAdsSpend)||(f==null?void 0:f.googleAdsSpend)||0).toFixed(2)]}),e.jsxs("p",{className:"text-cyan-600",children:["Ad Clicks (R): ",xa((f==null?void 0:f.rawGoogleAdsClicks)||(f==null?void 0:f.googleAdsClicks)||0)]}),e.jsxs("p",{className:"text-teal-600",children:["Blog Views (R): ",xa((f==null?void 0:f.rawBlogViews)||(f==null?void 0:f.blogViews)||0)]})]}),(f==null?void 0:f.newVideo)&&e.jsxs("p",{className:"text-red-600 font-medium mt-2",children:["ð¹ New: ",f.newVideo.videoTitle]}),(f==null?void 0:f.newBlog)&&e.jsxs("p",{className:"text-blue-600 font-medium mt-2",children:["ð New: ",f.newBlog.title]}),((O=f==null?void 0:f.annotations)==null?void 0:O.length)>0&&e.jsx("div",{className:"border-t border-amber-300 mt-2 pt-2 space-y-2",children:f.annotations.map((N,re)=>e.jsxs("div",{children:[e.jsxs("p",{className:"text-amber-600 font-medium flex items-center gap-1",children:["ð ",N.title]}),N.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:N.description})]},re))})]})}}),e.jsx(On,{}),e.jsx(In,{yAxisId:"left",type:"monotone",dataKey:"views",fill:"#dc2626",fillOpacity:.3,stroke:"#dc2626",strokeWidth:2,name:"YouTube Views (L)"}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"visits",stroke:"#22c55e",strokeWidth:2,dot:!1,name:"Website Visits (R)"}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"signups",stroke:"#a855f7",strokeWidth:2,dot:!1,name:"Signups (R)"}),e.jsx(Zt,{yAxisId:"right",dataKey:"spend",fill:"#f97316",opacity:.8,name:"YouTube Spend $ (R)",stackId:"spend"}),e.jsx(Zt,{yAxisId:"right",dataKey:"googleAdsSpend",fill:"#2563eb",opacity:.8,name:"Google Ads $ (R)",stackId:"spend"}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"googleAdsClicks",stroke:"#06b6d4",strokeWidth:2,strokeDasharray:"5 5",dot:!1,name:"Ad Clicks (R)"}),e.jsx(Vt,{yAxisId:"right",type:"monotone",dataKey:"blogViews",stroke:"#14b8a6",strokeWidth:2,strokeDasharray:"3 3",dot:!1,name:"Blog Views (R)"}),J.map((C,I)=>e.jsx(ir,{x:C.date,yAxisId:"left",stroke:"#ef4444",strokeDasharray:"5 5",label:{value:"ð¹",position:"top",fontSize:14}},`video-${I}`)),le.map((C,I)=>e.jsx(ir,{x:C.date,yAxisId:"left",stroke:"#2563eb",strokeDasharray:"5 5",label:{value:"ð",position:"top",fontSize:14}},`blog-${I}`)),se.filter(C=>C.annotations&&C.annotations.length>0).map(C=>{const I=u===C.fullDate;return e.jsx(ir,{x:C.date,yAxisId:"left",stroke:I?"#d97706":"#f59e0b",strokeWidth:I?4:2,strokeDasharray:I?"none":"4 4",label:{value:C.annotations.length>1?`ð${C.annotations.length}`:"ð",position:"top",fill:I?"#d97706":"#f59e0b",fontSize:I?18:14,fontWeight:I?"bold":"normal"},style:{filter:I?"drop-shadow(0 0 6px rgba(217, 119, 6, 0.6))":"none",transition:"all 0.2s ease-in-out"}},`annotation-${C.fullDate}`)})]},`chart-${i}`)})}):e.jsx("div",{className:"h-[400px] flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ji,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No YouTube correlation data available for this time range."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Connect your YouTube channel and start tracking performance."})]})})})]})]})})}function P4(){var D,$,se,J,le,C,I,y,f,R,O,N,re,H,pe,ye,Ie,ve,B,z,K,P,ue,V,U,j,Q,je,ce,be,ss,oe,Ne,Le,ae,xe,Fe;const s=Ya(),[t,a]=p.useState(null),{data:n}=_e({queryKey:["/api/exit-blocker/status"]}),{data:i}=_e({queryKey:["/api/exit-blocker/analytics-status"]}),{data:r,isLoading:l,refetch:c}=_e({queryKey:["/api/exit-blocker/analytics"]}),{data:o,isLoading:d}=_e({queryKey:["/api/exit-blocker/conversations"]}),{data:u}=_e({queryKey:["/api/exit-blocker/rage-signals"]}),{data:x}=_e({queryKey:["/api/exit-blocker/analytics/geo"]}),{data:m}=_e({queryKey:["/api/exit-blocker/analytics/traffic"]}),{data:v}=_e({queryKey:["/api/exit-blocker/analytics/devices"]}),{data:g}=_e({queryKey:["/api/exit-blocker/analytics/insights"]}),w=ws({mutationFn:async X=>await vs("POST","/api/exit-blocker/toggle",{enabled:X}),onSuccess:()=>{s.invalidateQueries({queryKey:["/api/exit-blocker/status"]}),s.invalidateQueries({queryKey:["/api/exit-blocker/analytics-status"]}),ta({title:n!=null&&n.enabled?"Exit Blocker Disabled":"Exit Blocker Enabled",description:n!=null&&n.enabled?"The exit intent chat will no longer appear to visitors.":"The exit intent chat is now active on landing pages."})},onError:()=>{ta({title:"Error",description:"Failed to toggle exit blocker status.",variant:"destructive"})}}),k=ws({mutationFn:async X=>await vs("PUT","/api/exit-blocker/analytics-toggle",{enabled:X}),onSuccess:()=>{s.invalidateQueries({queryKey:["/api/exit-blocker/analytics-status"]}),ta({title:i!=null&&i.analyticsEnabled?"Analytics Disabled":"Analytics Enabled",description:i!=null&&i.analyticsEnabled?"Exit blocker analytics collection is now disabled.":"Exit blocker analytics collection is now enabled."})},onError:()=>{ta({title:"Error",description:"Failed to toggle analytics collection.",variant:"destructive"})}}),b=()=>{window.location.href="/api/exit-blocker/export/questions"},S=async()=>
80{if(confirm("Are you sure you want to reset all ad blocker detection data? This cannot be undone."))try{await vs("DELETE","/api/exit-blocker/ad-blocker-detection/reset"),s.invalidateQueries({queryKey:["/api/exit-blocker/analytics"]}),ta({title:"Data Reset",description:"Ad blocker detection data has been cleared."})}catch{ta({title:"Error",description:"Failed to reset ad blocker data.",variant:"destructive"})}},A=async()=>{if(confirm("Are you sure you want to reset all top questions data? This cannot be undone."))try{await vs("DELETE","/api/exit-blocker/questions/reset"),s.invalidateQueries({queryKey:["/api/exit-blocker/analytics"]}),ta({title:"Data Reset",description:"Top questions data has been cleared."})}catch{ta({title:"Error",description:"Failed to reset top questions data.",variant:"destructive"})}},F=X=>{switch(X){case"rapid_clicks":return e.jsx(xp,{className:"h-4 w-4 text-orange-500"});case"repeated_dismiss":return e.jsx(Oo,{className:"h-4 w-4 text-red-500"});case"immediate_close":return e.jsx(oa,{className:"h-4 w-4 text-yellow-500"});case"capslock_yelling":case"expletive":return e.jsx(Fs,{className:"h-4 w-4 text-red-600"});default:return e.jsx(Fs,{className:"h-4 w-4 text-orange-500"})}},de=X=>X>=4?e.jsx(Y,{variant:"destructive",children:"High"}):X>=3?e.jsx(Y,{className:"bg-orange-500",children:"Medium"}):e.jsx(Y,{variant:"secondary",children:"Low"}),M=X=>{switch(X){case"converted":return e.jsx(Y,{className:"bg-green-500",children:"Converted"});case"engaged":return e.jsx(Y,{className:"bg-blue-500",children:"Engaged"});case"dismissed":return e.jsx(Y,{variant:"outline",children:"Dismissed"});case"abandoned":return e.jsx(Y,{variant:"destructive",children:"Abandoned"});default:return e.jsx(Y,{variant:"secondary",children:X})}},G=X=>{switch(X){case"mobile":return e.jsx(Ht,{className:"h-4 w-4"});case"tablet":return e.jsx(Ga,{className:"h-4 w-4"});default:return e.jsx(tt,{className:"h-4 w-4"})}};return l?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(Pt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Exit Blocker Analytics"}),e.jsx("p",{className:"text-muted-foreground",children:"GPT-powered Q&A to reduce bounce rate on landing pages"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(ee,{variant:"outline",size:"sm",onClick:b,"data-testid":"button-export-questions",children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export Questions"]}),e.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>c(),"data-testid":"button-refresh-analytics",children:[e.jsx(Pt,{className:"h-4 w-4 mr-2"}),"Refresh"]}),e.jsxs("div",{className:"flex items-center gap-2 border-l pl-4",children:[e.jsx(Ue,{htmlFor:"analytics-toggle",className:"text-sm",children:"Analytics"}),e.jsx(vr,{id:"analytics-toggle",checked:(i==null?void 0:i.analyticsEnabled)??!0,onCheckedChange:X=>k.mutate(X),disabled:k.isPending,"data-testid":"switch-analytics-toggle"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{htmlFor:"exit-blocker-toggle",className:"text-sm",children:"Exit Blocker"}),e.jsx(vr,{id:"exit-blocker-toggle",checked:(n==null?void 0:n.enabled)??!1,onCheckedChange:X=>w.mutate(X),disabled:w.isPending,"data-testid":"switch-exit-blocker-toggle"})]})]})]}),e.jsx(xs,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-4",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:["Conversations",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Total number of exit-intent chat sessions started. A conversation begins when a visitor triggers the exit blocker and sends their first message."})})]})]})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold","data-testid":"text-total-conversations",children:((D=r==null?void 0:r.summary)==null?void 0:D.totalConversations)??0})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:["Total Messages",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Total messages exchanged across all conversations. Includes both visitor questions and AI responses."})})]})]})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold","data-testid":"text-total-messages",children:(($=r==null?void 0:r.summary)==null?void 0:$.totalMessages)??0})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:["Avg Messages/Chat",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Average number of messages per conversation. Higher numbers indicate deeper engagement with the chat assistant."})})]})]})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold","data-testid":"text-avg-messages",children:((J=(se=r==null?void 0:r.summary)==null?void 0:se.averageMessagesPerConversation)==null?void 0:J.toFixed(1))??"0"})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:["Engagement Rate",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Percentage of visitors who engaged with the exit blocker chat (sent at least one message) out of all visitors who s
80aw it trigger."})})]})]})}),e.jsx(T,{children:e.jsxs("div",{className:"text-2xl font-bold text-blue-600","data-testid":"text-engagement-rate",children:[((C=(le=r==null?void 0:r.summary)==null?void 0:le.engagementRate)==null?void 0:C.toFixed(1))??"0","%"]})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:["Conversion Rate",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Percentage of exit blocker conversations that resulted in a conversion (signup, demo request, or other goal). Calculated from engaged conversations."})})]})]})}),e.jsx(T,{children:e.jsxs("div",{className:"text-2xl font-bold text-green-600","data-testid":"text-conversion-rate",children:[((y=(I=r==null?void 0:r.summary)==null?void 0:I.conversionRate)==null?void 0:y.toFixed(1))??"0","%"]})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:["Suggested Q Ratio",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Percentage of conversations where visitors clicked one of the suggested questions instead of typing their own. Lower ratios indicate more genuine engagement."})})]})]})}),e.jsx(T,{children:e.jsxs("div",{className:"text-2xl font-bold text-indigo-600","data-testid":"text-suggested-ratio",children:[((R=(f=r==null?void 0:r.summary)==null?void 0:f.suggestedQuestionRatio)==null?void 0:R.toFixed(0))??"0","%"]})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:["Rage Signals",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Detected frustration indicators: rapid clicking, repeated dismissals, immediate closes, ALL CAPS typing, or expletives. High counts may indicate UX issues."})})]})]})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold text-red-600","data-testid":"text-rage-signals",children:(u==null?void 0:u.total)??((O=r==null?void 0:r.summary)==null?void 0:O.rageSignalCount)??0})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:["Bounce Reduction",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Estimated reduction in bounce rate due to exit blocker engagement. Calculated from visitors who engaged with the chat instead of leaving immediately."})})]})]})}),e.jsx(T,{children:e.jsxs("div",{className:"text-2xl font-bold text-purple-600","data-testid":"text-bounce-reduction",children:[((((N=r==null?void 0:r.summary)==null?void 0:N.bounceReductionRate)??0)*100).toFixed(1),"%"]})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsxs(W,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(Oo,{className:"h-4 w-4"}),"Ad Blocker Impact",e.jsxs(Ce,{children:[e.jsx(Se,{asChild:!0,children:e.jsx(Cs,{className:"h-3 w-3 cursor-help opacity-50 hover:opacity-100"})}),e.jsx(Ae,{className:"max-w-xs",children:e.jsx("p",{children:"Percentage of visitors with ad blockers that may interfere with the exit blocker. Detected via bait elements and ad network requests. High rates may reduce effectiveness."})})]})]})}),e.jsxs(T,{children:[e.jsxs("div",{className:"text-2xl font-bold text-orange-600","data-testid":"text-ad-blocker-rate",children:[(((re=r==null?void 0:r.adBlockerStats)==null?void 0:re.blockRate)??0).toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[((H=r==null?void 0:r.adBlockerStats)==null?void 0:H.blockedCount)??0," of ",((pe=r==null?void 0:r.adBlockerStats)==null?void 0:pe.totalChecks)??0," visitors affected"]}),((ye=r==null?void 0:r.adBlockerStats)==null?void 0:ye.byMethod)&&Object.keys(r.adBlockerStats.byMethod).length>0&&e.jsxs("div",{className:"mt-2 pt-2 border-t text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Detection methods:"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(r.adBlockerStats.byMethod).map(([X,Be])=>e.jsxs(Y,{variant:"secondary",className:"text-xs",children:[X.replace(/_/g," "),": ",Be]},X))})]}),(((Ie=r==null?void 0:r.adBlockerStats)==null?void 0:Ie.totalChecks)??0)>0&&e.jsxs(ee,{variant:"outline",size:"sm",className:"mt-3 w-full text-xs",onClick:S,"data-testid":"button-reset-ad-blocker",children:[e.jsx(hi,{className:"h-3 w-3 mr-1"}),"Reset Data"]})]})]})]})}),e.jsxs(la,{defaultValue:"overview",className:"space-y-4",children:[e.jsxs(ca,{children:[e.jsxs(Ee,{value:"overview","data-testid":"tab-exit-overview",children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Overview"]}),e.jsxs(Ee,{value:"conversations","data-testid":"tab-exit-conversations",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Conversations"]}),e.jsxs(Ee,{value:"questions","data-testid":"tab-exit-questions",children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Top Questions"]}),e.jsxs(Ee,{value:"rage-signals","data-testid":"tab-exit-rage-signals",children:[e.jsx(Fs,{className:"h-4 w-4 mr-2"}),"Rage Signals",((u==null?void 0:u.total)??0)>0&&e.jsx(Y,{variant:"destructive",className:"ml-2",children:u==null?void 0:u.total})]}),e.jsxs(Ee,{value:"geographic","data-testid":"tab-exit-geographic",children:[e.jsx(ot,{className:"h-4 w-4 mr-2"}),"Geographic"]}),e.jsxs(Ee,{value:"traffic","data-testid":"tab-exit-traffic",children:[e.jsx(Wt,{className:"h-4 w-4 mr-2"}),"Traffic Sources"]}),e.jsxs(Ee,{value:"insights","data-testid":"tab-exit-insights",children:[e.jsx(Qt,{className:"h-4 w-4 mr-2"}),"AI Insights"]})]}),e.jsx(Ve,{value:"overview",className:"space-y-4",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Outcome Distribution"}),e.jsx(Oe,{children:"How visitors interacted with the exit blocker"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ui,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{children:"Converted"})]}),e.jsx("span",{className:"font-semibold",children:((ve=r==null?void 0:r.outcomeBreakdown)==null?void 0:ve.converted)??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{children:"Engaged"})]}),e.jsx("span",{className:"font-semibold",children:((B=r==null?void 0:r.outcomeBreakdown)==null?void 0:B.engaged)??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tn,{className:"h-4 w-4 text-slate-400"}),e.jsx("span",{children:"Dismissed"})]}),e.jsx("span",{className:"font-semibold",children:((z=r==null?void 0:r.outcomeBreakdown)==null?void 0:z.dismissed)??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tn,{className:"h-4 w-4 text-red-500"}),e.jsx("span",{children:"Abandoned"})]}),e.jsx("span",{className:"font-semibold",children:((K=r==null?void 0:r.outcomeBreakdown)==null?void 0:K.abandoned)??0})]})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Device Breakdown"}),e.jsx(Oe,{children:"Exit intent triggers by device type"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4"}),e.jsx("span",{children:"Desktop"})]}),e.jsx("span",{className:"font-semibold",children:((P=r==null?void 0:r.deviceBreakdown)==null?void 0:P.desktop)??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"h-4 w-4"}),e.jsx("span",{children:"Mobile"})]}),e.jsx("span",{className:"font-semibold",children:((ue=r==null?void 0:r.deviceBreakdown)==null?void 0:ue.mobile)??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"}),e.jsx("span",{children:"Tablet"})]}),e.jsx("span",{className:"font-semibold",children:((V=r==null?void 0:r.deviceBreakdown)==null?void 0:V.tablet)??0})]})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Trigger Methods"}),e.jsx(Oe,{children:"How exit intent was detected"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(r==null?void 0:r.triggerMethods)&&Object.entries(r.triggerMethods).map(([X,Be])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm capitalize",children:X.replace(/_/g," ")}),e.jsx(Y,{variant:"secondary",children:Be})]},X)),(!(r!=null&&r.triggerMethods)||Object.keys(r.triggerMethods).length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No trigger data yet"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Conversion Types"}),e.jsx(Oe,{children:"Where users converted after chat"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(r==null?void 0:r.conversionsByType)&&Object.entries(r.conversionsByType).map(([X,Be])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm capitalize",children:X}),e.jsx(Y,{className:"bg-green-500",children:Be})]},X)),(!(r!=null&&r.conversionsByType)||Object.keys(r.conversionsByType).length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No conversions yet"})]})})]})]})}),e.jsx(Ve,{value:"conversations",className:"space-y-4",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Recent
80Conversations"}),e.jsxs(Oe,{children:[(o==null?void 0:o.total)??0," total conversations"]})]}),e.jsx(T,{children:e.jsx(kt,{className:"h-[400px]",children:e.jsxs("div",{className:"space-y-2",children:[o==null?void 0:o.conversations.map(X=>{var Be,ns;return e.jsxs("div",{className:`p-3 rounded-lg border cursor-pointer transition-colors ${(t==null?void 0:t.id)===X.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,onClick:()=>a(X),"data-testid":`conversation-item-${X.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[G(X.deviceType),e.jsxs("span",{className:"text-sm font-medium",children:[X.messageCount," messages"]})]}),M(X.outcome)]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:X.exitPage}),e.jsx("span",{children:De(new Date(X.createdAt),"MMM d, h:mm a")})]}),((ns=(Be=X.transcript)==null?void 0:Be[0])==null?void 0:ns.content)&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:['"',X.transcript[0].content,'"']})]},X.id)}),(!(o!=null&&o.conversations)||o.conversations.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No conversations yet"})]})})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Conversation Detail"}),e.jsx(Oe,{children:t?`Session: ${t.sessionId.substring(0,16)}...`:"Select a conversation to view details"})]}),e.jsx(T,{children:t?e.jsx(kt,{className:"h-[400px]",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Device:"}),e.jsx("span",{className:"ml-2 capitalize",children:t.deviceType})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Time on page:"}),e.jsx("span",{className:"ml-2",children:t.timeOnPageBeforeExit?`${Math.round(t.timeOnPageBeforeExit/1e3)}s`:"N/A"})]})]}),e.jsx("div",{className:"border-t pt-4 space-y-3",children:(U=t.transcript)==null?void 0:U.map((X,Be)=>e.jsxs("div",{className:`p-3 rounded-lg ${X.role==="user"?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1 capitalize",children:X.role}),e.jsx("p",{className:"text-sm",children:X.content})]},Be))})]})}):e.jsx("div",{className:"h-[400px] flex items-center justify-center text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Zr,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"Select a conversation to view the full transcript"})]})})})]})]})}),e.jsx(Ve,{value:"questions",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(W,{className:"text-lg",children:"Most Asked Questions"}),e.jsx(Oe,{children:"Common questions visitors ask before leaving"})]}),e.jsxs(ee,{variant:"outline",size:"sm",onClick:A,"data-testid":"button-reset-questions",children:[e.jsx(hi,{className:"h-3 w-3 mr-1"}),"Reset Data"]})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(j=r==null?void 0:r.topQuestions)==null?void 0:j.map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground",children:["#",Be+1]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm",children:X.question}),X.category&&e.jsx(Y,{variant:"outline",className:"ml-2 text-xs",children:X.category})]})]}),e.jsxs(Y,{variant:"outline",children:[X.count," times"]})]},Be)),(!(r!=null&&r.topQuestions)||r.topQuestions.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No questions tracked yet"})]})})]})}),e.jsx(Ve,{value:"rage-signals",className:"space-y-4",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(Fs,{className:"h-5 w-5 text-red-500"}),"Rage Signals Timeline"]}),e.jsx(Oe,{children:"Frustrated user behavior detected on the exit blocker chat"})]}),e.jsx(T,{children:e.jsx(kt,{className:"h-[500px]",children:e.jsxs("div",{className:"space-y-3",children:[(Q=u==null?void 0:u.signals)==null?void 0:Q.map(X=>e.jsxs("div",{className:"p-4 rounded-lg border bg-muted/30 space-y-2","data-testid":`rage-signal-${X.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[F(X.signalType),e.jsx("span",{className:"font-medium capitalize",children:X.signalType.replace(/_/g," ")}),de(X.severity)]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:De(new Date(X.createdAt),"MMM d, h:mm a")})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Page:"})," ",X.page,X.scrollDepth!==null&&e.jsxs("span",{className:"ml-4",children:[e.jsx("span",{className:"font-medium",children:"Scroll:"})," ",X.scrollDepth,"%"]}),X.timeOnPage!==null&&e.jsxs("span",{className:"ml-4",children:[e.jsx("span",{className:"font-medium",children:"Time on page:"})," ",Math.round(X.timeOnPage/1e3),"s"]})]}),X.signalData&&e.jsxs("div",{className:"text-xs bg-muted p-2 rounded font-mono",children:[X.signalData.clickCount!==void 0&&e.jsxs("span",{children:["Clicks: ",X.signalData.clickCount," "]}),X.signalData.clicksPerSecond!==void 0&&e.jsxs("span",{children:["(",X.signalData.clicksPerSecond.toFixed(1),"/sec) "]}),X.signalData.dismissCount!==void 0&&e.jsxs("span",{children:["Dismisses: ",X.signalData.dismissCount," "]}),X.signalData.timeToClose!==void 0&&e.jsxs("span",{children:["Closed after: ",X.signalData.timeToClose,"ms "]}),X.signalData.capsPercentage!==void 0&&e.jsxs("span",{children:["Caps: ",X.signalData.capsPercentage,"% "]}),X.signalData.targetElement!==void 0&&e.jsxs("span",{children:["Target: ",X.signalData.targetElement]}
80)]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Session: ",X.sessionId.substring(0,20),"..."]})]},X.id)),(!(u!=null&&u.signals)||u.signals.length===0)&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ui,{className:"h-12 w-12 mx-auto mb-3 text-green-500 opacity-50"}),e.jsx("p",{className:"text-muted-foreground",children:"No rage signals detected"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Users are engaging positively with the exit blocker"})]})]})})})]})}),e.jsx(Ve,{value:"geographic",className:"space-y-4",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(ot,{className:"h-5 w-5 text-blue-500"}),"Visitors by Country"]}),e.jsx(Oe,{children:"Where your visitors are coming from"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(je=x==null?void 0:x.byCountry)==null?void 0:je.slice(0,10).map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:M4(X.countryCode)}),e.jsx("span",{children:X.country})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[X.conversions," conversions"]}),e.jsx(Y,{variant:"outline",children:X.count})]})]},Be)),(!(x!=null&&x.byCountry)||x.byCountry.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No geographic data yet"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(sn,{className:"h-5 w-5 text-red-500"}),"Top Cities"]}),e.jsx(Oe,{children:"Most active visitor locations"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(ce=x==null?void 0:x.byCity)==null?void 0:ce.slice(0,10).map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:X.city}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["(",X.region,")"]})]}),e.jsx(Y,{variant:"outline",children:X.count})]},Be)),(!(x!=null&&x.byCity)||x.byCity.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No city data yet"})]})})]})]})}),e.jsx(Ve,{value:"traffic",className:"space-y-4",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(Wt,{className:"h-5 w-5 text-green-500"}),"Traffic Sources"]}),e.jsx(Oe,{children:"How visitors are finding your site"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(be=m==null?void 0:m.bySource)==null?void 0:be.map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[R4(X.source),e.jsx("span",{className:"capitalize",children:X.source})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-green-600",children:[X.conversionRate.toFixed(1),"% CVR"]}),e.jsxs(Y,{variant:"outline",children:[X.count," visits"]})]})]},Be)),(!(m!=null&&m.bySource)||m.bySource.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No traffic data yet"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(yr,{className:"h-5 w-5 text-purple-500"}),"Campaign Performance"]}),e.jsx(Oe,{children:"UTM campaign tracking"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(ss=m==null?void 0:m.byCampaign)==null?void 0:ss.slice(0,10).map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-muted/30",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:X.campaign||"No Campaign"}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["via ",X.source]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm text-green-600",children:[X.conversions," conv"]}),e.jsx(Y,{variant:"outline",children:X.count})]})]},Be)),(!(m!=null&&m.byCampaign)||m.byCampaign.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No campaign data yet"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(tt,{className:"h-5 w-5 text-blue-500"}),"Device Breakdown"]}),e.jsx(Oe,{children:"Visitors by device type"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(oe=v==null?void 0:v.byDeviceType)==null?void 0:oe.map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[X.deviceType==="mobile"&&e.jsx(Ht,{className:"h-4 w-4"}),X.deviceType==="tablet"&&e.jsx(Ga,{className:"h-4 w-4"}),X.deviceType==="desktop"&&e.jsx(tt,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:X.deviceType||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-green-600",children:[X.conversionRate.toFixed(1),"% CVR"]}),e.jsx(Y,{variant:"outline",children:X.count})]})]},Be)),(!(v!=null&&v.byDeviceType)||v.byDeviceType.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No device data yet"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Top Referrers"}),e.jsx(Oe,{children:"Domains sending traffic to your site"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[(Ne=m==null?void 0:m.byReferrer)==null?void 0:Ne.slice(0,10).map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-mono",children:X.domain}),e.jsx(Y,{variant:"outline",children:X.count})]},Be)),(!(m!=null&&m.byReferrer)||m.byReferrer.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No referrer data yet"})]})})]})]})}),e.jsxs(Ve,{value:"insights",className:"space-y-4",children:[e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium text-muted-foreground",children:"Conversations Analyzed"})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold",children:(g==null?void 0:g.totalAnalyzed)??
800})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium text-muted-foreground",children:"Avg Conversion Likelihood"})}),e.jsx(T,{children:e.jsxs("div",{className:"text-2xl font-bold text-green-600",children:[((g==null?void 0:g.avgConversionLikelihood)??0).toFixed(1),"%"]})})]}),e.jsxs(_,{children:[e.jsx(q,{className:"pb-2",children:e.jsx(W,{className:"text-sm font-medium text-muted-foreground",children:"Competitor Mentions"})}),e.jsx(T,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:((Le=g==null?void 0:g.competitorMentions)==null?void 0:Le.length)??0})})]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(Qt,{className:"h-5 w-5 text-purple-500"}),"Sentiment Analysis"]}),e.jsx(Oe,{children:"How visitors feel about conversations"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[Object.entries((g==null?void 0:g.sentimentBreakdown)??{}).map(([X,Be])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[L4(X),e.jsx("span",{className:"capitalize",children:X})]}),e.jsx(Y,{variant:$4(X),children:Be})]},X)),Object.keys((g==null?void 0:g.sentimentBreakdown)??{}).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No sentiment data yet"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(lt,{className:"h-5 w-5 text-blue-500"}),"Buying Stage"]}),e.jsx(Oe,{children:"Where visitors are in the buyer journey"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-3",children:[Object.entries((g==null?void 0:g.buyingStageBreakdown)??{}).map(([X,Be])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"capitalize",children:X}),e.jsx(Y,{variant:"outline",children:Be})]},X)),Object.keys((g==null?void 0:g.buyingStageBreakdown)??{}).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No buying stage data yet"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Top Intents"}),e.jsx(Oe,{children:"What visitors are looking for"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-2",children:[(ae=g==null?void 0:g.topIntents)==null?void 0:ae.slice(0,8).map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:X.intent.replace(/_/g," ")}),e.jsx(Y,{variant:"secondary",children:X.count})]},Be)),(!(g!=null&&g.topIntents)||g.topIntents.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No intent data yet"})]})})]}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Inferred Roles"}),e.jsx(Oe,{children:"Who is asking questions"})]}),e.jsx(T,{children:e.jsxs("div",{className:"space-y-2",children:[(xe=g==null?void 0:g.inferredRoles)==null?void 0:xe.map((X,Be)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm capitalize",children:X.role.replace(/_/g," ")}),e.jsx(Y,{variant:"outline",children:X.count})]},Be)),(!(g!=null&&g.inferredRoles)||g.inferredRoles.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No role data yet"})]})})]}),e.jsxs(_,{className:"md:col-span-2",children:[e.jsxs(q,{children:[e.jsx(W,{className:"text-lg",children:"Common Objections"}),e.jsx(Oe,{children:"What's stopping visitors from converting"})]}),e.jsx(T,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[(Fe=g==null?void 0:g.topObjectionCategories)==null?void 0:Fe.map((X,Be)=>e.jsxs(Y,{variant:"destructive",className:"text-sm",children:[X.category.replace(/_/g," ")," (",X.count,")"]},Be)),(!(g!=null&&g.topObjectionCategories)||g.topObjectionCategories.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8 w-full",children:"No objection data yet"})]})})]})]})]})]})]})}function M4(s){if(!s||s.length!==2)return"ð";const t=s.toUpperCase().split("").map(a=>
80127397+a.charCodeAt(0));return String.fromCodePoint(...t)}function R4(s){switch(s.toLowerCase()){case"organic":return e.jsx(ot,{className:"h-4 w-4 text-green-500"});case"paid":return e.jsx(lt,{className:"h-4 w-4 text-orange-500"});case"social":return e.jsx(Ys,{className:"h-4 w-4 text-blue-500"});case"referral":return e.jsx(Wt,{className:"h-4 w-4 text-purple-500"});default:return e.jsx(ot,{className:"h-4 w-4 text-ink-soft"})}}function L4(s){switch(s.toLowerCase()){case"positive":return"ð";case"negative":return"ð";case"neutral":return"ð";case"mixed":return"ð¤";default:return"â"}}function $4(s){switch(s.toLowerCase()){case"positive":return"default";case"negative":return"destructive";case"neutral":return"secondary";default:return"outline"}}function k3(){const[s,t]=p.useState("overview"),{data:a}=_e({queryKey:["/api/user"]});return!a||a.role!=="admin"&&a.role!=="system_admin"?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx(_,{children:e.jsx(T,{className:"p-6",children:e.jsx("p",{className:"text-red-600",children:"Access denied. Admin privileges required."})})})}):e.jsxs("div",{className:"container mx-auto py-8 px-4",children:[e.jsx("div",{className:"mb-4",children:e.jsx(Fx,{fallbackHref:"/admin",fallbackLabel:"Admin",variant:"outline",testId:"button-back-to-dashboard"})}),e.jsxs("div",{className:"mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Marketing & Analytics Intelligence"}),e.jsx("p",{className:"text-muted-foreground",children:"Physician-centric marketing analytics and insights platform"})]}),e.jsx("div",{className:"mb-8",children:e.jsx(ob,{})}),e.jsxs(la,{value:s,onValueChange:t,className:"space-y-6",children:[e.jsxs(ca,{className:"flex flex-wrap gap-1 h-auto p-1",children:[e.jsxs(Ee,{value:"overview",className:"flex items-center gap-2","data-testid":"tab-overview",children:[e.jsx(Zs,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Overview"})]}),e.jsxs(Ee,{value:"agents",className:"flex items-center gap-2","data-testid":"tab-agents",children:[e.jsx(Xa,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"AI Agents"})]}),e.jsxs(Ee,{value:"advanced",className:"flex items-center gap-2","data-testid":"tab-advanced",children:[e.jsx(pp,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Analytics"})]}),e.jsxs(Ee,{value:"seo",className:"flex items-center gap-2","data-testid":"tab-seo",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"SEO"})]}),e.jsxs(Ee,{value:"ab-testing",className:"flex items-center gap-2","data-testid":"tab-ab-testing",children:[e.jsx(fi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"A/B Tests"})]}),e.jsxs(Ee,{value:"ad-platforms",className:"flex items-center gap-2","data-testid":"tab-ad-platforms",children:[e.jsx(yr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Ad Platforms"})]}),e.jsxs(Ee,{value:"youtube-impact",className:"flex items-center gap-2","data-testid":"tab-youtube-impact",children:[e.jsx(Ra,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"YouTube Impact"})]}),e.jsxs(Ee,{value:"cohorts",className:"flex items-center gap-2","data-testid":"tab-cohorts",children:[e.jsx(mc,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Cohorts"})]}),e.jsxs(Ee,{value:"healthcare",className:"flex items-center gap-2","data-testid":"tab-healthcare",children:[e.jsx(nc,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Healthcare"})]}),e.jsxs(Ee,{value:"acquisition",className:"flex items-center gap-2","data-testid":"tab-acquisition",children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Acquisition"})]}),e.jsxs(Ee,{value:"insights",className:"flex items-center gap-2","data-testid":"tab-insights",children:[e.jsx(Qt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Insights"})]}),e.jsxs(Ee,{value:"automations",className:"flex items-center gap-2","data-testid":"tab-automations",children:[e.jsx(oa,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Automations"})]}),e.jsxs(Ee,{value:"campaigns",className:"flex items-center gap-2","data-testid":"tab-campaigns",children:[e.jsx(ct,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Campaigns"})]}),e.jsxs(Ee,{value:"exit-blocker",className:"flex items-center gap-2","data-testid":"tab-exit-blocker",children:[e.jsx(Zr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Exit Blocker"})]})]}),e.jsxs(Ve,{value:"overview",className:"space-y-6",children:[e.jsx(D4,{showHeader:!0,defaultTimeRange:30}),e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Marketing Overview Dashboard"}),e.jsx(Oe,{children:"Real-time metrics and KPIs for your marketing performance"})]}),e.jsx(T,{children:e.jsx(_f,{})})]})]}),e.jsx(Ve,{value:"agents",className:"space-y-6",children:e.jsx(p4,{})}),e.jsx(Ve,{value:"advanced",className:"space-y-6",children:e.jsx(c4,{})}),e.jsx(Ve,{value:"seo",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"SEO Performance & Management"}),e.jsx(Oe,{children:"Search engine optimization metrics, rankings, and technical SEO health"})]}),e.jsx(T,{children:e.jsx(o4,{})})]})}),e.jsx(Ve,{value:"ab-testing",className:"space-y-6",children:e.jsx(d4,{})}),e.jsx(Ve,{value:"ad-platforms",className:"space-y-6",children:e.jsxs("div",{className:"w-full",children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Google Ads Integration"}),e.jsx(m4,{})]})}),e.jsx(Ve,{value:"youtube-impact",className:"space-y-6",children:e.jsx(C4,{})}),e.jsx(Ve,{value:"cohorts",className:"space-y-6",children:e.jsx(u4,{})}),e.jsx(Ve,{value:"healthcare",className:"space-y-6",children:e.jsx(x4,{})}),e.jsx(Ve,{value:"acquisition",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Acquisition Source Tracking"}),e.jsx(Oe,{children:"Track user signups by source, including UTM parameters and referrers"})]}),e.jsx(T,{children:e.jsx(ib,{})})]})}),e.jsx(Ve,{value:"insights",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Automated Insights & Recommendations"}),e.jsx(Oe,{children:"AI-driven analysis of metrics with actionable recommendations"})]}),e.jsx(T,{children:e.jsx(lb,{})})]})}),e.jsx(Ve,{value:"automations",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Marketing Automations"}),e.jsx(Oe,{children:"Configure automated responses: pause campaigns, A/B tests, notifications"})]}),e.jsx(T,{children:e.jsx(cb,{})})]})}),e.jsx(Ve,{value:"campaigns",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Campaign Performance & ROI Tracking"}),e.jsx(Oe,{children:"Manage campaigns, track ROI, and monitor marketing spend across all channels"})]}),e.jsx(T,{children:e.jsx(h4,{})})]})}),e.jsx(Ve,{value:"exit-blocker",className:"space-y-6",children:e.jsxs(_,{children:[e.jsxs(q,{children:[e.jsx(W,{children:"Exit Intent Blocker Analytics"}),e.jsx(Oe,{children:"GPT-powered Q&A chat to reduce bounce rate and capture leaving visitors"})]}),e.jsx(T,{children:e.jsx(P4,{})})]})})]})]})}export{k3 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.