1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jspdf.es.min-B-MU2tO3.js","assets/index-uZtOByCD.js","assets/index-DFwWSdvv.css","assets/browser-C1dUGcVA.js","assets/LiveQuestionFeed-CqZ-oUX-.js","assets/badge-0Vfv_Kne.js","assets/scroll-area-DHl_ouN0.js","assets/index-BTzyD0JA.js","assets/index-BdQq_4o_.js","assets/card-DhR4AuIr.js","assets/TranslateButton-D3DZ20rI.js","assets/languages-DNu0DsOQ.js","assets/collapsible-wSD8jkbI.js","assets/index-vXtTqUAH.js","assets/users-axGGvAqy.js","assets/trending-up-BgAIfrlO.js","assets/clock-AisMzcen.js","assets/thumbs-up-DJ7MI4D4.js","assets/thumbs-down-47O-Ic-N.js","assets/filter-yCTXmIxM.js","assets/search-BSymvr9r.js","assets/chevron-up-DQ49ezBI.js","assets/tabs-tbaZNHhH.js","assets/index-Ca6WzAYb.js","assets/skeleton-igHUvnUl.js","assets/trending-down-CH5S6YVp.js","assets/minus-CjxlOP4j.js","assets/sheet-DX6mMSmz.js","assets/external-link-DJ1pCNi1.js","assets/chart-column-D8l1Dnid.js","assets/activity-SGvnGbYM.js","assets/earth-BWNT61UB.js","assets/shield-check-BPQmoD2A.js","assets/landmark-puChGBuL.js","assets/radio-BNwdnMU8.js","assets/target-CB_M-BRz.js","assets/plane-CDzck0X0.js","assets/brain-FTmKe6_3.js","assets/database-B4LKFSWM.js","assets/swords-DX-tuG87.js","assets/credit-card-Cm5QKSlX.js","assets/crown-whcRiQvt.js","assets/wallet-bx_Ew6P4.js","assets/presentation-R1bBzu0_.js","assets/info-DIy84udW.js","assets/useAdminRole-iNe56p8n.js","assets/pencil-CaSA8Jhz.js","assets/uncensored-ai-logo-ClpAV7dz.js","assets/progress-BObXt_1O.js","assets/play-B1uLUs1-.js","assets/circle-check-e3ltB3tf.js","assets/circle-x-CQixe1_O.js","assets/shield-DLDD69IG.js","assets/file-down-CNQrefCb.js","assets/gauge-FGSWjG_d.js","assets/BarChart-BGI5MIft.js","assets/PieChart-XIbgOjx0.js","assets/index-Z1ZdL3PX.js","assets/tiny-invariant-CopsF_GD.js","assets/zap-CIB492dE.js","assets/globe-ByGJalKm.js","assets/book-open-RHpeCaXR.js","assets/user-minus-MEYFmoZ1.js","assets/CancellationsTab-uUM_tQQa.js","assets/calendar-CljLNaKh.js","assets/bot-DFp36bej.js","assets/map-pin-16wLhWO1.js","assets/TrendingTopicsTab-jE3FvcXH.js","assets/switch-n6dtz-69.js","assets/index-BiRDVOsj.js","assets/plus-BdzlXPoX.js","assets/save-C6oMu-59.js","assets/trash-2-Cm7euKJF.js","assets/ApiUsageTab-bXzYzKuq.js","assets/key-Cx6cnpih.js","assets/FeedbackTab-a66zFoGC.js","assets/flag-BfW0aq3L.js","assets/GeographicTab-CyQkb71k.js","assets/RabbitHoleTab-T47P3ui8.js","assets/StreamSmoothnessTab-DTyoK1-4.js","assets/DataExplorerTab-BRKwm8Ws.js","assets/table-CWpJVAiw.js","assets/file-spreadsheet-LFki_YoQ.js","assets/file-json-CpqrWFj8.js","assets/sectorTaxonomy-BsWaOo2d.js","assets/layers-BXubKMuc.js","assets/MarkdownRenderer-BNQuBw3K.js","assets/bookmark-D6beqX1u.js","assets/bookmark-plus-yZiMeSiF.js","assets/select-DoJBmvDp.js","assets/popover-CfJw9oSY.js","assets/sliders-horizontal-Ceg-QfG7.js","assets/rotate-ccw-DcH_a2_k.js","assets/list-DAwsvai0.js","assets/rows-3-D0oh_UN6.js","assets/LandingPagesTab-CpmEaAAM.js","assets/jspdf.plugin.autotable-DtM9Cxfv.js","assets/TrafficSourcesTab-BhfZiF3c.js","assets/tag-Czio6-l0.js","assets/AdminMemoryTab-Bp4Fa4Bl.js","assets/alert-dialog-B9lHQfUg.js","assets/history-BOjule8w.js","assets/pin-off-TN5XJgU0.js","assets/HiddenContextTab-Bn7KPtxK.js","assets/VoiceUsageTab-J2cyUpP_.js","assets/dollar-sign-CyJ0rTgq.js","assets/type-D3pjIcsJ.js","assets/WhoMoggedTab-CJrX4WCY.js","assets/trophy-D3c1H24B.js","assets/timer-DLEBUEhv.js","assets/image-WGbSrdZP.js","assets/SlopornotTab-CGuPpqhL.js","assets/IntakeTab-D2jPBs4z.js","assets/refresh-ccw-73eTDDrY.js","assets/FactCrackTab-BRzXNj6u.js","assets/RabbitRunTab-bqOkqXXP.js","assets/phraseOverrides-Cs_VjCty.js","assets/AssetsIrlTab-BPQPBvOT.js","assets/camera-BdbMl21G.js","assets/EmailUsersTab-qu3Ku2Ld.js","assets/file-text-C5-JMpmT.js","assets/ProTrialTab-BiRyTEi-.js","assets/shield-off-zTi-Vdpj.js","assets/RevenueRecoveryTab-mZDjAxGs.js","assets/ModerationTab-DPaQZ50z.js","assets/BannedIspsTab-Cix7FyzN.js","assets/AudienceProfileTab-CMgH_J0h.js","assets/AdminAccessTab-CbcsyiO0.js","assets/SignupAuditTab-CQIiSxTm.js","assets/ClientErrorsTab-D4F2ORCo.js"])))=>i.map(i=>d[i]); 2var Er=Object.defineProperty;var Ir=(t,a,s)=>a in t?Er(t,a,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[a]=s;var Ka=(t,a,s)=>Ir(t,typeof a!="symbol"?a+"":a,s);import{c as Pe,r as d,j as e,B as Se,R as Tt,cX as Jt,v as Rr,g as ke,t as Dr,X as ms,I as Sn,m as wn,q as Qa,p as qt,b7 as Ur,M as $r,T as ps,bw as Lr,at as Or,au as Fr,av as zr,aw as Kr,w as ce,P as Br,J as ha,a5 as Wr,a6 as Vr,_ as J,L as Hr,n as Gr,z as qr,ca as Yr,A as Qr,bp as Xr,H as ca,aA as Zr,de as ie,s as Jr}from"./index-uZtOByCD.js";import{C as ot,a as An,b as kn,c as lt}from"./card-DhR4AuIr.js";import{T as ei,c as Y}from"./tabs-tbaZNHhH.js";import{S as Qt}from"./skeleton-igHUvnUl.js";import{B as ue}from"./badge-0Vfv_Kne.js";import{T as xa}from"./trending-up-BgAIfrlO.js";import{T as Pn}from"./trending-down-CH5S6YVp.js";import{M as Cn}from"./minus-CjxlOP4j.js";import{S as ti,b as ai}from"./sheet-DX6mMSmz.js";import{S as si}from"./search-BSymvr9r.js";import{E as Tn}from"./external-link-DJ1pCNi1.js";import{C as Xa}from"./chart-column-D8l1Dnid.js";import{A as Mt}from"./activity-SGvnGbYM.js";import{U as Za}from"./users-axGGvAqy.js";import{E as ni}from"./earth-BWNT61UB.js";import{S as Hs}from"./shield-check-BPQmoD2A.js";import{L as ri}from"./landmark-puChGBuL.js";import{P as ii,R as Mn}from"./radio-BNwdnMU8.js";import{R as oi,T as li}from"./target-CB_M-BRz.js";import{P as ci}
2from"./plane-CDzck0X0.js";import{B as _t}from"./brain-FTmKe6_3.js";import{D as _n}from"./database-B4LKFSWM.js";import{T as En}from"./thumbs-up-DJ7MI4D4.js";import{S as di}from"./swords-DX-tuG87.js";import{C as Ja}from"./credit-card-Cm5QKSlX.js";import{C as es}from"./crown-whcRiQvt.js";import{W as ui}from"./wallet-bx_Ew6P4.js";import{P as mi}from"./presentation-R1bBzu0_.js";import{I as pi}from"./info-DIy84udW.js";import{u as hi}from"./useAdminRole-iNe56p8n.js";import{P as Gs}from"./pencil-CaSA8Jhz.js";import{u as gi}from"./uncensored-ai-logo-ClpAV7dz.js";import{P as xi}from"./progress-BObXt_1O.js";import{P as fi}from"./play-B1uLUs1-.js";import{C as vi}from"./circle-check-e3ltB3tf.js";import{C as yi}from"./circle-x-CQixe1_O.js";import{S as qs}from"./shield-DLDD69IG.js";import{F as ts}from"./file-down-CNQrefCb.js";import{G as Ys}from"./gauge-FGSWjG_d.js";import{S as bi,u as ji,g as Ni,a as In,G as Rn,b as Si,s as hs,c as gs,C as xs,d as wi,e as he,X as ge,Y as xe,T as te,B as Te,f as je}from"./BarChart-BGI5MIft.js";import{Z as Qs}from"./zap-CIB492dE.js";import{r as ea,b as Ai,c as ki,u as Ma,s as Pi,p as fs,d as Ci,e as Ti,f as Mi,g as _i,h as Dn,i as Ei,j as Xs,k as Oe,l as Un,m as _a,n as vs,o as Ii,Z as Ea,L as xt,D as Ia,q as Ri,t as Di,v as fa,w as $n,x as ga,y as Ui,z as ft,A as ta,B as ys,E as va,F as Ln,G as $i,H as Ra,I as Da,J as Ua,K as On,M as Fn,N as zn,O as $a,Q as Kn,T as Bn,U as Wn,V as Vn,W as Hn,X as ya,Y as ba,_ as ct,$ as Gn,a0 as qn,a1 as Yn,a2 as Qn,a3 as Xn,a4 as Zn,a5 as Li,a6 as Oi,a7 as Fi,a8 as zi,a9 as Ki,aa as ja,ab as Bi,ac as Wi,ad as Vi,ae as Hi,af as Zs,ag as Gi,ah as bs,R as ae,P as at,a as st,C as $e}from"./PieChart-XIbgOjx0.js";import{G as Ba}from"./globe-ByGJalKm.js";import{B as Js}from"./book-open-RHpeCaXR.js";import{U as en}from"./user-minus-MEYFmoZ1.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const js=Pe("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/** 8 * @license lucide-react v0.462.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const tn=Pe("Boxes",[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]);/** 13 * @license lucide-react v0.462.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const qi=Pe("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/** 18 * @license lucide-react v0.462.0 - ISC 19 * 20 * This source code is licensed under the ISC license. 21 * See the LICENSE file in the root directory of this source tree. 22 */const an=Pe("ChevronsLeft",[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]]);/** 23 * @license lucide-react v0.462.0 - ISC 24 * 25 * This source code is licensed under the ISC license. 26 * See the LICENSE file in the root directory of this source tree. 27 */const sn=Pe("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/** 28 * @license lucide-react v0.462.0 - ISC 29 * 30 * This source code is licensed under the ISC license. 31 * See the LICENSE file in the root directory of this source tree. 32 */const nn=Pe("CirclePause",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]);/** 33 * @license lucide-react v0.462.0 - ISC 34 * 35 * This source code is licensed under the ISC license. 36 * See the LICENSE file in the root directory of this source tree. 37 */const Yi=Pe("Dna",[["path",{d:"m10 16 1.5 1.5",key:"11lckj"}
37],["path",{d:"m14 8-1.5-1.5",key:"1ohn8i"}],["path",{d:"M15 2c-1.798 1.998-2.518 3.995-2.807 5.993",key:"80uv8i"}],["path",{d:"m16.5 10.5 1 1",key:"696xn5"}],["path",{d:"m17 6-2.891-2.891",key:"xu6p2f"}],["path",{d:"M2 15c6.667-6 13.333 0 20-6",key:"1pyr53"}],["path",{d:"m20 9 .891.891",key:"3xwk7g"}],["path",{d:"M3.109 14.109 4 15",key:"q76aoh"}],["path",{d:"m6.5 12.5 1 1",key:"cs35ky"}],["path",{d:"m7 18 2.891 2.891",key:"1sisit"}],["path",{d:"M9 22c1.798-1.998 2.518-3.995 2.807-5.993",key:"q3hbxp"}]]);/** 38 * @license lucide-react v0.462.0 - ISC 39 * 40 * This source code is licensed under the ISC license. 41 * See the LICENSE file in the root directory of this source tree. 42 */const Qi=Pe("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** 43 * @license lucide-react v0.462.0 - ISC 44 * 45 * This source code is licensed under the ISC license. 46 * See the LICENSE file in the root directory of this source tree. 47 */const Xi=Pe("Gamepad2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]);/** 48 * @license lucide-react v0.462.0 - ISC 49 * 50 * This source code is licensed under the ISC license. 51 * See the LICENSE file in the root directory of this source tree. 52 */const Zi=Pe("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** 53 * @license lucide-react v0.462.0 - ISC 54 * 55 * This source code is licensed under the ISC license. 56 * See the LICENSE file in the root directory of this source tree. 57 */const Ji=Pe("Lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/** 58 * @license lucide-react v0.462.0 - ISC 59 * 60 * This source code is licensed under the ISC license. 61 * See the LICENSE file in the root directory of this source tree. 62 */const eo=Pe("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"}]]);/** 63 * @license lucide-react v0.462.0 - ISC 64 * 65 * This source code is licensed under the ISC license. 66 * See the LICENSE file in the root directory of this source tree. 67 */const to=Pe("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/** 68 * @license lucide-react v0.462.0 - ISC 69 * 70 * This source code is licensed under the ISC license. 71 * See the LICENSE file in the root directory of this source tree. 72 */const ao=Pe("Radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);/** 73 * @license lucide-react v0.462.0 - ISC 74 * 75 * This source code is licensed under the ISC license. 76 * See the LICENSE file in the root directory of this source tree. 77 */const so=Pe("Sandwich",[["path",{d:"m2.37 11.223 8.372-6.777a2 2 0 0 1 2.516 0l8.371 6.777",key:"f1wd0e"}],["path",{d:"M21 15a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-5.25",key:"1pfu07"}],["path",{d:"M3 15a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h9",key:"1oq9qw"}],["path",{d:"m6.67 15 6.13 4.6a2 2 0 0 0 2.8-.4l3.15-4.2",key:"1fnwu5"}],["rect",{width:"20",height:"4",x:"2",y:"11",rx:"1",key:"itshg"}]]);/** 78 * @license lucide-react v0.462.0 - ISC 79 * 80 * This source code is licensed under the ISC license. 81 * See the LICENSE file in the root directory of this source tree. 82 */const no=Pe("UserSearch",[["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}],["path",{d:"M10.3 15H7a4 4 0 0 0-4 4v2",key:"3bnktk"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}]]),Me=t=>
82Number(t||0).toLocaleString("en-US"),ht=(t,a)=>Number(a)>0?`${(Number(t)/Number(a)*100).toFixed(1)}%`:"n/a",ro=({call:t})=>{var W;const[a,s]=d.useState([]),[n,o]=d.useState(0),[r,h]=d.useState(!1),[u,g]=d.useState(null),x=d.useCallback(async()=>{try{const S=await t({action:"list"});s((S==null?void 0:S.reports)||[]),g(null)}catch(S){g((S==null?void 0:S.message)||"Could not load reports")}},[t]);d.useEffect(()=>{x()},[x]);const f=async()=>{h(!0);try{await t({action:"refresh"}),await x()}catch(S){g((S==null?void 0:S.message)||"Refresh failed")}h(!1)},v=a[n],b=(v==null?void 0:v.payload)||{},N=(W=a[n+1])==null?void 0:W.payload,k=S=>{if(!N||N[S]==null)return null;const I=Number(b[S]||0)-Number(N[S]||0);return`${I>=0?"+":""}${I.toLocaleString("en-US")} vs prior month`},p=({label:S,value:I,sub:D})=>e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/20 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:S}),e.jsx("p",{className:"mt-1 text-lg font-semibold tabular-nums text-foreground",children:I}),D&&e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:D})]}),C=Object.entries(b.two_to_five_days_distribution||{}).sort((S,I)=>(S[0]==="10+"?99:Number(S[0]))-(I[0]==="10+"?99:Number(I[0])));return e.jsxs(ot,{children:[e.jsxs(An,{className:"flex flex-row flex-wrap items-center justify-between gap-3",children:[e.jsxs(kn,{className:"flex items-center gap-2 text-base",children:[e.jsx(qi,{className:"h-4 w-4 text-primary"})," Monthly usage report"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[a.length>0&&e.jsx("select",{className:"rounded-md border border-border bg-background px-2 py-1 text-sm",value:n,onChange:S=>o(Number(S.target.value)),children:a.map((S,I)=>{var D;return e.jsxs("option",{value:I,children:[((D=S.payload)==null?void 0:D.month)||S.month,S.is_partial?" (so far)":""]},S.month)})}),e.jsxs(Se,{size:"sm",variant:"outline",onClick:f,disabled:r,children:[e.jsx(Tt,{className:`mr-1.5 h-3.5 w-3.5 ${r?"animate-spin":""}`})," Update this month"]})]})]}),e.jsxs(lt,{className:"space-y-5",children:[u&&e.jsx("p",{className:"text-sm text-destructive",children:u}),v?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.first_day," to ",b.last_day,", ",Me(b.days_tracked)," tracked days."," ",v.emailed_at?`Emailed ${new Date(v.emailed_at).toLocaleDateString()}.`:"Emails on the 1st of next month."]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(p,{label:"Active chatters",value:Me(b.active_chatters),sub:k("active_chatters")}),e.jsx(p,{label:"Total responses",value:Me(b.total_responses),sub:k("total_responses")}),e.jsx(p,{label:"Came back on 2+ days",value:Me(b.returned_2plus_days),sub:ht(b.returned_2plus_days,b.active_chatters)}),e.jsx(p,{label:"3+ questions in a day",value:Me(b.users_3plus_day),sub:`${ht(b.users_3plus_day,b.active_chatters)} of chatters`}),e.jsx(p,{label:"5+ questions in a day",value:Me(b.users_5plus_day),sub:`${ht(b.users_5plus_day,b.active_chatters)} of chatters`}),e.jsx(p,{label:"5+ questions in the month",value:Me(b.users_5plus_month)}),e.jsx(p,{label:"Exactly 5, on 2+ days",value:Me(b.exact5_repeat_users),sub:`${ht(b.exact5_repeat_free,b.exact5_repeat_users)} free`}),e.jsx(p,{label:"2 to 5 a day, on 2+ days",value:Me(b.two_to_five_multi_day_users),sub:`${ht(b.two_to_five_multi_day_free,b.two_to_five_multi_day_users)} free`}),e.jsx(p,{label:"Pro share of chatters",value:ht(b.pro_active_chatters,b.active_chatters)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-foreground",children:"Paywall at 5 results"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(p,{label:"Free users who hit the paywall",value:Me(b.free_reached_paywall),sub:k("free_reached_paywall")}),e.jsx(p,{label:"Hit it on 2+ days",value:Me(b.free_reached_paywall_repeat)}),e.jsx(p,{label:"New Pro subscribers",value:Me(b.new_pro_subscribers),sub:k("new_pro_subscribers")}),e.jsx(p,{label:"New Pro after the paywall",value:Me(b.new_pro_after_paywall),sub:`${ht(b.new_pro_after_paywall,b.free_reached_paywall)} of paywall reach`})]})]}),C.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-foreground",children:"Days with 2 to 5 questions"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C.map(([S,I])=>e.jsxs("span",{className:"rounded-full border border-border/60 px-3 py-1 text-xs tabular-nums text-muted-foreground",children:[S," days: ",e.jsx("span",{className:"font-semibold text-foreground",children:Me(I)})]},S))})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No reports yet."})]})]})};function Na(){return Na=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},Na.apply(null,arguments)}function rn(t,a){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);a&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),s.push.apply(s,n)}return s}function Jn(t){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};
82a%2?rn(Object(s),!0).forEach(function(n){io(t,n,s[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):rn(Object(s)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(s,n))})}return t}function io(t,a,s){return(a=oo(a))in t?Object.defineProperty(t,a,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[a]=s,t}function oo(t){var a=lo(t,"string");return typeof a=="symbol"?a:a+""}function lo(t,a){if(typeof t!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var n=s.call(t,a||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}var Re=32,co={align:"center",iconSize:14,inactiveColor:"#ccc",layout:"horizontal",verticalAlign:"middle",labelStyle:{}};function uo(t){if(typeof t=="object"&&t!==null&&"strokeDasharray"in t)return String(t.strokeDasharray)}function mo(t){var a=t.data,s=t.iconType,n=t.inactiveColor,o=Re/2,r=Re/6,h=Re/3,u=a.inactive?n:a.color,g=s??a.type;if(g==="none")return null;if(g==="plainline")return d.createElement("line",{strokeWidth:4,fill:"none",stroke:u,strokeDasharray:uo(a.payload),x1:0,y1:o,x2:Re,y2:o,className:"recharts-legend-icon"});if(g==="line")return d.createElement("path",{strokeWidth:4,fill:"none",stroke:u,d:"M0,".concat(o,"h").concat(h,` 83 A`).concat(r,",").concat(r,",0,1,1,").concat(2*h,",").concat(o,` 84 H`).concat(Re,"M").concat(2*h,",").concat(o,` 85 A`).concat(r,",").concat(r,",0,1,1,").concat(h,",").concat(o),className:"recharts-legend-icon"});if(g==="rect")return d.createElement("path",{stroke:"none",fill:u,d:"M0,".concat(Re/8,"h").concat(Re,"v").concat(Re*3/4,"h").concat(-Re,"z"),className:"recharts-legend-icon"});if(d.isValidElement(a.legendIcon)){var x=Jn({},a);return delete x.legendIcon,d.cloneElement(a.legendIcon,x)}return d.createElement(bi,{fill:u,cx:o,cy:o,size:Re,sizeType:"diameter",type:g})}function po(t){var a=t.payload,s=t.iconSize,n=t.layout,o=t.formatter,r=t.inactiveColor,h=t.iconType,u=t.labelStyle,g={x:0,y:0,width:Re,height:Re},x={display:n==="horizontal"?"inline-block":"block",marginRight:10},f={display:"inline-block",verticalAlign:"middle",marginRight:4};return a.map((v,b)=>{var N=v.formatter||o,k=Jt({"recharts-legend-item":!0,["legend-item-".concat(b)]:!0,inactive:v.inactive});if(v.type==="none")return null;var p=typeof u=="object"?Jn({},u):{};p.color=v.inactive?r:p.color||v.color;var C=N?N(v.value,v,b):v.value;return d.createElement("li",Na({className:k,style:x,key:"legend-item-".concat(b)},Ai(t,v,b)),d.createElement(ki,{width:s,height:s,viewBox:g,style:f,"aria-label":"".concat(v.value," legend icon")},d.createElement(mo,{data:v,iconType:h,inactiveColor:r})),d.createElement("span",{className:"recharts-legend-item-text",style:p},C))})}var ho=t=>{var a=ea(t,co),s=a.payload,n=a.layout,o=a.align;if(!s||!s.length)return null;var r={padding:0,margin:0,textAlign:n==="horizontal"?o:"left"};return d.createElement("ul",{className:"recharts-default-legend",style:r},d.createElement(po,Na({},a,{payload:s})))};function go(){return Ma(Pi)}var xo=["contextPayload"];function as(){return as=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},as.apply(null,arguments)}function fo(t,a){return jo(t)||bo(t,a)||yo(t,a)||vo()}function vo(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 86In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yo(t,a){if(t){if(typeof t=="string")return on(t,a);var s={}.toString.call(t).slice(8,-1);return s==="Object"&&t.constructor&&(s=t.constructor.name),s==="Map"||s==="Set"?Array.from(t):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?on(t,a):void 0}}function on(t,a){(a==null||a>t.length)&&(a=t.length);for(var s=0,n=Array(a);s<a;s++)n[s]=t[s];return n}function bo(t,a){var s=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(s!=null){var n,o,r,h,u=[],g=!0,x=!1;try{if(r=(s=s.call(t)).next,a!==0)for(;
86!(g=(n=r.call(s)).done)&&(u.push(n.value),u.length!==a);g=!0);}catch(f){x=!0,o=f}finally{try{if(!g&&s.return!=null&&(h=s.return(),Object(h)!==h))return}finally{if(x)throw o}}return u}}function jo(t){if(Array.isArray(t))return t}function ln(t,a){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);a&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),s.push.apply(s,n)}return s}function Et(t){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};a%2?ln(Object(s),!0).forEach(function(n){No(t,n,s[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):ln(Object(s)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(s,n))})}return t}function No(t,a,s){return(a=So(a))in t?Object.defineProperty(t,a,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[a]=s,t}function So(t){var a=wo(t,"string");return typeof a=="symbol"?a:a+""}function wo(t,a){if(typeof t!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var n=s.call(t,a||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function Ao(t,a){if(t==null)return{};var s,n,o=ko(t,a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(n=0;n<r.length;n++)s=r[n],a.indexOf(s)===-1&&{}.propertyIsEnumerable.call(t,s)&&(o[s]=t[s])}return o}function ko(t,a){if(t==null)return{};var s={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(a.indexOf(n)!==-1)continue;s[n]=t[n]}return s}function Po(t){return t.value}function Co(t){var a=t.contextPayload,s=Ao(t,xo),n=Ni(a,t.payloadUniqBy,Po),o=Et(Et({},s),{},{payload:n});return d.isValidElement(t.content)?d.cloneElement(t.content,o):typeof t.content=="function"?d.createElement(t.content,o):d.createElement(ho,o)}function To(t,a,s,n,o,r){var h=a.layout,u=a.align,g=a.verticalAlign,x,f;return(!t||(t.left===void 0||t.left===null)&&(t.right===void 0||t.right===null))&&(u==="center"&&h==="vertical"?x={left:((n||0)-r.width)/2}:x=u==="right"?{right:s&&s.right||0}:{left:s&&s.left||0}),(!t||(t.top===void 0||t.top===null)&&(t.bottom===void 0||t.bottom===null))&&(g==="middle"?f={top:((o||0)-r.height)/2}:f=g==="bottom"?{bottom:s&&s.bottom||0}:{top:s&&s.top||0}),Et(Et({},x),f)}function Mo(t){var a=t.align,s=t.layout,n=t.verticalAlign,o=t.itemSorter,r=Dn();return d.useLayoutEffect(()=>{r(Ei({align:a,layout:s,verticalAlign:n,itemSorter:o}))},[r,a,s,n,o]),null}function _o(t){var a=t.width,s=t.height,n=Dn();return d.useLayoutEffect(()=>{n(Xs({width:a,height:s}))},[n,a,s]),d.useLayoutEffect(()=>()=>{n(Xs({width:0,height:0}))},[n]),null}function Eo(t,a,s,n){return t==="vertical"&&a!=null?{height:a}:t==="horizontal"?{width:s||n}:null}var Io={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",labelStyle:{},layout:"horizontal",verticalAlign:"bottom"};function Ro(t){var a=ea(t,Io),s=go(),n=Ci(),o=Ti(),r=a.width,h=a.height,u=a.wrapperStyle,g=a.portal,x=ji([s]),f=fo(x,2),v=f[0],b=f[1],N=Mi(),k=_i();if(N==null||k==null)return null;var p=N-((o==null?void 0:o.left)||0)-((o==null?void 0:o.right)||0),C=Eo(a.layout,h,r,p),W=g?u:Et(Et({position:"absolute",width:(C==null?void 0:C.width)||r||"auto",height:(C==null?void 0:C.height)||h||"auto"},To(u,a,o,N,k,v)),u),S=g??n;if(S==null||s==null)return null;var I=d.createElement("div",{className:"recharts-legend-wrapper",style:W,ref:b},d.createElement(Mo,{layout:a.layout,align:a.align,verticalAlign:a.verticalAlign,itemSorter:a.itemSorter}),!g&&d.createElement(_o,{width:v.width,height:v.height}),d.createElement(Co,as({},a,C,{margin:o,chartWidth:N,chartHeight:k,contextPayload:s})));return Rr.createPortal(I,S)}var Ye=d.memo(Ro,fs);Ye.displayName="Legend";function ss(){return ss=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},ss.apply(null,arguments)}var er=t=>{var a=t.cx,s=t.cy,n=t.r,o=t.className,r=Jt("recharts-dot",o);return Oe(a)&&Oe(s)&&Oe(n)?d.createElement("circle",ss({},_a(t),Un(t),{className:r,cx:a,cy:s,r:n}
86)):null},Do=["points"];function cn(t,a){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);a&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),s.push.apply(s,n)}return s}function Wa(t){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};a%2?cn(Object(s),!0).forEach(function(n){Uo(t,n,s[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):cn(Object(s)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(s,n))})}return t}function Uo(t,a,s){return(a=$o(a))in t?Object.defineProperty(t,a,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[a]=s,t}function $o(t){var a=Lo(t,"string");return typeof a=="symbol"?a:a+""}function Lo(t,a){if(typeof t!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var n=s.call(t,a||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function Sa(){return Sa=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},Sa.apply(null,arguments)}function Oo(t,a){if(t==null)return{};var s,n,o=Fo(t,a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(n=0;n<r.length;n++)s=r[n],a.indexOf(s)===-1&&{}.propertyIsEnumerable.call(t,s)&&(o[s]=t[s])}return o}function Fo(t,a){if(t==null)return{};var s={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(a.indexOf(n)!==-1)continue;s[n]=t[n]}return s}function zo(t){var a=t.option,s=t.dotProps,n=t.className;if(d.isValidElement(a))return d.cloneElement(a,s);if(typeof a=="function")return a(s);var o=Jt(n,typeof a!="boolean"?a.className:""),r=s??{};r.points;var h=Oo(r,Do);return d.createElement(er,Sa({},h,{className:o}))}function Ko(t,a){return t==null?!1:a?!0:t.length===1}function tr(t){var a=t.points,s=t.dot,n=t.className,o=t.dotClassName,r=t.dataKey,h=t.baseProps,u=t.needClip,g=t.clipPathId,x=t.zIndex,f=x===void 0?Ia.scatter:x;if(!Ko(a,s))return null;var v=vs(s),b=Ii(s),N=a.map((p,C)=>{var W,S,I=Wa(Wa(Wa({r:3},h),b),{},{index:C,cx:(W=p.x)!==null&&W!==void 0?W:void 0,cy:(S=p.y)!==null&&S!==void 0?S:void 0,dataKey:r,value:p.value,payload:p.payload,points:a});return d.createElement(zo,{key:"dot-".concat(C),option:s,dotProps:I,className:o})}),k={};return u&&g!=null&&(k.clipPath="url(#clipPath-".concat(v?"":"dots-").concat(g,")")),d.createElement(Ea,{zIndex:f},d.createElement(xt,Sa({className:n},k),N))}function dn(t,a){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);a&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),s.push.apply(s,n)}return s}function Va(t){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};a%2?dn(Object(s),!0).forEach(function(n){Bo(t,n,s[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):dn(Object(s)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(s,n))})}return t}function Bo(t,a,s){return(a=Wo(a))in t?Object.defineProperty(t,a,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[a]=s,t}function Wo(t){var a=Vo(t,"string");return typeof a=="symbol"?a:a+""}function Vo(t,a){if(typeof t!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var n=s.call(t,a||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}var Ho=t=>{var a=t.point,s=t.childIndex,n=t.mainColor,o=t.activeDot,r=t.dataKey,h=t.clipPath;if(o===!1||a.x==null||a.y==null)return null;var u={index:s,dataKey:r,cx:a.x,cy:a.y,r:4,fill:n??"none",strokeWidth:2,stroke:"#fff",payload:a.payload,value:a.value},g=Va(Va(Va({},u),$n(o)),Un(o)),x;return d.isValidElement(o)?x=d.cloneElement(o,g):typeof o=="function"?x=o(g):x=d.createElement(er,g),d.createElement(xt,{className:"recharts-active-dot",clipPath:h},x)};function ns(t){var a=t.points,s=t.mainColor,n=t.activeDot,o=t.itemDataKey,r=t.clipPath,h=t.zIndex,u=h===void 0?Ia.activeDot:h,g=Ma(Ri),x=Di();if(a==null||x==null)return null;var f=a.find(v=>x.includes(v.payload));return fa(f)?null:d.createElement(Ea,{zIndex:u},d.createElement(Ho,{point:f,childIndex:Number(g),mainColor:s,dataKey:o,activeDot:n,clipPath:r}))}var Go=["animationElapsedTime","isAnimating","isEntrance","visibleLength","strokeDasharray","connectNulls"];function rs(){return rs=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},rs.apply(null,arguments)}function qo(t,a){if(t==null)return{};var s,n,o=Yo(t,a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(n=0;n<r.length;n++)s=r[n],a.indexOf(s)===-1&&{}.propertyIsEnumerable.call(t,s)&&(o[s]=t[s])}return o}function Yo(t,a){if(t==null)return{};var s={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(a.indexOf(n)!==-1)continue;s[n]=t[n]}return s}function Qo(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function ar(t,a){return"".concat(a,"px ").concat(t,"px")}function Xo(t){return t.length%2!==0?[...t,...t]:t}function Zo(t,a){for(var s=[],n=0;n<a;++n)s.push(...t);return s}
86function Jo(t,a,s){var n=Xo(s),o=n.reduce((N,k)=>N+k,0);if(!o)return ar(a,t);for(var r=Math.floor(t/o),h=t%o,u=[],g=0,x=0;g<n.length;x+=(f=n[g])!==null&&f!==void 0?f:0,++g){var f,v=n[g];if(v!=null&&x+v>h){u=[...n.slice(0,g),h-x];break}}var b=u.length%2===0?[0,a]:[a];return[...Zo(n,r),...u,...b].map(N=>"".concat(N,"px")).join(", ")}function el(t,a,s){if(t){var n="".concat(t).split(/[,\s]+/gim).map(o=>parseFloat(o));return Jo(s,a,n)}return ar(a,s)}function tl(t){t.animationElapsedTime,t.isAnimating,t.isEntrance;var a=t.visibleLength,s=t.strokeDasharray,n=t.connectNulls,o=qo(t,Go),r=n??!1,h;if(a!=null){var u,g=o.pathRef,x=Qo((u=g==null?void 0:g.current)!==null&&u!==void 0?u:null);h=el(s,x,a)}else s!=null&&(h=String(s));return d.createElement(ga,rs({},o,{connectNulls:r,strokeDasharray:h}))}function al(t){var a=d.useRef(0),s=d.useRef(0),n=d.useRef(!1),o=d.useRef(t);return o.current!==t&&(a.current=s.current,o.current=t),d.useCallback((r,h)=>{if(n.current)return null;var u=Math.min(Ui(a.current+r*h),h);return r>0&&h>0&&(s.current=Math.max(s.current,u),u>=h)?(n.current=!0,null):u},[])}var sr=(t,a,s,n)=>Ra(t,"xAxis",a,n),nr=(t,a,s,n)=>Da(t,"xAxis",a,n),rr=(t,a,s,n)=>Ra(t,"yAxis",s,n),ir=(t,a,s,n)=>Da(t,"yAxis",s,n),sl=ft([ta,sr,rr,nr,ir],(t,a,s,n,o)=>ys(t,"xAxis")?va(a,n,!1):va(s,o,!1)),nl=(t,a,s,n,o)=>o;function rl(t){return t.type==="line"}var il=ft([Ln,nl],(t,a)=>t.filter(rl).find(s=>s.id===a)),ol=ft([ta,sr,rr,nr,ir,il,sl,$i],(t,a,s,n,o,r,h,u)=>{var g=u.chartData,x=u.dataStartIndex,f=u.dataEndIndex;if(!(r==null||a==null||s==null||n==null||o==null||n.length===0||o.length===0||h==null||t!=="horizontal"&&t!=="vertical")){var v=r.dataKey,b=r.data,N;if(b!=null&&b.length>0?N=b:N=g==null?void 0:g.slice(x,f+1),N!=null)return Cl({layout:t,xAxis:a,yAxis:s,xAxisTicks:n,yAxisTicks:o,dataKey:v,bandSize:h,displayedData:N})}});function or(t){var a=$n(t),s=3,n=2;if(a!=null){var o=a.r,r=a.strokeWidth,h=Number(o),u=Number(r);return(Number.isNaN(h)||h<0)&&(h=s),(Number.isNaN(u)||u<0)&&(u=n),{r:h,strokeWidth:u}}return{r:s,strokeWidth:n}}var ll=["id"],cl=["type","layout","connectNulls","needClip","shape","strokeDasharray"],dl=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function wa(){return wa=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},wa.apply(null,arguments)}function Ns(t,a){if(t==null)return{};var s,n,o=ul(t,a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(n=0;n<r.length;n++)s=r[n],a.indexOf(s)===-1&&{}.propertyIsEnumerable.call(t,s)&&(o[s]=t[s])}return o}function ul(t,a){if(t==null)return{};var s={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(a.indexOf(n)!==-1)continue;s[n]=t[n]}return s}function un(t,a){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);a&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),s.push.apply(s,n)}return s}function We(t){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};a%2?un(Object(s),!0).forEach(function(n){ml(t,n,s[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):un(Object(s)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(s,n))})}return t}function ml(t,a,s){return(a=pl(a))in t?Object.defineProperty(t,a,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[a]=s,t}function pl(t){var a=hl(t,"string");return typeof a=="symbol"?a:a+""}function hl(t,a){if(typeof t!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var n=s.call(t,a||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function gl(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function xl(t){var a=0,s=0;for(var n of t)n.status==="matched"&&n.prev.x!=null&&n.next.x!=null&&(a+=n.next.x-n.prev.x,s++);return s>0?a/s:0}var fl=(t,a)=>{if(t==null)return[];if(a===1)return t.flatMap(u=>u.status==="removed"?[]:[u.next]);var s=xl(t),n=[];
86for(var o of t)if(o.status==="matched")n.push(We(We({},o.next),{},{x:ct(o.prev.x,o.next.x,a),y:ct(o.prev.y,o.next.y,a)}));else if(o.status==="added")if(o.next.x!=null){var r=o.next.x-s;n.push(We(We({},o.next),{},{x:ct(r,o.next.x,a),y:o.next.y}))}else n.push(o.next);else if(o.status==="removed"&&o.prev.x!=null){var h=o.prev.x+s;n.push(We(We({},o.prev),{},{x:ct(o.prev.x,h,a),y:o.prev.y}))}return n},Ss={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",animationInterpolateFn:fl,animationMatchBy:Vn,connectNulls:!1,dot:!0,fill:"#fff",hide:!1,isAnimationActive:"auto",label:!1,legendType:"line",shape:tl,stroke:"#3182bd",strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:Ia.line,type:"linear"},vl=t=>{var a=t.dataKey,s=t.name,n=t.stroke,o=t.legendType,r=t.hide;return[{inactive:r,dataKey:a,type:o,color:n,value:$a(s,a),payload:t}]},yl=d.memo(t=>{var a=t.dataKey,s=t.data,n=t.stroke,o=t.strokeWidth,r=t.fill,h=t.name,u=t.hide,g=t.unit,x=t.tooltipType,f=t.id,v={dataDefinedOnItem:s,getPosition:Hn,settings:{stroke:n,strokeWidth:o,fill:r,dataKey:a,nameKey:void 0,name:$a(h,a),hide:u,type:x,color:n,unit:g,graphicalItemId:f}};return d.createElement(Kn,{tooltipEntrySettings:v})});function bl(t){var a=t.clipPathId,s=t.points,n=t.props,o=n.dot,r=n.dataKey,h=n.needClip;n.id;var u=Ns(n,ll),g=_a(u);return d.createElement(tr,{points:s,dot:o,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:r,baseProps:g,needClip:h,clipPathId:a})}function jl(t){var a=t.showLabels,s=t.children,n=t.points,o=d.useMemo(()=>n==null?void 0:n.map(r=>{var h,u,g={x:(h=r.x)!==null&&h!==void 0?h:0,y:(u=r.y)!==null&&u!==void 0?u:0,width:0,lowerWidth:0,upperWidth:0,height:0};return We(We({},g),{},{value:r.value,payload:r.payload,viewBox:g,parentViewBox:void 0,fill:void 0})}),[n]);return d.createElement(Qn,{value:a?o:void 0},s)}function Nl(t){var a=t.clipPathId,s=t.pathRef,n=t.points,o=t.props,r=t.animationElapsedTime,h=t.isAnimating,u=t.isEntrance,g=t.visibleLength,x=o.type,f=o.layout,v=o.connectNulls,b=o.needClip,N=o.shape,k=o.strokeDasharray,p=Ns(o,cl),C=We(We({},Xn(p)),{},{fill:"none",className:"recharts-line-curve",clipPath:b?"url(#clipPath-".concat(a,")"):void 0,points:n,type:x,layout:f,connectNulls:v,strokeDasharray:k??o.strokeDasharray,pathRef:s,animationElapsedTime:r,isAnimating:h,isEntrance:o.animateNewValues?u:!1,visibleLength:g});return d.createElement(d.Fragment,null,(n==null?void 0:n.length)>1&&d.createElement(Zn,{option:N,DefaultShape:Ss.shape,shapeProps:C}),d.createElement(bl,{points:n,clipPathId:a,props:o}))}function Sl(t){var a=t.clipPathId,s=t.props,n=t.pathRef,o=t.previousPointsRef,r=s.points,h=s.isAnimationActive,u=s.animationBegin,g=s.animationDuration,x=s.animationEasing,f=s.animationMatchBy,v=s.animationInterpolateFn,b=s.layout,N=gl(n.current),k=Gn(s.onAnimationStart,s.onAnimationEnd),p=k.isAnimating,C=k.handleAnimationStart,W=k.handleAnimationEnd,S=!p,I=al(r),D=d.useCallback(_=>_>0&&N>0,[N]);return d.createElement(jl,{points:r,showLabels:S},s.children,d.createElement(qn,{animationInput:r,animationIdPrefix:"recharts-line-",items:r,previousItemsRef:o,isAnimationActive:h,animationBegin:u,animationDuration:g,animationEasing:x,onAnimationStart:C,onAnimationEnd:W,animationInterpolateFn:v,animationMatchBy:f,shouldUpdatePreviousRef:D,layout:b},(_,V,B)=>{var F=p||V<1,de=F?I(V,N):null;return d.createElement(Nl,{props:s,points:_,clipPathId:a,pathRef:n,animationElapsedTime:V,isAnimating:F,isEntrance:B,visibleLength:de})}),d.createElement(Yn,{label:s.label}))}function wl(t){var a=t.clipPathId,s=t.props,n=d.useRef(null),o=d.useRef(null);return d.createElement(Sl,{props:s,clipPathId:a,previousPointsRef:n,pathRef:o})}var Al=(t,a)=>{var s,n;return{x:(s=t.x)!==null&&s!==void 0?s:void 0,y:(n=t.y)!==null&&n!==void 0?n:void 0,value:t.value,errorVal:ya(t.payload,a)}};class kl extends d.Component{render(){var a=this.props,s=a.hide,n=a.dot,o=a.points,r=a.className,h=a.xAxisId,u=a.yAxisId,g=a.top,x=a.left,f=a.width,v=a.height,b=a.id,N=a.needClip,k=a.zIndex;if(s)return null;var p=Jt("recharts-line",r),C=b,W=or(n),S=W.r,I=W.strokeWidth,D=vs(n),_=S*2+I,V=N?"url(#clipPath-".concat(D?"":"dots-").concat(C,")"):void 0;return d.createElement(Ea,{zIndex:k},d.createElement(xt,{className:p},N&&d.createElement("defs",null,d.createElement(Rn,{clipPathId:C,xAxisId:h,yAxisId:u}),!D&&d.createElement("clipPath",{id:"clipPath-dots-".concat(C)},d.createElement("rect",{x:x-_/2,y:g-_/2,width:f+_,height:v+_}))),d.createElement(Si,{xAxisId:h,yAxisId:u,data:o,dataPointFormatter:Al,errorBarOffset:0},d.createElement(wl,{props:this.props,clipPathId:C}))),d.createElement(ns,{activeDot:this.props.activeDot,points:o,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:V}))}}function Pl(t){var a=ea(t,Ss),s=a.activeDot,n=a.animateNewValues,o=a.animationBegin,r=a.animationDuration,h=a.animationEasing,u=a.connectNulls,g=a.dot,x=a.hide,f=a.isA
86nimationActive,v=a.label,b=a.legendType,N=a.xAxisId,k=a.yAxisId,p=a.id,C=Ns(a,dl),W=In(N,k),S=W.needClip,I=Bn(),D=Wn(),_=Ua(),V=Ma(ye=>ol(ye,N,k,_,p));if(D!=="horizontal"&&D!=="vertical"||V==null||I==null)return null;var B=I.height,F=I.width,de=I.x,q=I.y;return d.createElement(kl,wa({},C,{id:p,connectNulls:u,dot:g,activeDot:s,animateNewValues:n,animationBegin:o,animationDuration:r,animationEasing:h,isAnimationActive:f,hide:x,label:v,legendType:b,xAxisId:N,yAxisId:k,points:V,layout:D,height:B,width:F,left:de,top:q,needClip:S}))}function Cl(t){var a=t.layout,s=t.xAxis,n=t.yAxis,o=t.xAxisTicks,r=t.yAxisTicks,h=t.dataKey,u=t.bandSize,g=t.displayedData;return g.map((x,f)=>{var v=ya(x,h);if(a==="horizontal"){var b=ba({axis:s,ticks:o,bandSize:u,entry:x,index:f}),N=fa(v)?null:n.scale.map(v);return{x:b,y:N??null,value:v,payload:x}}var k=fa(v)?null:s.scale.map(v),p=ba({axis:n,ticks:r,bandSize:u,entry:x,index:f});return k==null||p==null?null:{x:k,y:p,value:v,payload:x}}).filter(Boolean)}function Tl(t){var a=ea(t,Ss),s=Ua();return d.createElement(On,{id:a.id,type:"line"},n=>d.createElement(d.Fragment,null,d.createElement(Fn,{legendPayload:vl(a)}),d.createElement(yl,{dataKey:a.dataKey,data:a.data,stroke:a.stroke,strokeWidth:a.strokeWidth,fill:a.fill,name:a.name,hide:a.hide,unit:a.unit,tooltipType:a.tooltipType,id:n}),d.createElement(zn,{type:"line",id:n,data:a.data,xAxisId:a.xAxisId,yAxisId:a.yAxisId,zAxisId:0,dataKey:a.dataKey,hide:a.hide,isPanorama:s}),d.createElement(Pl,wa({},a,{id:n}))))}var is=d.memo(Tl,fs);is.displayName="Line";var lr=(t,a,s)=>Ra(t,"xAxis",hs(t,a),s),cr=(t,a,s)=>Da(t,"xAxis",hs(t,a),s),dr=(t,a,s)=>Ra(t,"yAxis",gs(t,a),s),ur=(t,a,s)=>Da(t,"yAxis",gs(t,a),s),Ml=ft([ta,lr,dr,cr,ur],(t,a,s,n,o)=>ys(t,"xAxis")?va(a,n,!1):va(s,o,!1)),_l=(t,a)=>a,mr=ft([Ln,_l],(t,a)=>t.filter(s=>s.type==="area").find(s=>s.id===a)),pr=t=>{var a=ta(t),s=ys(a,"xAxis");return s?"yAxis":"xAxis"},El=(t,a)=>{var s=pr(t);return s==="yAxis"?gs(t,a):hs(t,a)},Il=(t,a,s)=>zi(t,pr(t),El(t,a),s),Rl=ft([mr,Il],(t,a)=>{var s;if(!(t==null||a==null)){var n=t.stackId,o=Li(t);if(!(n==null||o==null)){var r=(s=a[n])===null||s===void 0?void 0:s.stackedData,h=r==null?void 0:r.find(u=>u.key===o);if(h!=null)return h.map(u=>[u[0],u[1]])}}}),Dl=ft([ta,lr,dr,cr,ur,Rl,Oi,Ml,mr,Fi],(t,a,s,n,o,r,h,u,g,x)=>{var f=h.chartData,v=h.dataStartIndex,b=h.dataEndIndex;if(!(g==null||t!=="horizontal"&&t!=="vertical"||a==null||s==null||n==null||o==null||n.length===0||o.length===0||u==null)){var N=g.data,k;if(N&&N.length>0?k=N:k=f==null?void 0:f.slice(v,b+1),k!=null)return oc({layout:t,xAxis:a,yAxis:s,xAxisTicks:n,yAxisTicks:o,dataStartIndex:v,areaSettings:g,stackedData:r,displayedData:k,chartBaseValue:x,bandSize:u})}}),Ul=["animationElapsedTime","isAnimating","isEntrance","layout","isRange","stroke","connectNulls"],$l=["id","baseLine"];function Xt(){return Xt=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},Xt.apply(null,arguments)}function mn(t,a){if(t==null)return{};var s,n,o=Ll(t,a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(n=0;n<r.length;n++)s=r[n],a.indexOf(s)===-1&&{}.propertyIsEnumerable.call(t,s)&&(o[s]=t[s])}return o}function Ll(t,a){if(t==null)return{};var s={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(a.indexOf(n)!==-1)continue;s[n]=t[n]}return s}function Ol(t){var a,s,n=t.alpha,o=t.baseLine,r=t.points,h=t.strokeWidth,u=(a=r[0])===null||a===void 0?void 0:a.x,g=(s=r[r.length-1])===null||s===void 0?void 0:s.x;if(!ja(u)||!ja(g))return null;var x=n*Math.abs(u-g),f=Math.max(...r.map(v=>v.y||0));return Oe(o)?f=Math.max(o,f):o&&Array.isArray(o)&&o.length&&(f=Math.max(...o.map(v=>v.y||0),f)),Oe(f)?d.createElement("rect",{x:u<g?u:u-x,y:0,width:x,height:Math.floor(f+(h?parseInt("".concat(h),10):1))}):null}function Fl(t){var a,s,n=t.alpha,o=t.baseLine,r=t.points,h=t.strokeWidth,u=(a=r[0])===null||a===void 0?void 0:a.y,g=(s=r[r.length-1])===null||s===void 0?void 0:s.y;if(!ja(u)||!ja(g))return null;var x=n*Math.abs(u-g),f=Math.max(...r.map(v=>v.x||0));return Oe(o)?f=Math.max(o,f):o&&Array.isArray(o)&&o.length&&(f=Math.max(...o.map(v=>
86v.x||0),f)),Oe(f)?d.createElement("rect",{x:0,y:u<g?u:u-x,width:f+(h?parseInt("".concat(h),10):1),height:Math.floor(x)}):null}function zl(t){var a=t.alpha,s=t.layout,n=t.points,o=t.baseLine,r=t.strokeWidth;return s==="vertical"?d.createElement(Fl,{alpha:a,points:n,baseLine:o,strokeWidth:r}):d.createElement(Ol,{alpha:a,points:n,baseLine:o,strokeWidth:r})}function Kl(t){var a=t.animationElapsedTime,s=a===void 0?1:a,n=t.isAnimating,o=n===void 0?!1:n,r=t.isEntrance,h=r===void 0?!1:r,u=t.layout,g=t.isRange,x=t.stroke,f=t.connectNulls,v=mn(t,Ul),b=u==="vertical"?"vertical":"horizontal",N=f??!1,k=Ki(),p=v.id,C=v.baseLine,W=mn(v,$l),S=_a(W),I=d.createElement(ga,Xt({},v,{id:p,baseLine:C,connectNulls:N,stroke:"none",className:"recharts-area-area",layout:b})),D=x!=="none"&&d.createElement(ga,Xt({},S,{className:"recharts-area-curve",layout:b,type:v.type,connectNulls:N,fill:"none",stroke:x,points:v.points})),_=x!=="none"&&g&&Array.isArray(C)&&d.createElement(ga,Xt({},S,{className:"recharts-area-curve",layout:b,type:v.type,connectNulls:N,fill:"none",stroke:x,points:C}));if(h&&(o||s<1)){var V;return d.createElement(xt,null,d.createElement("defs",null,d.createElement("clipPath",{id:k},d.createElement(zl,{alpha:s,points:(V=v.points)!==null&&V!==void 0?V:[],baseLine:C,layout:b,strokeWidth:v.strokeWidth}))),d.createElement(xt,{clipPath:"url(#".concat(k,")")},I,D,_))}return d.createElement(d.Fragment,null,I,D,_)}var Bl=["id"],Wl=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function Aa(){return Aa=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)({}).hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},Aa.apply(null,arguments)}function hr(t,a){if(t==null)return{};var s,n,o=Vl(t,a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(n=0;n<r.length;n++)s=r[n],a.indexOf(s)===-1&&{}.propertyIsEnumerable.call(t,s)&&(o[s]=t[s])}return o}function Vl(t,a){if(t==null)return{};var s={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(a.indexOf(n)!==-1)continue;s[n]=t[n]}return s}function pn(t,a){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);a&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),s.push.apply(s,n)}return s}function It(t){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};a%2?pn(Object(s),!0).forEach(function(n){Hl(t,n,s[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):pn(Object(s)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(s,n))})}return t}function Hl(t,a,s){return(a=Gl(a))in t?Object.defineProperty(t,a,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[a]=s,t}function Gl(t){var a=ql(t,"string");return typeof a=="symbol"?a:a+""}function ql(t,a){if(typeof t!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var n=s.call(t,a||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}var Yl=(t,a)=>t==null?[]:a===1?t.flatMap(s=>s.status==="removed"?[]:[s.next]):t.flatMap(s=>s.status==="matched"?[It(It({},s.next),{},{x:ct(s.prev.x,s.next.x,a),y:ct(s.prev.y,s.next.y,a)})]:s.status==="added"?[s.next]:[]),gr={activeDot:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",animationMatchBy:Vn,animationInterpolateFn:Yl,connectNulls:!1,dot:!1,fill:"#3182bd",fillOpacity:.6,hide:!1,isAnimationActive:"auto",legendType:"line",stroke:"#3182bd",strokeWidth:1,type:"linear",label:!1,shape:Kl,xAxisId:0,yAxisId:0,zIndex:Ia.area};function ka(t,a){return t&&t!=="none"?t:a}var Ql=t=>{var a=t.dataKey,s=t.name,n=t.stroke,o=t.fill,r=t.legendType,h=t.hide;return[{inactive:h,dataKey:a,type:r,color:ka(n,o),value:$a(s,a),payload:t}]},Xl=d.memo(t=>{var a=t.dataKey,s=t.data,n=t.stroke,o=t.strokeWidth,r=t.fill,h=t.name,u=t.hide,g=t.unit,x=t.tooltipType,f=t.id,v={dataDefinedOnItem:s,getPosition:Hn,settings:{stroke:n,strokeWidth:o,fill:r,dataKey:a,nameKey:void 0,name:$a(h,a),hide:u,type:x,color:ka(n,r),unit:g,graphicalItemId:f}};return d.createElement(Kn,{tooltipEntrySettings:v})});function Zl(t){var a=t.clipPathId,s=t.points,n=t.props,o=n.needClip,r=n.dot,h=n.dataKey,u=_a(n);return d.createElement(tr,{points:s,dot:r,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:h,baseProps:u,needClip:o,clipPathId:a})}function Jl(t){var a=t.showLabels,s=t.children,n=t.points,o=n.map(r=>{var h,u,g={x:(h=r.x)!==null&&h!==void 0?h:0,y:(u=r.y)!==null&&u!==void 0?u:0,width:0,lowerWidth:0,upperWidth:0,height:0};return It(It({},g),{}
86,{value:r.value,payload:r.payload,parentViewBox:void 0,viewBox:g,fill:void 0})});return d.createElement(Qn,{value:a?o:void 0},s)}function ec(t){var a=t.points,s=t.baseLine,n=t.needClip,o=t.clipPathId,r=t.props,h=t.animationElapsedTime,u=t.isAnimating,g=t.isEntrance,x=r.layout,f=r.type,v=r.stroke,b=r.connectNulls,N=r.isRange,k=r.shape,p=r.id,C=hr(r,Bl),W=Xn(C),S=It(It({},W),{},{id:p,points:a,connectNulls:b,type:f,baseLine:s,layout:x,stroke:v,isRange:N,animationElapsedTime:h,isAnimating:u,isEntrance:g});return d.createElement(d.Fragment,null,(a==null?void 0:a.length)>1&&d.createElement(xt,{clipPath:n?"url(#clipPath-".concat(o,")"):void 0},d.createElement(Zn,{option:k,DefaultShape:gr.shape,shapeProps:S})),d.createElement(Zl,{points:a,props:C,clipPathId:o}))}function tc(t,a,s){if(Oe(t)){var n=Oe(a)?a:void 0;return ct(n,t,s)}if(fa(t)||Gi(t)){var o=Oe(a)?a:void 0;return ct(o,0,s)}return t}function ac(t){var a=t.needClip,s=t.clipPathId,n=t.props,o=t.previousPointsRef,r=t.previousBaselineRef,h=n.points,u=n.baseLine,g=n.isAnimationActive,x=n.animationBegin,f=n.animationDuration,v=n.animationEasing,b=n.animationMatchBy,N=n.animationInterpolateFn,k=d.useMemo(()=>({points:h,baseLine:u}),[h,u]),p=Vi(k,r),C=Hi(),W=Gn(n.onAnimationStart,n.onAnimationEnd),S=W.isAnimating,I=W.handleAnimationStart,D=W.handleAnimationEnd,_=p.startValue;if(C==null)return null;var V;return Array.isArray(u)&&Array.isArray(_)?V=Zs(_,u,b):Array.isArray(u)?V=Zs(null,u,b):V=null,d.createElement(qn,{animationInput:k,animationIdPrefix:"recharts-area-",items:h,previousItemsRef:o,isAnimationActive:g,animationBegin:x,animationDuration:f,animationEasing:v,onAnimationStart:I,onAnimationEnd:D,animationInterpolateFn:N,animationMatchBy:b,layout:C},(B,F,de)=>{var q;return F===1?q=u:Array.isArray(u)?q=N(V,F,C):q=de?u:tc(u,_,F),p.syncStepValue(q,F),d.createElement(Jl,{showLabels:!S,points:h},n.children,d.createElement(ec,{points:B,baseLine:q,needClip:a,clipPathId:s,props:n,animationElapsedTime:F,isAnimating:S||F<1,isEntrance:de}),d.createElement(Yn,{label:n.label}))})}function sc(t){var a=t.needClip,s=t.clipPathId,n=t.props,o=d.useRef(null),r=d.useRef();return d.createElement(ac,{needClip:a,clipPathId:s,props:n,previousPointsRef:o,previousBaselineRef:r})}class nc extends d.PureComponent{render(){var a=this.props,s=a.hide,n=a.dot,o=a.points,r=a.className,h=a.top,u=a.left,g=a.needClip,x=a.xAxisId,f=a.yAxisId,v=a.width,b=a.height,N=a.id,k=a.baseLine,p=a.zIndex;if(s)return null;var C=Jt("recharts-area",r),W=N,S=or(n),I=S.r,D=S.strokeWidth,_=vs(n),V=I*2+D,B=g?"url(#clipPath-".concat(_?"":"dots-").concat(W,")"):void 0;return d.createElement(Ea,{zIndex:p},d.createElement(xt,{className:C},g&&d.createElement("defs",null,d.createElement(Rn,{clipPathId:W,xAxisId:x,yAxisId:f}),!_&&d.createElement("clipPath",{id:"clipPath-dots-".concat(W)},d.createElement("rect",{x:u-V/2,y:h-V/2,width:v+V,height:b+V}))),d.createElement(sc,{needClip:g,clipPathId:W,props:this.props})),d.createElement(ns,{points:o,mainColor:ka(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:B}),this.props.isRange&&Array.isArray(k)&&d.createElement(ns,{points:k,mainColor:ka(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:B}))}}function rc(t){var a,s=t.activeDot,n=t.animationBegin,o=t.animationDuration,r=t.animationEasing,h=t.connectNulls,u=t.dot,g=t.fill,x=t.fillOpacity,f=t.hide,v=t.isAnimationActive,b=t.legendType,N=t.stroke,k=t.xAxisId,p=t.yAxisId,C=hr(t,Wl),W=Wn(),S=Wi(),I=In(k,p),D=I.needClip,_=Ua(),V=(a=Ma(be=>Dl(be,t.id,_)))!==null&&a!==void 0?a:{},B=V.points,F=V.isRange,de=V.baseLine,q=Bn();if(W!=="horizontal"&&W!=="vertical"||q==null||S!=="AreaChart"&&S!=="ComposedChart")return null;var ye=q.height,E=q.width,Z=q.x,X=q.y;return!B||!B.length?null:d.createElement(nc,Aa({},C,{activeDot:s,animationBegin:n,animationDuration:o,animationEasing:r,baseLine:de,connectNulls:h,dot:u,fill:g,fillOpacity:x,height:ye,hide:f,layout:W,isAnimationActive:v,isRange:F,legendType:b,needClip:D,points:B,stroke:N,width:E,left:Z,top:X,xAxisId:k,yAxisId:p}))}var ic=(t,a,s,n,o)=>{var r=s??a;if(Oe(r))return r;var h=t==="horizontal"?o:n,u=h.scale.domain();if(h.type==="number"){var g=Math.max(u[0],u[1]),x=Math.min(u[0],u[1]);return r==="dataMin"?x:r==="dataMax"||g<0?g:Math.max(Math.min(u[0],u[1]),0)}return r==="dataMin"?u[0]:r==="dataMax"?u[1]:u[0]};function oc(t){var a=t.areaSettings,s=a.connectNulls,n=a.baseValue,o=a.dataKey,r=t.stackedData,h=t.layout,u=t.chartBaseValue,g=t.xAxis,x=t.yAxis,f=t.displayedData,v=t.dataStartIndex,b=t.xAxisTicks,N=t.yAxisTicks,k=t.bandSize,p=r&&r.length,C=ic(h,u,
86n,g,x),W=h==="horizontal",S=!1,I=f.map((_,V)=>{var B,F,de,q;if(p)q=r[v+V];else{var ye=ya(_,o);Array.isArray(ye)?(q=ye,S=!0):q=[C,ye]}var E=(B=(F=q)===null||F===void 0?void 0:F[1])!==null&&B!==void 0?B:null,Z=E==null||p&&!s&&ya(_,o)==null;if(W){var X;return{x:ba({axis:g,ticks:b,bandSize:k,entry:_,index:V}),y:Z?null:(X=x.scale.map(E))!==null&&X!==void 0?X:null,value:q,payload:_}}return{x:Z?null:(de=g.scale.map(E))!==null&&de!==void 0?de:null,y:ba({axis:x,ticks:N,bandSize:k,entry:_,index:V}),value:q,payload:_}}),D;return p||S?D=I.map(_=>{var V,B=Array.isArray(_.value)?_.value[0]:null;if(W){var F;return{x:_.x,y:B!=null&&_.y!=null&&(F=x.scale.map(B))!==null&&F!==void 0?F:null,payload:_.payload}}return{x:B!=null&&(V=g.scale.map(B))!==null&&V!==void 0?V:null,y:_.y,payload:_.payload}}):D=W?x.scale.map(C):g.scale.map(C),{points:I,baseLine:D??0,isRange:S}}function lc(t){var a=ea(t,gr),s=Ua();return d.createElement(On,{id:a.id,type:"area"},n=>d.createElement(d.Fragment,null,d.createElement(Fn,{legendPayload:Ql(a)}),d.createElement(Xl,{dataKey:a.dataKey,data:a.data,stroke:a.stroke,strokeWidth:a.strokeWidth,fill:a.fill,name:a.name,hide:a.hide,unit:a.unit,tooltipType:a.tooltipType,id:n}),d.createElement(zn,{type:"area",id:n,data:a.data,dataKey:a.dataKey,xAxisId:a.xAxisId,yAxisId:a.yAxisId,zAxisId:0,stackId:Bi(a.stackId),hide:a.hide,barSize:void 0,baseValue:a.baseValue,isPanorama:s,connectNulls:a.connectNulls}),d.createElement(rc,Aa({},a,{id:n}))))}var it=d.memo(lc,fs);it.displayName="Area";var cc=["axis"],dc=d.forwardRef((t,a)=>d.createElement(xs,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:cc,tooltipPayloadSearcher:bs,categoricalChartProps:t,ref:a})),uc=["axis"],Wt=d.forwardRef((t,a)=>d.createElement(xs,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:uc,tooltipPayloadSearcher:bs,categoricalChartProps:t,ref:a})),mc=["axis"],pc=d.forwardRef((t,a)=>
86d.createElement(xs,{chartName:"ComposedChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:mc,tooltipPayloadSearcher:bs,categoricalChartProps:t,ref:a}));function oe({title:t,value:a,icon:s,subtitle:n,color:o,trend:r}){return e.jsxs(ot,{className:"analytics-stat-card group relative overflow-hidden bg-card/60 backdrop-blur-xl border-border/40 transition-[transform,border-color,box-shadow] duration-300 ease-out hover:-translate-y-[2px] hover:border-[hsl(var(--primary)/0.45)] hover:shadow-[0_10px_40px_-12px_hsl(var(--primary)/0.35)]",children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-[hsl(var(--primary)/0.6)] to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"}),e.jsx("div",{className:"pointer-events-none absolute -inset-20 bg-[radial-gradient(circle_at_top_right,hsl(var(--primary)/0.10),transparent_60%)] opacity-0 group-hover:opacity-100 transition-opacity duration-500"}),e.jsx(lt,{className:"relative p-3.5 sm:p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2 sm:gap-3",children:[e.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[e.jsx("p",{className:"text-[10px] sm:text-[10.5px] font-medium text-muted-foreground/90 uppercase tracking-[0.1em] sm:tracking-[0.12em] leading-snug break-words",children:t}),e.jsx("p",{className:"text-[21px] sm:text-[26px] leading-none font-semibold text-foreground tabular-nums tracking-tight truncate",children:typeof a=="number"?a.toLocaleString():a}),n&&e.jsx("p",{className:"text-[11px] text-muted-foreground/80 leading-tight pt-1 break-words",children:n}),r&&e.jsxs("div",{className:"flex items-center gap-1 mt-1.5",children:[r.value>0?e.jsx(xa,{className:"h-3 w-3 text-emerald-400"}):r.value<0?e.jsx(Pn,{className:"h-3 w-3 text-red-400"}):e.jsx(Cn,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:`text-[10px] font-semibold tabular-nums ${r.value>0?"text-emerald-400":r.value<0?"text-red-400":"text-muted-foreground"}`,children:[r.value>0?"+":"",r.value,"% ",e.jsx("span",{className:"font-normal text-muted-foreground/70",children:r.label})]})]})]}),e.jsx("div",{className:`relative p-1.5 sm:p-2 rounded-xl shrink-0 ring-1 ring-inset transition-all duration-300 group-hover:scale-[1.08] ${o?`${o} ring-white/10`:"bg-[hsl(var(--primary)/0.08)] ring-[hsl(var(--primary)/0.18)]"}`,children:e.jsx(s,{className:`h-3.5 w-3.5 sm:h-4 sm:w-4 ${o?"text-white":"text-primary"}`})})]})})]})}function $({title:t,children:a,className:s,action:n}){return e.jsxs(ot,{className:`analytics-chart-card relative overflow-hidden bg-card/60 backdrop-blur-xl border-border/40 transition-colors hover:border-border/60 ${s||""}`,children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-[hsl(var(--primary)/0.35)] to-transparent"}),e.jsxs(An,{className:"pb-2 flex flex-row items-center justify-between",children:[e.jsx(kn,{className:"text-[13px] font-semibold text-foreground tracking-tight",children:t}),n]}),e.jsx(lt,{className:"pt-0",children:a})]})}function P({label:t,value:a,highlight:s,badge:n}){return e.jsxs("div",{className:"group flex items-center justify-between py-2.5 px-1.5 -mx-1.5 rounded-md border-b border-border/15 last:border-0 transition-colors hover:bg-[hsl(var(--primary)/0.04)]",children:[e.jsx("span",{className:"text-[13px] text-muted-foreground group-hover:text-foreground/90 transition-colors",children:t}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx(ue,{variant:"secondary",className:"text-[9px] px-1.5 py-0 bg-muted/60 border-border/30",children:n}),e.jsx("span",{className:`text-[13px] font-semibold tabular-nums ${s?"text-primary":"text-foreground"}`,children:typeof a=="number"?a.toLocaleString():a})]})]})}function ze({icon:t,title:a,subtitle:s}){return e.jsxs("div",{className:"mb-3 flex items-end justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h2",{className:"text-[11px] font-semibold text-muted-foreground/90 uppercase tracking-[0.14em] flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"inline-flex shrink-0 items-center justify-center h-5 w-5 rounded-md bg-[hsl(var(--primary)/0.08)] ring-1 ring-inset ring-[hsl(var(--primary)/0.2)]",children:e.jsx(t,{className:"h-3 w-3 text-primary"})}),e.jsx("span",{className:"min-w-0 break-words leading-tight",children:a})]}),s&&e.jsx("p",{className:"text-[11px] leading-snug text-muted-foreground
86/70 mt-1 ml-0 sm:ml-7",children:s})]}),e.jsx("div",{className:"hidden sm:block flex-1 h-px bg-gradient-to-r from-border/40 via-border/15 to-transparent translate-y-[-6px]"})]})}function hn({emoji:t,title:a,description:s,severity:n}){const o={info:"bg-muted-foreground/50",positive:"bg-emerald-400/70",warning:"bg-amber-400/70",critical:"bg-red-400/70"},r=n||"info";return e.jsx("div",{className:"group relative rounded-xl border border-border/45 bg-card/35 p-3.5 transition-colors duration-300 hover:bg-card/50",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("span",{className:"text-lg leading-none",children:t}),e.jsx("span",{className:`absolute -top-0.5 -right-0.5 h-1.5 w-1.5 rounded-full ${o[r]}`})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[13px] font-semibold text-foreground tracking-tight",children:a}),e.jsx("p",{className:"text-[11px] text-muted-foreground/85 mt-1 leading-snug",children:s})]})]})})}const Ae=["hsl(192, 80%, 53%)","hsl(201, 98%, 39%)","hsl(38, 92%, 50%)","hsl(142, 71%, 45%)","hsl(0, 72%, 51%)","hsl(270, 70%, 55%)","hsl(340, 75%, 55%)","hsl(50, 90%, 50%)"],se={background:"hsl(var(--card) / 0.95)",border:"1px solid hsl(var(--border) / 0.6)",borderRadius:"10px",fontSize:"11px",boxShadow:"0 10px 40px -12px hsl(0 0% 0% / 0.4)",backdropFilter:"blur(12px)"},nt=t=>{const a=new Date(t);return`${a.getMonth()+1}/${a.getDate()}`};function Ge(t,a){return a===0?{value:t>0?100:0,label:"vs prior 24h"}:{value:Math.round((t-a)/a*100),label:"vs prior 24h"}}function hc(t,a){const s=[];return a.stickiness>30?s.push({emoji:"ð¥",title:`Strong daily stickiness: ${a.stickiness}%`,description:"DAU/MAU ratio indicates healthy daily engagement",severity:"positive"}):a.stickiness<10&&a.stickiness>0&&s.push({emoji:"â ï¸",title:`Low stickiness: ${a.stickiness}%`,description:"Users are not returning frequently enough",severity:"warning"}),a.paidConversionRate>5&&s.push({emoji:"ð°",title:`Paid conversion at ${a.paidConversionRate}%`,description:"Above typical SaaS benchmarks",severity:"positive"}),t.messagesToday>t.messagesYesterday*1.2&&s.push({emoji:"ð¬",title:"Message volume surging",description:`${t.messagesToday.toLocaleString()} messages in last 24h, above prior 24h pace`,severity:"positive"}),a.appleChurnRate>30&&s.push({emoji:"ð´",title:`Apple churn at ${a.appleChurnRate}%`,description:"Investigate iOS retention strategies",severity:"critical"}),a.forumParticipation<5&&s.push({emoji:"ðï¸",title:`Forum participation at ${a.forumParticipation}%`,description:"Opportunity to drive more community engagement",severity:"info"}),a.avgMsgsPerConvo>10&&s.push({emoji:"ð§ ",title:`Deep conversations: ${a.avgMsgsPerConvo} msgs/convo avg`,description:"Users are having substantive interactions",severity:"positive"}),s.length===0&&s.push({emoji:"ð",title:"Platform running normally",description:"No significant anomalies detected this period",severity:"info"}),s.slice(0,8)}const Rt=[{id:"overview",label:"Overview",items:[{value:"overview",label:"Executive Overview",icon:Xa,keywords:"kpi summary live"}]},{id:"audience",label:"Audience",items:[{value:"engagement",label:"Engagement",icon:Mt,keywords:"retention stickiness"},{value:"audienceprofile",label:"Audience Profile",icon:no,keywords:"persona who uses demographics region profile"},{value:"users",label:"Users",icon:Za,keywords:"segments accounts"},{value:"geographic",label:"Geographic",icon:ni,keywords:"countries cities map"},{value:"traffic",label:"Traffic Sources",icon:Qa,keywords:"referrers acquisition"},{value:"signupaudit",label:"Signup Audit",icon:Hs,keywords:"auth blocked"}]},{id:"content",label:"Content",items:[{value:"content",label:"Content",icon:qt,keywords:"conversations messages"},{value:"community",label:"Community",icon:ri,keywords:"forum 1a posts"},{value:"trending",label:"Trending",icon:ii,keywords:"topics"},{value:"rabbithole",label:"Rabbit Hole",icon:oi,keywords:"archives"},{value:"landing",label:"Landing Pages",icon:ci,keywords:"seo"}]},{id:"intelligence",label:"AI Intelligence",items:[{value:"intelligence",label:"Intelligence",icon:_t,keywords:"topics intents prompts"},{value:"streaming",label:"Streaming Smoothness",icon:Mt,keywords:"choppy lag ttft speed pro"},{value:"memory",label:"Memory",icon:_n,keywords:"semantic"},{value:"context",label:"Context",icon:Yi,keywords:"hidden context"},{value:"voice",label:"Voice",icon:Ur,keywords:"tts stt"},{value:"feedback",label:"Feedback",icon:En,keywords:"ratings thumbs"}]},{id:"products",label:"Products & Features",items:[{value:"whomogged",label:"Who Mogged",icon:di},{value:"slopornot",label:"Slop Score",icon:so}
86,{value:"factcrack",label:"FactCrack",icon:_t,keywords:"game quiz"},{value:"rabbitrun",label:"Rabbit Run",icon:Xi,keywords:"game"},{value:"assetsirl",label:"Assets IRL",icon:tn,keywords:"portfolio net worth assets"},{value:"intake",label:"Intake",icon:Zi,keywords:"submissions"},{value:"api",label:"API",icon:to,keywords:"keys credits"}]},{id:"revenue",label:"Revenue",items:[{value:"monetization",label:"Monetization",icon:Ja,keywords:"stripe subscriptions"},{value:"protrial",label:"Pro Trial",icon:es},{value:"cancellations",label:"Cancellations",icon:Qi,keywords:"churn"},{value:"recovery",label:"Revenue Recovery",icon:ui,keywords:"dunning past due"}]},{id:"operations",label:"Operations",items:[{value:"livefeed",label:"Live Feed",icon:Mn,keywords:"questions realtime"},{value:"data",label:"Data",icon:tn,keywords:"explorer tables"},{value:"emailusers",label:"Email Users",icon:$r},{value:"bannedisps",label:"Banned ISPs",icon:js},{value:"clienterrors",label:"Client Errors",icon:ps},{value:"moderation",label:"1A Moderation",icon:Lr},{value:"adminaccess",label:"Admin Access",icon:Hs,keywords:"admins roles permissions emails portal access"},{value:"investordeck",label:"Investor Deck",icon:mi,href:"/investor/deck",keywords:"investors pitch deck data room"}]}],gc=Rt.flatMap(t=>t.items.map(a=>({...a,group:t.label})));function xc(t){return gc.find(a=>a.value===t)}const gn="uai.analytics.sidebar.collapsed.v2",xn="uai.analytics.sidebar.groups";function fc(t){const[a,s]=d.useState(()=>{try{const n=localStorage.getItem(xn);if(n)return JSON.parse(n)}catch{}return Object.fromEntries(Rt.map(n=>[n.id,!0]))});return d.useEffect(()=>{try{localStorage.setItem(xn,JSON.stringify(a))}catch{}},[a]),d.useEffect(()=>{const n=Rt.find(o=>o.items.some(r=>r.value===t));n&&!a[n.id]&&s(o=>({...o,[n.id]:!0}))},[t]),[a,s]}function vc(){const[t,a]=d.useState(()=>{try{return localStorage.getItem(gn)==="1"}catch{return!1}});return d.useEffect(()=>{try{localStorage.setItem(gn,t?"1":"0")}catch{}},[t]),[t,a]}const os="group/nav w-full flex items-center gap-2.5 rounded-lg px-2.5 py-[7px] text-[12.5px] text-left transition-[background-color,color,box-shadow] duration-200 outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--primary)/0.6)]";function yc({item:t,active:a,collapsed:s,onSelect:n}){const o=t.icon,r=ke(os,s&&"justify-center px-0 py-2","text-muted-foreground hover:bg-foreground
86/[0.04] hover:text-foreground");return t.href?e.jsxs(wn,{to:t.href,title:s?t.label:void 0,className:r,children:[e.jsx("span",{className:"relative flex items-center justify-center shrink-0",children:e.jsx(o,{className:"h-[15px] w-[15px] text-muted-foreground/70 group-hover/nav:text-foreground/80 transition-colors"})}),!s&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"truncate",children:t.label}),e.jsx(Tn,{className:"ml-auto h-3 w-3 shrink-0 text-muted-foreground/50"})]})]}):e.jsxs("button",{type:"button",onClick:()=>n(t.value),title:s?t.label:void 0,"aria-current":a?"page":void 0,className:ke(os,s&&"justify-center px-0 py-2",a?"bg-[hsl(var(--primary)/0.10)] text-foreground shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.22)]":"text-muted-foreground hover:bg-foreground/[0.04] hover:text-foreground"),children:[e.jsx("span",{className:"relative flex items-center justify-center shrink-0",children:e.jsx(o,{className:ke("h-[15px] w-[15px] transition-colors",a?"text-primary":"text-muted-foreground/70 group-hover/nav:text-foreground/80")})}),!s&&e.jsx("span",{className:"truncate",children:t.label})]})}const bc=d.memo(function({activeTab:a,onSelect:s,collapsed:n,onToggleCollapsed:o}){const[r,h]=fc(a);return e.jsxs("nav",{"aria-label":"Analytics sections",className:ke("hidden lg:flex flex-col shrink-0 sticky top-[57px] max-h-[calc(100dvh-57px)] transition-[width] duration-200 ease-out",n?"w-[56px]":"w-[212px]"),children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-1 bg-background/85 backdrop-blur-sm pt-3 pb-2 pr-2",children:[!n&&e.jsx("span",{className:"flex-1 min-w-0 px-2.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/55",children:"Sections"}),e.jsx("button",{type:"button",onClick:o,title:n?"Expand sidebar":"Collapse sidebar","aria-label":n?"Expand sidebar":"Collapse sidebar","aria-expanded":!n,className:ke("press shrink-0 flex items-center justify-center rounded-lg border border-border/50 bg-card/40 text-muted-foreground transition-colors duration-200 hover:text-foreground hover:border-[hsl(var(--primary)/0.4)] hover:bg-[hsl(var(--primary)/0.08)] outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--primary)/0.6)]",n?"mx-auto h-8 w-8":"h-7 w-7"),children:n?e.jsx(sn,{className:"h-[15px] w-[15px]"}):e.jsx(an,{className:"h-[15px] w-[15px]"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-hide pb-4 pr-2 space-y-4",children:Rt.map(u=>{const g=n?!0:r[u.id]!==!1;return e.jsxs("div",{className:"space-y-0.5",children:[!n&&e.jsxs("button",{type:"button",onClick:()=>h(x=>({...x,[u.id]:!g})),"aria-expanded":g,className:"w-full flex items-center gap-1 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/60 hover:text-muted-foreground transition-colors",children:[e.jsx(Dr,{className:ke("h-3 w-3 transition-transform duration-200",g&&"rotate-90")}),u.label]}),n&&e.jsx("div",{className:"mx-3 my-2 h-px bg-border/40"}),g&&e.jsx("div",{className:"space-y-0.5",children:u.items.map(x=>e.jsx(yc,{item:x,active:x.value===a,collapsed:n,onSelect:s},x.value))})]},u.id)})}),e.jsx("div",{className:"border-t border-border/40 p-2",children:e.jsxs("button",{type:"button",onClick:o,className:ke(os,"text-muted-foreground hover:text-foreground hover:bg-foreground
86/[0.04]",n&&"justify-center px-0 py-2"),"aria-label":n?"Expand sidebar":"Collapse sidebar",children:[n?e.jsx(sn,{className:"h-[15px] w-[15px]"}):e.jsx(an,{className:"h-[15px] w-[15px]"}),!n&&e.jsx("span",{children:"Collapse"})]})})]})});function jc({openState:t,onOpenChange:a,activeTab:s,onSelect:n}){const[o,r]=d.useState("");d.useEffect(()=>{t||r("")},[t]);const h=d.useMemo(()=>{const g=o.trim().toLowerCase();return g?Rt.map(x=>({...x,items:x.items.filter(f=>f.label.toLowerCase().includes(g)||(f.keywords??"").includes(g)||x.label.toLowerCase().includes(g))})).filter(x=>x.items.length>0):Rt},[o]),u=g=>{n(g),a(!1)};return e.jsx(ti,{open:t,onOpenChange:a,children:e.jsxs(ai,{side:"left",className:"sidebar-solid-panel w-[86vw] max-w-[340px] p-0 flex flex-col gap-0 border-border/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-4 border-b border-border/40",style:{paddingTop:"calc(var(--safe-top, 0px) + 14px)",paddingBottom:"12px"},children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground/70",children:"Uncensored AI"}),e.jsx("p",{className:"text-[15px] font-semibold text-foreground tracking-tight",children:"Analytics"})]}),e.jsx("button",{type:"button",onClick:()=>a(!1),className:"h-9 w-9 inline-flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-foreground
86/[0.06] transition-colors","aria-label":"Close navigation",children:e.jsx(ms,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"px-3 py-2.5 border-b border-border/30",children:e.jsxs("div",{className:"relative",children:[e.jsx(si,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground/70"}),e.jsx(Sn,{value:o,onChange:g=>r(g.target.value),placeholder:"Search sections",className:"h-9 pl-8 text-[13px] bg-background/60",autoComplete:"off"})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-2 py-3 space-y-3",style:{paddingBottom:"calc(var(--safe-bottom, 0px) + 16px)"},children:[h.length===0&&e.jsxs("p",{className:"px-3 py-6 text-center text-[12px] text-muted-foreground",children:["No sections match â",o,"â."]}),h.map(g=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:"px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/55",children:g.label}),g.items.map(x=>{const f=x.icon,v=x.value===s,b=ke("w-full flex items-center gap-3 rounded-xl px-2.5 min-h-[44px] text-[13.5px] text-left transition-colors duration-200","text-muted-foreground active:bg-foreground
86/[0.06]");return x.href?e.jsxs(wn,{to:x.href,onClick:()=>a(!1),className:b,children:[e.jsx(f,{className:"h-4 w-4 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:x.label}),e.jsx(Tn,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground/50"})]},x.value):e.jsxs("button",{type:"button",onClick:()=>u(x.value),className:ke("w-full flex items-center gap-3 rounded-xl px-2.5 min-h-[44px] text-[13.5px] text-left transition-colors duration-200",v?"bg-[hsl(var(--primary)/0.12)] text-foreground shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.24)]":"text-muted-foreground active:bg-foreground/[0.06]"),children:[e.jsx(f,{className:ke("h-4 w-4 shrink-0",v?"text-primary":"text-muted-foreground/70")}),e.jsx("span",{className:"truncate",children:x.label})]},x.value)})]},g.id))]})]})})}const ws=t=>t==null?"â":typeof t=="number"?t.toLocaleString():t;function Nc({label:t}){return e.jsx(Or,{delayDuration:120,children:e.jsxs(Fr,{children:[e.jsx(zr,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`How this is calculated: ${t}`,className:"tap-exempt inline-flex items-center justify-center h-3.5 w-3.5 rounded-full text-muted-foreground/50 hover:text-primary transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--primary)/0.6)]",children:e.jsx(pi,{className:"h-3 w-3"})})}),e.jsx(Kr,{side:"top",className:"max-w-[240px] text-[11px] leading-snug",children:t})]})})}function xr({value:t,label:a,className:s}){const n=t>0?xa:t<0?Pn:Cn,o=t>0?"text-emerald-400":t<0?"text-red-400":"text-muted-foreground";return e.jsxs("span",{className:ke("inline-flex items-center gap-1 text-[11px] font-semibold tabular-nums",o,s),children:[e.jsx(n,{className:"h-3 w-3"}),t>0?"+":"",t,"%",a&&e.jsx("span",{className:"font-normal text-muted-foreground/70",children:a})]})}const ve=d.memo(function({label:a,value:s,context:n,trend:o,tooltip:r,tone:h="neutral",className:u}){const g={neutral:"text-foreground",primary:"text-foreground",premium:"text-premium",positive:"text-emerald-400",warning:"text-amber-400",critical:"text-red-400"}[h];return e.jsxs("div",{className:ke("analytics-kpi group relative rounded-[14px] border border-border/45 bg-card/45 px-3.5 py-3 transition-[border-color,background-color,transform] duration-200 hover:border-[hsl(var(--primary)/0.32)] hover:bg-card/65",h==="primary"&&"border-[hsl(var(--primary)/0.22)]",h==="premium"&&"border-[hsl(var(--premium)/0.22)]",u),children:[e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx("p",{className:"min-w-0 text-[10.5px] font-medium uppercase leading-[1.25] tracking-[0.1em] text-muted-foreground/80 break-words",children:a}),r&&e.jsx("span",{className:"shrink-0 pt-px",children:e.jsx(Nc,{label:r})})]}),e.jsx("p",{className:ke("mt-1.5 text-[24px] sm:text-[27px] font-semibold leading-none tracking-tight tabular-nums",g),children:ws(s)}),(n||o)&&e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-2 gap-y-1",children:[o&&e.jsx(xr,{value:o.value,label:o.label}),n&&e.jsx("span",{className:"text-[11px] text-muted-foreground/80 leading-tight",children:n})]})]})});function Vt({label:t,value:a,context:s,live:n,tone:o="neutral",trend:r}){const h={neutral:"text-foreground",positive:"text-emerald-400",warning:"text-amber-400",critical:"text-red-400"}[o],u={neutral:"hsl(var(--primary) / 0.16)",positive:"hsl(152 70% 45% / 0.18)",warning:"hsl(38 92% 55% / 0.18)",critical:"hsl(0 80% 60% / 0.18)"}[o];return e.jsxs("div",{className:"group/live relative min-w-0 px-3.5 py-3.5 sm:py-4 transition-colors duration-300 hover:bg-foreground
86/[0.02]",children:[e.jsx("span",{className:"pointer-events-none absolute inset-x-0 top-0 h-px opacity-0 transition-opacity duration-300 group-hover/live:opacity-100",style:{background:`linear-gradient(90deg, transparent, ${u.replace("0.1","0.5")}, transparent)`}}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[n?e.jsxs("span",{className:"relative flex h-1.5 w-1.5 shrink-0",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-70"}),e.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-emerald-500"})]}):e.jsx("span",{className:"h-2.5 w-px shrink-0 bg-primary/45"}),e.jsx("p",{className:"min-w-0 text-[9.5px] font-semibold uppercase leading-[1.3] tracking-[0.14em] text-muted-foreground/70 break-words",children:t})]}),e.jsx("p",{className:ke("mt-2 text-[24px] sm:text-[27px] font-semibold leading-none tracking-[-0.02em] tabular-nums transition-colors duration-300",h),style:{textShadow:`0 0 22px ${u}`},children:ws(a)}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-2",children:[r&&e.jsx(xr,{value:r.value,label:r.label}),s&&e.jsx("span",{className:"text-[10px] uppercase tracking-[0.06em] text-muted-foreground/60 leading-tight truncate",children:s})]})]})}function Sc({children:t}){return e.jsxs("div",{className:"relative overflow-hidden rounded-[18px] border border-primary/15 bg-card/45 shadow-[0_1px_0_hsl(var(--foreground)/0.04)_inset,0_18px_40px_-32px_hsl(var(--primary)/0.5)]",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-[0.18]",style:{backgroundImage:"linear-gradient(to right, hsl(var(--primary) / 0.35) 1px, transparent 1px), linear-gradient(to bottom, hsl(var(--primary) / 0.28) 1px, transparent 1px)",backgroundSize:"46px 46px",maskImage:"radial-gradient(120% 130% at 0% 0%, black, transparent 70%)",WebkitMaskImage:"radial-gradient(120% 130% at 0% 0%, black, transparent 70%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{background:"radial-gradient(120% 140% at 0% 0%, hsl(var(--primary) / 0.09), transparent 58%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px",style:{background:"linear-gradient(90deg, transparent, hsl(var(--primary) / 0.55), transparent)"}}),e.jsx("div",{className:"relative grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 divide-x divide-y sm:divide-y-0 divide-border/30 [&>*:nth-child(-n+2)]:sm:border-t-0",children:t})]})}function wc({segments:t,className:a}){const s=t.reduce((n,o)=>n+Math.max(o.value,0),0)||1;return e.jsxs("div",{className:ke("space-y-2",a),children:[e.jsx("div",{className:"flex h-1.5 w-full overflow-hidden rounded-full bg-muted/40",children:t.map(n=>e.jsx("div",{style:{width:`${Math.max(n.value,0)/s*100}%`,background:n.color},className:"h-full transition-[width] duration-500"},n.label))}),e.jsx("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1",children:t.map(n=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:n.color}}),n.label,e.jsxs("span",{className:"font-semibold tabular-nums text-foreground/90",children:[(Math.max(n.value,0)/s*100).toFixed(1),"%"]})]},n.label))})]})}function Ha({title:t,rows:a,className:s}){return e.jsxs("div",{className:ke("rounded-[16px] border border-border/45 bg-card/35 p-3.5",s),children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground/70",children:t}),e.jsx("div",{className:"mt-2.5 divide-y divide-border/25",children:a.map(n=>e.jsxs("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[e.jsx("span",{className:"text-[12.5px] text-muted-foreground min-w-0 truncate",children:n.label}),e.jsxs("span",{className:"text-right",children:[e.jsx("span",{className:"text-[14px] font-semibold tabular-nums text-foreground",children:ws(n.value)}),n.context&&e.jsx("span",{className:"block text-[10.5px] text-muted-foreground/70",children:n.context})]})]},n.label))})]})}function Ac({tone:t,children:a}){const s={live:"border-emerald-500/30 bg-emerald-500/[0.07] text-emerald-400",warning:"border-amber-500/30 bg-amber-500/[0.07] text-amber-400",critical:"border-red-500/30 bg-red-500/[0.07] text-red-400",muted:"border-border/50 bg-muted/25 text-muted-foreground"}[t];return e.jsxs("span",{className:ke("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-semibold whitespace-nowrap",s),children:[t==="live"&&e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-70"}),e.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-emerald-500"})]}),a]})}
86function kc(t){return e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...t,children:e.jsx("path",{d:"M16.365 1.43c0 1.14-.43 2.22-1.21 3.02-.85.88-2.23 1.56-3.36 1.47-.13-1.1.43-2.26 1.18-3.03.83-.86 2.27-1.5 3.39-1.46zM20.5 17.27c-.55 1.27-.82 1.83-1.53 2.94-.99 1.55-2.39 3.48-4.12 3.5-1.54.02-1.93-1-4.02-.99-2.09.01-2.52 1.01-4.06.99-1.73-.02-3.05-1.76-4.04-3.31C-.07 16.93-.36 12.06 1.41 9.39c1.26-1.9 3.24-3.01 5.1-3.01 1.9 0 3.09 1.04 4.66 1.04 1.52 0 2.45-1.04 4.64-1.04 1.66 0 3.42.9 4.67 2.47-4.11 2.25-3.44 8.13.02 9.42z"})})}function Pc(t){return e.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",...t,children:[e.jsx("path",{d:"M3.6 1.7C3.23 2.09 3 2.66 3 3.4v17.2c0 .74.23 1.31.6 1.7l.09.08L13.3 12.7v-1.4L3.69 1.62l-.09.08z",fill:"#00C3F0"}),e.jsx("path",{d:"M16.5 15.9l-3.2-3.2v-1.4l3.2-3.2.07.04 3.79 2.15c1.08.61 1.08 1.62 0 2.24l-3.79 2.15-.07.04z",fill:"#FFCB07"}),e.jsx("path",{d:"M16.57 15.86 13.3 12 3.6 22.3c.36.38.95.42 1.62.05l11.35-6.49z",fill:"#F6362F"}),e.jsx("path",{d:"M16.57 8.14 5.22 1.65C4.55 1.28 3.96 1.32 3.6 1.7L13.3 12l3.27-3.86z",fill:"#00DD7E"})]})}const kt={apple:{total:16900,sinceLabel:"since Mar 18, 2026"},google:{total:6090,sinceLabel:"since May 4, 2026"},lastUpdated:"May 18, 2026"};function Cc(){const[t,a]=d.useState(null),[s,n]=d.useState(null),[o,r]=d.useState(""),[h,u]=d.useState(!1),{isAdmin:g}=hi(),x=async()=>{const{data:D,error:_}=await ce.from("app_store_downloads").select("id, total, since_label, last_synced_at, metadata");if(_){console.error("[AppStoreDownloads] load error",_);return}a(D??[])},f=(D,_)=>{n(D),r(String(_))},v=async()=>{if(!s)return;const D=Math.max(0,Math.floor(Number(o.replace(/[^\d]/g,""))));if(!Number.isFinite(D)){ha.error("Enter a valid number");return}u(!0);try{const _=t==null?void 0:t.find(F=>F.id===s),V=(_==null?void 0:_.since_label)??(s==="apple"?kt.apple.sinceLabel:kt.google.sinceLabel),{error:B}=await ce.from("app_store_downloads").upsert({id:s,total:D,since_label:V,last_synced_at:new Date().toISOString(),metadata:{...(_==null?void 0:_.metadata)??{},manual_override:!0,manual_set_at:new Date().toISOString()}},{onConflict:"id"});if(B)throw B;ha.success(`${s==="apple"?"Apple":"Google"} total updated`),n(null),await x()}catch(_){ha.error(`Save failed: ${_ instanceof Error?_.message:String(_)}`)}finally{u(!1)}};d.useEffect(()=>{x()},[]);const b=t==null?void 0:t.find(D=>D.id==="apple"),N=t==null?void 0:t.find(D=>D.id==="google"),k=(b==null?void 0:b.total)??kt.apple.total,p=(N==null?void 0:N.total)??kt.google.total,C=k+p,W=`Lifetime · ${kt.apple.sinceLabel} · synced every 24hrs`,S=`Lifetime · ${kt.google.sinceLabel} · synced every 24hrs`,I=D=>e.jsxs("div",{className:"flex items-center gap-1.5 mt-2",children:[e.jsx(Sn,{type:"text",inputMode:"numeric",value:o,onChange:_=>r(_.target.value),className:"h-8 text-sm",autoFocus:!0}),e.jsx(Se,{size:"sm",variant:"default",onClick:v,disabled:h,className:"h-8 px-2",children:e.jsx(Br,{className:"h-3.5 w-3.5"})}),e.jsx(Se,{size:"sm",variant:"outline",onClick:()=>n(null),disabled:h,className:"h-8 px-2",children:e.jsx(ms,{className:"h-3.5 w-3.5"})})]});return e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx(ze,{icon:Qa,title:"App Store Downloads"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(oe,{title:"Apple App Store",value:k,icon:kc,subtitle:W,color:"bg-zinc-900"}),g&&s!=="apple"&&e.jsx("button",{onClick:()=>f("apple",k),className:"absolute bottom-2 right-2 h-5 w-5 flex items-center justify-center rounded opacity-50 hover:opacity-100 transition-opacity","aria-label":"Edit Apple total",children:e.jsx(Gs,{className:"h-3 w-3"})}),g&&s==="apple"&&e.jsx("div",{className:"px-4 pb-3",children:I()})]}),e.jsxs("div",{className:"relative",children:[e.jsx(oe,{title:"Google Play",value:p,icon:Pc,subtitle:S,color:"bg-white"}),g&&s!=="google"&&e.jsx("button",{onClick:()=>f("google",p),className:"absolute bottom-2 right-2 h-5 w-5 flex items-center justify-center rounded opacity-50 hover:opacity-100 transition-opacity","aria-label":"Edit Google total",children:e.jsx(Gs,{className:"h-3 w-3"})}),g&&s==="google"&&e.jsx("div",{className:"px-4 pb-3",children:I()})]}),e.jsx(oe,{title:"Total Mobile Installs",value:C,icon:Qa,subtitle:"Combined iOS + Android",color:"bg-primary"})]})]})}const Tc=6e4;async function Mc(t){var h;const{data:a}=await ce.auth.getSession(),s=(h=a==null?void 0:a.session)==null?void 0:h.access_token;if(!s)return null;const n=await fetch(`${Wr}/functions/v1/live-visitor-count`,{method:"GET",headers:{apikey:Vr,Authorization:`Bearer ${s}`,"Content-Type":"application/json"},signal:t});if(!n.ok){try{await n.text()}catch{}return null}const o=await n.json(),r=Number(o==null?void 0:o.count);return Number.isFinite(r)?r:null}
86function _c(){const[t,a]=d.useState(null),[s,n]=d.useState(!0),o=d.useRef(null),r=d.useCallback(async()=>{if(document.visibilityState==="visible"){for(let h=0;h<2;h++){const u=new AbortController,g=setTimeout(()=>u.abort(),8e3);try{const x=await Mc(u.signal);if(x!==null){o.current=x,a(x);return}}catch{}finally{clearTimeout(g),n(!1)}h===0&&await new Promise(x=>setTimeout(x,600))}a(o.current),n(!1)}},[]);return d.useEffect(()=>{r();const h=setInterval(r,Tc),u=()=>{document.visibilityState==="visible"&&r()};return document.addEventListener("visibilitychange",u),()=>{clearInterval(h),document.removeEventListener("visibilitychange",u)}},[r]),{count:t,loading:s,refresh:r}}const fn=t=>typeof t=="number"?t.toLocaleString():(t??"â").toString();async function rt(t){const{title:a,subtitleLines:s=[],filename:n,sections:o}=t,[{default:r},{default:h}]=await Promise.all([J(()=>import("./jspdf.es.min-B-MU2tO3.js").then(S=>S.j),__vite__mapDeps([0,1,2,3])),J(()=>import("./jspdf.plugin.autotable-DtM9Cxfv.js"),[])]),u=new r({unit:"pt",format:"letter"}),g=u.internal.pageSize.getWidth(),x=new Date,f=48,v=new Image;v.src=gi;try{await v.decode()}catch{}const b=26,N=v.naturalWidth&&v.naturalHeight?v.naturalWidth/v.naturalHeight:8,k=b*N;v.complete&&v.naturalWidth>0&&u.addImage(v,"PNG",f,36,k,b),u.setFontSize(9),u.setTextColor(148,163,184),u.text(x.toLocaleString(),g-f,52,{align:"right"}),u.setDrawColor(226,232,240),u.setLineWidth(.5),u.line(f,76,g-f,76),u.setFontSize(20),u.setTextColor(15,23,42),u.setFont("helvetica","bold"),u.text(a,f,104),u.setFont("helvetica","normal"),u.setFontSize(10),u.setTextColor(100,116,139),s.forEach((S,I)=>{u.text(S,f,122+I*14)});let p=138+Math.max(0,s.length-1)*14;const C=()=>{const S=u.internal.pageSize.getHeight();u.setDrawColor(226,232,240),u.setLineWidth(.5),u.line(f,S-32,g-f,S-32),u.setFontSize(8),u.setTextColor(148,163,184),u.text("uncensored.ai â Confidential report",f,S-18),u.text(`Page ${u.getNumberOfPages()}`,g-f,S-18,{align:"right"})},W=(S,I)=>{u.setFillColor(6,182,212),u.rect(f,I-10,3,14,"F"),u.setFontSize(12),u.setTextColor(15,23,42),u.setFont("helvetica","bold"),u.text(S,f+10,I),u.setFont("helvetica","normal")};for(const S of o)p>u.internal.pageSize.getHeight()-120&&(u.addPage(),p=60),W(S.title,p),p+=10,S.headers&&S.body?h(u,{startY:p,head:[S.headers],body:S.body.map(I=>I.map(D=>fn(D))),styles:{fontSize:9,cellPadding:6,textColor:[30,41,59]},headStyles:{fillColor:[6,182,212],textColor:255,fontStyle:"bold"},alternateRowStyles:{fillColor:[248,250,252]},margin:{left:f,right:f},didDrawPage:C}):h(u,{startY:p,body:(S.rows??[]).map(([I,D])=>[I,fn(D)]),styles:{fontSize:10,cellPadding:6,textColor:[30,41,59]},alternateRowStyles:{fillColor:[248,250,252]},columnStyles:{0:{cellWidth:180,fontStyle:"bold",textColor:[71,85,105]},1:{halign:"left"}},margin:{left:f,right:f},didDrawPage:C}),p=u.lastAutoTable.finalY+26;C(),u.save(n)}const Ec="https://xpasfhcxsldtjymqemey.supabase.co",Ic="sb_publishable_ffUSDgpKldxZrcNI8WRaWw_PHdOocvc",ls="analyticsBackfill.run.v2",vn=30,Rc=18e4,yn={runId:"",status:"idle",startedAt:0,finishedAt:null,totalDays:0,rangeStart:"",rangeEnd:"",chunks:[],currentIndex:0,lastProcessedDay:null,daysWritten:0,authScanned:0,subsScanned:0,failures:[],lastError:null,lastChunkMs:null,avgChunkMs:null},Dc=()=>{try{if(typeof localStorage>"u")return null;const t=localStorage.getItem(ls);if(!t)return null;const a=JSON.parse(t);return!(a!=null&&a.runId)||!Array.isArray(a.chunks)?null:(a.status==="running"&&(a.status="paused"),a)}catch{return null}},Uc=t=>{try{if(typeof localStorage>"u")return;if(!t||t.status==="idle"){localStorage.removeItem(ls);return}localStorage.setItem(ls,JSON.stringify(t))}catch{}},$c=(t,a)=>{const s=r=>r.toISOString().slice(0,10),n=[],o=new Date(t);for(;o.getTime()<=a.getTime();){const r=new Date(o);r.setUTCDate(r.getUTCDate()+vn-1),r.getTime()>a.getTime()&&r.setTime(a.getTime()),n.push({start:s(o),end:s(r)}),o.setUTCDate(o.getUTCDate()+vn)}return n},Lc=async(t,a,s)=>{const n=window.setTimeout(()=>{try{s.__timeoutAborted=!0}catch{}},Rc);try{const o=await fetch(`${Ec}/functions/v1/analytics-backfill`,{method:"POST",headers:{"Content-Type":"application/json",apikey:Ic,Authorization:`Bearer ${t}`},body:JSON.stringify({start_date:a.start,end_date:a.end}),signal:s}),r=await o.text();let h=null;try{h=r?JSON.parse(r):null}catch{h={error:r}}if(!o.ok){const u=(h==null?void 0:h.error)||(h==null?void 0:h.message)||`HTTP ${o.status}`;throw new Error(u)}return h}finally{window.clearTimeout(n)}};function Oc(){const[t,a]=d.useState(()=>Dc()??yn),s=d.useRef(t),n=d.useRef(null),o=d.useRef([]);d.useEffect(()=>{s.current=t,Uc(t)},[t]);const r=d.useCallback(async(f,v)=>{const b=new AbortController;for(n.current=b;;
86){const k=s.current;if(k.status!=="running"||k.currentIndex>=k.chunks.length||b.signal.aborted)break;const p=k.currentIndex,C=k.chunks[p],W=Date.now();try{const S=await Lc(f,C,b.signal);if(S!=null&&S.error&&typeof S.days_written!="number")throw new Error(S.error);const I=Date.now()-W;o.current.push(I);const D=o.current.reduce((_,V)=>_+V,0)/o.current.length;a(_=>({..._,currentIndex:p+1,lastProcessedDay:C.end,daysWritten:_.daysWritten+(S.days_written??0),authScanned:S.auth_users_scanned??_.authScanned,subsScanned:S.subscriptions_scanned??_.subsScanned,lastError:null,lastChunkMs:I,avgChunkMs:D}))}catch(S){if(b.signal.aborted){a(D=>({...D,status:D.status==="running"?"paused":D.status}));break}const I=String((S==null?void 0:S.message)??S);a(D=>({...D,currentIndex:p+1,lastProcessedDay:C.end,lastError:`${C.start}â${C.end}: ${I}`,failures:[...D.failures,{range:`${C.start}â${C.end}`,error:I,at:Date.now()}]}))}}const N=s.current;N.status==="running"&&N.currentIndex>=N.chunks.length&&(a(k=>({...k,status:k.failures.length===0?"completed":"failed",finishedAt:Date.now()})),v==null||v()),n.current=null},[]),h=d.useCallback(({totalDays:f,accessToken:v,onCompleteRefresh:b})=>{if(s.current.status==="running")return;const N=Math.max(1,Math.min(365,Math.floor(f))),k=new Date;k.setUTCHours(0,0,0,0);const p=new Date(k);p.setUTCDate(k.getUTCDate()-(N-1));const C=$c(p,k);o.current=[];const W={runId:`run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`,status:"running",startedAt:Date.now(),finishedAt:null,totalDays:N,rangeStart:p.toISOString().slice(0,10),rangeEnd:k.toISOString().slice(0,10),chunks:C,currentIndex:0,lastProcessedDay:null,daysWritten:0,authScanned:0,subsScanned:0,failures:[],lastError:null,lastChunkMs:null,avgChunkMs:null};a(W),s.current=W,queueMicrotask(()=>{r(v,b)})},[r]),u=d.useCallback(({accessToken:f,onCompleteRefresh:v})=>{const b=s.current;if(b.status!=="paused"&&b.status!=="failed"||b.currentIndex>=b.chunks.length)return;o.current=b.avgChunkMs?[b.avgChunkMs]:[];const N={...b,status:"running",lastError:null};a(N),s.current=N,queueMicrotask(()=>{r(f,v)})},[r]),g=d.useCallback(()=>{var f;(f=n.current)==null||f.abort(),a(v=>v.status==="running"?{...v,status:"cancelled",finishedAt:Date.now()}:v)},[]),x=d.useCallback(()=>{var f;(f=n.current)==null||f.abort(),a(yn)},[]);return{state:t,start:h,resume:u,cancel:g,dismiss:x}}const Ga={formatDuration(t){if(!Number.isFinite(t)||t<=0)return"â";const a=Math.floor(t/1e3);if(a<60)return`${a}s`;const s=Math.floor(a/60),n=a%60;return s<60?`${s}m ${n}s`:`${Math.floor(s/60)}h ${s%60}m`}},Fc={idle:{label:"Idle",tone:"text-muted-foreground",icon:nn},running:{label:"Running",tone:"text-[hsl(var(--primary))]",icon:Hr},paused:{label:"Paused",tone:"text-amber-400",icon:nn},completed:{label:"Completed",tone:"text-emerald-400",icon:vi},failed:{label:"Completed with errors",tone:"text-rose-400",icon:yi},cancelled:{label:"Cancelled",tone:"text-muted-foreground",icon:js}};function zc({state:t,onCancel:a,onDismiss:s,onResume:n}){const o=Fc[t.status],r=o.icon,h=t.chunks.length,u=t.currentIndex,g=h===0?0:Math.round(u/h*100),{elapsedMs:x,etaMs:f}=d.useMemo(()=>{if(!t.startedAt)return{elapsedMs:0,etaMs:0};const b=(t.finishedAt??Date.now())-t.startedAt,N=Math.max(0,h-u),k=t.status==="running"&&t.avgChunkMs?Math.round(t.avgChunkMs*N):0;return{elapsedMs:b,etaMs:k}},[t.startedAt,t.finishedAt,t.avgChunkMs,t.status,h,u]);if(t.status==="idle")return null;const v=(t.status==="paused"||t.status==="failed"||t.status==="cancelled")&&u<h;return e.jsxs("div",{className:"rounded-xl border border-border/50 bg-card/70 backdrop-blur-md px-4 sm:px-5 py-3.5 sm:py-4 shadow-[0_4px_24px_-12px_hsl(var(--foreground)/0.2)]",role:"status","aria-live":"polite",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-start gap-2.5 min-w-0",children:[e.jsx(r,{className:`h-4 w-4 mt-0.5 shrink-0 ${o.tone} ${t.status==="running"?"animate-spin":""}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-semibold text-foreground",children:"Analytics backfill"}),e.jsx(ue,{variant:"outline",className:`text-[10px] uppercase tracking-wide border-current/40 ${o.tone}`,children:o.label}),e.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:[t.rangeStart," â ",t.rangeEnd]})]}),t.lastError&&e.jsxs("p",{className:"text-[11px] text-rose-400/90 mt-1 line-clamp-2",children:["Last error: ",t.lastError]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[t.status==="running"&&e.jsxs(Se,{variant:"ghost",size:"sm",onClick:a,className:"h-7 px-2 text-xs text-muted-foreground hover:text-rose-400",children:[e.jsx(js,{className:"h-3.5 w-3.5 mr-1"}),"Cancel"]}),v&&e.jsxs(Se,{variant:"ghost",size:"sm",onClick:n,className:"h-7 px-2 text-xs text-[hsl(var(--primary))] hover:bg-[hsl(var(--primary)/0.08)]",children:[e.jsx(fi,{className:"h-3.5 w-3.5 mr-1"}),"Resume"]}),t.status!=="running"&&e.jsx(Se,{variant:"ghost",size:"icon",onClick:s,className:"h-7 w-7 text-muted-foreground hover:text-foreground","aria-label":"Dismiss",children:e.jsx(ms,{className:"h-3.5 w-3.5"})})]})]}),e.jsx(xi,{value:g,className:"h-1.5 mb-3"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-x-4 gap-y-2 text-[11px]",children:[e.jsx(qe,{label:"Progress",value:`${g}%`,accent:!0}),e.jsx(qe,{label:"Chunks",value:`${u} / ${h}`}),e.jsx(qe,{label:"Last day",value:t.lastProcessedDay??"â",mono:!0}),e.jsx(qe,{label:"Days written",value:t.daysWritten.toLocaleStr
86ing()}),e.jsx(qe,{label:"Elapsed",value:Ga.formatDuration(x)}),e.jsx(qe,{label:t.status==="running"?"ETA":"Failures",value:t.status==="running"?Ga.formatDuration(f):t.failures.length.toString(),tone:t.status!=="running"&&t.failures.length>0?"text-rose-400":void 0}),e.jsx(qe,{label:"Auth users",value:t.authScanned?t.authScanned.toLocaleString():"â"}),e.jsx(qe,{label:"Subscriptions",value:t.subsScanned?t.subsScanned.toLocaleString():"â"}),e.jsx(qe,{label:"Avg / chunk",value:t.avgChunkMs?Ga.formatDuration(t.avgChunkMs):"â"})]})]})}function qe({label:t,value:a,accent:s,mono:n,tone:o}){return e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-muted-foreground/80 uppercase tracking-wide text-[9px]",children:t}),e.jsx("div",{className:`truncate ${n?"font-mono":""} ${s?"text-foreground font-semibold text-sm":o??"text-foreground/90"}`,title:a,children:a})]})}class Kc extends d.Component{constructor(){super(...arguments);Ka(this,"state",{hasError:!1,error:null});Ka(this,"handleRetry",()=>{var s,n;this.setState({hasError:!1,error:null}),(n=(s=this.props).onReset)==null||n.call(s)})}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){console.error(`[AnalyticsTab:${this.props.tabName??"unknown"}]`,s,n)}render(){var s;return this.state.hasError?e.jsxs("div",{className:"rounded-2xl border border-destructive/30 bg-destructive/5 p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(ps,{className:"w-5 h-5"}),e.jsxs("div",{className:"font-semibold text-sm",children:["This tab failed to render",this.props.tabName?` (${this.props.tabName})`:"","."]})]}),e.jsx("div",{className:"text-xs text-muted-foreground font-mono break-all",children:((s=this.state.error)==null?void 0:s.message)??"Unknown error"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:this.handleRetry,className:"inline-flex items-center gap-1.5 rounded-lg bg-primary/10 hover:bg-primary/20 text-primary text-xs font-medium px-3 py-1.5 transition-colors",children:[e.jsx(Tt,{className:"w-3.5 h-3.5"}),"Retry"]}),e.jsx("button",{onClick:()=>window.location.reload(),className:"inline-flex items-center gap-1.5 rounded-lg bg-card/60 hover:bg-card border border-border/40 text-foreground text-xs font-medium px-3 py-1.5 transition-colors",children:"Refresh Page"})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Other analytics tabs remain available â switch tabs to keep working."})]}):this.props.children}}const Bc=ie(()=>J(()=>import("./LiveQuestionFeed-CqZ-oUX-.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62]))),Wc=ie(()=>J(()=>import("./CancellationsTab-uUM_tQQa.js"),__vite__mapDeps([63,1,2,9,5,12,13,6,7,8,62,25,16,64,65,66,21,22,23,24,15,26,27,20,28,29,30,14,31,32,33,34,35,36,37,38,17,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61]))),Vc=ie(()=>J(()=>import("./TrendingTopicsTab-jE3FvcXH.js"),__vite__mapDeps([67,1,2,9,68,69,5,14,70,71,72])).then(t=>({default:t.TrendingTopicsTab}))),Hc=ie(()=>J(()=>import("./ApiUsageTab-bXzYzKuq.js"),__vite__mapDeps([73,1,2,9,5,30,56,57,55,58,74,40,20,21,22,23,7,24,15,25,26,27,28,29,14,31,32,33,34,35,36,37,38,17,39,41,42,43,44,45,46,47,48,49,50,51,52,53,54,59,60,61,62]))),Gc=ie(()=>J(()=>import("./FeedbackTab-a66zFoGC.js"),__vite__mapDeps([75,1,2,9,5,10,11,6,7,8,17,18,76,16,21,22,23,24,15,25,26,27,20,28,29,30,14,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62]))),qc=ie(()=>J(()=>import("./GeographicTab-CyQkb71k.js"),__vite__mapDeps([77,1,2,5,6,7,8,56,57,55,58,14,62,60,66,16,21,15,11,30,20,9,22,23,24,25,26,27,28,29,31,32,33,34,35,36,37,38,17,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,59,61]))),Yc=ie(()=>J(()=>import("./RabbitHoleTab-T47P3ui8.js"),__vite__mapDeps([78,1,2,9,5,24,64,15,60,16,35,56,57,55,58,61,14,22,23,7,25,26,27,20,28,29,30,31,32,33,34,36,37,38,17,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,59,62]))),Qc=ie(()=>J(()=>import("./StreamSmoothnessTab-DTyoK1-4.js"),__vite__mapDeps([79,1,2,9,24]))),Xc=ie(()=>J(()=>import("./DataExplorerTab-BRKwm8Ws.js"),__vite__mapDeps([80,1,2,9,5,81,27,22,23,7,12,13,44,38,82,83,84,20,15,25,85,35,30,14,50,86,28,87,88,72,89,8,69,21,90,91,92,54,59,37,29,93,94,24,26,31,32,33,34,36,17,39,40,41,42,43,45,46,47,48,49,51,52,53,55,56,57,58,60,61,62]))),Zc=ie(()=>J(()=>
86import("./LandingPagesTab-CpmEaAAM.js"),__vite__mapDeps([95,1,2,9,24,5,0,3,96,15,53,28]))),Jc=ie(()=>J(()=>import("./TrafficSourcesTab-BhfZiF3c.js"),__vite__mapDeps([97,1,2,9,24,5,0,3,96,60,53,98]))),ed=ie(()=>J(()=>import("./AdminMemoryTab-Bp4Fa4Bl.js"),__vite__mapDeps([99,1,2,9,5,100,37,59,20,101,60,30,70,34,102,46,72]))),td=ie(()=>J(()=>import("./HiddenContextTab-Bn7KPtxK.js"),__vite__mapDeps([103,1,2,9,5,38,50]))),ad=ie(()=>J(()=>import("./VoiceUsageTab-J2cyUpP_.js"),__vite__mapDeps([104,1,2,9,5,41,54,20,105,106,16,72,32,22,23,7,24,15,25,26,27,28,29,30,14,31,33,34,35,36,37,38,17,39,40,42,43,44,45,46,47,48,49,50,51,52,53,55,56,57,58,59,60,61,62]))),sd=ie(()=>J(()=>import("./WhoMoggedTab-CJrX4WCY.js"),__vite__mapDeps([107,1,2,9,24,5,39,30,50,108,14,109,110,56,57,55,58,22,23,7,15,25,26,27,20,28,29,31,32,33,34,35,36,37,38,17,40,41,42,43,44,45,46,47,48,49,51,52,53,54,59,60,61,62]))),nd=ie(()=>J(()=>import("./SlopornotTab-CGuPpqhL.js"),__vite__mapDeps([111,1,2,9,24,5,50,14,30,18,17,109,110,56,57,55,58,22,23,7,15,25,26,27,20,28,29,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,51,52,53,54,59,60,61,62]))),rd=ie(()=>J(()=>import("./IntakeTab-D2jPBs4z.js"),__vite__mapDeps([112,1,2,9,5,113,53,22,23,7,24,15,25,26,27,20,28,29,30,14,31,32,33,34,35,36,37,38,17,39,40,41,42,43,44,45,46,47,48,49,50,51,52,54,55,56,57,58,59,60,61,62]))),id=ie(()=>J(()=>import("./FactCrackTab-BRzXNj6u.js"),__vite__mapDeps([114,1,2,9,5,37,113,49,35,59,14,108,16]))),od=ie(()=>J(()=>import("./RabbitRunTab-bqOkqXXP.js"),__vite__mapDeps([115,1,2,9,5,116,35,113,49,14,54,108,109,92,71]))),ld=ie(()=>J(()=>import("./AssetsIrlTab-BPQPBvOT.js"),__vite__mapDeps([117,1,2,9,113,14,42,15,118,30,85,22,23,7,24,5,25,26,27,20,28,29,31,32,33,34,35,36,37,38,17,39,40,41,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62]))),cd=ie(()=>J(()=>import("./EmailUsersTab-qu3Ku2Ld.js"),__vite__mapDeps([119,1,2,9,5,23,7,69,89,8,21,120,71,72,88,14,113]))),dd=ie(()=>J(()=>import("./ProTrialTab-BiRyTEi-.js"),__vite__mapDeps([121,1,2,9,5,41,113,16,122]))),ud=ie(()=>J(()=>import("./RevenueRecoveryTab-mZDjAxGs.js"),__vite__mapDeps([123,1,2,9,5,113,50,25,16,22,23,7,24,15,26,27,20,28,29,30,14,31,32,33,34,35,36,37,38,17,39,40,41,42,43,44,45,46,47,48,49,51,52,53,54,55,56,57,58,59,60,61,62]))),md=ie(()=>J(()=>import("./ModerationTab-DPaQZ50z.js"),__vite__mapDeps([124,1,2,32,72,52,20]))),pd=ie(()=>J(()=>import("./BannedIspsTab-Cix7FyzN.js"),__vite__mapDeps([125,1,2,9,5,53,122,14,60,28,22,23,7,24,15,25,26,27,20,29,30,31,32,33,34,35,36,37,38,17,39,40,41,42,43,44,45,46,47,48,49,50,51,52,54,55,56,57,58,59,61,62]))),hd=ie(()=>J(()=>import("./AudienceProfileTab-CMgH_J0h.js"),__vite__mapDeps([126,1,2,84,31,9,22,23,7,24,5,15,25,26,27,20,28,29,30,14,32,33,34,35,36,37,38,17,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62]))),gd=ie(()=>J(()=>import("./AdminAccessTab-CbcsyiO0.js"),__vite__mapDeps([127,1,2,9,5,24,32]))),xd=ie(()=>J(()=>import("./SignupAuditTab-CQIiSxTm.js"),__vite__mapDeps([128,1,2,9,5,24,52]))),fd=ie(()=>J(()=>import("./ClientErrorsTab-D4F2ORCo.js"),__vite__mapDeps([129,1,2,9,5,24]))),ne=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qt,{className:"h-8 w-48"}),e.jsx(Qt,{className:"h-64 w-full"}),e.jsx(Qt,{className:"h-40 w-full"})]});function gt({icon:t,title:a,subtitle:s,onExport:n}){return e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-foreground flex items-center gap-2 min-w-0",children:[e.jsx(t,{className:"w-4 h-4 shrink-0 text-brand"}),e.jsx("span",{className:"truncate",children:a})]}),e.jsx("p",{className:"text-[11px] sm:text-xs text-muted-foreground mt-0.5",children:s})]}),e.jsxs(Se,{variant:"outline",size:"sm",onClick:()=>{n()},className:"h-8 shrink-0 self-start sm:self-auto gap-1.5 px-2.5 text-[11px] sm:text-xs whitespace-nowrap border-brand/40 text-brand-bright hover:bg-brand/10 hover:text-brand-bright",children:[e.jsx(ts,{className:"w-3.5 h-3.5 shrink-0"}),"Export PDF"]})]})}const _e=async(t,a,s)=>{let n;try{return await Promise.race([t,new Promise((o,r)=>{n=setTimeout(()=>r(new Error(s)),a)})])}finally{n&&clearTimeout(n)}},Pa=t=>{var s;const a=((s=t==null?void 0:t.context)==null?void 0:s.status)??(t==null?void 0:t.status)??(t==null?void 0:t.statusCode);return typeof a=="number"?a:null},fr="https://xpasfhcxsldtjymqemey.supabase.co",vd="sb_publishable_ffUSDgpKldxZrcNI8WRaWw_PHdOocvc";let Ht=null,Ee=null;const cs=new Set,vr=async t=>{if(!t||cs.has(t))return!1;if((Ee==null?void 0:Ee.token)===t&&Ee.expiresAt>Date.now())return!0;try{const{data:a,error:s}=await _e(ce.auth.getUser(t),6e3,"Analytics session validation timed out.");return s||!a.user?(cs.add(t),(Ee==null?void 0:Ee.token)===t&&(Ee=null),!1):(Ee={token:t,expiresAt:Date.now()+3e4},!0)}catch{return!1}},bn=async()=>Ht||(Ht=ce.auth.refreshSession().then(async({data:t,error:a})=>{var n;const s=a?null:((n=t.session)==null?void 0:n.access_token)||null;return!s||!await vr(s)?null:s}
86).catch(()=>null).finally(()=>{Ht=null}),Ht),De=async(t,a,s,n=2e4)=>{const o=new AbortController,r=window.setTimeout(()=>o.abort(),n);try{const h=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,u=`${fr}/functions/v1/${t}?_cb=${h}`,g=N=>fetch(u,{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",apikey:vd,Authorization:`Bearer ${N}`,"Cache-Control":"no-cache, no-store, must-revalidate",Pragma:"no-cache","X-Cache-Bust":h},body:JSON.stringify(s),signal:o.signal});let x=a;if(!await vr(x)){const N=await bn();if(!N){const k=new Error("Your admin session expired. Please sign in again.");throw k.status=401,k.context={status:401,body:{error:"Invalid session"}},k}x=N}let f=await g(x),v=await f.text(),b=null;try{b=v?JSON.parse(v):null}catch{b={error:v}}if(f.status===401){cs.add(x),(Ee==null?void 0:Ee.token)===x&&(Ee=null);const N=await bn();if(N){f=await g(N),v=await f.text();try{b=v?JSON.parse(v):null}catch{b={error:v}}}}if(!f.ok){const N=(b==null?void 0:b.error)||(b==null?void 0:b.message)||`Function failed: ${f.status}`,k=new Error(N);throw k.status=f.status,k.context={status:f.status,body:b},k}return b}finally{window.clearTimeout(r)}},yd=async t=>{var s;const a=(s=(await ce.auth.getSession()).data.session)==null?void 0:s.access_token;if(!a)throw new Error("Please sign in again.");return De("monthly-usage-report",a,t,6e4)},Ca="adminAnalytics.overviewSnapshot.v19",bd=30*60*1e3,yr=32271,jd=345e3,Zt=jd+yr,Ta=t=>Number.isFinite(t)?Math.max(0,Math.floor(t)):0,Nd=new Set(["9706f928-8bb8-4031-a2c4-c9fa27358069"]),Ke=(t,a)=>{const s=String(t||"").trim().toLowerCase();return!!(s&&Nd.has(s))},br=t=>{const a=Ta(t);return a>=1e5?a:Math.max(a,Zt)},Sd=t=>{const a=Ta(t);return a>=4e5?a:a+yr},wd=(t,a)=>{const s=Ta(t),n=Ta(a);if(n<1e5)return s>0?s:Zt;if(s<1e5)return n;const o=n<=Zt,r=s<=Zt;return o&&s>n?s:(r&&n>s,n)},Ad=(t,a,s)=>{let n=Math.max(0,Math.floor(Number(t||0))),o=Math.max(0,Math.floor(Number(a||0))),r=Math.max(0,Math.floor(Number(s||0)));return!n&&(o||r)&&(n=o+r),n>0&&(!o&&!r?(o=Math.round(n/2),r=n-o):!o&&r&&n>r?o=n-r:!r&&o&&n>o&&(r=n-o)),{totalMessagesFinal:n,totalUserMessagesFinal:o,totalAiMessagesFinal:r}},jr=(t=30)=>Array.from({length:t},(a,s)=>{const n=new Date;return n.setUTCHours(0,0,0,0),n.setUTCDate(n.getUTCDate()-(t-1-s)),{day:n.toISOString().slice(0,10),value:0}}),le=t=>Array.isArray(t)?t:[],K=t=>{const a=Number(t??0);return Number.isFinite(a)?a:0},da=t=>{const a=le(t).map(s=>({day:String((s==null?void 0:s.day)||(s==null?void 0:s.date)||(s==null?void 0:s.created_at)||"").slice(0,10),value:Math.max(0,Math.floor(K((s==null?void 0:s.value)??(s==null?void 0:s.count)??(s==null?void 0:s.cnt))))})).filter(s=>/^\d{4}-\d{2}-\d{2}$/.test(s.day));return a.length?a:jr()},Le=t=>le(t).map(a=>({name:String((a==null?void 0:a.name)??(a==null?void 0:a.topic)??(a==null?void 0:a.intent)??(a==null?void 0:a.language)??(a==null?void 0:a.sentiment)??"Unknown"),count:Math.max(0,Math.floor(K((a==null?void 0:a.count)??(a==null?void 0:a.value)??(a==null?void 0:a.cnt))))})).filter(a=>a.name&&a.name!=="undefined"),Nr=t=>{var g,x,f,v,b,N,k;if(!t||typeof t!="object")return null;const a=Le(t.topTopics),s=Le(t.topTopics7d),n=Le(t.topTopics24h),o=Le(t.intents),r=Le(t.languages),h=Le(t.sentiments),u=le(t.top5topics).filter(Boolean).map(String);return{...t,totalClassified:Math.max(0,Math.floor(K(t.totalClassified))),topTopics:a,topTopics7d:s,topTopics24h:n,intents:o,languages:r,sentiments:h,avgPromptLength:Math.max(0,Math.floor(K(t.avgPromptLength))),promptLengthBuckets:le(t.promptLengthBuckets).map(p=>({range:String((p==null?void 0:p.range)||""),count:Math.max(0,Math.floor(K(p==null?void 0:p.count)))})),intentTrends:le(t.intentTrends).map(p=>({name:String((p==null?void 0:p.name)||"unknown"),current:K(p==null?void 0:p.current),previous:K(p==null?void 0:p.previous),change:K(p==null?void 0:p.change)})),powerUsers:le(t.powerUsers).map(p=>({userId:String((p==null?void 0:p.userId)||(p==null?void 0:p.user_id)||"unknown"),msgCount:Math.max(0,Math.floor(K((p==null?void 0:p.msgCount)??(p==null?void 0:p.count))))})),powerUserCount:Math.max(0,Math.floor(K(t.powerUserCount))),powerUserThreshold:Math.max(1,Math.floor(K(t.powerUserThreshold||10))),conversationDepth:le(t.conversationDepth).map(p=>({range:String((p==null?void 0:p.range)||""),count:Math.max(0,Math.floor(K(p==null?void 0:p.count)))})),topKeywords:le(t.topKeywords).map(p=>({word:String((p==null?void 0:p.word)||(p==null?void 0:p.name)||""),count:Math.max(0,Math.floor(K(p==null?void 0:p.count)))})).filter(p=>p.word),trendingKeywords:le(t.trendingKeywords).map(p=>({word:String((p==null?void 0:p.word)||(p==null?void 0:p.name)||""),current:Math.max(0,Math.floor(K((p==null?void 0:p.current)??(p==null?void 0:p.count)))),previous:Math.max(0,Math.floor(K(p==null?void 0:p.previous))),change:K(p==null?void 0:p.change),changePct:K(p==null?void 0:p.changePct)})).filter(p=>
86p.word),topicTimeSeries:le(t.topicTimeSeries).filter(Boolean),top5topics:u.length?u:a.slice(0,5).map(p=>p.name),topicIntentCross:le(t.topicIntentCross).map(p=>({topic:String((p==null?void 0:p.topic)||""),topIntent:String((p==null?void 0:p.topIntent)||"unknown"),topIntentPct:K(p==null?void 0:p.topIntentPct),intents:Le(p==null?void 0:p.intents)})).filter(p=>p.topic),firstMessageAnalysis:{firstMessages:Math.max(0,Math.floor(K((g=t.firstMessageAnalysis)==null?void 0:g.firstMessages))),followUps:Math.max(0,Math.floor(K((x=t.firstMessageAnalysis)==null?void 0:x.followUps))),firstMsgRatio:K((f=t.firstMessageAnalysis)==null?void 0:f.firstMsgRatio),topFirstMsgTopics:Le((v=t.firstMessageAnalysis)==null?void 0:v.topFirstMsgTopics)},sentimentByTopic:le(t.sentimentByTopic).map(p=>({topic:String((p==null?void 0:p.topic)||""),positive:K(p==null?void 0:p.positive),neutral:K(p==null?void 0:p.neutral),negative:K(p==null?void 0:p.negative),positiveRate:K(p==null?void 0:p.positiveRate)})).filter(p=>p.topic),topicUserCounts:le(t.topicUserCounts).map(p=>({name:String((p==null?void 0:p.name)||(p==null?void 0:p.topic)||""),prompts:Math.max(0,Math.floor(K((p==null?void 0:p.prompts)??(p==null?void 0:p.count)))),uniqueUsers:Math.max(0,Math.floor(K(p==null?void 0:p.uniqueUsers))),promptsPerUser:K(p==null?void 0:p.promptsPerUser)})).filter(p=>p.name),topicMomentum:le(t.topicMomentum).map(p=>({topic:String((p==null?void 0:p.topic)||""),total:Math.max(0,Math.floor(K(p==null?void 0:p.total))),current7d:Math.max(0,Math.floor(K(p==null?void 0:p.current7d))),previous7d:Math.max(0,Math.floor(K(p==null?void 0:p.previous7d))),change:K(p==null?void 0:p.change),changePct:K(p==null?void 0:p.changePct),isEmerging:!!(p!=null&&p.isEmerging),isHot:!!(p!=null&&p.isHot),isDeclining:!!(p!=null&&p.isDeclining)})).filter(p=>p.topic),topicDrilldown:le(t.topicDrilldown).map(p=>({topic:String((p==null?void 0:p.topic)||""),totalPrompts:Math.max(0,Math.floor(K(p==null?void 0:p.totalPrompts))),subTopics:Le(p==null?void 0:p.subTopics)})).filter(p=>p.topic),hourlyHeatmap:Array.from({length:24},(p,C)=>K(le(t.hourlyHeatmap)[C])),dayOfWeekHeatmap:Array.from({length:7},(p,C)=>K(le(t.dayOfWeekHeatmap)[C])),sentimentTimeSeries:le(t.sentimentTimeSeries).filter(Boolean),conversationStarters:{topIntents:Le((b=t.conversationStarters)==null?void 0:b.topIntents),topSentiments:Le((N=t.conversationStarters)==null?void 0:N.topSentiments),total:Math.max(0,Math.floor(K((k=t.conversationStarters)==null?void 0:k.total)))},geo:t.geo?Yt(t.geo):null}},kd=t=>{var x,f,v,b,N,k,p,C,W;const a=t||{},s={totalUsers:0,paidPro:0,paidProStripe:0,paidProApple:0,whitelistedPro:0,freeUsers:0,churnedApple:0,totalAppleEver:0,totalConversations:0,totalMessages:0,totalUserMessages:0,totalAiMessages:0,totalForumPosts:0,totalForumThreads:0,totalFileUploads:0,totalForumProfiles:0,totalDMs:0,newToday:0,new7d:0,new30d:0,activeToday:0,active7d:0,active30d:0,convosToday:0,messagesToday:0,postsToday:0,newYesterday:0,convosYesterday:0,messagesYesterday:0,totalEpsteinDocs:0,totalApiKeys:0,totalAnalyticsEvents:0,totalSessions:0,totalUniqueAnalyticsUsers:0},n={avgMsgsPerConvo:0,avgConvosPerUser:0,avgMsgsPerUser:0,conversionRate:0,paidConversionRate:0,appleChurnRate:0,retention7d:0,retention30d:0,forumParticipation:0,stickiness:0},o=Object.fromEntries(Object.entries({...s,...a.stats||{}}).map(([S,I])=>[S,Math.max(0,K(I))])),r=a.kpis&&typeof a.kpis=="object"?a.kpis:{},h=Object.fromEntries(Object.entries({...n,...r}).filter(([S])=>S!=="proNet24h").map(([S,I])=>[S,K(I)])),u=r.proNet24h;u&&typeof u=="object"&&Number.isFinite(Number(u.net))&&(h.proNet24h={...u,added:Number(u.added||0),lost:Number(u.lost||0),net:Number(u.net),rate:Number(u.rate||0)});const g=((x=a.apiIntelligence)==null?void 0:x.summary)||{};return{...a,stats:o,kpis:h,series:{conversations:da((f=a.series)==null?void 0:f.conversations),messages:da((v=a.series)==null?void 0:v.messages),forumPosts:da((b=a.series)==null?void 0:b.forumPosts),userGrowth:da((N=a.series)==null?void 0:N.userGrowth)},topicIntelligence:Nr(a.topicIntelligence),apiIntelligence:{users:le((k=a.apiIntelligence)==null?void 0:k.users),summary:{totalUsers:Math.max(0,Math.floor(K(g.totalUsers))),totalKeys:Math.max(0,Math.floor(K(g.totalKeys))),totalRevenue:Math.max(0,K(g.totalRevenue)),totalCalls:Math.max(0,Math.floor(K(g.totalCalls))),totalTokens:Math.max(0,Math.floor(K(g.totalTokens))),totalCreditsPurchased:Math.max(0,K(g.totalCreditsPurchased)),totalCreditsUsed:Math.max(0,K(g.totalCreditsUsed))}},modelSpeed:a.modelSpeed&&typeof a.modelSpeed=="object"?{avgMs:Math.max(0,K(a.modelSpeed.avgMs)),responseCount:Math.max(0,Math.floor(K(a.modelSpeed.responseCount))),activeUsers:Math.max(0,Math.floor(K(a.modelSpeed.activeUsers))),lastWindowMinutes:Math.max(1,Math.floor(K(a.modelSpeed.lastWindowMinutes||30))),routeBreakdown:a.modelSpeed.routeBreakdown&&t
86ypeof a.modelSpeed.routeBreakdown=="object"?a.modelSpeed.routeBreakdown:{}}:{avgMs:0,responseCount:0,activeUsers:0,lastWindowMinutes:30,routeBreakdown:{}},recentQuestions:{items:le(((p=a.recentQuestions)==null?void 0:p.items)??(Array.isArray(a.recentQuestions)?a.recentQuestions:[])),totalCount:Math.max(0,Math.floor(K(((C=a.recentQuestions)==null?void 0:C.totalCount)??le((W=a.recentQuestions)==null?void 0:W.items).length)))},feedbackIntelligence:(()=>{var D,_,V,B,F,de,q,ye;const S=le((D=a.feedbackIntelligence)==null?void 0:D.allEntries),I=S.filter(E=>(E==null?void 0:E.rating)==="flagged").length;return{total:Math.max(0,Math.floor(K((_=a.feedbackIntelligence)==null?void 0:_.total))),good:Math.max(0,Math.floor(K((V=a.feedbackIntelligence)==null?void 0:V.good))),bad:Math.max(0,Math.floor(K((B=a.feedbackIntelligence)==null?void 0:B.bad))),flagged:Math.max(Math.max(0,Math.floor(K((F=a.feedbackIntelligence)==null?void 0:F.flagged))),I),goodRate:Math.max(0,K((de=a.feedbackIntelligence)==null?void 0:de.goodRate)),weakSpots:le((q=a.feedbackIntelligence)==null?void 0:q.weakSpots),recentBad:le((ye=a.feedbackIntelligence)==null?void 0:ye.recentBad),allEntries:S}})(),cancellationIntelligence:le(a.cancellationIntelligence),recentUsers:le(a.recentUsers),topPosters:le(a.topPosters),timestamp:a.timestamp||new Date().toISOString()}},Pt=t=>Array.isArray(t)?t.map(a=>({name:String((a==null?void 0:a.name)??(a==null?void 0:a.country)??(a==null?void 0:a.region)??(a==null?void 0:a.city)??(a==null?void 0:a.timezone)??"Unknown"),count:Math.max(0,Math.floor(Number((a==null?void 0:a.count)??(a==null?void 0:a.cnt)??0)))})).filter(a=>a.name&&a.name!=="undefined"):[],Yt=t=>{const a=Pt(t==null?void 0:t.countries),s=Pt(t==null?void 0:t.regions),n=Pt(t==null?void 0:t.cities),o=Pt(t==null?void 0:t.timezones);return{countries:a,regions:s,cities:n,timezones:o,usersWithGeo:Math.max(0,Math.floor(Number((t==null?void 0:t.usersWithGeo)||0))),countryTopTopics:Array.isArray(t==null?void 0:t.countryTopTopics)?t.countryTopTopics.map(r=>({country:String((r==null?void 0:r.country)||""),topics:Pt(r==null?void 0:r.topics).slice(0,5)})).filter(r=>r.country):[],countryLanguages:Array.isArray(t==null?void 0:t.countryLanguages)?t.countryLanguages.map(r=>({country:String((r==null?void 0:r.country)||""),languages:Pt(r==null?void 0:r.languages).slice(0,5)})).filter(r=>r.country):[],countrySentiment:Array.isArray(t==null?void 0:t.countrySentiment)?t.countrySentiment.map(r=>({country:String((r==null?void 0:r.country)||""),positive:Number((r==null?void 0:r.positive)||0),neutral:Number((r==null?void 0:r.neutral)||0),negative:Number((r==null?void 0:r.negative)||0),total:Number((r==null?void 0:r.total)||0),positiveRate:Number((r==null?void 0:r.positiveRate)||0)})).filter(r=>r.country):[],countryUserCounts:Array.isArray(t==null?void 0:t.countryUserCounts)?t.countryUserCounts.map(r=>({country:String((r==null?void 0:r.country)||(r==null?void 0:r.name)||""),uniqueUsers:Math.max(0,Math.floor(Number((r==null?void 0:r.uniqueUsers)??(r==null?void 0:r.unique_users)??0)))})).filter(r=>r.country):[],enrichedCities:Array.isArray(t==null?void 0:t.enrichedCities)?t.enrichedCities.map(r=>({city:String((r==null?void 0:r.city)||(r==null?void 0:r.name)||"Unknown"),country:String((r==null?void 0:r.country)||""),region:String((r==null?void 0:r.region)||""),count:Math.max(0,Math.floor(Number((r==null?void 0:r.count)??(r==null?void 0:r.cnt)??0)))})):n.map(r=>({city:r.name,country:"",region:"",count:r.count})),countryTimeSeries:Array.isArray(t==null?void 0:t.countryTimeSeries)?t.countryTimeSeries:[],top5countries:Array.isArray(t==null?void 0:t.top5countries)?t.top5countries.filter(Boolean).map(String):a.slice(0,5).map(r=>r.name),countryPeakHours:Array.isArray(t==null?void 0:t.countryPeakHours)?t.countryPeakHours.map(r=>({country:String((r==null?void 0:r.country)||""),peakHour:Math.max(0,Math.min(23,Math.floor(Number((r==null?void 0:r.peakHour)||0)))),distribution:Array.isArray(r==null?void 0:r.distribution)?r.distribution.map(h=>Number(h||0)).slice(0,24):Array(24).fill(0)})).filter(r=>r.country):[]}},Ce=t=>{t=kd(t);const a={...t.stats};a.totalUsers=br(Number(a.totalUsers||0));const{totalMessagesFinal:s,totalUserMessagesFinal:n,totalAiMessagesFinal:o}=Ad(a.totalMessages,a.totalUserMessages,a.totalAiMessages);a.totalMessages=s,a.totalUserMessages=n,a.totalAiMessages=o,a.paidProStripe=Number(a.paidProStripe||0),a.paidProApple=Number(a.paidProApple||0),a.whitelistedPro=Number(a.whitelistedPro||0),a.paidPro=Math.max(Number(a.paidPro||
860),a.paidProStripe+a.paidProApple),a.freeUsers=Math.max(a.totalUsers-a.paidPro-a.whitelistedPro,0);const r={...t.kpis};r.conversionRate=a.totalUsers?+((a.paidPro+a.whitelistedPro)/a.totalUsers*100).toFixed(2):0,r.paidConversionRate=a.totalUsers?+(a.paidPro/a.totalUsers*100).toFixed(2):0,r.avgConvosPerUser=a.totalUsers?+(Number(a.totalConversations||0)/a.totalUsers).toFixed(1):0,r.avgMsgsPerUser=a.totalUsers?+(Number(a.totalUserMessages||0)/a.totalUsers).toFixed(1):0,r.avgMsgsPerConvo=Number(a.totalConversations||0)?+(Number(a.totalMessages||0)/Number(a.totalConversations)).toFixed(1):0,r.retention7d=a.totalUsers?+(Number(a.active7d||0)/a.totalUsers*100).toFixed(1):0,r.retention30d=a.totalUsers?+(Number(a.active30d||0)/a.totalUsers*100).toFixed(1):0;const h=Nr(t.topicIntelligence);return{...t,stats:a,kpis:r,topicIntelligence:h}},ua=(t,a)=>{var B,F,de,q,ye;if(!(t!=null&&t.stats))return a;const s=t.stats,n={...a.stats};n.totalUsers=wd(Number(s.totalUsers||0),Number(n.totalUsers||0));const o=["totalUsers","freeUsers","paidPro","paidProStripe","paidProApple","whitelistedPro","churnedApple","totalAppleEver","activeToday","active7d","active30d","newToday","new7d","new30d","newYesterday","totalConversations","totalMessages","totalUserMessages","totalAiMessages","convosToday","messagesToday","convosYesterday","messagesYesterday","postsToday","totalForumPosts","totalForumThreads","totalForumProfiles","totalDMs","totalFileUploads","totalEpsteinDocs","totalApiKeys","totalAnalyticsEvents","totalSessions","totalUniqueAnalyticsUsers"],h=String(a.signupMetricSource||"").includes("engaged"),u=new Set(["newToday","new7d","new30d","newYesterday"]),g=new Set(["paidProStripe","paidProApple","paidPro","whitelistedPro","churnedApple","totalAppleEver"]),x=!!a.billingAuthoritativeAt;for(const E of o){const Z=Number(n[E]||0),X=Number(s[E]||0);if(g.has(E)){!x&&X>Z&&(n[E]=X);continue}Z===0&&X>0&&!(h&&u.has(E))&&(n[E]=X)}typeof n.stripeMonthly!="number"&&typeof s.stripeMonthly=="number"&&(n.stripeMonthly=s.stripeMonthly,n.stripeAnnual=s.stripeAnnual),n.paidPro=Math.max(Number(n.paidPro||0),Number(n.paidProStripe||0)+Number(n.paidProApple||0));const f=E=>Array.isArray(E)&&E.some(Z=>Number(Z.value||0)>0),v={...a.series};!f(v.userGrowth)&&f((B=t.series)==null?void 0:B.userGrowth)&&(v.userGrowth=t.series.userGrowth),!f(v.conversations)&&f((F=t.series)==null?void 0:F.conversations)&&(v.conversations=t.series.conversations),!f(v.messages)&&f((de=t.series)==null?void 0:de.messages)&&(v.messages=t.series.messages);const b=t.modelSpeed,N=a.modelSpeed,k=Number((N==null?void 0:N.responseCount)||0)>0?N:Number((b==null?void 0:b.responseCount)||0)>0?b:N,p=(E,Z)=>{const X=Array.isArray(E)?E:[],be=Array.isArray(Z)?Z:[];return X.length===0&&be.length>0?be:X},C=(E,Z,X)=>E?X(E)?E:Z&&X(Z)?Z:E:Z??E,W=(()=>{var X,be;const E=(X=a==null?void 0:a.recentQuestions)==null?void 0:X.items,Z=(be=t==null?void 0:t.recentQuestions)==null?void 0:be.items;return(!Array.isArray(E)||E.length===0)&&Array.isArray(Z)&&Z.length>0?t.recentQuestions:a.recentQuestions})(),S=C(a.feedbackIntelligence,t.feedbackIntelligence,E=>Number((E==null?void 0:E.total)||0)>0||Array.isArray(E==null?void 0:E.allEntries)&&E.allEntries.length>0),I=C(a.topicIntelligence,t.topicIntelligence,E=>{var dt;if(!E)return!1;const Z=Array.isArray(E.topics)?E.topics.length:0,X=Array.isArray(E.categories)?E.categories.length:0,be=Array.isArray((dt=E==null?void 0:E.geo)==null?void 0:dt.countries)?E.geo.countries.length:0;return Z+X+be>0}),D=C(a.apiIntelligence,t.apiIntelligence,E=>Array.isArray(E==null?void 0:E.users)&&E.users.length>0),_=["appleChurnRate","stickiness","forumParticipation","paidConversionRate","conversionRate","retention7d","retention30d"],V={...a.kpis};for(const E of _){const Z=Number(V[E]||0),X=Number(((q=t.kpis)==null?void 0:q[E])||0);Z===0&&X>0&&(V[E]=X)}return!V.proNet24h&&((ye=t.kpis)!=null&&ye.proNet24h)&&(V.proNet24h=t.kpis.proNet24h),Ce({...a,stats:n,kpis:V,series:v,modelSpeed:k,cancellationIntelligence:Sr(t.cancellationIntelligence,a.cancellationIntelligence),recentQuestions:W,feedbackIntelligence:S,topicIntelligence:I,apiIntelligence:D,recentUsers:p(a.recentUsers,t.recentUsers),topPosters:p(a.topPosters,t.topPosters)})},Sr=(t,a)=>{const s=Array.isArray(t)?t:[],n=Array.isArray(a)?a:[];if(n.length===0&&s.length>0)return s;const o=new Map;for(const r of s){const h=r.id||r.user_id;h&&o.set(h,r),r.user_id&&o.set(`user:${r.user_id}`,r)}return n.map(r=>{const h=o.get(r.id||r.user_id)||o.get(`user:${r.user_id}`);if(!h)return r;const u=Array.isArray(h.messages)?h.messages:[],g=Array.isArray(r.messages)?r.messages:[];return{...h,...r,user_email:r.user_email||h.user_email,messages:g.length>=u.length?g:u}})},jn=(t,a)=>{var h;if(!(t!=null&&t.stats)||!a||typeof a!="object")return t;const s={...t.stats},n=String(a.source||"").includes("service_role_subscriptions")||((h=a.sources)==null?void 0:h.stripe)==="stripe_live",o=(u,g)=>{const x=Number(u||0),f=typeof g=="number"&&Number.isFinite(g)?Math.max(0,Math.floor(g)):0;return n?f:Math.max(x,f)};typeof a.stripe=="number"&&(s.paidProStripe=o(s.paidProStripe,a.stripe)),typeof a.stripe_monthly=="number"&&typeof a.stripe_annual=="number"&&(s.stripeMonthly=a.stripe_monthly,s.stripeAnnual=a.stripe_annual),typeof a.apple=="number"&&(s.paidProApple=o(s.paidProApple,a.apple)),typeof a.whitelisted=="number"&&(s.whitelistedPro=o(s.whitelistedPro,a.whitelisted)),s.paidPro=Number(s.paidProStripe||0)+Number(s.paidProApple||0),s.freeUsers=Math.max(Number(s.totalUsers||0)-s.paidPro-Number(s.whitelistedPro||0),0);const r={...t.kpis};if(r.conversionRate=s.totalUsers?+((s.paidPro+Number(s.whitelistedPro||0))/s.totalUsers*100).toFixed(2):0,r.paidConversionRate=s.totalUsers?+(s.paidPro/s.totalUsers*100).toFixed(2):0,a.appleChurn&&typeof a.appleChurn=="object"){const u=a.appleChurn;typeof u.churned=="number"&&(s.churnedApple=Math.max(Number(s.churnedApple||0),u.churned)),typeof u.totalEver=="number"&&(s.totalAppleEver=Math.max(Number(s.totalAppleEver||0),u.totalEver));const g=Number(s.churnedApple||0),x=Number(s.totalAppleEver||0);x>0?r.appleChurnRate=+Math.min(100,g/x*100).toFixed(2):typeof u.rate=="number"&&Number.isFinite(u.rate)&&(r.appleChurnRate=+u.rate.toFixed(2))}return a.proNet24h&&typeof a.proNet24h=="object"&&(r.proNet24h=a.proNet24h),{...t,stats:s,kpis:r,...n?{billingAuthoritativeAt:new Date().toISOString()}:{}}},qa=t=>{var a;if(!t||typeof window>"u")return null;try{const s=window.sessionStorage.getItem(Ca);if(!s)return null;const n=JSON.parse(s);if((n==null?void 0:n.userId)!==t)return null;if(!Number.isFinite(n==null?void 0:n.savedAt)||Date.now()-Number(n.savedAt)>bd)return window.sessionStorage.removeItem(Ca),null;const o=n.snapshot;if(!(o!=null&&o.stats)||!(o!=null&&o.kpis))return null;const r=Ce(o),h=Number(((a=r.stats)==null?void 0:a.totalUsers)||0);return r}catch{return null}},Ya=(t,a)=>{if(!a||typeof window>"u")return;const s=t==null?void 0:t.stats;if(t!=null&&t.fallback&&(!s||Number(s.totalUsers||0)===0))return;const n=Number((s==null?void 0:s.totalUsers)||0),o=String((t==null?void 0:t.reason)||(t==null?void 0:t.mode)||"");if(!(n<=Zt&&/shell|timeout|fallback|deferred|rehydrating|rechecking/i.test(o)))try{window.sessionStorage.setItem(Ca,JSON.stringify({userId:a,savedAt:Date.now(),snapshot:Ce(t)}))}catch{}},ds="adminAnalytics.verifiedBilling.v1",Pd=7*24*60*60*1e3,us=()=>
86{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(ds);if(!t)return null;const a=JSON.parse(t);if(!Number.isFinite(a==null?void 0:a.savedAt)||Date.now()-Number(a.savedAt)>Pd)return window.localStorage.removeItem(ds),null;const s=a.counts;return!s||typeof s!="object"?null:s}catch{return null}},Cd=t=>{if(typeof window>"u"||!t||typeof t!="object"||!(["stripe","apple","whitelisted"].some(n=>typeof t[n]=="number"&&t[n]>0)||t.proNet24h&&typeof t.proNet24h=="object"))return;const s=us();try{window.localStorage.setItem(ds,JSON.stringify({savedAt:Date.now(),counts:{stripe:t.stripe,apple:t.apple,whitelisted:t.whitelisted,appleChurn:t.appleChurn??(s==null?void 0:s.appleChurn)??null,proNet24h:t.proNet24h&&typeof t.proNet24h=="object"?t.proNet24h:(s==null?void 0:s.proNet24h)??null,sources:t.sources??null}}))}catch{}},ma=t=>{const a=new Date;return a.setUTCDate(a.getUTCDate()-t),a},As=jr,pa=(t,a="created_at",s=30)=>{const n=As(s),o=Object.fromEntries(n.map(r=>[r.day,0]));for(const r of t||[]){const h=String((r==null?void 0:r[a])||"").slice(0,10);h in o&&(o[h]+=1)}return n.map(r=>({day:r.day,value:o[r.day]||0}))},Be=(t="client_fallback")=>{const a=As();return{fallback:!0,mode:"client_smooth_fallback",reason:t,stats:{totalUsers:0,paidPro:0,paidProStripe:0,paidProApple:0,whitelistedPro:0,freeUsers:0,churnedApple:0,totalAppleEver:0,totalConversations:0,totalMessages:0,totalUserMessages:0,totalAiMessages:0,totalForumPosts:0,totalForumThreads:0,totalFileUploads:0,totalForumProfiles:0,totalDMs:0,newToday:0,new7d:0,new30d:0,activeToday:0,active7d:0,active30d:0,convosToday:0,messagesToday:0,postsToday:0,newYesterday:0,convosYesterday:0,messagesYesterday:0,totalEpsteinDocs:0,totalApiKeys:0,totalAnalyticsEvents:0,totalSessions:0,totalUniqueAnalyticsUsers:0},kpis:{avgMsgsPerConvo:0,avgConvosPerUser:0,avgMsgsPerUser:0,conversionRate:0,paidConversionRate:0,appleChurnRate:0,retention7d:0,retention30d:0,forumParticipation:0,stickiness:0},series:{conversations:a,messages:a,forumPosts:a,userGrowth:a},topicIntelligence:null,apiIntelligence:{users:[],summary:{totalUsers:0,totalKeys:0,totalRevenue:0,totalCalls:0,totalTokens:0,totalCreditsPurchased:0,totalCreditsUsed:0}},modelSpeed:{avgMs:0,responseCount:0,activeUsers:0,lastWindowMinutes:30,routeBreakdown:{}},recentQuestions:{items:[],totalCount:0},feedbackIntelligence:{total:0,good:0,bad:0,goodRate:0,weakSpots:[],recentBad:[],allEntries:[]},cancellationIntelligence:[],recentUsers:[],topPosters:[],timestamp:new Date().toISOString()}},re=async(t,a,s={})=>{const n=new AbortController,o=window.setTimeout(()=>n.abort(),s.timeoutMs??1400);try{let r=ce.from(t).select(s.column||"id",{count:s.exact?"exact":"estimated",head:!0});a&&(r=a(r));const h=await r.abortSignal(n.signal);return h!=null&&h.error?0:Number((h==null?void 0:h.count)||0)}catch{return 0}finally{window.clearTimeout(o)}},Ct=t=>ce.from(t),Gt=async(t,a=[],s=1400)=>{const n=new AbortController,o=window.setTimeout(()=>n.abort(),s);try{const r=await t.abortSignal(n.signal);return r!=null&&r.error?a:(r==null?void 0:r.data)||a}catch{return a}finally{window.clearTimeout(o)}},Nn=t=>Array.isArray(t)&&t.some(a=>Number((a==null?void 0:a.value)||0)>0),Td=async(t,a="created_at",s=30,n=1200,o="id")=>{const r=As(s);return await Promise.all(r.map(async({day:u})=>{const g=new Date(`${u}T00:00:00.000Z`),x=new Date(g);x.setUTCDate(x.getUTCDate()+1);const f=await re(t,v=>v.gte(a,g.toISOString()).lt(a,x.toISOString()),{timeoutMs:n,column:o,exact:!0});return{day:u,value:f}}))},Md=async(t,a=6e3)=>{if(!t)return!1;const s=new AbortController,n=window.setTimeout(()=>s.abort(),a);try{const o=await fetch(`${fr}/functions/v1/admin-portal-access`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:"{}",signal:s.signal});if(!o.ok)return!1;const r=await o.json().catch(()=>null);return(r==null?void 0:r.allowed)===!0}catch{return!1}finally{window.clearTimeout(n)}},wr=async(t,a=4e3,s=null)=>{var r;if(Ke(t))return!0;const n=new AbortController,o=window.setTimeout(()=>n.abort(),a);try{const h=await Ct("user_roles").select("id").eq("user_id",t).eq("role","admin").limit(1).maybeSingle().abortSignal(n.signal);if(!(h!=null&&h.error)&&((r=h==null?void 0:h.data)!=null&&r.id))return!0}catch{}finally{window.clearTimeout(o)}return await Md(s)},_d=async t=>{var St,Ft,wt,me;if(!await wr(t))throw new Error("Admin access required");const s=new Date,n=ma(1),o=ma(7),r=ma(30),h=ma(2),u=n.toISOString(),g=r.toISOString(),x=Be("edge_function_slow"),f=async(L,Q,we=2500)=>{const Ue=new AbortController,la=window.setTimeout(()=>Ue.abort(),we);try{const Ve=await ce.rpc(L,Q).abortSignal(Ue.signal);if(Ve!=null&&Ve.error)return 0;
86const Fe=Ve==null?void 0:Ve.data;return typeof Fe=="number"?Fe:Array.isArray(Fe)&&Fe[0]!=null?Number(Fe[0]):Number(Fe||0)}catch{return 0}finally{window.clearTimeout(la)}},v=await Promise.all([re("profiles"),re("profiles"),re("subscriptions",L=>L.in("status",["active","trialing"])),re("subscriptions",L=>L.in("status",["active","trialing"]).eq("provider","stripe")),re("subscriptions",L=>L.in("status",["active","trialing"]).eq("processor","stripe")),re("subscriptions",L=>L.in("status",["active","trialing"]).in("provider",["apple","appstore","ios","revenuecat","iap"])),re("subscriptions",L=>L.in("status",["active","trialing"]).in("processor",["apple","appstore","ios","revenuecat","iap"])),Promise.resolve(0),re("chat_conversations"),re("chat_messages"),re("chat_messages",L=>L.eq("role","user")),re("chat_messages",L=>L.in("role",["assistant","ai"])),re("user_memory"),f("count_auth_users_since",{_since:u}).then(L=>L||re("profiles",Q=>Q.gte("created_at",u))),f("count_auth_users_since",{_since:o.toISOString()}).then(L=>L||re("profiles",Q=>Q.gte("created_at",o.toISOString()))),f("count_auth_users_since",{_since:r.toISOString()}).then(L=>L||re("profiles",Q=>Q.gte("created_at",r.toISOString()))),f("count_auth_users_active_since",{_since:u}).then(L=>L||re("profiles",Q=>Q.gte("updated_at",u))),f("count_auth_users_active_since",{_since:o.toISOString()}).then(L=>L||re("profiles",Q=>Q.gte("updated_at",o.toISOString()))),f("count_auth_users_active_since",{_since:r.toISOString()}).then(L=>L||re("profiles",Q=>Q.gte("updated_at",r.toISOString()))),re("chat_conversations",L=>L.gte("created_at",u)),re("chat_messages",L=>L.gte("created_at",u)),f("count_auth_users_since",{_since:h.toISOString()}).then(async L=>{const Q=await f("count_auth_users_since",{_since:u}),we=(Number(L)||0)-(Number(Q)||0);return we>0?we:re("profiles",Ue=>Ue.gte("created_at",h.toISOString()).lt("created_at",u))}),re("chat_conversations",L=>L.gte("created_at",h.toISOString()).lt("created_at",u)),re("chat_messages",L=>L.gte("created_at",h.toISOString()).lt("created_at",u)),Gt(Ct("chat_conversations").select("created_at").gte("created_at",g).order("created_at",{ascending:!1}).limit(1e3)),Gt(Ct("chat_messages").select("created_at").gte("created_at",g).order("created_at",{ascending:!1}).limit(1500)),(async()=>{let L=[];try{const we=await ce.rpc("count_auth_users_by_day",{_days:30});!(we!=null&&we.error)&&Array.isArray(we==null?void 0:we.data)&&(L=we.data.map(Ue=>({day:String(Ue.day).slice(0,10),value:Number(Ue.count)||0})))}catch{}if(Nn(L))return L;const Q=await Td("user_usage","created_at",30,1100,"user_id");return Nn(Q)?Q:L})(),Gt(Ct("chat_messages").select("id, content, conversation_id, created_at, message_type, role").eq("role","user").order("created_at",{ascending:!1}).limit(50)),Gt(Ct("profiles").select("id, email, display_name, avatar_url, created_at, updated_at").order("created_at",{ascending:!1}).limit(10)),re("forum_posts"),re("forum_threads"),re("forum_profiles"),re("direct_messages"),re("forum_posts",L=>L.gte("created_at",u)),Gt(Ct("forum_posts").select("created_at").gte("created_at",g).order("created_at",{ascending:!1}).limit(1500))]),[b,N,k,p,C,W,S,I,D,_,V,B,F,de,q,ye,E,Z,X,be,dt,La,Dt,Ut,aa,Oa,Qe,$t,sa,na,vt,yt,ra,ia,oa]=v;let Xe=null,ut=null,mt=null;try{const L=(St=(await ce.auth.getSession()).data.session)==null?void 0:St.access_token,Q=L?await De("admin-platform-analytics",L,{action:"subscription_counts"},3e4):null;Q&&typeof Q=="object"&&(((Ft=Q.sources)==null?void 0:Ft.stripe)==="stripe_live"&&typeof Q.stripe_live=="number"&&(Xe=Q.stripe_live),typeof Q.apple=="number"&&(ut=Q.apple),typeof Q.whitelisted=="number"&&(mt=Q.whitelisted))}catch(L){console.warn("subscription_counts unavailable, falling back to RLS-scoped client counts",L)}let bt=null;if(Xe===null)try{const L=(wt=(await ce.auth.getSession()).data.session)==null?void 0:wt.access_token,Q=L?await De("admin-platform-analytics",L,{action:"stripe_live_count"},3e4):null;Q&&typeof Q.count=="number"&&(bt=Q.count)}catch(L){console.warn("live stripe count unavailable, using subscriptions mirror",L)}const fe=br(Number(b||N||0)),jt=Xe!==null?Xe:bt!==null?bt:Number(p||C||k||0),Nt=ut!==null?ut:Number(W||S||0),Ze=mt!==null?mt:Number(I||0),pt=jt+Nt,Lt=pt+Ze,Ot=Math.max(fe-Lt,0);return{...x,stats:{...x.stats,totalUsers:fe,paidPro:pt,paidProStripe:jt,paidProApple:Nt,whitelistedPro:Ze,freeUsers:Ot,totalAppleEver:Nt,totalConversations:Number(D||0),totalMessages:Number(_||0),totalUserMessages:Number(V||0),totalAiMessages:Number(B||0),totalForumPosts:Number(na||0),totalForumThreads:Number(vt||0),totalFileUploads:Number(F||0),totalForumProfiles:Number(yt||0),totalDMs:Number(ra||0),newToday:Number(de||0),new7d:Number(q||0),new30d:Number(ye||0),activeToday:Number(E||0),active7d:Number(Z||0),active30d:Number(X||0),convosToday:Number(be||0),messagesToday:Number(dt||0),postsToday:Number(ia||0),newYesterday:Number(La||0),convosYesterday:Number(Dt||0),messagesYesterday:Number(Ut||0),totalEpsteinDocs:0,totalApiKeys:0,totalAnalyticsEvents:0,totalSessions:0,totalUniqueAnalyticsUsers:0},kpis:{avgMsgsPerConvo:D?+(Number(_||0)/Number(D)).toFixed(1):0,avgConvosPerUser:fe?+(Number(D||0)/fe).toFixed(1):0,avgMsgsPerUser:fe?+(Number(V||0)/fe).toFixed(1):0,conversionRate:fe?+(Lt/fe*100).toFixed(2):0,paidConversionRate:fe?+(
86pt/fe*100).toFixed(2):0,appleChurnRate:0,retention7d:fe?+(Number(Z||0)/fe*100).toFixed(1):0,retention30d:fe?+(Number(X||0)/fe*100).toFixed(1):0,forumParticipation:fe?+(Number(yt||0)/fe*100).toFixed(1):0,stickiness:X?+(Number(E||0)/Number(X)*100).toFixed(1):0},series:{conversations:pa(aa),messages:pa(Oa),forumPosts:pa(oa||[]),userGrowth:Array.isArray(Qe)&&Qe.length>0&&((me=Qe[0])==null?void 0:me.value)!==void 0?Qe:pa(Qe)},apiIntelligence:{users:[],summary:{totalUsers:0,totalKeys:0,totalRevenue:0,totalCalls:0,totalTokens:0,totalCreditsPurchased:0,totalCreditsUsed:0}},modelSpeed:{avgMs:0,responseCount:0,activeUsers:0,lastWindowMinutes:30,routeBreakdown:{}},recentQuestions:{items:$t.map(L=>({id:L.id,content:String(L.content||"").slice(0,1e3),aiResponse:null,topic:"General Chat",intent:"unknown",sentiment:"neutral",created_at:L.created_at,user_id:"unknown",user_email:null,is_pro:!1,message_type:L.message_type})),totalCount:$t.length},feedbackIntelligence:{total:0,good:0,bad:0,goodRate:0,weakSpots:[],recentBad:[],allEntries:[]},recentUsers:sa,topPosters:[],timestamp:s.toISOString()}},Ed=async(t,a,s,n)=>{const o=async()=>({data:await De("admin-platform-analytics",t,n,n.feedSearchEmail||n.feedSearchKeyword?4e4:45e3),error:null});if(n.feedSearchEmail||n.feedSearchKeyword)return _e(o(),42e3,"Analytics search timed out.");const r=async()=>{try{return{data:await _e(_d(a),7e3,"Client analytics fallback timed out."),error:null}}catch(u){if(Ke(a))return console.warn("Using empty analytics shell after fallback failure:",u),{data:Be("client_fallback_failed"),error:null};throw u}},h=async()=>{try{return await r()}catch(u){return console.warn("Fast analytics fallback unavailable:",u),null}};return _e(o(),47e3,"Analytics request timed out.").then(async u=>{const g=Pa(u==null?void 0:u.error);return u!=null&&u.error&&g!==401&&g!==403?r():u}).catch(async u=>{const g=Pa(u);if(g===401||g===403)return await h()||{data:null,error:u};const x=await h();if(x)return x;if(!Ke(a))throw u;return console.warn("Using analytics shell while legacy overview reconnects:",u),{data:Be("legacy_overview_deferred"),error:null}})};function Id(){var Es,Is,Rs,Ds,Us,$s,Ls,Os,Fs,zs;const{user:t,session:a,loading:s}=Gr(),n=(a==null?void 0:a.access_token)??null,[o,r]=d.useState(!1),[h,u]=d.useState(!1),[g,x]=d.useState(null),f=d.useRef(null);d.useEffect(()=>{let i=!1;if(!s){if(!(t!=null&&t.id)){f.current=!1,x(!1);return}if(Ke(t.id,t.email)){f.current=!0,x(!0),u(!1);return}return f.current=null,x(null),wr(t.id,4e3,n).then(m=>{if(!i&&(f.current=m,x(m),m&&u(!1),!m)){r(!1),u(!0),F(null);try{window.sessionStorage.removeItem(Ca)}catch{}}}),()=>{i=!0}}},[s,t==null?void 0:t.id,t==null?void 0:t.email,n]);const v=d.useCallback(i=>{r(i===!0?f.current===!0:!1)},[]),b=d.useCallback(i=>{if(i!==!0){u(!1);return}u(f.current!==!0)},[]),[N,k]=d.useState("overview"),[p,C]=d.useState(!1),[W,S]=vc(),I=qr(),D=d.useRef(!1);d.useLayoutEffect(()=>{const i=typeof history<"u"?history.scrollRestoration:void 0;try{"scrollRestoration"in history&&(history.scrollRestoration="manual")}catch{}const m=()=>{window.scrollY===0&&document.documentElement.scrollTop===0||(window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0)};m();const y=()=>{D.current=!0},j=()=>{D.current||m()},w=["touchstart","wheel","keydown","pointerdown"];w.forEach(M=>window.addEventListener(M,y,{passive:!0,capture:!0})),window.addEventListener("scroll",j,{passive:!0});const O=requestAnimationFrame(m),R=[0,60,180,400,800].map(M=>window.setTimeout(m,M)),A=window.setTimeout(y,1200);return()=>{w.forEach(M=>window.removeEventListener(M,y,{capture:!0})),window.removeEventListener("scroll",j),cancelAnimationFrame(O),R.forEach(M=>window.clearTimeout(M)),window.clearTimeout(A);try{i&&"scrollRestoration"in history&&(history.scrollRestoration=i)}catch{}}},[]),d.useEffect(()=>{const i=()=>{Jr.forceReset(),document.documentElement.setAttribute("data-analytics-active","true"),document.body.removeAttribute("data-scroll-locked-by"),document.body.removeAttribute("data-scroll-locked"),document.body.style.overflow="",document.body.style.overflowY="",document.body.style.overflowX="",document.body.style.touchAction="",document.body.style.pointerEvents="",document.body.style.position="",document.body.style.height="",document.body.style.maxHeight="",document.body.style.overscrollBehavior="",document.documentElement.style.overflow="",document.documentElement.style.overflowY="",document.documentElement.style.overflowX="",document.documentElement.style.height="",document.documentElement.style.maxHeight="",document.documentElement.style.position="",document.documentElement.style.touchAction="";const w=document.getElementById("root");w&&(w.style.overflow="",w.style.overflowY="",w.style.height="",w.style.maxHeight="",w.style.position="")};document.documentElement.setAttribute("data-analytics-active","true"),document.body.setAttribute("data-analytics-active","true"),i();const m=requestAnimationFrame(i),y=window.setTimeout(i,100),j=window.setTimeout(i,400);return()=>{document.documentElement.removeAttribute("data-analytics-active"),document.body.removeAttribute("data-analytics-active"),cancelAnimationFrame(m),window.clearTimeout(y),window.clearTimeout(j)}},[]);const{count:_,loading:V}
86=_c(),[B,F]=d.useState(null),[de,q]=d.useState(!0),[ye,E]=d.useState(null),[Z,X]=d.useState(!1),[be,dt]=d.useState(!1),[La,Dt]=d.useState(null),[Ut,aa]=d.useState(new Date),[Oa,Qe]=d.useState(!1),[$t,sa]=d.useState(null),na=d.useRef(null),vt=d.useRef(!1),yt=d.useRef(!0),ra=d.useRef(!1);d.useLayoutEffect(()=>{if(ra.current||g!==!0||de||!B)return;ra.current=!0;const i=()=>{if(D.current)return;window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0;const j=document.getElementById("root");j&&(j.scrollTop=0)};i();const m=window.requestAnimationFrame(()=>{i(),window.requestAnimationFrame(i)}),y=window.setTimeout(i,180);return()=>{window.cancelAnimationFrame(m),window.clearTimeout(y)}},[B,de,g]);const ia=d.useRef(!1);d.useEffect(()=>{if(!ia.current){ia.current=!0;return}window.scrollTo({top:0,left:0,behavior:"auto"}),document.documentElement.scrollTop=0,document.body.scrollTop=0},[N]);const oa=d.useRef(0),Xe=d.useRef(!1);d.useEffect(()=>(yt.current=!0,()=>{yt.current=!1}),[]),d.useEffect(()=>{na.current=$t},[$t]);const ut=d.useCallback(async(i=!0)=>{var m;try{const y=n||((m=(await _e(ce.auth.getSession(),6e3,"Analytics session check timed out. Please refresh and sign in again.")).data.session)==null?void 0:m.access_token);if(!y)throw new Error("Please sign in again to load geographic intelligence.");i&&dt(!0),Dt(null);const j=await De("admin-platform-analytics",y,{action:"topic_geo"},45e3),w=Yt(j==null?void 0:j.geo);F(O=>O&&{...O,topicIntelligence:{...O.topicIntelligence||{},geo:w}}),w.countries.length===0&&Dt("No geographic rows were returned yet. The backend query completed successfully.")}catch(y){console.warn("Geographic intelligence unavailable:",y),Dt(String((y==null?void 0:y.message)||y||"Could not load geographic intelligence."))}finally{i&&dt(!1)}},[n]),mt=d.useRef(!1),bt=d.useRef(0),fe=d.useCallback(async()=>{var i;if(!mt.current&&!(Date.now()-bt.current<5e3)){mt.current=!0;try{const m=n||((i=(await _e(ce.auth.getSession(),6e3,"Analytics session check timed out.")).data.session)==null?void 0:i.access_token);if(!m)return;const y=await De("admin-platform-analytics",m,{action:"api_intelligence"},45e3),j=y==null?void 0:y.apiIntelligence;if(!j||!Array.isArray(j.users))return;F(w=>{if(!w)return w;const O=w.apiIntelligence;return j.users.length===0&&O&&Array.isArray(O.users)&&O.users.length>0?w:{...w,apiIntelligence:j}})}catch(m){console.warn("API intelligence refresh unavailable:",m)}finally{mt.current=!1,bt.current=Date.now()}}},[n]),jt=d.useRef(!1),Nt=d.useRef(0),Ze=d.useCallback(async()=>{var i;if(!jt.current&&!(Date.now()-Nt.current<5e3)){jt.current=!0;try{const m=n||((i=(await _e(ce.auth.getSession(),6e3,"Analytics session check timed out.")).data.session)==null?void 0:i.access_token);if(!m)return;const y=await De("admin-platform-analytics",m,{action:"cancellation_intelligence",limit:250},45e3),j=y==null?void 0:y.cancellationIntelligence;if(!Array.isArray(j))return;F(w=>w&&{...w,cancellationIntelligence:Sr(w.cancellationIntelligence,j)})}catch(m){console.warn("Cancellation intelligence refresh unavailable:",m)}finally{jt.current=!1,Nt.current=Date.now()}}},[n]),pt=d.useRef(!1),Lt=d.useRef(0),Ot=d.useCallback(async()=>{var i;if(!pt.current&&!(Date.now()-Lt.current<5e3)){pt.current=!0;try{const m=n||((i=(await _e(ce.auth.getSession(),6e3,"Analytics session check timed out.")).data.session)==null?void 0:i.access_token);if(!m)return;const y=await De("admin-platform-analytics",m,{action:"feedback_intelligence"},45e3),j=y==null?void 0:y.feedbackIntelligence;if(!j)return;F(w=>{if(!w)return w;const O=w.feedbackIntelligence,R=Number(j.total||0)===0&&(!Array.isArray(j.allEntries)||j.allEntries.length===0),A=O&&(Number(O.total||0)>0||Array.isArray(O.allEntries)&&O.allEntries.length>0);return R&&A?w:{...w,feedbackIntelligence:j}})}catch(m){console.warn("Feedback intelligence refresh unavailable:",m)}finally{pt.current=!1,Lt.current=Date.now()}}},[n]),St=d.useRef(!1),Ft=d.useRef(0),wt=d.useCallback(async()=>{var i;if(!St.current&&!(Date.now()-Ft.current<5e3)){St.current=!0;try{const m=n||((i=(await _e(ce.auth.getSession(),6e3,"Analytics session check timed out.")).data.session)==null?void 0:i.access_token);if(!m)return;const y=await De("admin-platform-analytics",m,{action:"topic_intelligence",limit:3e3},6e4),j=y==null?void 0:y.topicIntelligence;if(!j)return;F(w=>{if(!w)return w;const O=w.topicIntelligence,R=Number(j.totalClassified||0)===0,A=O&&Number(O.totalClassified||0)>0;if(R&&A)return w;const M={...j,geo:j.geo??(O==null?void 0:O.geo)??null};return{...w,topicIntelligence:M}})}catch(m){console.warn("Topic intelligence refresh unavailable:",m)}finally{St.current=!1,Ft.current=Date.now()}}},[n]),me=d.useRef(null),L=d.useRef(!1),Q=d.useRef(0),we=d.useRef(null),Ue=d.useRef(!1),la=d.useRef(!1),Ve=d.useRef(0),[Fe,ks]=d.useState(!1),[Ar,Ps]=d.use
86State(()=>{var m;const i=(m=us())==null?void 0:m.proNet24h;return i&&typeof i=="object"&&Number.isFinite(Number(i.net))?i:null}),[Cs,kr]=d.useState(0),Fa=d.useRef(!1),Ts=d.useRef(0),Ms=d.useCallback(async i=>{const m=Date.now();if(!(Fa.current||m-Ts.current<2*60*1e3)){Fa.current=!0;try{const y=await De("admin-platform-analytics",i,{action:"signup_metrics"},4e4),j=y==null?void 0:y.signupMetrics;if(!j)return;const w=String(j.source||"signup_metrics_endpoint"),O=w.includes("engaged")&&!w.includes("estimate");F(R=>{if(!R)return R;const A=O&&Number(j.total||0)>=1e5?Sd(Number(j.total)):Number(R.stats.totalUsers||0),M=Ce({...R,signupMetricSource:O?w:R.signupMetricSource,stats:{...R.stats,totalUsers:O?A:Number(R.stats.totalUsers||0),newToday:Number(O?j.newToday||0:R.stats.newToday||0),newYesterday:Number(O?j.newYesterday||0:R.stats.newYesterday||0),new7d:Number(O?j.new7d||0:R.stats.new7d||0),new30d:Number(O?j.new30d||0:R.stats.new30d||0)},series:{...R.series,userGrowth:Array.isArray(j.userGrowth)&&j.userGrowth.some(U=>Number(U.value||0)>0)?j.userGrowth:R.series.userGrowth}});return Ya(M,t==null?void 0:t.id),M})}catch(y){console.warn("Signup metric refresh unavailable:",y)}finally{Fa.current=!1,Ts.current=Date.now()}}},[t==null?void 0:t.id]),At=d.useCallback(async(i,m)=>{var O,R;if(L.current)return;L.current=!0;const y=++oa.current,j=t==null?void 0:t.id,w=A=>{yt.current&&y===oa.current&&A()};try{const A=n||((O=(await _e(ce.auth.getSession(),6e3,"Analytics session check timed out. Please refresh and sign in again.")).data.session)==null?void 0:O.access_token);if(!A){w(()=>{Ke(j,t==null?void 0:t.email)?(v(!0),b(!1),F(Ce(Be("session_token_rehydrating"))),window.setTimeout(()=>{var G;(G=me.current)==null||G.call(me)},4e3)):(v(!1),b(!0),F(null)),E(null)});return}if(!j){w(()=>{v(!1),b(!0),F(null),E(null)});return}const M=i===void 0?na.current:i,U={action:"overview_fast"};M&&(U.feedSearchEmail=M,U.feedLimit=1e3),m&&(U.feedSearchKeyword=m,U.feedLimit=1e3);const{data:H,error:pe}=await Ed(A,j,t==null?void 0:t.email,U);if(pe){const G=Pa(pe);if(G===401||G===403){w(()=>{Ke(j,t==null?void 0:t.email)?(v(!0),b(!1),F(tt=>tt||Ce(Be("admin_auth_rechecking"))),window.setTimeout(()=>{var tt;(tt=me.current)==null||tt.call(me)},5e3)):(v(!1),b(!0),F(null)),E(null)});return}throw pe}if(H!=null&&H.error&&/admin|auth|required|forbidden/i.test(String(H.error))){w(()=>{Ke(j,t==null?void 0:t.email)?(v(!0),b(!1),F(G=>G||Ce(Be("admin_auth_rechecking"))),window.setTimeout(()=>{var G;(G=me.current)==null||G.call(me)},5e3)):(v(!1),b(!0),F(null)),E(null)});return}if(!(H!=null&&H.stats))throw new Error((H==null?void 0:H.error)||"Missing stats");if((H==null?void 0:H.fallback)&&Number(((R=H==null?void 0:H.stats)==null?void 0:R.totalUsers)||0)===0){const G=qa(t==null?void 0:t.id),tt=Ce(G||H);w(()=>{v(!0),b(!1),F(He=>ua(He,tt)),E(null)}),window.setTimeout(()=>{var He;(He=me.current)==null||He.call(me)},6e3);return}let Ne=Ce(H);if(Ne!=null&&Ne.recentQuestions){const G=Ne.recentQuestions;"items"in G&&Array.isArray(G.items)?Ne.recentQuestions=G:Array.isArray(G)&&(Ne.recentQuestions={items:G,totalCount:G.length})}w(()=>{v(!0),b(!1),E(null),F(G=>{var Ws,Vs;const tt=!i&&!m&&((Vs=(Ws=G==null?void 0:G.recentQuestions)==null?void 0:Ws.items)==null?void 0:Vs.length),He=G==null?void 0:G.apiIntelligence,Bt=Ne==null?void 0:Ne.apiIntelligence,_r=Bt&&Array.isArray(Bt.users)&&Bt.users.length>0?Bt:He&&Array.isArray(He.users)&&He.users.length>0?He:Bt,Ks=ua(G,{...Ne,apiIntelligence:_r}),Bs=tt&&G?{...Ks,recentQuestions:G.recentQuestions}:Ks;return Ya(Bs,t==null?void 0:t.id),Bs}),aa(H.timestamp?new Date(H.timestamp):new Date)});const z=String(H.signupMetricSource||"");(!z||z.includes("timeout")||z.includes("unverified"))&&Ms(A)}catch(A){console.error("Analytics fetch error:",A),w(()=>{const M=qa(t==null?void 0:t.id);if(M)v(!0),b(!1),F(U=>ua(U,M)),E(null);else{const U=A instanceof Error?A.message:String(A||"Could not load analytics.");Ke(j,t==null?void 0:t.email)?(v(!0),b(!1),F(Ce(Be("initial_overview_deferred"))),E(null),window.setTimeout(()=>{var H;(H=me.current)==null||H.call(me)},6e3)):(F(H=>H),E(U))}})}finally{L.current=!1,Q.current=Date.now(),w(()=>{q(!1),X(!1)})}},[n,t==null?void 0:t.id,t==null?void 0:t.email,N,Ms]),_s=d.useCallback((i=400,m=8e3)=>{we.current&&window.clearTimeout(we.current),we.current=window.setTimeout(()=>{var y;we.current=null,!L.current&&(Date.now()-Q.current<m||(y=me.current)==null||y.call(me))},i)},[]);d.useEffect(()=>{me.current=At},[At]);const za=d.useRef({keyword:null,email:null}),Je=d.useCallback(async(i,m,y=!1)=>{var j,w,O;if(!vt.current)try{vt.current=!0,Qe(!0),za.current={keyword:i,email:m};const R=n||((j=(await _e(ce.auth.getSession(),6e3,"Analytics session check timed out.")).data.session)==null?void 0:j.access_token);if(!R)return;const A=y&&((O=(w=B==null?void 0:B.recentQuestions)==null?void 0:w.items)==null?void 0:O.length)||0,M=await _e(De("admin-platform-analytics",R,{action:"feed_search",feedSearchKeyword:i||void 0,feedSearchEmail:m||void 0,feedLimit:i||m?1e3:100,feedOffset:A},2e4),21e3,"Feed search timed out.");if(M!=null&&M.error){const pe=Pa(M);throw(pe===401||pe===403)&&b(!0),new Error(String(M.error))}const U=(M==null?void 0:M.items)||[],H=(M==null?void 0:M.totalCount)||0;F(pe=>{var Ie;return pe&&{...pe,recentQuestions:{items:y?[...((Ie=pe.recentQuestions)==null?void 0:Ie.items)||[],...U]:U,totalCount:H},timestamp:new Date().toISOString()}}),E(pe=>pe==="Showing the last loaded analytics snapshot while live data reconnects."?null:pe)}catch(R){console.error("Feed search error:",R)}finally{vt.current=!1,Qe(!1)}},[(Is=(Es=B==null?void 0:B.recentQuestions)==null?void 0:Es.items)==null?void 0:Is.length,n]),Pr=d.useCallback(()=>{const{keyword:i,email:m}=za.current;Je(i,m,!0)},[Je]),Cr=d.useCallback(i=>{const m=(i==null?void 0:i.trim().toLowerCase())||null;sa(m),Je(null,m)},[Je]),Tr=d.useCallback(i=>{sa(null),Je(i,null)},[Je]);d.useEffect(()=>{if(s)return;if(!t){v(!1),b(!0),q(!1),X(!1),F(null);return}if(g!==!0){g===!1&&(q(!1),X(!1));return}b(!1),E(null);const i=qa(t.id);i&&!B?(F(i),v(!0),q(!1),aa(i.timestamp?new Date(i.timestamp):new Date)):!B&&Ke(t.id,t.email)?(F(Ce(Be("initial_admin_shell"))),v(!0),q(!1)):q(m=>m||!B),At()},[s,t==null?void 0:t.id,t==null?void 0:t.email,g,At]),d.useEffect(()=>{if(!o||h)return;const i=window.setInterval(()=>{document.visibilityState==="visible"&&_s(0,2e4)},2*60*1e3);return()=>window.clearInterval(i)},[o,h,_s]),d.useEffect(()=>{if(!o||h||!B||la.current)return;la.current=!0;const i=us();i&&(i.proNet24h&&typeof i.proNet24h=="object"&&Number.isFinite(Number(i.proNet24h.net))&&Ps(i.proNet24h),F(m=>m&&Ce(jn(m,i))))},[B,o,h]),d.useEffect(()=>{if(!o||h||N!=="overview"||!n)return;let i=!1;const m=Cs>0,y=async(w=m)=>{const O=Date.now();if(Ue.current||!w&&O-Ve.current<5*60*1e3)return;Ue.current=!0,ks(!0);let R=!1;try{const A=await _e(De("pro-counts",n,w?{refresh_segments:!0}:{prefer_snapshot:!0},8e3),9e3,"Verified billing snapshot timed out.");if(i)return;if(!A||typeof A!="object")throw new Error("Billing snapshot was unavailable.");Ve.current=Date.now(),Cd(A),A.proNet24h&&typeof A.proNet24h=="object"&&Number.isFinite(Number(A.proNet24h.net))&&Ps(A.proNet24h),F(M=>{if(!M)return M;const U=ua(M,Ce(jn(M,A)));return Ya(U,t==null?void 0:t.id),U}),R=!w}catch(A){console.warn("Authoritative billing count refresh unavailable:",A)}finally{Ue.current=!1,i||ks(!1)}R&&!i&&y(!0)};y();const j=window.setInterval(()=>{document.visibilityState==="visible"&&y()},5*60*1e3);return()=>{i=!0,window.clearInterval(j)}},[N,h,o,n,t==null?void 0:t.id,Cs]),d.useEffect(()=>{if(!o||h)return;const i=()=>
86{if(document.visibilityState!=="visible")return;const{keyword:y,email:j}=za.current;y||j||vt.current||Je(null,null)};i();const m=window.setInterval(i,3e4);return()=>window.clearInterval(m)},[o,h,Je]),d.useEffect(()=>{var m;!o||h||N!=="geographic"||Yt((m=B==null?void 0:B.topicIntelligence)==null?void 0:m.geo).countries.length>0||be||Xe.current||(Xe.current=!0,ut(!0))},[N,h,(Rs=B==null?void 0:B.topicIntelligence)==null?void 0:Rs.geo,be,o,ut]),d.useEffect(()=>{if(!o||h||N!=="api")return;fe();const i=window.setInterval(()=>{document.visibilityState==="visible"&&fe()},45e3);return()=>window.clearInterval(i)},[N,h,o,fe]),d.useEffect(()=>{if(!o||h||N!=="cancellations")return;Ze();const i=window.setInterval(()=>{document.visibilityState==="visible"&&Ze()},45e3);return()=>window.clearInterval(i)},[N,h,o,Ze]),d.useEffect(()=>{if(!o||h||N!=="feedback")return;Ot();const i=window.setInterval(()=>{document.visibilityState==="visible"&&Ot()},6e4);return()=>window.clearInterval(i)},[N,h,o,Ot]),d.useEffect(()=>{if(!o||h||N!=="intelligence")return;wt();const i=window.setInterval(()=>{document.visibilityState==="visible"&&wt()},6e4);return()=>window.clearInterval(i)},[N,h,o,wt]),d.useEffect(()=>{if(!o||h)return;let i;const m=()=>{i&&window.clearTimeout(i),i=window.setTimeout(()=>{Ze()},2500)},y=ce.channel("analytics-cancellations-live").on("postgres_changes",{event:"*",schema:"public",table:"cancellation_events"},m).on("postgres_changes",{event:"*",schema:"public",table:"subscriptions"},m).subscribe();return()=>{i&&window.clearTimeout(i),ce.removeChannel(y)}},[o,h,Ze]);const zt=()=>{X(!0),E(null),B||(Ke(t==null?void 0:t.id,t==null?void 0:t.email)?(F(Ce(Be("manual_refresh_shell"))),v(!0),b(!1),q(!1)):q(!0)),At()},Kt=Oc(),Mr=d.useCallback(async()=>{var i;try{const m=n||((i=(await ce.auth.getSession()).data.session)==null?void 0:i.access_token);if(!m)throw new Error("Please sign in again to resume backfill.");Kt.resume({accessToken:m,onCompleteRefresh:()=>zt()})}catch(m){ha.error("Could not resume backfill",{description:String((m==null?void 0:m.message)||m)})}},[Kt,n]);if(s||t&&g===null)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})});if(!t||h||g!==!0)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx(ot,{className:"max-w-md",children:e.jsxs(lt,{className:"p-8 text-center",children:[e.jsx(qs,{className:"h-12 w-12 text-destructive mx-auto mb-4"}),e.jsx("h2",{className:"text-xl font-bold text-foreground mb-2",children:"Access Denied"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Admin privileges required. Sign in with an admin account and retry."}),e.jsx(Se,{onClick:()=>I("/"),variant:"outline",children:"Go Home"})]})})});const ee=Ce(B||Be("render_shell")),l=ee.stats,T=ee.kpis,c=ee.topicIntelligence,et=ee.modelSpeed??null;return e.jsxs("div",{"data-analytics-scroll-root":"true",className:"analytics-page min-h-[100dvh] bg-background relative",children:[e.jsx("div",{className:"pointer-events-none fixed inset-x-0 top-0 h-[480px] -z-10 opacity-60",style:{background:"radial-gradient(ellipse 80% 60% at 50% 0%, hsl(var(--primary) / 0.10), transparent 70%)"}}),e.jsxs("header",{className:"analytics-header sticky top-0 z-40 bg-background supports-[backdrop-filter]:bg-background/95 backdrop-blur-2xl border-b border-border/40",children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-px bg-gradient-to-r from-transparent via-[hsl(var(--primary)/0.35)] to-transparent"}),e.jsxs("div",{className:"max-w-[1680px] mx-auto px-3 sm:px-5 flex items-center gap-2 sm:gap-3",children:[e.jsx(Se,{variant:"ghost",size:"icon",onClick:()=>C(!0),className:"lg:hidden shrink-0 h-9 w-9 tap-dense text-muted-foreground hover:text-primary hover:bg-[hsl(var(--primary)/0.10)]","aria-label":"Open analytics navigation",children:e.jsx(Yr,{className:"h-[18px] w-[18px]"})}),e.jsx(Se,{variant:"ghost",size:"icon",onClick:()=>I(-1),className:"hidden lg:inline-flex shrink-0 h-9 w-9 text-muted-foreground hover:text-primary hover:bg-[hsl(var(--primary)/0.10)]","aria-label":"Go back",children:e.jsx(Qr,{className:"h-[18px] w-[18px]"})}),e.jsxs("button",{onClick:()=>I("/"),className:"flex items-center min-w-0 shrink hover:opacity-80 transition-opacity","aria-label":"Go to homepage",children:[e.jsx("img",{src:"/lovable-uploads/176b9413-7402-4864-a1a3-d82814d968f2.png",alt:"Uncensored AI",className:"h-[18px] sm:h-6 w-auto max-w-[150px] sm:max-w-none object-contain hidden dark:block"}),e.jsx("img",{src:"/__l5e/assets-v1/4a012eb1-4f1a-4735-b892-6a9a3c02fd39/uai-wordmark-black.png",alt:"Uncensored AI",className:"h-[18px] sm:h-6 w-auto max-w-[150px] sm:max-w-none object-contain dark:hidden"})]}),e.jsxs("div",{className:"hidden sm:flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"text-border/70",children:"/"}),e.jsx("span",{className:"text-[13px] font-medium text-muted-foreground",children:"Analytics"}),e.jsx("span",{className:"text-border/70",children:"/"}),e.jsx("span",{className:"text-[13px] font-semibold text-foreground truncate",children:((Ds=xc(N))==null?void 0:Ds.label)??"Overview"})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 sm:gap-2 shrink-0 tap-dense",children:[e.jsxs("span",{className:"hidden md:inline text-[11px] text-muted-foreground
86/70 tabular-nums whitespace-nowrap",children:["Updated ",Ut.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})]}),e.jsx(Se,{variant:"ghost",size:"icon",onClick:zt,disabled:Z,className:"h-9 w-9 shrink-0 text-muted-foreground hover:text-primary hover:bg-[hsl(var(--primary)/0.10)]","aria-label":"Refresh analytics",children:e.jsx(Tt,{className:`h-[16px] w-[16px] ${Z?"animate-spin":""}`})}),e.jsx("div",{className:"shrink-0",children:e.jsx(Ac,{tone:"live",children:"Live"})})]})]})]}),e.jsx(jc,{openState:p,onOpenChange:C,activeTab:N,onSelect:k}),e.jsxs("div",{className:"analytics-content max-w-[1680px] mx-auto px-3 sm:px-5 space-y-4 sm:space-y-6",children:[e.jsx(zc,{state:Kt.state,onCancel:Kt.cancel,onDismiss:Kt.dismiss,onResume:Mr}),ye&&B&&e.jsxs("div",{className:"rounded-lg border border-[hsl(var(--primary)/0.25)] bg-[hsl(var(--primary)/0.06)] px-4 py-2 text-xs text-muted-foreground flex items-center gap-2",children:[e.jsx(ps,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{children:ye})]}),de?e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3",children:Array.from({length:24}).map((i,m)=>e.jsx(ot,{className:"bg-card/80",children:e.jsxs(lt,{className:"p-4",children:[e.jsx(Qt,{className:"h-4 w-20 mb-2"}),e.jsx(Qt,{className:"h-7 w-24"})]})},m))}):!l||!T?e.jsx(ot,{className:"bg-card/80 border-border/50",children:e.jsxs(lt,{className:"p-8 text-center space-y-3",children:[e.jsx(qs,{className:"h-10 w-10 text-muted-foreground mx-auto"}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Analytics unavailable"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:ye||"Could not load analytics.
86Confirm your admin session is active."}),e.jsxs(Se,{variant:"outline",onClick:zt,disabled:Z,className:"gap-2",children:[e.jsx(Tt,{className:`h-4 w-4 ${Z?"animate-spin":""}`})," Retry"]})]})}):e.jsx(ei,{value:N,onValueChange:k,className:"space-y-0",children:e.jsxs("div",{className:"flex gap-4 xl:gap-6 items-start",children:[e.jsx(bc,{activeTab:N,onSelect:k,collapsed:W,onToggleCollapsed:()=>S(i=>!i)}),e.jsx("div",{className:"min-w-0 flex-1 space-y-5",children:e.jsxs(Kc,{tabName:N,children:[e.jsxs(Y,{value:"overview",className:"mt-0 space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-foreground flex items-center gap-2 min-w-0",children:[e.jsx(Xa,{className:"w-4 h-4 shrink-0 text-brand"}),e.jsx("span",{className:"break-words",children:"Executive Overview"})]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsxs("span",{className:"inline-flex items-center rounded-full border border-border/50 bg-muted/30 px-2 py-0.5 text-[10px] sm:text-[11px] font-medium text-muted-foreground tabular-nums whitespace-nowrap",children:[Ut.toLocaleDateString(void 0,{month:"short",day:"numeric"})," · ",Ut.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})]}),e.jsx("p",{className:"text-[11px] sm:text-xs text-muted-foreground",children:"Live metrics, growth, segments, and platform totals"})]})]}),e.jsxs(Se,{variant:"outline",size:"sm",onClick:async()=>{const[{default:i},{default:m}]=await Promise.all([J(()=>import("./jspdf.es.min-B-MU2tO3.js").then(H=>H.j),__vite__mapDeps([0,1,2,3])),J(()=>import("./jspdf.plugin.autotable-DtM9Cxfv.js"),[])]),y=new i({unit:"pt",format:"letter"}),j=y.internal.pageSize.getWidth(),w=new Date,O=new Image;O.src=Xr;try{await O.decode()}catch{}const R=44;O.complete&&O.naturalWidth>0&&y.addImage(O,"PNG",40,28,R,R);const A=40+R+14;y.setFontSize(16),y.setTextColor(15,23,42),y.text("Executive Overview",A,50),y.setFontSize(10),y.setTextColor(100,116,139),y.text(`Generated: ${w.toLocaleString()}`,A,66),y.text(`Live visitors: ${(_??0).toLocaleString()}`,A,80);const M=H=>typeof H=="number"?H.toLocaleString():(H??"â").toString(),U=(H,pe,Ie)=>{m(y,{startY:pe,head:[[H,"Value"]],body:Ie.map(([Ne,z])=>[Ne,M(z)]),styles:{fontSize:10,cellPadding:6},headStyles:{fillColor:[6,182,212],textColor:255,fontStyle:"bold"},alternateRowStyles:{fillColor:[248,250,252]},columnStyles:{0:{cellWidth:280},1:{halign:"right"}},margin:{left:40,right:40},didDrawPage:()=>{const Ne=y.internal.pageSize.getHeight();y.setFontSize(8),y.setTextColor(148,163,184),y.text("uncensored.ai â Confidential investor report",40,Ne-20),y.text(String(y.getNumberOfPages()),j-40,Ne-20,{align:"right"})}})};U("Executive Summary",110,[["Total Users",l.totalUsers],["Active (24h)",l.activeToday],["Active (7d)",l.active7d],["Active (30d)",l.active30d],["Total Conversations",l.totalConversations],["Total Messages",l.totalMessages],["Stickiness (DAU/MAU)",`${T.stickiness}%`],["Avg Convos / User",T.avgConvosPerUser],["Avg Msgs / User",T.avgMsgsPerUser]]),U("User Segments",y.lastAutoTable.finalY+20,[["Paid Pro (Stripe)",l.paidProStripe],["Paid Pro (Apple)",l.paidProApple],["Whitelisted Pro",l.whitelistedPro],["Total Pro",l.paidPro+l.whitelistedPro],["Free Users",l.freeUsers],["Paid Conversion Rate",`${T.paidConversionRate}%`],["Overall Conversion",`${T.conversionRate}%`],["Apple Churn Rate",`${T.appleChurnRate}%`],["Churned (Apple)",`${l.churnedApple} of ${l.totalAppleEver}`]]),U("Growth Metrics",y.lastAutoTable.finalY+20,[["New Users (24h)",l.newToday],["New Users (Prior 24h)",l.newYesterday],["New Users (7d)",l.new7d],["New Users (30d)",l.new30d]]),U("Last 24h Activity",y.lastAutoTable.finalY+20,[["Conversations (24h)",l.convosToday],["Conversations (Prior 24h)",l.convosYesterday],["Messages (24h)",l.messagesToday],["Messages (Prior 24h)",l.messagesYesterday],["Forum Posts (24h)",l.postsToday]]),U("Platform Totals",y.lastAutoTable.finalY+20,[["Total User Messages",l.totalUserMessages],["Total AI Responses",l.totalAiMessages],["Total Forum Posts",l.totalForumPosts],["Total Forum Threads",l.totalForumThreads],["Total Direct Messages",l.totalDMs],["Total File Uploads",l.totalFileUploads],["Total Forum Profiles",l.totalForumProfiles],["Forum Participation",`${T.forumParticipation}%`],["Total Epstein Docs",l.totalEpsteinDocs],["Total API Keys",l.totalApiKeys],["Total Analytics Events",l.totalAnalyticsEvents],["Avg Messages / Conversation",T.avgMsgsPerConvo]]),y.save(`overview-${w.toISOString().slice(0,10)}.pdf`)},className:"h-8 shrink-0 self-start sm:self-auto gap-1.5 px-2.5 text-[11px] sm:text-xs whitespace-nowrap border-brand/40 text-brand-bright hover:bg-brand/10 hover:text-brand-bright",children:[e.jsx(ts,{className:"w-3.5 h-3.5 shrink-0"}),"Export PDF"]})]}),e.jsxs("div",{children:[e.jsx(ze,{icon:Mn,title:"Live Platform Status",subtitle:"What is happening on the platform right now"}),e.jsxs(Sc,{children:[e.jsx(Vt,{label:"Live Now",value:_===null?null:_,context:"visitors on platform",live:!0,tone:"positive"}),(()=>{const i=et?et.avgMs/1e3:0,m=(et==null?void 0:et.responseCount)??0,y=(et==null?void 0:et.lastWindowMinutes)??30,j=m===0?"Calibrating":i<2?"Lightning":i<4?"Quick":i<7?"Fast":i<12?"Medium":i<20?"Slow":"Very Slow",w=m===0?"neutral":i<4?"positive":i<12?"neutral":i<20?"warning":"critical";return e.jsx(Vt,{label:"Model Response",value:m===0?"â":`${i.toFixed(1)}
86s`,context:m===0?`awaiting samples · ${y}m`:`${j} · ${m} sample${m!==1?"s":""} / ${y}m`,tone:w})})(),e.jsx(Vt,{label:"New Users",value:l.newToday,trend:Ge(l.newToday,l.newYesterday),context:"24h"}),e.jsx(Vt,{label:"Conversations",value:l.convosToday,trend:Ge(l.convosToday,l.convosYesterday),context:"24h"}),e.jsx(Vt,{label:"Messages",value:l.messagesToday,trend:Ge(l.messagesToday,l.messagesYesterday),context:"24h"})]})]}),e.jsxs("div",{children:[e.jsx(ze,{icon:Ys,title:"Primary KPIs",subtitle:"How big are we right now"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-2.5 sm:gap-3",children:[(()=>{const i=Number(l.totalUsers||0),m=Number(l.newToday||0),y=Math.max(i-m,0),w=y>0&&m>0?+(m/y*100).toFixed(m/y>=.01?2:3):null;return e.jsx(ve,{label:"Total Users",value:i,tone:"primary",context:m>0?`+${m.toLocaleString()} today${w!==null?` · +${w}%`:""}`:"Legacy auth total",tooltip:"All registered accounts in the auth database."})})(),e.jsx(ve,{label:"New Users 24h",value:l.newToday,trend:Ge(l.newToday,l.newYesterday),context:`${Number(l.newYesterday||0).toLocaleString()} prior 24h`,tooltip:"Accounts created in the last 24 hours, compared with the prior 24 hours."}),e.jsx(ve,{label:"Active 24h",value:l.activeToday,context:`${T.stickiness}% stickiness`,tooltip:"Users with at least one tracked action in the last 24h. Stickiness = active 24h ÷ active 30d."}),e.jsx(ve,{label:"Active 7d",value:l.active7d,context:`${T.retention7d}% of registered`,tooltip:"Users active at least once in the last 7 days, as a share of all registered accounts."}),e.jsx(ve,{label:"Active 30d",value:l.active30d,context:`${T.retention30d}% of registered`,tooltip:"Users active at least once in the last 30 days, as a share of all registered accounts. If this exceeds 100%, the underlying series counts activity records rather than unique accounts."}),e.jsx(ve,{label:"Total Pro",value:l.paidPro+l.whitelistedPro,tone:"premium",context:`${T.conversionRate}% of all users`,tooltip:"Paid Stripe + paid Apple + whitelisted Pro accounts."})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(ze,{icon:wi,title:"User Segments",subtitle:"Subscription and account distribution"})}),e.jsxs(Se,{type:"button",variant:"outline",size:"sm",disabled:Fe,onClick:()=>kr(i=>i+1),className:"press shrink-0 gap-1.5 mb-3 h-8",children:[e.jsx(Tt,{className:`h-3.5 w-3.5 ${Fe?"animate-spin":""}`}),Fe?"Refreshing":"Refresh billing"]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)] gap-3",children:[e.jsxs("div",{className:"rounded-[16px] border border-border/45 bg-card/35 p-3.5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2.5",children:[e.jsx(ve,{label:"Free Users",value:l.freeUsers,className:"border-0 bg-transparent px-0 py-0 hover:bg-transparent"}),e.jsx(ve,{label:"Total Pro",value:l.paidPro+l.whitelistedPro,tone:"premium",className:"border-0 bg-transparent px-0 py-0 hover:bg-transparent"}),e.jsx(ve,{label:"Conversion",value:`${T.paidConversionRate}%`,tooltip:"Paying Pro accounts ÷ total registered accounts.",className:"border-0 bg-transparent px-0 py-0 hover:bg-transparent"})]}),e.jsx(wc,{segments:[{label:"Free",value:Number(l.freeUsers||0),color:"hsl(var(--muted-foreground) / 0.45)"},{label:"Pro",value:Number(l.paidPro||0)+Number(l.whitelistedPro||0),color:"hsl(var(--premium))"}]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 sm:gap-3",children:[e.jsx(ve,{label:"Stripe Pro",value:l.paidProStripe,context:typeof l.stripeMonthly=="number"?`${Number(l.stripeMonthly).toLocaleString()} monthly · ${Number(l.stripeAnnual).toLocaleString()} annual`:"Monthly + annual subs",tone:"premium"}),e.jsx(ve,{label:"Apple Pro",value:l.paidProApple,context:"iOS subs"}),e.jsx(ve,{label:"Whitelisted",value:l.whitelistedPro,context:"Manual overrides"}),(()=>{const i=Ar||T.proNet24h;if(!(!!i&&typeof i=="object"&&Number.isFinite(Number(i.net))))return e.jsx(ve,{label:"Pro Churn 24h",value:"â",tone:"neutral",context:"Awaiting billing refresh",tooltip:"Pro subscriptions added minus cancelled over the last 24 hours. Populates on the next billing refresh."});const y=Number(i.net||0),j=Number(i.rate||0),w=y>=1?"positive":y<=-1?"critical":"neutral";return e.jsx(ve,{label:"Pro Churn 24h",value:`${y>0?"+":""}
86${y.toLocaleString()}`,tone:w,context:`${Number(i.added||0).toLocaleString()} new · ${Number(i.lost||0).toLocaleString()} lost · ${j>0?"+":""}${j}%`,tooltip:`Net Pro subscription movement in the last 24 hours: new subscriptions minus cancellations, with the percentage measured against the Pro base at the start of the window.${i.appleIncluded?" Includes Appleâs newest published daily event report.":" Stripe only â Appleâs daily report was not yet published."}`})})()]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-5",children:[e.jsxs("div",{children:[e.jsx(ze,{icon:xa,title:"Growth",subtitle:"New account creation"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2.5 sm:gap-3",children:[e.jsx(ve,{label:"New 24h",value:l.newToday,trend:Ge(l.newToday,l.newYesterday)}),e.jsx(ve,{label:"New 7d",value:l.new7d,context:`~${Math.round(l.new7d/7).toLocaleString()}/day`}),e.jsx(ve,{label:"New 30d",value:l.new30d,context:`~${Math.round(l.new30d/30).toLocaleString()}/day`})]})]}),e.jsxs("div",{children:[e.jsx(ze,{icon:Qs,title:"Last 24h Activity",subtitle:"Conversation and community volume"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2.5 sm:gap-3",children:[e.jsx(ve,{label:"Convos 24h",value:l.convosToday,trend:Ge(l.convosToday,l.convosYesterday)}),e.jsx(ve,{label:"Messages 24h",value:l.messagesToday,trend:Ge(l.messagesToday,l.messagesYesterday)}),e.jsx(ve,{label:"Posts 24h",value:l.postsToday})]})]})]}),e.jsx(Cc,{}),e.jsxs("div",{children:[e.jsx(ze,{icon:Xa,title:"Platform Usage Totals",subtitle:"Lifetime volume by area"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(Ha,{title:"AI Usage",rows:[{label:"Conversations",value:l.totalConversations,context:`${T.avgConvosPerUser} per user`},{label:"User messages",value:l.totalUserMessages,context:`${(l.totalUserMessages/Math.max(l.totalMessages,1)*100).toFixed(0)}% of all messages`},{label:"AI responses",value:l.totalAiMessages},{label:"Avg messages / conversation",value:T.avgMsgsPerConvo},{label:"Avg messages / user",value:T.avgMsgsPerUser}]}),e.jsx(Ha,{title:"Community",rows:[{label:"Forum posts",value:l.totalForumPosts},{label:"Threads",value:l.totalForumThreads},{label:"Profiles",value:l.totalForumProfiles,context:`${T.forumParticipation}% participation`},{label:"Direct messages",value:l.totalDMs}]}),e.jsx(Ha,{title:"Platform",rows:[{label:"File uploads",value:l.totalFileUploads},{label:"Analytics events",value:l.totalAnalyticsEvents},{label:"API keys",value:l.totalApiKeys},{label:"Epstein documents",value:l.totalEpsteinDocs},{label:"Total messages",value:l.totalMessages}]})]})]}),e.jsxs("div",{children:[e.jsx(ze,{icon:ao,title:"Insights & Alerts",subtitle:"Automated observations from the current snapshot"}),(()=>{const i=hc(l,T),m={critical:0,warning:1,info:2,positive:3},y=[...i].sort((j,w)=>m[j.severity??"info"]-m[w.severity??"info"]);return y.length===0?e.jsxs("div",{className:"rounded-[16px] border border-border/45 bg-card/35 px-4 py-6 text-center",children:[e.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"Nothing needs attention"}),e.jsx("p",{className:"text-[11.5px] text-muted-foreground mt-1",children:"No thresholds were crossed in the current snapshot."})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2.5 sm:gap-3",children:y.map((j,w)=>e.jsx(hn,{...j},w))})})()]})]}),e.jsxs(Y,{value:"engagement",className:"space-y-6",children:[e.jsx(gt,{icon:Mt,title:"Engagement & Retention",subtitle:"DAU/WAU/MAU, retention, cohort drop-off and conversation depth",onExport:()=>{const i=new Date,m=[{title:"Active Users",rows:[["DAU (24h)",l.activeToday],["WAU (7d)",l.active7d],["MAU (30d)",l.active30d],["Stickiness (DAU/MAU)",`${T.stickiness}%`]]},{title:"Retention & Churn",rows:[["7-Day Retention",`${T.retention7d}%`],["30-Day Retention",`${T.retention30d}%`],["Apple Churn Rate",`${T.appleChurnRate}%`],["Returning Users (7d est)",Math.max(l.active7d-l.new7d,0)],["Dormant Users",Math.max(l.totalUsers-l.active30d,0)]]},{title:"Engagement Depth",rows:[["Avg Messages / Conversation",T.avgMsgsPerConvo],["Avg Conversations / User",T.avgConvosPerUser],["Avg Messages / User",T.avgMsgsPerUser],["Forum Participation",`${T.forumParticipation}%`],["DMs per Forum User",l.totalForumProfiles>0?(l.totalDMs/l.totalForumProfiles).toFixed(1):"0"]]},{title:"Drop-off Funnel",rows:[["Registered",l.totalUsers],["â Active 30d",`${l.active30d} (${T.retention30d}%)`],["â Active 7d",l.active7d],["â Active 24h",l.activeToday],["â Sent Messages (24h)",l.messagesToday],["â Started Convos (24h)",l.convosToday]]},{title:"Daily Activity (last 30d)",headers:["Date","Conversations","Messages","Forum Posts"],body:ee.series.messages.map((y,j)=>{var w,O;return[y.day,((w=ee.series.conversations[j])==null?void 0:w.value)??0,y.value,((O=ee.series.forumPosts[j])==null?void 0:O.value)??0]})}];return rt({title:"Engagement & Retention",subtitleLines:[`Active 7d: ${l.active7d.toLocaleStr
86ing()} · 30d: ${l.active30d.toLocaleString()}`],filename:`engagement-${i.toISOString().slice(0,10)}.pdf`,sections:m})}}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(oe,{title:"DAU",value:l.activeToday,icon:Mt,subtitle:"Daily Active Users"}),e.jsx(oe,{title:"WAU",value:l.active7d,icon:Mt,subtitle:"Weekly Active Users"}),e.jsx(oe,{title:"MAU",value:l.active30d,icon:Mt,subtitle:"Monthly Active Users"}),e.jsx(oe,{title:"Stickiness (DAU/MAU)",value:`${T.stickiness}%`,icon:Ys,subtitle:T.stickiness>20?"Healthy engagement":"Room to improve"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx($,{title:"Daily Conversations (30d)",children:e.jsx(ae,{width:"100%",height:260,children:e.jsxs(Wt,{data:ee.series.conversations,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"convGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"hsl(192, 80%, 53%)",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"hsl(192, 80%, 53%)",stopOpacity:0})]})}),e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"day",tickFormatter:nt,fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se,labelFormatter:i=>`Date: ${i}`}),e.jsx(it,{type:"monotone",dataKey:"value",stroke:"hsl(192, 80%, 53%)",fill:"url(#convGrad)",strokeWidth:2,name:"Conversations"})]})})}),e.jsx($,{title:"Daily Messages (30d)",children:e.jsx(ae,{width:"100%",height:260,children:e.jsxs(Te,{data:ee.series.messages,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"day",tickFormatter:nt,fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se,labelFormatter:i=>`Date: ${i}`}),e.jsx(je,{dataKey:"value",fill:"hsl(201, 98%, 39%)",radius:[3,3,0,0],name:"Messages"})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsx($,{title:"Retention & Churn",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"7-Day Retention",value:`${T.retention7d}%`,highlight:!0}),e.jsx(P,{label:"30-Day Retention",value:`${T.retention30d}%`,highlight:!0}),e.jsx(P,{label:"Apple Churn Rate",value:`${T.appleChurnRate}%`}),e.jsx(P,{label:"Active Users (7d)",value:l.active7d}),e.jsx(P,{label:"Active Users (30d)",value:l.active30d}),e.jsx(P,{label:"Returning Users (est)",value:l.active7d-l.new7d>0?l.active7d-l.new7d:0,badge:"7d"})]})}),e.jsx($,{title:"Engagement Depth",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Avg Messages/Conversation",value:T.avgMsgsPerConvo}),e.jsx(P,{label:"Avg Conversations/User",value:T.avgConvosPerUser}),e.jsx(P,{label:"Avg Messages/User",value:T.avgMsgsPerUser}),e.jsx(P,{label:"Forum Participation",value:`${T.forumParticipation}%`}),e.jsx(P,{label:"DMs per Forum User",value:l.totalForumProfiles>0?(l.totalDMs/l.totalForumProfiles).toFixed(1):"0"})]})}),e.jsx($,{title:"Daily Forum Posts (30d)",children:e.jsx(ae,{width:"100%",height:220,children:e.jsxs(Wt,{data:ee.series.forumPosts,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"forumGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"hsl(142, 71%, 45%)",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"hsl(142, 71%, 45%)",stopOpacity:0})]})}),e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"day",tickFormatter:nt,fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se,labelFormatter:i=>`Date: ${i}`}),e.jsx(it,{type:"monotone",dataKey:"value",stroke:"hsl(142, 71%, 45%)",fill:"url(#forumGrad)",strokeWidth:2,name:"Posts"})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx($,{title:"Cohort Retention Snapshot",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Day 1 Retention (est)",value:`${l.active7d>0&&l.new7d>
860?Math.min(Math.round((l.active7d-l.new7d)/l.active7d*100),100):0}%`,highlight:!0}),e.jsx(P,{label:"Week 1 â Week 2",value:`${T.retention7d}%`}),e.jsx(P,{label:"Week 1 â Month 1",value:`${T.retention30d}%`}),e.jsx(P,{label:"New â Active (7d)",value:l.new7d>0?`${Math.round(Math.min(l.active7d,l.new7d)/l.new7d*100)}%`:"â"}),e.jsx(P,{label:"New â Active (30d)",value:l.new30d>0?`${Math.round(Math.min(l.active30d,l.new30d)/l.new30d*100)}%`:"â"}),e.jsx(P,{label:"Dormant Rate",value:`${l.totalUsers>0?Math.round((l.totalUsers-l.active30d)/l.totalUsers*100):0}%`,badge:`${Math.max(l.totalUsers-l.active30d,0)} users`})]})}),e.jsx($,{title:"Engagement Drop-off Funnel",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Registered",value:l.totalUsers}),e.jsx(P,{label:"â Active 30d",value:l.active30d,badge:`${T.retention30d}%`}),e.jsx(P,{label:"â Active 7d",value:l.active7d,badge:`${l.active30d>0?Math.round(l.active7d/l.active30d*100):0}%`}),e.jsx(P,{label:"â Active (24h)",value:l.activeToday,badge:`${l.active7d>0?Math.round(l.activeToday/l.active7d*100):0}%`,highlight:!0}),e.jsx(P,{label:"â Sent Messages (24h)",value:l.messagesToday}),e.jsx(P,{label:"â Started Convos (24h)",value:l.convosToday}),e.jsx(P,{label:"Drop: RegisteredâActive30d",value:`${l.totalUsers>0?Math.round((l.totalUsers-l.active30d)/l.totalUsers*100):0}%`,badge:"lost"})]})})]})]}),e.jsxs(Y,{value:"users",className:"space-y-6",children:[e.jsx(gt,{icon:Za,title:"User Intelligence",subtitle:"Signups, segments, power users and growth velocity",onExport:()=>{const i=new Date,m=[{title:"User Totals",rows:[["Total Users",l.totalUsers],["Active (24h)",l.activeToday],["Active (7d)",l.active7d],["Active (30d)",l.active30d],["New (24h)",l.newToday],["New (7d)",l.new7d],["New (30d)",l.new30d]]},{title:"Subscription Breakdown",rows:[["Pro (Stripe)",l.paidProStripe],["Pro (Apple)",l.paidProApple],["Whitelisted Pro",l.whitelistedPro],["Free Users",l.freeUsers],["Paid Conversion Rate",`${T.paidConversionRate}%`],["Overall Conversion",`${T.conversionRate}%`]]},{title:"Segments (Estimated)",rows:[["Active Users (7d)",l.active7d],[`Power Users (â¥${(c==null?void 0:c.powerUserThreshold)??10} msgs/7d)`,(c==null?void 0:c.powerUserCount)??"â"],["Casual Users (30d only)",Math.max(l.active30d-l.active7d,0)],["Dormant Users",Math.max(l.totalUsers-l.active30d,0)],["New This Month",l.new30d],["Returning (7d)",Math.max(l.active7d-l.new7d,0)]]},{title:"Growth Velocity",rows:[["Daily Signup Rate (7d avg)",`~${Math.round(l.new7d/7)}`],["Daily Signup Rate (30d avg)",`~${Math.round(l.new30d/30)}`],["New (24h) vs Prior 24h",`${l.newToday} vs ${l.newYesterday}`],["Week-over-week Growth",l.new7d>0?`${(l.new7d/Math.max(l.new30d-l.new7d,1)*100).toFixed(0)}%`:"â"]]},{title:"Platform Reach",rows:[["Tracked Sessions (7d)",l.totalSessions],["Unique Analytics Users (7d)",l.totalUniqueAnalyticsUsers],["Total Analytics Events (all time)",l.totalAnalyticsEvents],["Avg Events / Session (7d)",l.totalSessions>0?(l.totalAnalyticsEvents/l.totalSessions).toFixed(0):"0"]]},...c&&c.powerUsers.length>0?[{title:"Top Power Users (7d)",headers:["Rank","User ID","Messages"],body:c.powerUsers.slice(0,25).map((y,j)=>[j+1,y.userId,y.msgCount])}]:[],{title:"New Signups (last 30d)",headers:["Date","New Users"],body:ee.series.userGrowth.map(y=>[y.day,y.value])}];return rt({title:"User Intelligence",subtitleLines:[`Total users: ${l.totalUsers.toLocaleString()} · 30d active: ${l.active30d.toLocaleString()}`],filename:`users-${i.toISOString().slice(0,10)}.pdf`,sections:m})}}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx($,{title:"New User Signups (30d)",children:e.jsx(ae,{width:"100%",height:280,children:e.jsxs(dc,{data:ee.series.userGrowth,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"day",tickFormatter:nt,fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se,labelFormatter:i=>`Date: ${i}`}),e.jsx(is,{type:"monotone",dataKey:"value",stroke:"hsl(270, 70%, 55%)",strokeWidth:2,dot:!1,name:"New Users"})]})})}),e.jsx($,{title:"User Subscription Breakdown",children:e.jsx(ae,{width:"100%",height:280,children:e.jsxs(at,{children:[e.jsx(st,{data:[{name:"Pro (Stripe)",value:l.paidProStripe},{name:"Pro (Apple)",value:l.paidProApple},{name:"Whitelisted",value:l.whitelistedPro},{name:"Free",value:l.freeUsers}],cx:"50%",cy:"50%",innerRadius:55,outerRadius:95,paddingAngle:3,dataKey:"value",children:[0,1,2,3].map(i=>e.jsx($e,{fill:Ae[i]},i))}),e.jsx(te,{contentStyle:se}),e.jsx(Ye,{wrapperStyle:{fontSize:"11px"}})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx($,{title:"User Segments (Estimated)",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Active Users (7d)",value:l.active7d,highlight:!0}),e.jsx(P,{label:`Power Users (â¥${(c==null?void 0:c.powerUserThreshold)??10} msgs/7d)`,value:(c==null?void 0:c.powerUserCount)??"â",highlight:!0}),e.jsx(P,{label:"Casual Users (30d only)",value:Math.max(l.active30d-l.active7d,0)}),e.jsx(P,{label:"Dormant Users",value:Math.max(l.totalUsers-l.active30d,0)}),e.jsx(P,{label:"New This Month",value:l.new30d,badge:"new"}),e.jsx(P,{label:"Returning (7d)",value:Math.max(l.active7d-l.new7d,0)})]})}),e.jsx($,{title:"Growth Velocity",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Daily Signup Rate (7d avg)",value:`~${Math.round(l.new7d/7)}`}),e.jsx(P,{label:"Daily Signup Rate (30d avg)",value:`~${Math.round(l.new30d/30)}`}),e.jsx(P,{label:"New (24h) vs Prior 24h",value:`${l.newToday} vs ${l.newYesterday}`,highlight:!0}),e.jsx(P,{label:"Week-over-week Growth",value:l.new7d>0?`${(l.new7d/Math.max(l.new30d-l.new7d,1)*100).toFixed(0)}%`:"â"})]})}),e.jsx($,{title:"Platform Reach",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Tracked Sessions (7d)",value:l.totalSessions}),e.jsx(P,{label:"Unique Analytics Users (7d)",value:l.totalUniqueAnalyticsUsers}),e.jsx(P,{label:"Total Analytics Events (all time)",value:l.totalAnalyticsEvents}),e.jsx(P,{label:"Avg Events/Session (7d)",value:l.totalSessions>0?(l.totalAnalyticsEvents/l.totalSessions).toFixed(0):"0"})]})})]}),c?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs($,{title:"Top 10 Most Active (7d)",children:[e.jsxs("div",{className:"space-y-1.5 max-h-64 overflow-y-auto py-1",children:[c.power
86Users.map((i,m)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"text-foreground font-mono text-xs",children:[m+1,". ",i.userId]}),e.jsxs(ue,{variant:"secondary",className:"text-xs",children:[i.msgCount," msgs"]})]},i.userId)),c.powerUsers.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet"})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Power User = â¥",c.powerUserThreshold??10," classified prompts in last 7 days"]})]}),e.jsx($,{title:"Conversation Depth",children:e.jsx(ae,{width:"100%",height:220,children:e.jsxs(Te,{data:c.conversationDepth,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"range",fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(270, 70%, 55%)",radius:[4,4,0,0],name:"Conversations"})]})})}),e.jsx($,{title:"Prompt Length Distribution",children:e.jsx(ae,{width:"100%",height:220,children:e.jsxs(Te,{data:c.promptLengthBuckets,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"range",fontSize:9,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(192, 80%, 53%)",radius:[4,4,0,0],name:"Prompts"})]})})})]}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx($,{title:"User Activity Summary",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Avg Msgs/User",value:T.avgMsgsPerUser,highlight:!0}),e.jsx(P,{label:"Avg Convos/User",value:T.avgConvosPerUser}),e.jsx(P,{label:"Total Messages",value:l.totalMessages}),e.jsx(P,{label:"Total Conversations",value:l.totalConversations})]})}),e.jsx($,{title:"Conversation Depth (est)",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Avg Msgs/Convo",value:T.avgMsgsPerConvo,highlight:!0}),e.jsx(P,{label:"Total User Msgs",value:l.totalUserMessages}),e.jsx(P,{label:"Total AI Msgs",value:l.totalAiMessages}),e.jsx(P,{label:"User:AI Ratio",value:l.totalAiMessages>0?`1:${(l.totalAiMessages/Math.max(l.totalUserMessages,1)).toFixed(1)}`:"â"})]})}),e.jsx($,{title:"Activity Breakdown",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Messages (24h)",value:l.messagesToday}),e.jsx(P,{label:"Convos (24h)",value:l.convosToday}),e.jsx(P,{label:"Posts (24h)",value:l.postsToday}),e.jsx(P,{label:"File Uploads",value:l.totalFileUploads})]})})]})]}),e.jsxs(Y,{value:"geographic",className:"space-y-6",children:[e.jsx(gt,{icon:Ba,title:"Geographic Intelligence",subtitle:"Country, region, city and timezone distribution",onExport:()=>{const i=new Date,m=Yt(c==null?void 0:c.geo),y=[{title:"Coverage",rows:[["Users with Geo Data",(m==null?void 0:m.usersWithGeo)??0],["Total Users",l.totalUsers],["Coverage",l.totalUsers>0?`${(((m==null?void 0:m.usersWithGeo)??0)/l.totalUsers*100).toFixed(1)}%`:"â"],["Countries Tracked",m.countries.length],["Regions Tracked",m.regions.length],["Cities Tracked",m.cities.length]]},...m.countries.length?[{title:"Top Countries",headers:["Rank","Country","Users"],body:m.countries.slice(0,30).map((j,w)=>[w+1,j.name,j.count])}]:[],...m.regions.length?[{title:"Top Regions",headers:["Rank","Region","Users"],body:m.regions.slice(0,25).map((j,w)=>[w+1,j.name,j.count])}]:[],...m.cities.length?[{title:"Top Cities",headers:["Rank","City","Users"],body:m.cities.slice(0,25).map((j,w)=>[w+1,j.name,j.count])}]:[],...m.timezones.length?[{title:"Top Timezones",headers:["Rank","Timezone","Users"],body:m.timezones.slice(0,20).map((j,w)=>[w+1,j.name,j.count])}]:[]];return rt({title:"Geographic Intelligence",subtitleLines:[`${m.usersWithGeo.toLocaleString()} users across ${m.countries.length} countries`],filename:`geographic-${i.toISOString().slice(0,10)}.pdf`,sections:y})}}),c!=null&&c.geo&&Array.isArray(c.geo.countries)&&c.geo.countries.length>0?e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(qc,{geo:Yt(c.geo),totalUsers:l.totalUsers})}):e.jsx(ot,{className:"bg-card/80 border-primary/20",children:e.jsxs(lt,{className:"p-8 text-center space-y-3",children:[e.jsx(Ba,{className:`h-10 w-10 mx-auto ${be?"text-primary animate-pulse":"text-muted-foreground"}`}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:be?"Loading geographic intelligence":"Geographic data unavailable"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:La||"Pulling the latest country, region, city, and timezone aggregates from classified messages."}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(ue,{variant:"outline",className:"text-[10px]",children:be?"Querying backend":"Ready to retry"}),e.jsxs(Se,{variant:"outline",size:"sm",onClick:()=>{Xe.current=!0,ut(!0)},disabled:be,className:"h-7 gap-1.5 text-xs border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(Tt,{className:`h-3.5 w-3.5 ${be?"animate-spin":""}`}),"Reload Geo"]})]})]})})]}),e.jsxs(Y,{value:"content",className:"space-y-6",children:[e.jsx(gt,{icon:ca,title:"Content & Topics",subtitle:"Message volume, topic mix, intents, languages and sentiment",onExport:()=>{var y,j,w,O,R;const i=new Date,m=[{title:"Content Volume",rows:[["Total User Messages",l.totalUserMessages],["Total AI Responses",l.totalAiMessages],["Messages (24h)",l.messagesToday],["Conversations (24h)",l.convosToday],["Avg Messages / Conversation",T.avgMsgsPerConvo],["Total Conversations",l.totalConversations],["AI:User Ratio",l.totalUserMessages>0?`${(l.totalAiMessages/l.totalUserMessages).toFixed(2)}:1`:"â"],["Peak Day (30d, msgs)",Math.max(...ee.series.messages.map(A=>A.value))]]},...c&&c.totalClassified>0?[{title:"Classification Summary",rows:[["Classified Prompts",c.totalClassified],["Unique Topics",c.topTopics.length],["Avg Prompt Length (chars)",c.avgPromptLength],["Openers (first msgs)",((y=c.firstMessageAnalysis)==null?void 0:y.firstMessages)??0],["Follow-ups",((j=c.firstMessageAnalysis)==null?void 0:j.followUps)??0],["Opener Ratio",`${((w=c.firstMessageAnalysis)==null?void 0:w.firstMsgRatio)??0}%`]]},...c.topTopics24h.length?[{title:"Hot Topics (24h)",headers:["Rank","Topic","Prompts"],body:c.topTopics24h.slice(0,20).map((A,M)=>[M+1,A.name,A.count])}
86]:[],...c.topTopics7d.length?[{title:"Trending Topics (7d)",headers:["Rank","Topic","Prompts"],body:c.topTopics7d.slice(0,20).map((A,M)=>[M+1,A.name,A.count])}]:[],{title:"All-Time Top Topics",headers:["Rank","Topic","Prompts"],body:c.topTopics.slice(0,25).map((A,M)=>[M+1,A.name,A.count])},...c.intents.length?[{title:"Top User Intents",headers:["Rank","Intent","Count"],body:c.intents.slice(0,15).map((A,M)=>[M+1,A.name.replace(/_/g," "),A.count])}]:[],...c.languages.length?[{title:"Languages Detected",headers:["Rank","Language","Count"],body:c.languages.slice(0,15).map((A,M)=>[M+1,A.name.toUpperCase(),A.count])}]:[],...c.sentiments.length?[{title:"Sentiment Breakdown",headers:["Sentiment","Count","% of Classified"],body:c.sentiments.map(A=>[A.name,A.count,`${(A.count/c.totalClassified*100).toFixed(1)}%`])}]:[],...(O=c.topicUserCounts)!=null&&O.length?[{title:"Topic Engagement (Users)",headers:["Topic","Prompts","Unique Users","Prompts/User"],body:c.topicUserCounts.slice(0,25).map(A=>[A.name,A.prompts,A.uniqueUsers,A.promptsPerUser])}]:[],...(R=c.topKeywords)!=null&&R.length?[{title:"Top Content Keywords",headers:["Rank","Keyword","Mentions"],body:c.topKeywords.slice(0,40).map((A,M)=>[M+1,A.word,A.count])}]:[]]:[],{title:"Daily Messages (30d)",headers:["Date","Messages"],body:ee.series.messages.map(A=>[A.day,A.value])}];return rt({title:"Content & Topics",subtitleLines:c?[`${c.totalClassified.toLocaleString()} prompts classified across ${c.topTopics.length} topics`]:[`${l.totalMessages.toLocaleString()} total messages`],filename:`content-${i.toISOString().slice(0,10)}.pdf`,sections:m})}}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3",children:[e.jsx(oe,{title:"User Messages",value:l.totalUserMessages,icon:qt,subtitle:"Prompts sent"}),e.jsx(oe,{title:"AI Responses",value:l.totalAiMessages,icon:_t,subtitle:"Responses generated"}),e.jsx(oe,{title:"Messages (24h)",value:l.messagesToday,icon:Qs,trend:Ge(l.messagesToday,l.messagesYesterday)}),e.jsx(oe,{title:"Convos (24h)",value:l.convosToday,icon:Js,trend:Ge(l.convosToday,l.convosYesterday)}),e.jsx(oe,{title:"Avg Msgs/Convo",value:T.avgMsgsPerConvo,icon:qt,subtitle:"Conversation depth"}),c&&e.jsx(oe,{title:"Classified",value:c.totalClassified,icon:ca,subtitle:`${c.topTopics.length} topics`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx($,{title:"Message Volume & Trend (30d)",children:e.jsx(ae,{width:"100%",height:260,children:e.jsxs(pc,{data:ee.series.messages,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"day",tickFormatter:nt,fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se,labelFormatter:i=>`Date: ${i}`}),e.jsx(je,{dataKey:"value",fill:"hsl(201, 98%, 39%)",radius:[3,3,0,0],name:"Messages",opacity:.6}),e.jsx(is,{type:"monotone",dataKey:"value",stroke:"hsl(270, 70%, 55%)",strokeWidth:2,dot:!1,name:"Trend"})]})})}),e.jsx($,{title:"Message Type & Content Ratio",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 items-center",children:[e.jsx(ae,{width:"100%",height:220,children:e.jsxs(at,{children:[e.jsxs(st,{data:[{name:"User Messages",value:l.totalUserMessages},{name:"AI Responses",value:l.totalAiMessages}],cx:"50%",cy:"50%",innerRadius:45,outerRadius:80,paddingAngle:3,dataKey:"value",children:[e.jsx($e,{fill:Ae[0]}),e.jsx($e,{fill:Ae[3]})]}),e.jsx(te,{contentStyle:se}),e.jsx(Ye,{wrapperStyle:{fontSize:"11px"}})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(P,{label:"AI:User Ratio",value:l.totalUserMessages>0?`${(l.totalAiMessages/l.totalUserMessages).toFixed(2)}:1`:"â",highlight:!0}),e.jsx(P,{label:"Avg User Msgs/Day (7d)",value:Math.round(l.totalUserMessages>0?ee.series.messages.slice(-7).reduce((i,m)=>i+m.value,0)/7:0)}),e.jsx(P,{label:"Peak Day (30d)",value:Math.max(...ee.series.messages.map(i=>i.value)),badge:"msgs"}),e.jsx(P,{label:"Convos/User",value:T.avgConvosPerUser})]})]})})]}),c&&c.totalClassified>0&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx($,{title:"Conversation Depth Distribution",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Te,{data:c.conversationDepth,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"range",fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(270, 70%, 55%)",radius:[4,4,0,0],name:"Conversations"})]})})}),e.jsx($,{title:"Prompt Length Distribution",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Te,{data:c.promptLengthBuckets,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"range",fontSize:9,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(192, 80%, 53%)",radius:[4,4,0,0],name:"Prompts"})]})})})]}),e.jsxs("div",{children:[e.jsx(ze,{icon:ca,title:"Content Topics",subtitle:c?`${c.totalClassified.toLocaleStr
86ing()} prompts classified across ${c.topTopics.length} topics`:"Collecting data"}),c&&c.totalClassified>0?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx($,{title:"Hot Topics (24 Hours)",children:e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto py-1",children:c.topTopics24h.length>0?c.topTopics24h.slice(0,10).map((i,m)=>{var j;const y=((j=c.topTopics24h[0])==null?void 0:j.count)||1;return e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-foreground capitalize font-medium",children:[m+1,". ",i.name]}),e.jsx("span",{className:"text-muted-foreground tabular-nums",children:i.count})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-red-500/70 transition-all",style:{width:`${i.count/y*100}%`}})})]},i.name)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No data in last 24h"})})}),e.jsx($,{title:"Trending Topics (7 Days)",children:e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto py-1",children:c.topTopics7d.length>0?c.topTopics7d.slice(0,10).map((i,m)=>{var j;const y=((j=c.topTopics7d[0])==null?void 0:j.count)||1;return e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-foreground capitalize font-medium",children:[m+1,". ",i.name]}),e.jsx("span",{className:"text-muted-foreground tabular-nums",children:i.count})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500/70 transition-all",style:{width:`${i.count/y*100}%`}})})]},i.name)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No data yet"})})}),e.jsx($,{title:"All-Time Topic Rankings",children:e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto py-1",children:c.topTopics.slice(0,10).map((i,m)=>{var j;const y=((j=c.topTopics[0])==null?void 0:j.count)||1;return e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-foreground capitalize font-medium",children:[m+1,". ",i.name]}),e.jsx("span",{className:"text-muted-foreground tabular-nums",children:i.count})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary/70 transition-all",style:{width:`${i.count/y*100}%`}})})]},i.name)})})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx($,{title:"User Intents",children:e.jsx(ae,{width:"100%",height:220,children:e.jsxs(Te,{data:c.intents.slice(0,8).map(i=>({name:i.name.replace(/_/g," "),count:i.count})),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"name",fontSize:8,stroke:"hsl(var(--muted-foreground))",angle:-25,textAnchor:"end",height:50}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(var(--primary))",radius:[3,3,0,0]})]})})}),e.jsx($,{title:"Languages Detected",children:e.jsx(ae,{width:"100%",height:220,children:e.jsxs(at,{children:[e.jsx(st,{data:c.languages.map(i=>({name:i.name.toUpperCase(),value:i.count})),cx:"50%",cy:"50%",outerRadius:70,innerRadius:25,dataKey:"value",nameKey:"name",label:({name:i,percent:m})=>`${i} ${(m*100).toFixed(0)}%`,labelLine:!1,fontSize:10,children:c.languages.map((i,m)=>e.jsx($e,{fill:Ae[m%Ae.length]},m))}),e.jsx(te,{contentStyle:se})]})})}),e.jsx($,{title:"Sentiment Breakdown",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(ae,{width:"100%",height:160,children:e.jsxs(at,{children:[e.jsx(st,{data:c.sentiments.map(i=>({name:i.name,value:i.count})),cx:"50%",cy:"50%",outerRadius:60,innerRadius:25,dataKey:"value",label:({name:i,percent:m})=>`${i} ${(m*100).toFixed(0)}
86%`,labelLine:!1,fontSize:10,children:c.sentiments.map((i,m)=>e.jsx($e,{fill:i.name==="positive"?"#22c55e":i.name==="negative"?"#ef4444":"#94a3b8"},m))}),e.jsx(te,{contentStyle:se})]})}),e.jsx("div",{className:"flex gap-3 text-[10px]",children:c.sentiments.map(i=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${i.name==="positive"?"bg-emerald-500":i.name==="negative"?"bg-red-500":"bg-slate-400"}`}),i.name,": ",(i.count/c.totalClassified*100).toFixed(0),"%"]},i.name))})]})})]}),c.topKeywords&&c.topKeywords.length>0&&e.jsx($,{title:"Content Keywords",action:e.jsxs(ue,{variant:"outline",className:"text-[9px]",children:[c.topKeywords.length," keywords"]}),children:e.jsx("div",{className:"flex flex-wrap gap-2 py-2",children:c.topKeywords.slice(0,30).map(i=>{var w;const m=((w=c.topKeywords[0])==null?void 0:w.count)||1,y=.65+i.count/m*.7,j=.5+i.count/m*.5;return e.jsxs("span",{className:"inline-block px-2.5 py-1 rounded-full border border-border/40 text-foreground capitalize cursor-default hover:border-primary/50 transition-colors",style:{fontSize:`${y}rem`,opacity:j},title:`${i.word}: ${i.count} mentions`,children:[i.word," ",e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",i.count,")"]})]},i.word)})})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[c.sentimentByTopic&&c.sentimentByTopic.length>0&&e.jsx($,{title:"Sentiment by Topic",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Te,{data:c.sentimentByTopic.slice(0,6),layout:"vertical",children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{type:"number",fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{type:"category",dataKey:"topic",fontSize:10,stroke:"hsl(var(--muted-foreground))",width:70}),e.jsx(te,{contentStyle:se}),e.jsx(Ye,{wrapperStyle:{fontSize:"11px"}}),e.jsx(je,{dataKey:"positive",stackId:"a",fill:"#22c55e",name:"Positive"}),e.jsx(je,{dataKey:"neutral",stackId:"a",fill:"#94a3b8",name:"Neutral"}),e.jsx(je,{dataKey:"negative",stackId:"a",fill:"#ef4444",name:"Negative"})]})})}),c.firstMessageAnalysis&&e.jsx($,{title:"First Message Analysis",children:e.jsxs("div",{className:"py-2 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-xl font-bold text-foreground",children:c.firstMessageAnalysis.firstMessages.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Openers"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-xl font-bold text-foreground",children:c.firstMessageAnalysis.followUps.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Follow-ups"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-primary/10",children:[e.jsxs("p",{className:"text-xl font-bold text-primary",children:[c.firstMessageAnalysis.firstMsgRatio,"%"]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Opener Ratio"})]})]}),e.jsx(P,{label:"Avg Prompt Length",value:`${c.avgPromptLength} chars`}),e.jsx(P,{label:"Classified Messages",value:c.totalClassified})]})})]}),c.topicUserCounts&&c.topicUserCounts.length>0&&e.jsx($,{title:"Content Engagement by Topic",action:e.jsxs(ue,{variant:"outline",className:"text-[9px]",children:[c.topicUserCounts.length," topics"]}),children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/30",children:[e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground font-medium",children:"#"}),e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground font-medium",children:"Topic"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground font-medium",children:"Prompts"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground font-medium",children:"Users"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground font-medium",children:"Intensity"}),e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground font-medium w-24",children:"Share"})]})}),e.jsx("tbody",{children:c.topicUserCounts.slice(0,12).map((i,m)=>{const y=c.totalClassified>0?Math.round(i.prompts/c.totalClassified*100):0;return e.jsxs("tr",{className:"border-b border-border/10 hover:bg-muted/20",children:[e.jsx("td",{className:"py-1.5 px-2 text-muted-foreground",children:m+1}),e.jsx("td",{className:"py-1.5 px-2 text-foreground capitalize font-medium",children:i.name}),e.jsx("td",{className:"py-1.5 px-2 text-right tabular-nums",children:i.prompts.toLocaleStr
86ing()}),e.jsx("td",{className:"py-1.5 px-2 text-right tabular-nums",children:i.uniqueUsers}),e.jsx("td",{className:"py-1.5 px-2 text-right",children:e.jsxs(ue,{variant:i.promptsPerUser>3?"default":"secondary",className:"text-[9px]",children:[i.promptsPerUser,"x"]})}),e.jsx("td",{className:"py-1.5 px-2",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"flex-1 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary/60",style:{width:`${y}%`}})}),e.jsxs("span",{className:"text-[9px] text-muted-foreground tabular-nums w-7",children:[y,"%"]})]})})]},i.name)})})]})})})]}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx($,{title:"Content Volume",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Total Messages",value:l.totalMessages,highlight:!0}),e.jsx(P,{label:"User Messages",value:l.totalUserMessages}),e.jsx(P,{label:"AI Messages",value:l.totalAiMessages}),e.jsx(P,{label:"Messages Today",value:l.messagesToday})]})}),e.jsx($,{title:"Content Engagement",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Avg Msgs/Convo",value:T.avgMsgsPerConvo}),e.jsx(P,{label:"Total Conversations",value:l.totalConversations}),e.jsx(P,{label:"Convos Today",value:l.convosToday}),e.jsx(P,{label:"File Uploads",value:l.totalFileUploads})]})}),e.jsx($,{title:"Community Content",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Forum Posts",value:l.totalForumPosts}),e.jsx(P,{label:"Forum Threads",value:l.totalForumThreads}),e.jsx(P,{label:"Posts Today",value:l.postsToday}),e.jsx(P,{label:"Direct Messages",value:l.totalDMs})]})})]})]})]}),e.jsxs(Y,{value:"monetization",className:"space-y-6",children:[e.jsx(ro,{call:yd}),e.jsx(gt,{icon:Ja,title:"Monetization",subtitle:"Conversion funnel, revenue sources, churn and MRR estimates",onExport:()=>{const i=new Date,m=l.paidProStripe*9.99,y=l.paidProApple*9.99,j=m+y,w=[{title:"Subscription Headline",rows:[["Total Paid (Active)",l.paidPro],["Pro (Stripe)",l.paidProStripe],["Pro (Apple)",l.paidProApple],["Whitelisted Pro",l.whitelistedPro],["Total Pro (incl. Whitelist)",l.paidPro+l.whitelistedPro],["Free Users",l.freeUsers]]},{title:"Conversion Funnel",rows:[["Total Registered",l.totalUsers],["Active (30d)",`${l.active30d} (${T.retention30d}%)`],["Active (7d)",`${l.active7d} (${T.retention7d}%)`],["Free Users",l.freeUsers],["Paid Pro",`${l.paidPro} (${T.paidConversionRate}%)`],["Whitelisted",l.whitelistedPro],["Overall Conversion",`${T.conversionRate}%`]]},{title:"Churn Analysis (Apple)",rows:[["Total Apple Ever",l.totalAppleEver],["Currently Active (Apple)",l.paidProApple],["Churned (Apple)",l.churnedApple],["Apple Churn Rate",`${T.appleChurnRate}%`],["Apple Retention Rate",`${(100-T.appleChurnRate).toFixed(1)}%`]]},{title:"Revenue Estimates ($9.99 ARPU)",rows:[["Stripe MRR (est)",`~$${m.toFixed(0)}`],["Apple MRR (est)",`~$${y.toFixed(0)}`],["Combined MRR (est)",`~$${j.toFixed(0)}`],["Estimated ARR",`~$${(j*12).toFixed(0)}`],["Churn-Adjusted LTV (12mo)",`~$${(9.99*12*(1-T.appleChurnRate/100)).toFixed(0)}`]]},{title:"Pre-Upgrade Behavior",rows:[["Avg Msgs/Convo (all)",T.avgMsgsPerConvo],["Active Free Users (7d)",Math.max(l.active7d-(l.paidPro+l.whitelistedPro),0)],["Forum â Pro Rate",l.totalForumProfiles>0?`${(l.paidPro/Math.max(l.totalForumProfiles,1)*100).toFixed(1)}%`:"â"],["Forum Participation",`${T.forumParticipation}%`]]}];return rt({title:"Monetization",subtitleLines:[`Paid: ${l.paidPro.toLocaleString()} · Conversion: ${T.paidConversionRate}% · Est MRR: ~$${j.toFixed(0)}`],filename:`monetization-${i.toISOString().slice(0,10)}.pdf`,sections:w})}}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(oe,{title:"Total Paid",value:l.paidPro,icon:Ja,subtitle:"Active paying users",color:"bg-blue-600"}),e.jsx(oe,{title:"Conversion Rate",value:`${T.paidConversionRate}%`,icon:li,subtitle:"Free â Paid"}),e.jsx(oe,{title:"Total Pro (incl. WL)",value:l.paidPro+l.whitelistedPro,icon:es,subtitle:`${T.conversionRate}% of total`,color:"bg-primary"}
86),e.jsx(oe,{title:"Apple Churn",value:`${T.appleChurnRate}%`,icon:en,subtitle:`${l.churnedApple} churned`})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx($,{title:"Conversion Funnel",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Total Registered",value:l.totalUsers}),e.jsx(P,{label:"Active (30d)",value:l.active30d,badge:`${T.retention30d}%`}),e.jsx(P,{label:"Active (7d)",value:l.active7d,badge:`${T.retention7d}%`}),e.jsx(P,{label:"â Free Users",value:l.freeUsers}),e.jsx(P,{label:"â Paid Pro",value:l.paidPro,highlight:!0,badge:`${T.paidConversionRate}%`}),e.jsx(P,{label:"â Whitelisted",value:l.whitelistedPro})]})}),e.jsx($,{title:"Revenue Sources",children:e.jsx(ae,{width:"100%",height:220,children:e.jsxs(at,{children:[e.jsxs(st,{data:[{name:"Stripe",value:l.paidProStripe},{name:"Apple IAP",value:l.paidProApple}],cx:"50%",cy:"50%",innerRadius:45,outerRadius:80,paddingAngle:5,dataKey:"value",children:[e.jsx($e,{fill:Ae[0]}),e.jsx($e,{fill:Ae[1]})]}),e.jsx(te,{contentStyle:se}),e.jsx(Ye,{wrapperStyle:{fontSize:"11px"}})]})})}),e.jsx($,{title:"Churn Analysis",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Total Apple Ever",value:l.totalAppleEver}),e.jsx(P,{label:"Currently Active (Apple)",value:l.paidProApple}),e.jsx(P,{label:"Churned (Apple)",value:l.churnedApple}),e.jsx(P,{label:"Apple Churn Rate",value:`${T.appleChurnRate}%`,highlight:!0}),e.jsx(P,{label:"Apple Retention Rate",value:`${(100-T.appleChurnRate).toFixed(1)}%`})]})})]}),c?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx($,{title:"Pre-Upgrade Behavior Signals",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Avg Msgs/Convo (Free)",value:T.avgMsgsPerConvo}),e.jsx(P,{label:"Active Free Users (7d)",value:Math.max(l.active7d-(l.paidPro+l.whitelistedPro),0)}),e.jsx(P,{label:"High-Intent Free Users",value:c.powerUserCount>0?`~${Math.min(c.powerUserCount,Math.max(l.active7d-(l.paidPro+l.whitelistedPro),1))}`:"â",badge:"engaged"}),e.jsx(P,{label:"Forum â Pro Rate",value:l.totalForumProfiles>0?`${(l.paidPro/Math.max(l.totalForumProfiles,1)*100).toFixed(1)}%`:"â"})]})}),e.jsx($,{title:"Revenue Composition",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Stripe MRR (est)",value:`~$${(l.paidProStripe*9.99).toFixed(0)}`,highlight:!0}),e.jsx(P,{label:"Apple MRR (est)",value:`~$${(l.paidProApple*9.99).toFixed(0)}`,highlight:!0}),e.jsx(P,{label:"Combined MRR (est)",value:`~$${((l.paidProStripe+l.paidProApple)*9.99).toFixed(0)}`,badge:"MRR"}),e.jsx(P,{label:"LTV/user (est 12mo)",value:`~$${((l.paidPro>0?1:0)*9.99*12*(1-T.appleChurnRate/100)).toFixed(0)}`})]})})]}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx($,{title:"Upgrade Signals",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Free â Paid Rate",value:`${T.paidConversionRate}%`,highlight:!0}),e.jsx(P,{label:"Avg Msgs/User (all)",value:T.avgMsgsPerUser}),e.jsx(P,{label:"Active Free (7d)",value:Math.max(l.active7d-(l.paidPro+l.whitelistedPro),0)}),e.jsx(P,{label:"Forum Users (engaged)",value:l.totalForumProfiles,badge:`${T.forumParticipation}%`})]})}),e.jsx($,{title:"Revenue Estimates",children:e.jsxs("div",{className:"py-2",children:[e.jsx(P,{label:"Stripe MRR (est)",value:`~$${(l.paidProStripe*9.99).toFixed(0)}`,highlight:!0}),e.jsx(P,{label:"Apple MRR (est)",value:`~$${(l.paidProApple*9.99).toFixed(0)}`,highlight:!0}),e.jsx(P,{label:"Combined MRR",value:`~$${((l.paidProStripe+l.paidProApple)*9.99).toFixed(0)}`,badge:"MRR"}),e.jsx(P,{label:"Est. ARR",value:`~$${((l.paidProStripe+l.paidProApple)*9.99*12).toFixed(0)}`})]})})]})]}),e.jsxs(Y,{value:"community",className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(oe,{title:"Forum Profiles",value:l.totalForumProfiles,icon:Za,subtitle:`${T.forumParticipation}% participation`}),e.jsx(oe,{title:"Forum Posts",value:l.totalForumPosts,icon:eo}),e.jsx(oe,{title:"Threads",value:l.totalForumThreads,icon:Js}),e.jsx(oe,{title:"Direct Messages",value:l.totalDMs,icon:qt})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx($,{title:"Newest Community Members",children:e.jsxs("div",{className:"space-y-2 py-2 max-h-[340px] overflow-y-auto",children:[ee.recentUsers.map((i,m)=>{var y,j;return e.jsxs("div",{className:"flex items-center gap-3 py-1.5 hover:bg-muted/30 rounded-lg px-2 transition-colors",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/20 flex items-center justify-center text-xs font-bold text-primary shrink-0",children:((y=i.display_name)==null?void 0:y[0])||((j=i.username)==null?void 0:j[0])||"?"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:i.display_name||i.username}),i.is_verified&&e.jsx(ue,{variant:"secondary",className:"text-[9px] px-1 py-0",children:"â"})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["@",i.username," · ",i.post_count," posts"]})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:new Date(i.created_at).toLocaleDateString()})]},m)}),ee.recentUsers.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No community members yet"})]})}),e.jsx($,{title:"Top Posters",children:e.jsxs("div",{className:"space-y-2 py-2 max-h-[340px] overflow-y-auto",children:[ee.topPosters.map((i,m)=>e.jsxs("div",{className:"flex items-center gap-3 py-1.5 hover:bg-muted/30 rounded-lg px-2 transition-colors",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-primary/20 flex items-center justify-center text-[10px] font-bold text-primary shrink-0",children:m+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate block",children:i.display_name||i.username}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Rep: ",i.reputation_score]})]}),e.jsx("span",{className:"text-sm font-semibold text-foreground tabular-nums",children:i.post_count})]},m)),ee.topPosters.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No posters yet"})]})})]}),e.jsx($,{title:"Daily Forum Activity (30d)",children:e.jsx(ae,{width:"100%",height:220,children:e.jsxs(Wt,{data:ee.series.forumPosts,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"forumGrad2",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",
86stopColor:"hsl(38, 92%, 50%)",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"hsl(38, 92%, 50%)",stopOpacity:0})]})}),e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"day",tickFormatter:nt,fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se,labelFormatter:i=>`Date: ${i}`}),e.jsx(it,{type:"monotone",dataKey:"value",stroke:"hsl(38, 92%, 50%)",fill:"url(#forumGrad2)",strokeWidth:2,name:"Forum Posts"})]})})})]}),e.jsxs(Y,{value:"intelligence",className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-3 mb-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("h2",{className:"text-base sm:text-lg font-bold text-foreground flex items-center gap-2 min-w-0",children:[e.jsx(_t,{className:"h-5 w-5 shrink-0 text-primary"}),e.jsx("span",{className:"truncate",children:"Advanced Intelligence"})]}),e.jsx("p",{className:"text-[11px] sm:text-sm text-muted-foreground",children:c?`${c.totalClassified.toLocaleString()} prompts analyzed · ${c.topTopics.length} topics · ${c.intents.length} intents`:"Classification pipeline active â data populates as users chat"})]}),e.jsxs(Se,{variant:"outline",size:"sm",className:"gap-2 text-xs",onClick:async()=>{try{let i=0,m=0,y=!0;for(;y;){const{data:j}=await ce.functions.invoke("backfill-classifications",{body:{batchSize:500,offset:m}});if(i+=(j==null?void 0:j.inserted)||0,y=(j==null?void 0:j.hasMore)||!1,m=(j==null?void 0:j.nextOffset)||m+500,!y)break}alert(`Backfill complete! ${i} messages classified.`),zt()}catch(i){alert("Backfill error: "+String(i))}},children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Backfill Existing Messages"]}),e.jsxs(Se,{variant:"outline",size:"sm",className:"gap-2 text-xs",onClick:async()=>{var i,m,y,j;try{const{data:w}=await ce.from("prompt_classifications").select("user_id").is("country",null).limit(1);if(((w==null?void 0:w.length)||0)===0){alert("All records already have geo data!");return}const R=((j=(y=(m=(i=Intl==null?void 0:Intl.DateTimeFormat)==null?void 0:i.call(Intl))==null?void 0:m.resolvedOptions)==null?void 0:y.call(m))==null?void 0:j.timeZone)||"America/New_York",{data:A}=await ce.rpc("get_distinct_classification_users"),M=(A||[]).map(U=>({userId:U.user_id,timezone:R}));if(M.length>0){let U=0;for(let H=0;H<M.length;H+=50){const pe=M.slice(H,H+50),{data:Ie}=await ce.functions.invoke("backfill-geo",{body:{mode:"bulk",mappings:pe}});U+=(Ie==null?void 0:Ie.updated)||0}alert(`Geo backfill complete! ${U} records updated across ${M.length} users.`)}else{const{data:U}=await ce.functions.invoke("backfill-geo",{body:{mode:"all"}});alert(`Geo backfill complete! ${(U==null?void 0:U.updated)||0} records updated, ${(U==null?void 0:U.remaining)||0} remaining.`)}zt()}catch(w){alert("Geo backfill error: "+String(w))}},children:[e.jsx(Ba,{className:"h-3.5 w-3.5"}),"Backfill Geo Data"]}),e.jsxs(Se,{variant:"outline",size:"sm",onClick:()=>{var y,j,w,O,R,A,M,U,H,pe,Ie,Ne;const i=new Date,m=[{title:"Intelligence Summary",rows:[["Classified Prompts",(c==null?void 0:c.totalClassified)??0],["Unique Topics",(c==null?void 0:c.topTopics.length)??0],["Unique Intents",(c==null?void 0:c.intents.length)??0],["Languages Detected",(c==null?void 0:c.languages.length)??0],["Avg Prompt Length (chars)",(c==null?void 0:c.avgPromptLength)??0],[`Power Users (â¥${(c==null?void 0:c.powerUserThreshold)??10} msgs/7d)`,(c==null?void 0:c.powerUserCount)??0]]},...c!=null&&c.topTopics.length?[{title:"All-Time Top Topics",headers:["Rank","Topic","Prompts","% of Total"],body:c.topTopics.slice(0,30).map((z,G)=>[G+1,z.name,z.count,`${(z.count/c.totalClassified*100).toFixed(1)}%`])}]:[],...(y=c==null?void 0:c.topTopics7d)!=null&&y.length?[{title:"Trending Topics (7d)",headers:["Rank","Topic","Prompts"],body:c.topTopics7d.slice(0,20).map((z,G)=>[G+1,z.name,z.count])}]:[],...(j=c==null?void 0:c.topTopics24h)!=null&&j.length?[{title:"Hot Topics (24h)",headers:["Rank","Topic","Prompts"],body:c.topTopics24h.slice(0,20).map((z,G)=>[G+1,z.name,z.count])}]:[],...(w=c==null?void 0:c.topicMomentum)!=null&&w.length?[{title:"Topic Momentum (7d vs prior 7d)",headers:["Topic","Current 7d","Prior 7d","Change","Change %","Status"],body:c.topicMomentum.slice(0,25).map(z=>[z.topic,z.current7d,z.previous7d,z.change,`${z.changePct>0?"+":""}${z.changePct}%`,z.isHot?"HOT":z.isEmerging?"EMERGING":z.isDeclining?"DECLINING":"â"])}]:[],...(O=c==null?void 0:c.intents)!=null&&O.length?[{title:"User Intents",headers:["Rank","Intent","Count"],body:c.intents.slice(0,20).map((z,G)=>[G+1,z.name.replace(/_/g," "),z.count])}]:[],...(R=c==null?void 0:c.sentiments)!=null&&R.length?[{title:"Sentiment Breakdown",headers:["Sentiment","Count","% of Classified"],body:c.sentiments.map(z=>[z.name,z.count,`${(z.count/Math.max(c.totalClassified,1)*100).toFixed(1)}%`])}]:[],...(A=c==null?void 0:c.sentimentByTopic)!=null&&A.length?[{title:"Sentiment by Topic",headers:["Topic","Positive","Neutral","Negative","Positive Rate"],body:c.sentimentByTopic.slice(0,20).map(z=>[z.topic,z.positive,z.neutral,z.negative,`${z.positiveRate}%`])}]:[],...(M=c==null?void 0:c.languages)!=null&&M.length?[{title:"Languages Detected",headers:["Rank","Language","Count"],body:c.languages.slice(0,20).map((z,G)=>[G+1,z.name.toUpperCase(),z.count])}]:[],...(U=c==null?void 0:c.topKeywords)!=null&&U.length?[{title:"Top Keywords",headers:["Rank","Keyword","Mentions"],body:c.topKeywords.slice(0,50).map((z,G)=>[G+1,z.word,z.count])}]:[],...(H=c==null?void 0:c.topicUserCounts)!=null&&H.length?[{title:"Topic Engagement (Users)",headers:["Topic","Prompts","Unique Users","Prompts/User"],body:c.topicUserCounts.slice(0,25).map(z=>[z.name,z.prompts,z.uniqueUsers,z.promptsPerUser])}]:[],...(pe=c==null?void 0:c.powerUsers)!=null&&pe.length?[{title:"Top Power Users (7d)",headers:["Rank","User ID","Messages"],body:c.powerUsers.slice(0,25).map((z,G)=>[G+1,z.userId,z.msgCount])}]:[],...(Ie=c==null?void 0:c.hourlyHeatmap)!=null&&Ie.length?[{title:"Hourly Activity (UTC)",headers:["Hour","Prompts"],body:c.hourlyHeatmap.map((z,G)=>[`${String(G).padStart(2,"0")}:00`,z])}]:[],...(Ne=c==null?void 0:c.dayOfWeekHeatmap)!=null&&Ne.length?[{title:"Day-of-Week Activity",headers:["Day","Prompts"],body:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map((z,G)=>[z,c.dayOfWeekHeatmap[G]??0])}]:[]];rt({title:"Advanced Intelligence",subtitleLines:c?[`${c.totalClassified.toLocaleStr
86ing()} prompts · ${c.topTopics.length} topics · ${c.intents.length} intents`]:["Classification pipeline active"],filename:`intelligence-${i.toISOString().slice(0,10)}.pdf`,sections:m})},className:"h-8 shrink-0 self-start sm:self-auto gap-1.5 px-2.5 text-[11px] sm:text-xs whitespace-nowrap border-brand/40 text-brand-bright hover:bg-brand/10 hover:text-brand-bright",children:[e.jsx(ts,{className:"w-3.5 h-3.5 shrink-0"}),"Export PDF"]})]}),c&&c.totalClassified>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ze,{icon:Zr,title:"Intelligence Signals",subtitle:"Automated observations from classified data"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:(()=>{var R,A,M;const i=[];if(c.topTopics[0]){const U=Math.round(c.topTopics[0].count/c.totalClassified*100);i.push({emoji:U>30?"ð¯":"ð",title:`"${c.topTopics[0].name}" leads at ${U}%`,description:U>30?"High concentration â users are heavily focused on this topic":"Healthy topic diversity across conversations",severity:U>40?"warning":"info"})}const m=c.sentiments.find(U=>U.name==="positive"),y=c.sentiments.find(U=>U.name==="negative");if(m&&y){const U=Math.round(m.count/c.totalClassified*100),H=Math.round(y.count/c.totalClassified*100);i.push({emoji:U>H?"ð":"ð",title:`Sentiment: ${U}% positive, ${H}% negative`,description:H>20?"Elevated negative sentiment â review challenging topics":"Healthy overall user sentiment",severity:H>25?"warning":U>40?"positive":"info"})}const j=((R=c.topicMomentum)==null?void 0:R.filter(U=>U.isEmerging))||[];j.length>0&&i.push({emoji:"â¨",title:`${j.length} emerging topic${j.length>1?"s":""}`,description:`New: ${j.slice(0,3).map(U=>U.topic).join(", ")}`,severity:"positive"});const w=((A=c.topicMomentum)==null?void 0:A.filter(U=>U.isHot))||[];w.length>0&&i.push({emoji:"ð¥",title:`${w.length} hot topic${w.length>1?"s":""} surging`,description:w.slice(0,3).map(U=>`${U.topic} (+${U.changePct<500?U.changePct+"%":"new"})`).join(", "),severity:"positive"});const O=((M=c.topicMomentum)==null?void 0:M.filter(U=>U.isDeclining))||[];return O.length>0&&i.push({emoji:"ð",title:`${O.length} declining topic${O.length>1?"s":""}`,description:O.slice(0,3).map(U=>U.topic).join(", "),severity:"warning"}),c.powerUserCount>0&&i.push({emoji:"ð",title:`${c.powerUserCount} power user${c.powerUserCount===1?"":"s"} (â¥${c.powerUserThreshold??10} msgs/7d)`,description:c.powerUsers[0]?`Top user: ${c.powerUsers[0].msgCount} messages classified`:"Engaged cohort detected",severity:"info"}),c.topTopics.length>=10&&i.push({emoji:"ð",title:`${c.topTopics.length} distinct topics detected`,description:"Rich topic diversity indicates broad platform use",severity:"positive"}),c.avgPromptLength>200&&i.push({emoji:"ð",title:`Avg prompt: ${c.avgPromptLength} chars`,description:"Users are writing detailed, substantive prompts",severity:"positive"}),i.length===0&&i.push({emoji:"ð",title:"Intelligence pipeline active",description:"Signals will appear as more data is classified",severity:"info"}),i.slice(0,8).map((U,H)=>e.jsx(hn,{...U},H))})()})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3",children:[e.jsx(oe,{title:"Prompts Classified",value:c.totalClassified,icon:ca,subtitle:"Total analyzed"}),e.jsx(oe,{title:"Unique Topics",value:c.topTopics.length,icon:_t,subtitle:"Categories detected"}),e.jsx(oe,{title:"Top Topic",value:((Us=c.topTopics[0])==null?void 0:Us.name)||"-",icon:xa,subtitle:`${(($s=c.topTopics[0])==null?void 0:$s.count)||0} prompts`}),e.jsx(oe,{title:"Avg Prompt Length",value:`${c.avgPromptLength}`,icon:qt,subtitle:"Characters"}),e.jsx(oe,{title:"Opener Ratio",value:`${((Ls=c.firstMessageAnalysis)==null?void 0:Ls.firstMsgRatio)||0}%`,icon:Ji,subtitle:"First msgs vs follow-ups"}),e.jsx(oe,{title:"Power Users",value:c.powerUserCount,icon:es,subtitle:`â¥${c.powerUserThreshold??10} msgs in 7d`})]}),c.topicMomentum&&c.topicMomentum.length>0&&e.jsx($,{title:"Topic Momentum â 7-Day Trend vs Prior Week",action:e.jsxs("div",{className:"flex gap-2 text-[9px]",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-500"})," Hot"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-amber-500"})," Emerging"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500"})," Declining"]})]}),children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/30",children:[e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground font-medium",children:"Topic"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground font-medium",children:"Total"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground font-medium",children:"This 7d"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground font-medium",children:"Prev 7d"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground font-medium",children:"Change"}),e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground font-medium w-20",children:"Velocity"}),e.jsx("th",{className:"text-center py-2 px-2 text-muted-foreground font-medium",children:"Status"})]})}),e.jsx("tbody",{children:c.topicMomentum.map(i=>{const m=Math.max(...c.topicMomentum.map(y=>y.current7d),1);return e.jsxs("tr",{className:"border-b border-border/10 hover:bg-muted/20",children:[e.jsx("td",{className:"py-2 px-2 text-foreground capitalize font-medium",children:i.topic}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-muted-foreground",children:i.total}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums font-medium",children:i.current7d}),e.jsx("td",{className:"py-2 px-2 text-right tabular-nums text-muted-foreground",children:i.previous7d}),e.jsx("td",{className:"py-2 px-2 text-right",children:e.jsxs(ue,{variant:i.change>0?"default":i.change<0?"destructive":"secondary",className:"text-[9px] px-1.5",children:[i.change>0?"+":"",i.change,i.changePct!==0&&i.changePct<500?` (${i.changePct>0?"+":""}${i.changePct}%)`:""]})}),e.jsx("td",{className:"py-2 px-2",children:e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${i.isHot?"bg-emerald-500":i.isDeclining?"bg-red-500":"bg-primary/60"}`,style:{width:`${i.current7d/m*100}%`}})})}),e.jsxs("td",{className:"py-2 px-2 text-center",children:[i.isHot&&e.jsx(ue,{className:"text-[8px] bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:"Hot"}),i.isEmerging&&e.jsx(ue,{className:"text-[8px] bg-amber-500/20 text-amber-400 border-amber-500/30",children:"New"}),i.isDeclining&&e.jsx(ue,{className:"text-[8px] bg-red-500/20 text-red-400 border-red-500/30",children:"Falling"}),!i.isHot&&!i.isEmerging&&!i.isDeclining&&e.jsx("span",{className:"text-muted-foreground text-[9px]",children:"Stable"})]})]},i.topic)})})]})})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx($,{title:"Topic Distribution",children:e.jsx(ae,{width:"100%",height:300,children:e.jsxs(at,{children:[e.jsx(st,{data:c.topTopics.slice(0,10).map(i=>({name:i.name,value:i.count})),cx:"50%",cy:"50%",outerRadius:100,innerRadius:40,dataKey:"value",nameKey:"name",label:({name:i,percent:m})=>`${i} ${(m*100).toFixed(0)}
86%`,labelLine:!1,fontSize:10,children:c.topTopics.slice(0,10).map((i,m)=>e.jsx($e,{fill:Ae[m%Ae.length]},m))}),e.jsx(te,{contentStyle:se}),e.jsx(Ye,{wrapperStyle:{fontSize:"11px"}})]})})}),e.jsx($,{title:"Intent Distribution",children:e.jsx(ae,{width:"100%",height:300,children:e.jsxs(Te,{data:c.intents.slice(0,10).map(i=>({name:i.name.replace(/_/g," "),count:i.count})),layout:"vertical",children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{type:"number",fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{type:"category",dataKey:"name",fontSize:10,stroke:"hsl(var(--muted-foreground))",width:90}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(var(--primary))",radius:[0,4,4,0]})]})})})]}),c.topicTimeSeries&&c.topicTimeSeries.length>0&&c.top5topics&&e.jsx($,{title:"ð Topic Velocity (14-Day Trend)",action:e.jsx(ue,{variant:"outline",className:"text-[9px]",children:"Top 5 Topics"}),children:e.jsx(ae,{width:"100%",height:300,children:e.jsxs(Wt,{data:c.topicTimeSeries,children:[e.jsx("defs",{children:c.top5topics.map((i,m)=>e.jsxs("linearGradient",{id:`topicGrad${m}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:Ae[m%Ae.length],stopOpacity:.2}),e.jsx("stop",{offset:"95%",stopColor:Ae[m%Ae.length],stopOpacity:0})]},i))}),e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"day",tickFormatter:nt,fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se,labelFormatter:i=>`Date: ${i}`}),e.jsx(Ye,{wrapperStyle:{fontSize:"11px"}}),c.top5topics.map((i,m)=>e.jsx(it,{type:"monotone",dataKey:i,stroke:Ae[m%Ae.length],fill:`url(#topicGrad${m})`,strokeWidth:2,name:i},i))]})})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[c.sentimentTimeSeries&&c.sentimentTimeSeries.length>0&&e.jsx($,{title:"Sentiment Trend (14 Days)",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Wt,{data:c.sentimentTimeSeries,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"day",tickFormatter:nt,fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se,labelFormatter:i=>`Date: ${i}`}),e.jsx(Ye,{wrapperStyle:{fontSize:"11px"}}),e.jsx(it,{type:"monotone",dataKey:"positive",stackId:"1",stroke:"#22c55e",fill:"#22c55e",fillOpacity:.3,name:"Positive"}),e.jsx(it,{type:"monotone",dataKey:"neutral",stackId:"1",stroke:"#94a3b8",fill:"#94a3b8",fillOpacity:.2,name:"Neutral"}),e.jsx(it,{type:"monotone",dataKey:"negative",stackId:"1",stroke:"#ef4444",fill:"#ef4444",fillOpacity:.3,name:"Negative"})]})})}),c.hourlyHeatmap&&e.jsx($,{title:"â° Peak Activity Hours (UTC, 7d)",action:e.jsxs(ue,{variant:"outline",className:"text-[9px]",children:["Peak: ",c.hourlyHeatmap.indexOf(Math.max(...c.hourlyHeatmap)).toString().padStart(2,"0"),":00 UTC"]}),children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Te,{data:c.hourlyHeatmap.map((i,m)=>({hour:`${m.toString().padStart(2,"0")}:00`,count:i})),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"hour",fontSize:8,stroke:"hsl(var(--muted-foreground))",interval:2}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",radius:[3,3,0,0],name:"Messages",children:c.hourlyHeatmap.map((i,m)=>{const y=Math.max(...c.hourlyHeatmap),j=y>0?i/y:0;return e.jsx($e,{fill:j>.7?"#22c55e":j>.4?"hsl(192, 80%, 53%)":j>.15?"hsl(201, 98%, 39%)":"hsl(var(--muted-foreground))",opacity:.4+j*.6},m)})})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[c.topKeywords&&c.topKeywords.length>0&&e.jsx($,{title:"ð¤ Keyword Cloud â All Time",action:e.jsxs(ue,{variant:"outline",className:"text-[9px]",children:[c.topKeywords.length," keywords"]}),children:e.jsx("div",{className:"flex flex-wrap gap-2 py-3",children:c.topKeywords.slice(0,35).map(i=>{var j;const m=((j=c.topKeywords[0])==null?void 0:j.count)||1,y=.65+i.count/m*.85;return e.jsxs("span",{className:"inline-block px-2.5 py-1 rounded-full border border-border/40 text-foreground capitalize cursor-default transition-transform hover:scale-110 hover:border-primary/50",style:{fontSize:`${y}rem`,opacity:.45+i.count/m*.55},title:`${i.word}: ${i.count}`,children:[i.word," ",e.jsxs("span",{className:"text-muted-foreground text-[10px]",children:["(",i.count,")"]})]},i.word)})})}),c.trendingKeywords&&c.trendingKeywords.length>0&&e.jsx($,{title:"ð Trending Keywords (7d vs Prior 7d)",children:e.jsx("div",{className:"space-y-1.5 max-h-[300px] overflow-y-auto py-1",children:c.trendingKeywords.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-xs py-0.5",children:[e.jsx("span",{className:"text-foreground capitalize font-medium",children:i.word}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-muted-foreground tabular-nums",children:[i.previous,"â",i.current]}),e.jsxs(ue,{variant:i.change>0?"default":i.change<0?"destructive":"secondary",className:"text-[9px] px-1.5",children:[i.change>0?"+":"",i.change,i.changePct>0&&i.changePct<500?` (${i.changePct}%)`:i.changePct>=500?" ð":""]})]})]},i.word))})})]}),c.topicDrilldown&&c.topicDrilldown.length>0&&c.topicDrilldown.some(i=>i.subTopics.length>0)&&e.jsx($,{title:"ð Topic Drilldown â Sub-Topic Breakdown",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 py-2",children:c.topicDrilldown.filter(i=>i.subTopics.length>0).slice(0,8).map(i=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold text-foreground capitalize",children:i.topic}),e.jsx(ue,{variant:"secondary",className:"text-[9px]",children:i.totalPrompts})]}),i.subTopics.slice(0,5).map(m=>{const y=i.totalPrompts>0?Math.round(m.count/i.totalPrompts*100):0;return e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-[10px]",children:[e.jsx("span",{className:"text-muted-foreground capitalize",children:m.name}),e.jsxs("span",{className:"text-muted-foreground tabular-nums",children:[m.count," (",y,"%)"]})]}),e.jsx("div",{className:"h-1 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary/60",style:{width:`${y}%`}})})]},m.name)})]},i.topic))})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsx($,{title:"Language Distribution",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(at,{children:[e.jsx(st,{data:c.languages.map(i=>({name:i.name.toUpperCase(),value:i.count})),cx:"50%",cy:"50%",outerRadius:80,innerRadius:30,dataKey:"value",nameKey:"name",label:({name:i,percent:m})=>`${i} ${(m*100).toFixed(0)}
86%`,labelLine:!1,fontSize:10,children:c.languages.map((i,m)=>e.jsx($e,{fill:Ae[m%Ae.length]},m))}),e.jsx(te,{contentStyle:se})]})})}),e.jsx($,{title:"Sentiment Analysis",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(at,{children:[e.jsx(st,{data:c.sentiments.map(i=>({name:i.name,value:i.count})),cx:"50%",cy:"50%",outerRadius:80,innerRadius:30,dataKey:"value",nameKey:"name",label:({name:i,percent:m})=>`${i} ${(m*100).toFixed(0)}%`,labelLine:!1,fontSize:10,children:c.sentiments.map((i,m)=>e.jsx($e,{fill:i.name==="positive"?"#22c55e":i.name==="negative"?"#ef4444":"#94a3b8"},m))}),e.jsx(te,{contentStyle:se})]})})}),e.jsx($,{title:"Day of Week Activity (7d)",children:c.dayOfWeekHeatmap&&e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Te,{data:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map((i,m)=>({name:i,count:c.dayOfWeekHeatmap[m]||0})),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"name",fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(38, 92%, 50%)",radius:[4,4,0,0],name:"Messages"})]})})})]}),c.topicIntentCross&&c.topicIntentCross.length>0&&e.jsx($,{title:"ð§© Topic à Intent Matrix â What users want per topic",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/30",children:[e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground font-medium",children:"Topic"}),e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground font-medium",children:"Dominant Intent"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground font-medium",children:"%"}),e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground font-medium",children:"Other Intents"})]})}),e.jsx("tbody",{children:c.topicIntentCross.map(i=>e.jsxs("tr",{className:"border-b border-border/10 hover:bg-muted/20",children:[e.jsx("td",{className:"py-2 px-2 text-foreground capitalize font-medium",children:i.topic}),e.jsx("td",{className:"py-2 px-2",children:e.jsx(ue,{variant:"default",className:"text-[9px] capitalize",children:i.topIntent.replace(/_/g," ")})}),e.jsxs("td",{className:"py-2 px-2 text-right text-foreground tabular-nums",children:[i.topIntentPct,"%"]}),e.jsx("td",{className:"py-2 px-2",children:e.jsx("div",{className:"flex gap-1 flex-wrap",children:i.intents.slice(1,4).map(m=>e.jsxs(ue,{variant:"secondary",className:"text-[8px] capitalize",children:[m.name.replace(/_/g," ")," (",m.count,")"]},m.name))})})]},i.topic))})]})})}),c.sentimentByTopic&&c.sentimentByTopic.length>0&&e.jsx($,{title:"Sentiment by Topic",children:e.jsx(ae,{width:"100%",height:280,children:e.jsxs(Te,{data:c.sentimentByTopic,layout:"vertical",children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{type:"number",fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{type:"category",dataKey:"topic",fontSize:10,stroke:"hsl(var(--muted-foreground))",width:80}),e.jsx(te,{contentStyle:se}),e.jsx(Ye,{wrapperStyle:{fontSize:"11px"}}),e.jsx(je,{dataKey:"positive",stackId:"a",fill:"#22c55e",name:"Positive"}),e.jsx(je,{dataKey:"neutral",stackId:"a",fill:"#94a3b8",name:"Neutral"}),e.jsx(je,{dataKey:"negative",stackId:"a",fill:"#ef4444",name:"Negative"})]})})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[c.conversationStarters&&e.jsx($,{title:"Conversation Starters",children:e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider",children:"How people start conversations"}),c.conversationStarters.topIntents.slice(0,6).map(i=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-foreground capitalize",children:i.name.replace(/_/g," ")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-16 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary/60",style:{width:`${c.conversationStarters.total>0?i.count/c.conversationStarters.total*100:0}%`}})}),e.jsx(ue,{variant:"secondary",className:"text-[9px]",children:i.count})]})]},i.name)),e.jsxs("div",{className:"pt-2 border-t border-border/20",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Starter Sentiment"}),e.jsx("div",{className:"flex gap-2",children:c.conversationStarters.topSentiments.map(i=>e.jsxs(ue,{variant:"secondary",className:`text-[9px] ${i.name==="positive"?"bg-emerald-500/10 text-emerald-400":i.name==="negative"?"bg-red-500/10 text-red-400":""}`,children:[i.name,": ",i.count]},i.name))})]})]})}),c.firstMessageAnalysis&&e.jsxs($,{title:"First Message Analysis",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 py-2",children:[e.jsxs("div",{className:"text-center p-3 rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:c.firstMessageAnalysis.firstMessages.toLocaleStr
86ing()}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Openers"})]}),e.jsxs("div",{className:"text-center p-3 rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:c.firstMessageAnalysis.followUps.toLocaleString()}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Follow-ups"})]})]}),c.firstMessageAnalysis.topFirstMsgTopics.length>0&&e.jsxs("div",{className:"mt-2 space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider",children:"Top Opener Topics"}),c.firstMessageAnalysis.topFirstMsgTopics.slice(0,5).map((i,m)=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-foreground capitalize",children:[m+1,". ",i.name]}),e.jsx(ue,{variant:"secondary",className:"text-[9px]",children:i.count})]},i.name))]})]}),c.topicUserCounts&&c.topicUserCounts.length>0&&e.jsx($,{title:"Topic Engagement",children:e.jsx("div",{className:"overflow-y-auto max-h-[300px]",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-card",children:e.jsxs("tr",{className:"border-b border-border/30",children:[e.jsx("th",{className:"text-left py-1.5 px-1 text-muted-foreground font-medium",children:"Topic"}),e.jsx("th",{className:"text-right py-1.5 px-1 text-muted-foreground font-medium",children:"Msgs"}),e.jsx("th",{className:"text-right py-1.5 px-1 text-muted-foreground font-medium",children:"Users"}),e.jsx("th",{className:"text-right py-1.5 px-1 text-muted-foreground font-medium",children:"Int."})]})}),e.jsx("tbody",{children:c.topicUserCounts.slice(0,12).map(i=>e.jsxs("tr",{className:"border-b border-border/10",children:[e.jsx("td",{className:"py-1 px-1 text-foreground capitalize",children:i.name}),e.jsx("td",{className:"py-1 px-1 text-right tabular-nums",children:i.prompts}),e.jsx("td",{className:"py-1 px-1 text-right tabular-nums",children:i.uniqueUsers}),e.jsx("td",{className:"py-1 px-1 text-right",children:e.jsxs(ue,{variant:i.promptsPerUser>3?"default":"secondary",className:"text-[8px]",children:[i.promptsPerUser,"x"]})})]},i.name))})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx($,{title:"Topics â Last 7 Days",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Te,{data:c.topTopics7d.slice(0,8).map(i=>({name:i.name,count:i.count})),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"name",fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(200, 80%, 55%)",radius:[4,4,0,0]})]})})}),e.jsx($,{title:"Intent Trends (7d vs Prior 7d)",children:e.jsxs("div",{className:"space-y-1.5 max-h-[250px] overflow-y-auto py-1",children:[c.intentTrends.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-foreground capitalize text-xs",children:i.name.replace(/_/g," ")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-muted-foreground text-xs tabular-nums",children:[i.previous,"â",i.current]}),e.jsxs(ue,{variant:i.change>0?"default":i.change<0?"destructive":"secondary",className:"text-[9px] px-1.5",children:[i.change>0?"+":"",i.change]})]})]},i.name)),c.intentTrends.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Need 14+ days of data"})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx($,{title:"Conversation Depth",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Te,{data:c.conversationDepth,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"range",fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(142, 71%, 45%)",radius:[4,4,0,0],name:"Conversations"})]})})}),e.jsx($,{title:"Prompt Length Breakdown",children:e.jsx(ae,{width:"100%",height:250,children:e.jsxs(Te,{data:c.promptLengthBuckets,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ge,{dataKey:"range",fontSize:9,stroke:"hsl(var(--muted-foreground))"}),e.jsx(xe,{fontSize:10,stroke:"hsl(var(--muted-foreground))"}),e.jsx(te,{contentStyle:se}),e.jsx(je,{dataKey:"count",fill:"hsl(340, 75%, 55%)",radius:[4,4,0,0],name:"Prompts"})]})})})]})]}):e.jsx(e.Fragment,{children:e.jsx(ot,{className:"bg-card/80 border-primary/20",children:e.jsxs(lt,{className:"p-8 text-center space-y-3",children:[e.jsx(_t,{className:"h-10 w-10 text-muted-foreground mx-auto"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"No classifications yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:'Click "Backfill Existing Messages" above to classify all historical messages, or data will populate automatically as users chat.'})]})})})]}),e.jsxs(Y,{value:"feedback",className:"space-y-6",children:[e.jsx(gt,{icon:En,title:"Response Feedback",subtitle:"Thumbs up/down ratings, weak spots and recent flagged responses",onExport:()=>{var w,O,R;const i=new Date,m=ee.feedbackIntelligence,y=(A,M=160)=>(A??"").replace(/\s+/g," ").trim().slice(0,M)+((A??"").length>M?"â¦":""),j=[{title:"Feedback Headline",rows:[["Total Ratings",(m==null?void 0:m.total)??0],["ð Good",(m==null?void 0:m.good)??0],["ð Bad",(m==null?void 0:m.bad)??0],["Good Rate",`${(m==null?void 0:m.goodRate)??0}%`],["Bad Rate",m!=null&&m.total?`${(m.bad/m.total*100).toFixed(1)}%`:"0%"]]},...(((w=m==null?void 0:m.weakSpots)==null?void 0:w.length)??0)>0?[{title:"Weak Spots (most-flagged categories)",headers:["Rank","Category","Bad Ratings"],body:m.weakSpots.slice(0,25).map((A,M)=>[M+1,A.category||"uncategorized",A.count])}]:[],...(((O=m==null?void 0:m.recentBad)==null?void 0:O.length)??0)>0?[{title:"Recent Flagged Responses",headers:["When","Category","User Message","AI Response"],body:m.recentBad.slice(0,40).map(A=>
86[new Date(A.created_at).toLocaleString(),A.category||"â",y(A.userMessage,140),y(A.aiMessage,180)])}]:[],...(((R=m==null?void 0:m.allEntries)==null?void 0:R.length)??0)>0?[{title:`All Feedback Entries (showing ${Math.min(m.allEntries.length,100)} of ${m.allEntries.length})`,headers:["When","Rating","Category","User Message"],body:m.allEntries.slice(0,100).map(A=>[new Date(A.created_at).toLocaleString(),A.rating==="good"?"ð":"ð",A.category||"â",y(A.userMessage,140)])}]:[]];return rt({title:"Response Feedback",subtitleLines:[`${((m==null?void 0:m.total)??0).toLocaleString()} ratings · ${(m==null?void 0:m.goodRate)??0}% positive`],filename:`feedback-${i.toISOString().slice(0,10)}.pdf`,sections:j})}}),e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Gc,{feedback:ee.feedbackIntelligence,allEntries:((Os=ee.feedbackIntelligence)==null?void 0:Os.allEntries)||[]})})]}),e.jsxs(Y,{value:"cancellations",className:"space-y-6",children:[e.jsx(gt,{icon:en,title:"Cancellations",subtitle:"Cancellation events with user context and stated reasons",onExport:()=>{const i=new Date,m=ee.cancellationIntelligence||[],y=(R,A=200)=>(R??"").replace(/\s+/g," ").trim().slice(0,A)+((R??"").length>A?"â¦":""),j={price:0,expensive:0,refund:0,quality:0,accuracy:0,wrong:0,bug:0,broken:0,slow:0,competitor:0,chatgpt:0,grok:0,claude:0,unused:0,"don't use":0,accidental:0};m.forEach(R=>{const A=R.messages.map(M=>M.content).join(" ").toLowerCase();Object.keys(j).forEach(M=>{A.includes(M)&&j[M]++})});const w=Object.entries(j).filter(([,R])=>R>0).sort((R,A)=>A[1]-R[1]).map(([R,A],M)=>[M+1,R,A,m.length>0?`${(A/m.length*100).toFixed(0)}%`:"0%"]),O=[{title:"Cancellations Summary",rows:[["Total Cancellation Events",m.length],["Apple Total Churned",l.churnedApple],["Apple Churn Rate",`${T.appleChurnRate}%`],["Currently Paying (All)",l.paidPro],["Active 30d",l.active30d]]},...w.length?[{title:"Reason Keywords (auto-tagged from cancellation chat)",headers:["Rank","Keyword","Mentions","% of Events"],body:w}]:[],...m.length?[{title:`Cancellation Events (${m.length})`,headers:["When","User Email","Messages","First Message"],body:m.slice(0,100).map(R=>{var A;return[new Date(R.created_at).toLocaleString(),R.user_email||"â",R.messages.length,y(((A=R.messages[0])==null?void 0:A.content)||"",180)]})}]:[]];return m.slice(0,25).forEach((R,A)=>{O.push({title:`#${A+1} · ${R.user_email||R.user_id} · ${new Date(R.created_at).toLocaleString()}`,headers:["When","Type","Message"],body:R.messages.map(M=>[new Date(M.created_at).toLocaleString(),M.message_type||"â",y(M.content,280)])})}),rt({title:"Cancellations",subtitleLines:[`${m.length.toLocaleString()} events · Apple churn ${T.appleChurnRate}%`],filename:`cancellations-${i.toISOString().slice(0,10)}.pdf`,sections:O})}}),e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Wc,{events:ee.cancellationIntelligence||[]})})]}),e.jsx(Y,{value:"livefeed",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Bc,{questions:((Fs=ee.recentQuestions)==null?void 0:Fs.items)||[],totalCount:((zs=ee.recentQuestions)==null?void 0:zs.totalCount)||0,feedback:ee.feedbackIntelligence,onSearchByEmail:Cr,onSearchByKeyword:Tr,onLoadMore:Pr,isSearching:Oa})})}),e.jsx(Y,{value:"api",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Hc,{apiIntelligence:ee.apiIntelligence,onRefresh:()=>At(),refreshing:Z})})}),e.jsx(Y,{value:"trending",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Vc,{})})}),e.jsx(Y,{value:"streaming",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Qc,{})})}),e.jsx(Y,{value:"rabbithole",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Yc,{})})}),e.jsx(Y,{value:"landing",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Zc,{})})}),e.jsx(Y,{value:"audienceprofile",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(hd,{})})}),e.jsx(Y,{value:"traffic",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Jc,{})})}),e.jsx(Y,{value:"data",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(Xc,{})})}),e.jsx(Y,{value:"memory",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(ed,{})})}),e.jsx(Y,{value:"context",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(td,{})})}),e.jsx(Y,{value:"voice",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(ad,{})})}),e.jsx(Y,{value:"whomogged",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(sd,{})})}),e.jsx(Y,{value:"slopornot",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(nd,{})})}),e.jsx(Y,{value:"factcrack",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(id,{})})}),e.jsx(Y,{value:"rabbitrun",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(od,{})})}),e.jsx(Y,{value:"assetsirl",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(ld,{})})}),e.jsx(Y,{value:"intake",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(rd,{})})}),e.jsx(Y,{value:"emailusers",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(cd,{})})}),e.jsx(Y,{value:"recovery",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(ud,{})})}),e.jsx(Y,{value:"protrial",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(dd,{})})}),e.jsx(Y,{value:"bannedisps",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(pd,{})})}),e.jsx(Y,{value:"clienterrors",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(fd,{})})}),e.jsx(Y,{value:"signupaudit",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(xd,{})})}),e.jsx(Y,{value:"moderation",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(md,{})})}),e.jsx(Y,{value:"adminaccess",className:"space-y-6",children:e.jsx(d.Suspense,{fallback:e.jsx(ne,{}),children:e.jsx(gd,{})})})]},N)})]})})]})]})}const ku=Object.freeze(Object.defineProperty({__proto__:null,default:Id},Symbol.toStringTag,{value:"Module"}));
86export{Wt as A,js as B,Ae as C,Zi as I,ve as K,Ye as L,Ha as M,ze as S,$ as a,oe as b,it as c,dc as d,is as e,nn as f,tn as g,rt as h,Ac as i,Nc as j,ku as k,se as t};
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.