PageSourceSearch

https://kleverbet.ai/assets/SuperAdminPage-CNnG_PQy.js

js kleverbet.ai collected 2026-10-05 15:11:31 UTC 1,455,751 bytes, 427 lines download raw bytes

1import{N as ns,am as ul,r as v,j as e,D as Ue,z as Be,A as ze,F as Ke,an as vs,ao as ys,ae as Ns,ap as _s,a1 as ge,s as T,C as G,m as je,n as fe,k as J,aq as gs,a9 as Le,ar as st,as as B,U as oa,M as dt,al as $s,at as Dt,B as R,au as Es,S as oe,b as de,c as ue,d as me,e as V,H as Ws,a0 as Me,a2 as _e,J as K,G as Vs,av as ke,l as ne,aw as Ks,ax as rt,ay as Ur,az as Ii,f as St,T as Xs,aA as lt,aB as ut,h as no,aC as _t,a7 as Kn,aD as ws,aE as Ss,aF as ks,aG as Cs,aH as Ps,aI as Fs,aJ as Ts,aK as Ls,aL as cs,aM as Ct,a4 as hs,aN as qt,aO as Is,aP as Ri,a6 as ls,ak as La,V as ta,aQ as qi,aR as lo,aS as $a,aT as Ea,aU as Vn,aV as wr,aW as Br,aX as io,aY as co,aZ as $i,a_ as Hn,a$ as fr,b0 as bt,b1 as oo,b2 as sa,b3 as uo,b4 as dn,b5 as mo,b6 as mr,b7 as ka,b8 as xo,b9 as ft,ba as xr,bb as it,aj as Sr,bc as ho,bd as zr,be as Kr,bf as Vr,bg as ht,I as pe,K as rs,w as xs,p as js,q as fs,t as Ne,v as we,y as As,L as Q,X as He,a5 as Js,x as Ds,bh as Wn,bi as ml,bj as Da,o as De,aa as zt,ab as Us,ac as Bs,ad as zs,bk as da,bl as tt,bm as Gn,bn as ss,bo as ts,bp as vr,E as us,bq as kt,br as qn,bs as Pt,bt as Oa,bu as po,W as $n,bv as It,bw as ua,bx as ma,by as xa,$ as xt,bz as ha,bA as go,bB as jo,bC as Hr,bD as Ms,bE as Ua,bF as ra,bG as fo,P as Ee,bH as pa,bI as aa,bJ as Ba,bK as za,bL as Ka,bM as Va,bN as Qn,bO as yr,_ as mt,a3 as Nr,bP as xl,bQ as Oi,bR as vo,bS as an,Y as na,bT as yo,bU as un,bV as mn,bW as xn,bX as No,bY as hl,bZ as _o,a as bo,b_ as wo,b$ as So,c0 as ko,c1 as Co,c2 as ms,c3 as Po,c4 as Fo,c5 as rn,c6 as Ui,c7 as Ao}from"./index-RlfPafXb.js";import{S as is}from"./separator-X1rkI55I.js";import{g as pl}from"./usStates-BHRD-4i6.js";import{T as os}from"./trash-2-BpT-O6u3.js";import{V as kr}from"./video-DsPMyOVq.js";import{B as Fa,C as To,P as Bi,a as zi,b as Lo,A as Jt,c as Eo,U as Do,L as Mo,T as Io}from"./TradingRndPanel-puV7WaXR.js";import{E as Ma}from"./external-link-Bl-EHl4Q.js";import{B as Ro,u as qo,a as $o,b as Oo,T as Uo,c as Bo,d as zo,e as Ko,M as Ki,f as Vo,g as Ho,h as Wo,i as Go,j as Qo,k as Yo,l as Jo,m as Zo}from"./useLiveSupportEvents-C-V63ufD.js";import{C as Vi}from"./clipboard-list-2nmlw1NG.js";import{R as Hi,X as Wi,T as Gi,C as Xo,Y as ed,L as sd,B as hn}from"./generateCategoricalChart-Q0TQI5_p.js";import{A as td,a as ad}from"./AreaChart-C609C54y.js";import{S as rd,a as nd,b as ld,c as id,d as cd,u as od,e as dd}from"./useKommunityCategories-Nnu73kZl.js";import{G as Yn}from"./VenueName-BUQ_Llfd.js";import{P as Zs}from"./plus-DRvaSj9M.js";import{W as ga,C as Qi,H as Yi,U as ud,P as md,D as xd,a as Ji,b as hd,B as pd,S as gd,c as jd,d as fd,e as vd,f as gl,g as yd,h as Nd}from"./command-BMdATKPX.js";import{D as Gt}from"./download-C32jNHqB.js";import{P as va}from"./pencil-DZTZJEBh.js";import{T as Re,a as qe,b as he,c as U,d as $e,e as M}from"./table-B5Czgr_G.js";import{S as Ge}from"./switch-DcBrwkLI.js";import{a as _d,C as bd,U as Wr}from"./user-plus-8W40NfOB.js";import{P as Jn}from"./percent-ChfCyDU2.js";import{S as Zn}from"./shield-check-BvbUujBE.js";import{I as Ys}from"./info-CdSA8qpO.js";import{P as Rt}from"./play-DUI8maFc.js";import{E as Ht}from"./eye-off-D72gIhsL.js";import{S as ya}from"./settings-Bb9igy-R.js";import{C as Ha}from"./cpu-G_lC7g6G.js";import{F as Zi}from"./flag-DOEOgwoH.js";import{I as Ot}from"./image-BRwAI76J.js";import{A as Mt}from"./award-Dza6MG98.js";import{U as Ia,D as wd,u as Sd}from"./UserTierBadge-BBU5-aax.js";import{M as kd}from"./map-pin-DNn_52e_.js";import{P as Cd}from"./phone-C-SJxl4l.js";import{S as Rs}from"./search-9dbwn2sC.js";import{R as Ut,a as nt}from"./radio-group-B6fYPlOd.js";import{C as vt}from"./copy-CadKg1Nl.js";import{L as nn,P as Zt,u as Xi,i as ec,a as sc,b as tc,B as ac,I as rc,H as Pd,c as nc,d as Xn,E as lc,e as Fd,v as Ad}from"./InsertImageDialog-Cnb9MHYQ.js";import{S as Wt}from"./star-Ledyk4aM.js";import{G as ja}from"./gift-CMDM5emF.js";import{P as Td}from"./package-BC1DDQEB.js";import{C as Ld}from"./coins-3tI20TQj.js";import{S as Bt}from"./square-pen-D73XevSi.js";import{o as el,s as ot,n as Rr,a as Ed,b as hr,e as Gr,u as Wa,t as Ga,z as Te}from"./index-Bk8EUoL5.js";import{U as fa,u as sl}from"./index-B5wqGV1v.js";import{F as Cr,a as Ye,b as Je,c as Ze,d as er,e as Xe,f as es}from"./form-A0WAG1fG.js";import{S as Dd}from"./types-BhtqzfOk.js";import{P as Md}from"./PostContent-D63UMnYD.js";import{B as ic}from"./book-open-BBXyG-JR.js";import{p as jt}from"./parseISO-BkhuY4Gh.js";import{S as Id}from"./sliders-horizontal-DozHeKFY.js";import{L as tl,a as Rd}from"./list-checks-MY4XyDIh.js";import{S as jl}from"./slider-BkOABbdd.js";import{g as qd}from"./sportCodeMapping-CD37tffF.js";import{f as al}from"./timeUtils-D2yY3Ym7.js";import{F as Qa}from"./index-DjxUGDUz.js";import{S as $d,A as Od,T as Ud}from"./timer-BP1WaAL3.js";import{S as Bd}from"./snowflake-ClyTA6EQ.js";import{u as zd,a as Kd,b as Vd}from"./useGamePacePatterns-DYeQ25n9.js";import{g as Qr}from"./periodLabels-BKrmzIqD.js";import{P as cc}from"./pen-yHn44Vx1.js";import{N as oc}from"./newspaper-BQqY0iGk.js";import{u as Hd}from"./use-mobile-PLXtAV0d.js";import{S as Wd}from"./share-2-Bxi2Bxtp.js";import{C as Gd}from"./cloud-D3DJGyRh.js";import{g as Qd}from"./sportUtils-BUh_lJv2.js";import"./arrow-up-CGns11YL.js";import"./strategyRegistry-DYcBfYet.js";import"./VolatilityEvScopeChips-CvHwMgDS.js";import"./useInfiniteQuery-DiiB9X4t.js";import"./useSubscribedSports-FZSkR8m5.js";import"./teamAbbreviations-DiMHKL8s.js";import"./PlayerStatsTab-DbR8T3NG.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const Nt=ns("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const Yd=ns("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}
11],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
12 * @license lucide-react v0.462.0 - ISC
13 *
14 * This source code is licensed under the ISC license.
15 * See the LICENSE file in the root directory of this source tree.
16 */const Jd=ns("CheckCheck",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);/**
17 * @license lucide-react v0.462.0 - ISC
18 *
19 * This source code is licensed under the ISC license.
20 * See the LICENSE file in the root directory of this source tree.
21 */const dc=ns("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
22 * @license lucide-react v0.462.0 - ISC
23 *
24 * This source code is licensed under the ISC license.
25 * See the LICENSE file in the root directory of this source tree.
26 */const pn=ns("CloudSun",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z",key:"s09mg5"}]]);/**
27 * @license lucide-react v0.462.0 - ISC
28 *
29 * This source code is licensed under the ISC license.
30 * See the LICENSE file in the root directory of this source tree.
31 */const Zd=ns("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
32 * @license lucide-react v0.462.0 - ISC
33 *
34 * This source code is licensed under the ISC license.
35 * See the LICENSE file in the root directory of this source tree.
36 */const Yr=ns("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
37 * @license lucide-react v0.462.0 - ISC
38 *
39 * This source code is licensed under the ISC license.
40 * See the LICENSE file in the root directory of this source tree.
41 */const Xd=ns("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/**
42 * @license lucide-react v0.462.0 - ISC
43 *
44 * This source code is licensed under the ISC license.
45 * See the LICENSE file in the root directory of this source tree.
46 */const eu=ns("FileX",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m14.5 12.5-5 5",key:"b62r18"}],["path",{d:"m9.5 12.5 5 5",key:"1rk7el"}]]);/**
47 * @license lucide-react v0.462.0 - ISC
48 *
49 * This source code is licensed under the ISC license.
50 * See the LICENSE file in the root directory of this source tree.
51 */const fl=ns("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
52 * @license lucide-react v0.462.0 - ISC
53 *
54 * This source code is licensed under the ISC license.
55 * See the LICENSE file in the root directory of this source tree.
56 */const uc=ns("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/**
57 * @license lucide-react v0.462.0 - ISC
58 *
59 * This source code is licensed under the ISC license.
60 * See the LICENSE file in the root directory of this source tree.
61 */const vl=ns("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]]);/**
62 * @license lucide-react v0.462.0 - ISC
63 *
64 * This source code is licensed under the ISC license.
65 * See the LICENSE file in the root directory of this source tree.
66 */const su=ns("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}
66]]);/**
67 * @license lucide-react v0.462.0 - ISC
68 *
69 * This source code is licensed under the ISC license.
70 * See the LICENSE file in the root directory of this source tree.
71 */const tu=ns("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"}]]);/**
72 * @license lucide-react v0.462.0 - ISC
73 *
74 * This source code is licensed under the ISC license.
75 * See the LICENSE file in the root directory of this source tree.
76 */const au=ns("Gavel",[["path",{d:"m14.5 12.5-8 8a2.119 2.119 0 1 1-3-3l8-8",key:"15492f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m9 7 8 8",key:"5jnvq1"}],["path",{d:"m21 11-8-8",key:"z4y7zo"}]]);/**
77 * @license lucide-react v0.462.0 - ISC
78 *
79 * This source code is licensed under the ISC license.
80 * See the LICENSE file in the root directory of this source tree.
81 */const mc=ns("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
82 * @license lucide-react v0.462.0 - ISC
83 *
84 * This source code is licensed under the ISC license.
85 * See the LICENSE file in the root directory of this source tree.
86 */const ru=ns("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/**
87 * @license lucide-react v0.462.0 - ISC
88 *
89 * This source code is licensed under the ISC license.
90 * See the LICENSE file in the root directory of this source tree.
91 */const nu=ns("Heading3",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2",key:"68ncm8"}],["path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2",key:"1ejuhz"}]]);/**
92 * @license lucide-react v0.462.0 - ISC
93 *
94 * This source code is licensed under the ISC license.
95 * See the LICENSE file in the root directory of this source tree.
96 */const lu=ns("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/**
97 * @license lucide-react v0.462.0 - ISC
98 *
99 * This source code is licensed under the ISC license.
100 * See the LICENSE file in the root directory of this source tree.
101 */const iu=ns("HeartHandshake",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M12 5 9.04 7.96a2.17 2.17 0 0 0 0 3.08c.82.82 2.13.85 3 .07l2.07-1.9a2.82 2.82 0 0 1 3.79 0l2.96 2.66",key:"4oyue0"}],["path",{d:"m18 15-2-2",key:"60u0ii"}],["path",{d:"m15 18-2-2",key:"6p76be"}]]);/**
102 * @license lucide-react v0.462.0 - ISC
103 *
104 * This source code is licensed under the ISC license.
105 * See the LICENSE file in the root directory of this source tree.
106 */const cu=ns("Hourglass",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]]);/**
107 * @license lucide-react v0.462.0 - ISC
108 *
109 * This source code is licensed under the ISC license.
110 * See the LICENSE file in the root directory of this source tree.
111 */const ou=ns("ImageOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);/**
112 * @license lucide-react v0.462.0 - ISC
113 *
114 * This source code is licensed under the ISC license.
115 * See the LICENSE file in the root directory of this source tree.
116 */const du=ns("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/**
117 * @license lucide-react v0.462.0 - ISC
118 *
119 * This source code is licensed under the ISC license.
120 * See the LICENSE file in the root directory of this source tree.
121 */const Jr=ns("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/**
122 * @license lucide-react v0.462.0 - ISC
123 *
124 * This source code is licensed under the ISC license.
125 * See the LICENSE file in the root directory of this source tree.
126 */const uu=ns("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/**
127 * @license lucide-react v0.462.0 - ISC
128 *
129 * This source code is licensed under the ISC license.
130 * See the LICENSE file in the root directory of this source tree.
131 */const Zr=ns("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/**
132 * @license lucide-react v0.462.0 - ISC
133 *
134 * This source code is licensed under the ISC license.
135 * See the LICENSE file in the root directory of this source tree.
136 */const Ra=ns("ListPlus",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]);/**
137 * @license lucide-react v0.462.0 - ISC
138 *
139 * This source code is licensed under the ISC license.
140 * See the LICENSE file in the root directory of this source tree.
141 */const qr=ns("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/**
142 * @license lucide-react v0.462.0 - ISC
143 *
144 * This source code is licensed under the ISC license.
145 * See the LICENSE file in the root directory of this source tree.
146 */const _r=ns("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/**
147 * @license lucide-react v0.462.0 - ISC
148 *
149 * This source code is licensed under the ISC license.
150 * See the LICENSE file in the root directory of this source tree.
151 */const Xr=ns("MousePointerClick",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z",key:"s0h3yz"}]]);/**
152 * @license lucide-react v0.462.0 - ISC
153 *
154 * This source code is licensed under the ISC license.
155 * See the LICENSE file in the root directory of this source tree.
156 */const mu=ns("Quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);/**
157 * @license lucide-react v0.462.0 - ISC
158 *
159 * This source code is licensed under the ISC license.
160 * See the LICENSE file in the root directory of this source tree.
161 */const xc=ns("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]);/**
162 * @license lucide-react v0.462.0 - ISC
163 *
164 * This source code is licensed under the ISC license.
165 * See the LICENSE file in the root directory of this source tree.
166 */const pr=ns("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/**
167 * @license lucide-react v0.462.0 - ISC
168 *
169 * This source code is licensed under the ISC license.
170 * See the LICENSE file in the root directory of this source tree.
171 */const xu=ns("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/**
172 * @license lucide-react v0.462.0 - ISC
173 *
174 * This source code is licensed under the ISC license.
175 * See the LICENSE file in the root directory of this source tree.
176 */const hu=ns("ScrollText",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/**
177 * @license lucide-react v0.462.0 - ISC
178 *
179 * This source code is licensed under the ISC license.
180 * See the LICENSE file in the root directory of this source tree.
181 */const pu=ns("SkipForward",[["polygon",{points:"5 4 15 12 5 20 5 4",key:"16p6eg"}],["line",{x1:"19",x2:"19",y1:"5",y2:"19",key:"futhcm"}]]);/**
182 * @license lucide-react v0.462.0 - ISC
183 *
184 * This source code is licensed under the ISC license.
185 * See the LICENSE file in the root directory of this source tree.
186 */const hc=ns("SlidersVertical",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/**
187 * @license lucide-react v0.462.0 - ISC
188 *
189 * This source code is licensed under the ISC license.
190 * See the LICENSE file in the root directory of this source tree.
191 */const gu=ns("Stethoscope",[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]]);/**
192 * @license lucide-react v0.462.0 - ISC
193 *
194 * This source code is licensed under the ISC license.
195 * See the LICENSE file in the root directory of this source tree.
196 */const ju=ns("Strikethrough",[["path",{d:"M16 4H9a3 3 0 0 0-2.83 4",key:"43sutm"}],["path",{d:"M14 12a4 4 0 0 1 0 8H6",key:"nlfj13"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
197 * @license lucide-react v0.462.0 - ISC
198 *
199 * This source code is licensed under the ISC license.
200 * See the LICENSE file in the root directory of this source tree.
201 */const fu=ns("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
202 * @license lucide-react v0.462.0 - ISC
203 *
204 * This source code is licensed under the ISC license.
205 * See the LICENSE file in the root directory of this source tree.
206 */const yl=ns("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
207 * @license lucide-react v0.462.0 - ISC
208 *
209 * This source code is licensed under the ISC license.
210 * See the LICENSE file in the root directory of this source tree.
211 */const pc=ns("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]);/**
212 * @license lucide-react v0.462.0 - ISC
213 *
214 * This source code is licensed under the ISC license.
215 * See the LICENSE file in the root directory of this source tree.
216 */const On=ns("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/**
217 * @license lucide-react v0.462.0 - ISC
218 *
219 * This source code is licensed under the ISC license.
220 * See the LICENSE file in the root directory of this source tree.
221 */const vu=ns("UserMinus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/**
222 * @license lucide-react v0.462.0 - ISC
223 *
224 * This source code is licensed under the ISC license.
225 * See the LICENSE file in the root directory of this source tree.
226 */const yu=ns("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);function Nu(s,a){return+ul(s)==+ul(a)}const _u={too_expensive:"bg-red-500",not_winning:"bg-yellow-500",hard_to_use:"bg-orange-500",not_using:"bg-blue-500",missing_features:"bg-purple-500",switching_service:"bg-pink-500",payment_failed:"bg-rose-600",other:"bg-gray-500"},bu={scheduled_cancellation:"bg-slate-400",unknown:"bg-gray-400"},Nl=["duplicate_cleanup","superseded_by_stripe_sync","replaced_by_extended_trial","upgrading","downgrading"],_l={..._u,...bu},wu={too_expensive:"Too Expensive",not_winning:"Not Winning Enough",hard_to_use:"Hard to Use",not_using:"Not Using It",missing_features:"Missing Features",switching_service:"Switching Service",payment_failed:"Payment Failed",other:"Other",scheduled_cancellation:"Scheduled Cancellation",unknown:"Unknown"},Su=["too_expensive","not_winning","hard_to_use","not_using","missing_features","switching_service","payment_failed","other"];function ku({open:s,onOpenChange:a,data:t,total:n}){const[r,i]=v.useState(!1),l=t.filter(u=>u.isUserReason),m=t.filter(u=>!u.isUserReason),o=l.reduce((u,x)=>u+x.count,0),h=m.reduce((u,x)=>u+x.count,0),N=Math.max(...l.map(u=>u.count),1),d=Math.max(...m.map(u=>u.count),1),y=(u,x,g=!1)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:`font-medium ${g?"text-muted-foreground":""}`,children:u.label}),e.jsxs("span",{className:"text-muted-foreground",children:[u.count," (",u.percentage.toFixed(1),"%)"]})]}),e.jsx("div",{className:"h-2 w-full bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${_l[u.reason]||_l.unknown} transition-all ${g?"opacity-60":""}`,style:{width:`${u.count/x*100}%`}})})]},u.reason);return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"sm:max-w-md max-h-[80vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Churn Breakdown by Reason"})}),e.jsx("div",{className:"space-y-4 py-4",children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"No churn data available"}):e.jsxs(e.Fragment,{children:[l.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-sm font-semibold text-foreground",children:["User Feedback (",o,")"]}),l.map(u=>y(u,N))]}),m.length>0&&e.jsxs(vs,{open:r,onOpenChange:i,className:"pt-2",children:[e.jsxs(ys,{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ns,{className:`h-4 w-4 transition-transform ${r?"rotate-180":""}`}),"System Reasons (",h,")"]}),e.jsx(_s,{className:"space-y-3 pt-3",children:m.map(u=>y(u,d,!0))})]}),e.jsxs("div",{className:"pt-4 border-t space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"User Churn"}),e.jsx("span",{className:"font-medium",children:o})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm font-semibold",children:[e.jsx("span",{children:"Total"}),e.jsx("span",{children:n})]})]})]})})]})})}const gn=["459783a0-6c2b-406a-9d04-4110c57e798e","675a95d1-5303-422f-ad7a-c5e12415bc86"];function Cu(){const{data:s,isLoading:a}=ge({queryKey:["dashboard-stats"],queryFn:async()=>{const{data:j}=await T.from("user_profiles").select("id").not("deleted_at","is",null),c=(j==null?void 0:j.map(Ve=>Ve.id))||[],p=[...gn,...c],{count:w}=await T.from("user_profiles").select("*",{count:"exact",head:!0}).is("deleted_at",null),{data:S}=await T.from("user_subscriptions").select("user_id").or("status.in.(active,trial,paused,past_due),paused_at.not.is.null"),P=new Set((S==null?void 0:S.map(Ve=>Ve.user_id))||[]),C=(w||0)-P.size,{count:O}=await T.from("user_subscriptions").select("*",{count:"exact",head:!0}).eq("status","trial").is("paused_at",null),{count:$}=await T.from("user_subscriptions").select("*",{count:"exact",head:!0}).eq("status","active"),{count:z}=await T.from("user_subscriptions").select("*",{count:"exact",head:!0}).eq("status","cancelled"),{count:D}=await T.from("user_subscriptions").select("*",{count:"exact",head:!0}).or("status.eq.paused,paused_at.not.is.null"),{count:A}=await T.from("user_subscriptions").select("*",{count:"exact",head:!0}).eq("status","past_due"),{count:F}=await T.from("user_subscriptions").select("*",{count:"exact",head:!0}).not("user_id","in",`(${p.join(",")})`),{data:q}=await T.from("user_subscriptions").select("cancel_reason").not("user_id","in",`(${p.join(",")})`).or("status.eq.cancelled,cancel_reason.not.is.null"),E=(q==null?void 0:q.filter(Ve=>!Nl.includes(Ve.cancel_reason||"")).length)||0,L=F&&F>0?(E||0)/F*100:0,{data:H}=await T.from("user_subscriptions").select("start_date, end_date, price_at_subscription, subscription_packages!package_id(price)").not("user_id","in",`(${p.join(",")})`);let Z=0,se=0;H==null||H.forEach(Ve=>{var Oe;const as=Ve.price_at_subscription||((Oe=Ve.subscription_packages)==null?void 0:Oe.price)||0;if(as>0&&Ve.start_date){const Ie=new Date(Ve.start_date),ds=Ve.end_date?new Date(Ve.end_date):new Date,be=Math.max(1,Math.ceil((ds.getTime()-Ie.getTime())/(1e3*60*60*24*30)));Z+=as*be,se++}});const ie=se>0?Z/se:0,{data:Y}=await T.from("user_subscriptions").select("package_id, subscription_packages!package_id(price)").not("user_id","in",`(${p.join(",")})`).or("status.eq.active,and(status.eq.trial,cancel_reason.is.null)"),I=(Y==null?void 0:Y.reduce((Ve,as)=>{var Oe;return Ve+(((Oe=as.subscription_packages)==null?void 0:Oe.price)||0)},0))||0,{data:ee}=await T.from("user_subscriptions").select("package_id, subscription_packages!package_id(price)").not("user_id","in",`(${p.join(",")})`).eq("status","active"),le=(ee==null?void 0:ee.reduce((Ve,as)=>{var Oe;return Ve+(((Oe=as.subscription_packages)==null?void 0:Oe.price)||0)},0))||0,ve=new Date;ve.setDate(ve.getDate()-30);const te=new Date;te.setDate(te.getDate()-60);const{count:X}=await T.from("user_profiles").select("*",{count:"exact",head:!0}).gte("created_at",ve.toISOString()),{count:ae}=await T.from("user_profiles").select("*",{count:"exact",head:!0}).gte("created_at",te.toISOString()).lt("created_at",ve.toISOString()),W=ae&&ae>0?((X||0)-ae)/ae*100:(X||0)>0?100:0,{count:re}=await T.from("user_subscriptions").select("*",{count:"exact",head:!0}).eq("status","active").lt("created_at",ve.toISOString()),ce=re&&re>0?(($||0)-re)/re*100:($||0)>0?100:0,{data:Pe}=await T.from("user_subscriptions").select("package_id, subscription_packages!package_id(price)").not("user_id","in",`(${gn.join(",")})`).eq("status","active").lt("created_at",ve.toISOString()),Fe=(Pe==null?void 0:Pe.reduce((Ve,as)=>{var Oe;return Ve+(((Oe=as.subscription_packages)==null?void 0:Oe.price)||0)},0))||0,Ae=Fe>0?(le-Fe)/Fe*100:le>0?100:0;return{totalUsers:w||0,freeUsers:Math.max(0,C),trialUsers:O||0,cancelledSubscriptions:z||0,pausedSubscriptions:D||0,pastDueSubscriptions:A||0,churnRate:Math.round(L*10)/10,avgLtv:Math.round(ie*100)/100,activeSubscriptions:$||0,potentialRevenue:I,currentRevenue:le,userGrowth:Math.round(W),subscriptionGrowth:Math.round(ce),revenueGrowth:Math.round(Ae)}},refetchInterval:3e4}),{data:t,isLoading:n}=ge({queryKey:["dashboard-churn-breakdown"],queryFn:async()=>{const{data:j}=await T.from("user_profiles").select("id").not("deleted_at","is",null),c=(j==null?void 0:j.map($=>
226$.id))||[],p=[...gn,...c],{data:w}=await T.from("user_subscriptions").select("cancel_reason").not("user_id","in",`(${p.join(",")})`).or("status.eq.cancelled,cancel_reason.not.is.null"),S=(w==null?void 0:w.filter($=>!Nl.includes($.cancel_reason||"")))||[];if(S.length===0)return{data:[],total:0};const P={};S.forEach($=>{const z=$.cancel_reason||"unknown";P[z]=(P[z]||0)+1});const C=S.length;return{data:Object.entries(P).map(([$,z])=>({reason:$,label:wu[$]||$,count:z,percentage:z/C*100,isUserReason:Su.includes($)})).sort(($,z)=>$.isUserReason!==z.isUserReason?$.isUserReason?-1:1:z.count-$.count),total:C}},refetchInterval:3e4}),{data:r,isLoading:i}=ge({queryKey:["dashboard-trial-breakdown"],queryFn:async()=>{const{data:j}=await T.from("user_subscriptions").select("package_id, cancel_reason, subscription_packages!package_id(name)").eq("status","trial").is("paused_at",null);if(!j||j.length===0)return{data:[],total:0,scheduledToCancelCount:0};const c={};let p=0;j.forEach(P=>{var $;const C=P.package_id||"unknown",O=(($=P.subscription_packages)==null?void 0:$.name)||"Unknown Package";c[C]||(c[C]={name:O,count:0}),c[C].count++,P.cancel_reason&&p++});const w=j.length;return{data:Object.entries(c).map(([P,{name:C,count:O}])=>({packageId:P,packageName:C,count:O,percentage:O/w*100})).sort((P,C)=>C.count-P.count),total:w,scheduledToCancelCount:p}},refetchInterval:3e4}),{data:l,isLoading:m}=ge({queryKey:["dashboard-active-breakdown"],queryFn:async()=>{const{data:j}=await T.from("user_subscriptions").select("package_id, subscription_packages!package_id(name)").eq("status","active");if(!j||j.length===0)return{data:[],total:0};const c={};j.forEach(S=>{var O;const P=S.package_id||"unknown",C=((O=S.subscription_packages)==null?void 0:O.name)||"Unknown Package";c[P]||(c[P]={name:C,count:0}),c[P].count++});const p=j.length;return{data:Object.entries(c).map(([S,{name:P,count:C}])=>({packageId:S,packageName:P,count:C,percentage:C/p*100})).sort((S,P)=>P.count-S.count),total:p}},refetchInterval:3e4}),{data:o,isLoading:h}=ge({queryKey:["dashboard-contact-submissions"],queryFn:async()=>{const{data:j}=await T.from("contact_submissions").select("id, name, email, category, message, status, created_at, user_id").order("created_at",{ascending:!1}).limit(10);return j||[]},refetchInterval:3e4}),{data:N,isLoading:d}=ge({queryKey:["sport-statuses"],queryFn:async()=>{const{data:j}=await T.from("sport_statuses").select("*").order("sport_name");return j||[]},refetchInterval:6e4}),{data:y,isLoading:u}=ge({queryKey:["dashboard-support-activity"],queryFn:async()=>{const{data:j}=await T.from("support_tickets").select("id, subject, category, status, created_at, user_id, user_profiles(display_name, username, full_name)").order("created_at",{ascending:!1}).limit(10),{data:c}=await T.from("support_ticket_comments").select("id, ticket_id, message, created_at, user_id, user_profiles(display_name, username, full_name), support_tickets(subject)").eq("is_admin_reply",!1).order("created_at",{ascending:!1}).limit(10),p=(j||[]).map(S=>{var P,C,O;return{id:S.id,type:"ticket",title:S.subject,subtitle:`New ticket - ${S.category}`,status:S.status,created_at:S.created_at,ticket_id:S.id,user_name:((P=S.user_profiles)==null?void 0:P.display_name)||((C=S.user_profiles)==null?void 0:C.username)||((O=S.user_profiles)==null?void 0:O.full_name)||"Unknown User"}}),w=(c||[]).map(S=>{var P,C,O,$,z,D;return{id:S.id,type:"ticket_reply",title:((P=S.support_tickets)==null?void 0:P.subject)||"Ticket Reply",subtitle:((C=S.message)==null?void 0:C.substring(0,60))+(((O=S.message)==null?void 0:O.length)>60?"...":""),status:"new_reply",created_at:S.created_at,ticket_id:S.ticket_id,user_name:(($=S.user_profiles)==null?void 0:$.display_name)||((z=S.user_profiles)==null?void 0:z.username)||((D=S.user_profiles)==null?void 0:D.full_name)||"Unknown User"}});return[...p,...w].sort((S,P)=>new Date(P.created_at).getTime()-new Date(S.created_at).getTime()).slice(0,10)},refetchInterval:3e4}),{data:x,isLoading:g}=ge({queryKey:["dashboard-feedback-submissions"],queryFn:async()=>{const{data:j}=await T.from("feedback_submissions").select("id, email, suggested_price_per_sport, overall_experience, likelihood_to_recommend, selected_sport, status, created_at").order("created_at",{ascending:!1}).limit(10);return j||[]},refetchInterval:3e4}),{data:f,isLoading:_}=ge({queryKey:["dashboard-feedback-bookings"],queryFn:async()=>{const{data:j}=await T.from("feedback_call_bookings").select("id, email, name, booking_date, booking_time, selected_sport, status, reward_claimed, created_at").order("created_at",{ascending:!1}).limit(10);return j||[]},refetchInterval:3e4}),{data:k,isLoading:b}=ge({queryKey:["dashboard-social-activity"],queryFn:async()=>{const{data:j}=await T.from("social_webhook_events").select("id, event_type, platform, payload, created_at").in("event_type",["message.received","comment.received"]).eq("processed",!1).order("created_at",{ascending:!1}).limit(10);return(j||[]).map(c=>{var F,q;const p=c.payload||{},w=p.normalized||{},S=p.comment||{},P=p.message||{},C=p.data||{},O=w.author||S.author||P.sender||p.sender||C.sender||C.author||{},$=O.name||O.username||"Unknown",z=w.text||S.text||P.text||C.text||p.text||"",D=z.length>60?z.substring(0,60)+"...":z,A=w.kind||(c.event_type==="comment.received"?"comment":"message");return{id:c.id,event_type:c.event_type,platform:c.platform,sender_name:$,message_preview:D||"(no text)",created_at:c.created_at,kind:A,text:z,external_id:w.external_id||S.id||P.id||C.id||null,account_id:w.account_id||((F=p==null?void 0:p.account)==null?void 0:F._id)||((q=p==null?void 0:p.account)==null?void 0:q.id)||C.accountId||null,parent_post_id:w.parent_post_id||S.platformPostId||S.postId||null,conversation_id:w.conversation_id||P.conversationId||C.conversationId||p.
226conversationId||null,author:{id:O.id||null,name:O.name||null,username:O.username||null,avatar_url:O.avatarUrl||O.avatar_url||O.profilePictureUrl||null}}})},refetchInterval:3e4});return{stats:s,activity:o,sportStatuses:N,supportActivity:y||[],feedbackSubmissions:x||[],feedbackBookings:f||[],socialActivity:k||[],churnBreakdown:(t==null?void 0:t.data)||[],churnTotal:(t==null?void 0:t.total)||0,trialBreakdown:(r==null?void 0:r.data)||[],trialTotal:(r==null?void 0:r.total)||0,trialScheduledToCancelCount:(r==null?void 0:r.scheduledToCancelCount)||0,activeBreakdown:(l==null?void 0:l.data)||[],activeTotal:(l==null?void 0:l.total)||0,isLoading:a||h||d||u||g||_||b}}function $t({title:s,value:a,secondaryValue:t,secondaryLabel:n,change:r,icon:i,isLoading:l,onClick:m,clickLabel:o}){return l?e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(fe,{className:"text-sm font-medium",children:s}),e.jsx(i,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(J,{children:[e.jsx(gs,{className:"h-8 w-24 mb-1"}),e.jsx(gs,{className:"h-4 w-32"})]})]}):e.jsxs(G,{className:Le(m&&"cursor-pointer transition-all hover:border-primary/50 hover:shadow-md"),onClick:m,children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(fe,{className:"text-sm font-medium",children:s}),e.jsx(i,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(J,{children:[e.jsx("div",{className:"text-2xl font-bold",children:a}),t&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n&&e.jsxs("span",{children:[n,": "]}),e.jsx("span",{className:"font-medium",children:t})]}),r!==void 0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsxs("span",{className:r>=0?"text-green-600":"text-red-600",children:[r>=0?"+":"",r,"%"]})," ","from last month"]}),m&&o&&e.jsxs("p",{className:"text-xs text-primary mt-1 flex items-center gap-1",children:[o,e.jsx(st,{className:"h-3 w-3"})]})]})]})}function Pu({submission:s,open:a,onOpenChange:t,onStatusChange:n,onDelete:r}){const{toast:i}=Ws(),[l,m]=v.useState(!1);if(!s)return null;const o=u=>{switch(u){case"pending":return"destructive";case"reviewed":return"secondary";case"resolved":return"default";default:return"outline"}},h=s.category==="Profile Change Request";let N=null;if(h)try{N=JSON.parse(s.message)}catch{N=null}const d=u=>new Date(u+"T00:00:00").toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"}),y=async()=>{if(N){m(!0);try{const{error:u}=await T.functions.invoke("apply-profile-change",{body:{userId:N.userId,stateCode:N.newState,dateOfBirth:N.newDOB}});if(u)throw u;n(s.id,"resolved"),i({title:"Changes applied",description:"User profile has been updated successfully"}),t(!1)}catch(u){console.error("Error applying changes:",u),i({title:"Error",description:u.message||"Failed to apply changes",variant:"destructive"})}finally{m(!1)}}};return e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2",children:[h?"Profile Change Request":"Contact Submission",e.jsx(B,{variant:o(s.status),children:s.status})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("a",{href:`mailto:${s.email}`,className:"text-primary hover:underline",children:s.email})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fu,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(B,{variant:"outline",children:s.category})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx($s,{className:"h-4 w-4"}),Dt(new Date(s.created_at),{addSuffix:!0})]})]}),e.jsx(is,{}),h&&N?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Requested Changes"}),e.jsxs("div",{className:"bg-muted/50 p-4 rounded-md space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Current State:"}),e.jsx("p",{className:"font-medium",children:pl(N.currentState)||N.currentState})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"New State:"}),e.jsx("p",{className:"font-medium",children:N.newState?pl(N.newState)||N.newState:e.jsx("span",{className:"text-muted-foreground italic",children:"No change"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Current Birthdate:"}),e.jsx("p",{className:"font-medium",children:d(N.currentDOB)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"New Birthdate:"}),e.jsx("p",{className:"font-medium",children:N.newDOB?d(N.newDOB):e.jsx("span",{className:"text-muted-foreground italic",children:"No change"})})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Reason:"}),e.jsx("p",{className:"mt-1",children:N.reason})]})]}),s.status!=="resolved"&&e.jsxs(R,{onClick:y,disabled:l,className:"w-full",children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),l?"Applying...":"Apply Changes & Resolve"]})]}):e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Message"}),e.jsx("div",{className:"bg-muted/50 p-4 rounded-md",children:e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:s.message})})]}),e.jsx(is,{}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Status:"}),e.jsxs(oe,{value:s.status,onValueChange:u=>{n(s.id,u),t(!1)},children:[e.jsx(de,{className:"w-[150px]",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"pending",children:"Pending"}),e.jsx(V,{value:"reviewed",children:"Reviewed"}),e.jsx(V,{value:"resolved",children:"Resolved"})]})]})]}),e.jsxs(R,{variant:"destructive",size:"sm",onClick:()=>{r(s.id),t(!1)},children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})}function Fu({booking:s,open:a,onOpenChange:t,onDelete:n}){const r=Me(),[i,l]=v.useState(!1),m=_e({mutationFn:async({id:g,status:f})=>{const{error:_}=await T.from("feedback_call_bookings").update({status:f,updated_at:new Date().toISOString()}).eq("id",g);if(_)throw _},onSuccess:(g,{status:f})=>{r.invalidateQueries({queryKey:["dashboard-feedback-bookings"]}),K.success(`Booking marked as ${f}`),t(!1)},onError:()=>{K.error("Failed to update booking status")}}),o=_e({mutationFn:async g=>{const{data:f,error:_}=await T.functions.invoke("complete-feedback-call",{body:{bookingId:g}});if(_)throw _;if(f!=null&&f.error)throw new Error(f.error);return f},onSuccess:()=>{r.invalidateQueries({queryKey:["dashboard-feedback-bookings"]}),K.success("Call completed & 30-day trial activated!"),t(!1)},onError:g=>{K.error(g.message||"Failed to complete call and grant trial")}});if(!s)return null;const h=new Date(s.booking_date),N=parseInt(s.booking_time.split(":")[0]),d=N>=13?`${N-12}:${s.booking_time.split(":")[1].slice(0,2)} PM`:`${N}:${s.booking_time.split(":")[1].slice(0,2)} PM`,y=g=>{switch(g){case"scheduled":return"default";case"completed":return"secondary";case"no_show":return"destructive";case"cancelled":return"outline";default:return"outline"}},u=s.status!=="scheduled",x=async()=>
226{l(!0);try{await o.mutateAsync(s.id)}finally{l(!1)}};return e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-md",children:[e.jsxs(ze,{children:[e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(kr,{className:"h-5 w-5 text-cyan-500"}),"Feedback Call Booking"]}),e.jsx(Vs,{children:"Manage this feedback call and grant the free trial when completed."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Name"}),e.jsx("span",{className:"font-medium",children:s.name})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Email"}),e.jsx("span",{className:"font-medium text-sm",children:s.email})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Date"}),e.jsx("span",{className:"font-medium",children:ke(h,"MMMM d, yyyy")})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Time"}),e.jsxs("span",{className:"font-medium",children:[d," CT"]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Sport"}),e.jsx("span",{className:"font-medium uppercase",children:s.selected_sport})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx(B,{variant:y(s.status),children:s.status})]}),s.reward_claimed&&e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Reward"}),e.jsx(B,{variant:"secondary",className:"bg-green-500/10 text-green-600",children:"Trial Granted"})]})]}),u?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"This booking has already been processed."}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs(R,{className:"w-full bg-green-600 hover:bg-green-700",onClick:x,disabled:i||o.isPending,children:[i?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Mark Completed & Grant 30-Day Trial"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{variant:"outline",className:"flex-1",onClick:()=>m.mutate({id:s.id,status:"no_show"}),disabled:m.isPending,children:[e.jsx(rt,{className:"h-4 w-4 mr-2"}),"No Show"]}),e.jsxs(R,{variant:"outline",className:"flex-1",onClick:()=>m.mutate({id:s.id,status:"cancelled"}),disabled:m.isPending,children:[e.jsx(Fa,{className:"h-4 w-4 mr-2"}),"Cancel"]})]})]}),u&&n&&e.jsxs(R,{variant:"destructive",size:"sm",onClick:n,className:"w-full",children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete Booking"]})]})]})})}function Au({item:s,open:a,onOpenChange:t}){var _;const n=Me(),[r,i]=v.useState(""),l=()=>{i(""),t(!1)},m=()=>{n.invalidateQueries({queryKey:["dashboard-social-activity"]})},o=_e({mutationFn:async()=>{if(!s||!r.trim())throw new Error("Reply text is required");const k=s.kind==="comment";if(k&&!s.parent_post_id)throw new Error("Cannot reply — original post id is missing for this comment");const b=k?{action:"reply-comment",commentId:s.external_id,accountId:s.account_id,parentPostId:s.parent_post_id,text:r.trim(),eventId:s.id}:{action:"reply-message",conversationId:s.conversation_id,accountId:s.account_id,text:r.trim(),platform:s.platform},{data:j,error:c}=await T.functions.invoke("late-social-setup",{body:b});if(c)throw c;if(j!=null&&j.error)throw new Error(j.error);return k||await T.from("social_webhook_events").update({processed:!0}).eq("id",s.id),j},onSuccess:()=>{K.success("Reply sent"),m(),l()},onError:k=>K.error((k==null?void 0:k.message)||"Failed to send reply")}),h=_e({mutationFn:async()=>{if(!s)return;if(s.kind!=="comment")throw new Error("Only comments can be deleted from the platform");if(!s.external_id||!s.account_id)throw new Error("Missing comment id or account id");if(!s.parent_post_id)throw new Error("Cannot delete — original post id is missing for this comment");const{data:k,error:b}=await T.functions.invoke("late-social-setup",{body:{action:"delete-comment",commentId:s.external_id,accountId:s.account_id,parentPostId:s.parent_post_id,eventId:s.id}});if(b)throw b;if(k!=null&&k.error)throw new Error(k.error);return k},onSuccess:()=>{K.success("Comment deleted from platform"),m(),l()},onError:k=>K.error((k==null?void 0:k.message)||"Failed to delete comment")}),N=_e({mutationFn:async()=>
226{if(!s)return;const{error:k}=await T.from("social_webhook_events").update({processed:!0}).eq("id",s.id);if(k)throw k},onSuccess:()=>{K.success("Dismissed from Recent Activity"),m(),l()},onError:()=>K.error("Failed to dismiss")});if(!s)return null;const d=s.platform==="instagram"?Ur:s.platform==="facebook"?Ii:St,y=s.platform==="instagram"?"text-pink-500":s.platform==="facebook"?"text-blue-600":"text-muted-foreground",u=s.platform?s.platform.charAt(0).toUpperCase()+s.platform.slice(1):"Social",x=s.kind==="comment",g=(_=s.author)!=null&&_.username?`@${s.author.username}`:null,f=(()=>{if(!x||!s.parent_post_id)return null;if(s.platform==="facebook"){const k=s.parent_post_id.split("_"),b=k[0],j=k[1]||k[0];return`https://www.facebook.com/${b}/posts/${j}`}return s.platform==="instagram"?`https://www.instagram.com/p/${s.parent_post_id}/`:null})();return e.jsx(Ue,{open:a,onOpenChange:k=>{k?t(!0):l()},children:e.jsxs(Be,{className:"max-w-lg",children:[e.jsxs(ze,{children:[e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(d,{className:`h-5 w-5 ${y}`}),u," ",x?"Comment":"Message"]}),e.jsxs(Vs,{children:["From ",e.jsx("span",{className:"font-medium text-foreground",children:s.sender_name}),g&&e.jsxs(e.Fragment,{children:[" (",g,")"]})," · ",e.jsx("span",{title:ke(new Date(s.created_at),"PPpp"),children:Dt(new Date(s.created_at),{addSuffix:!0})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm whitespace-pre-wrap break-words",children:s.text||e.jsx("span",{className:"text-muted-foreground italic",children:"(no text)"})}),f&&e.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ma,{className:"h-3 w-3"}),"View original post"]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-xs font-medium text-muted-foreground",children:["Reply ",x?"as Klever Bet":""]}),e.jsx(Xs,{value:r,onChange:k=>i(k.target.value),placeholder:x?"Write a public reply…":"Write a direct message reply…",rows:3})]})]}),e.jsxs(lt,{className:"flex-col gap-2 sm:flex-row sm:justify-between",children:[e.jsxs("div",{className:"flex gap-2",children:[x&&e.jsxs(R,{variant:"destructive",size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,children:[e.jsx(os,{className:"h-4 w-4 mr-1"}),"Delete from platform"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>N.mutate(),disabled:N.isPending,children:[e.jsx(Ro,{className:"h-4 w-4 mr-1"}),"Dismiss"]})]}),e.jsxs(R,{size:"sm",onClick:()=>o.mutate(),disabled:!r.trim()||o.isPending,children:[e.jsx(ut,{className:"h-4 w-4 mr-1"}),"Send Reply"]})]})]})})}function Tu({activity:s,supportActivity:a,feedbackSubmissions:t,feedbackBookings:n,socialActivity:r,isLoading:i}){const l=no(),m=Me(),[o,h]=v.useState(null),[N,d]=v.useState(null),[y,u]=v.useState(null),[x,g]=v.useState(null),[f,_]=v.useState(null),[k,b]=v.useState(!1),[j,c]=v.useState(null),p=_e({mutationFn:async()=>{const A=[];r.length>0&&A.push(Promise.resolve(T.from("social_webhook_events").update({processed:!0}).eq("processed",!1)).then(({error:q})=>{if(q)throw q})),s.filter(q=>q.status==="pending").length>0&&A.push(Promise.resolve(T.from("contact_submissions").update({status:"resolved"}).eq("status","pending")).then(({error:q})=>{if(q)throw q})),await Promise.all(A)},onSuccess:()=>{m.invalidateQueries({queryKey:["dashboard-contact-submissions"]}),m.invalidateQueries({queryKey:["dashboard-social-activity"]}),K.success("All items marked as read")},onError:()=>K.error("Failed to mark all as read")}),w=_e({mutationFn:async()=>{const A=[];s.length>0&&A.push(Promise.resolve(T.from("contact_submissions").delete().in("id",s.map(F=>F.id))).then(({error:F})=>{if(F)throw F})),t.length>0&&A.push(Promise.resolve(T.from("feedback_submissions").delete().in("id",t.map(F=>F.id))).then(({error:F})=>{if(F)throw F})),n.length>0&&A.push(Promise.resolve(T.from("feedback_call_bookings").delete().in("id",n.map(F=>F.id))).then(({error:F})=>{if(F)throw F})),r.length>0&&A.push(Promise.resolve(T.from("social_webhook_events").update({processed:!0}).eq("processed",!1)).then(({error:F})=>{if(F)throw F})),await Promise.all(A)},onSuccess:()=>
226{m.invalidateQueries({queryKey:["dashboard-contact-submissions"]}),m.invalidateQueries({queryKey:["dashboard-feedback-submissions"]}),m.invalidateQueries({queryKey:["dashboard-feedback-bookings"]}),m.invalidateQueries({queryKey:["dashboard-social-activity"]}),b(!1),K.success("All activity cleared")},onError:()=>K.error("Failed to delete all activity")}),S=_e({mutationFn:async({id:A,status:F})=>{const{error:q}=await T.from("contact_submissions").update({status:F}).eq("id",A);if(q)throw q},onSuccess:()=>{m.invalidateQueries({queryKey:["dashboard-contact-submissions"]}),K.success("Status updated")},onError:()=>{K.error("Failed to update status")}}),P=_e({mutationFn:async A=>{const{error:F}=await T.from("contact_submissions").delete().eq("id",A);if(F)throw F},onSuccess:()=>{m.invalidateQueries({queryKey:["dashboard-contact-submissions"]}),d(null),h(null),K.success("Submission deleted")},onError:()=>{K.error("Failed to delete submission")}}),C=_e({mutationFn:async A=>{const{error:F}=await T.from("feedback_submissions").delete().eq("id",A);if(F)throw F},onSuccess:()=>{m.invalidateQueries({queryKey:["dashboard-feedback-submissions"]}),g(null),K.success("Feedback survey deleted")},onError:()=>{K.error("Failed to delete feedback survey")}}),O=_e({mutationFn:async A=>{const{error:F}=await T.from("feedback_call_bookings").delete().eq("id",A);if(F)throw F},onSuccess:()=>{m.invalidateQueries({queryKey:["dashboard-feedback-bookings"]}),_(null),u(null),K.success("Call booking deleted")},onError:()=>{K.error("Failed to delete call booking")}}),$=A=>{switch(A){case"pending":return"destructive";case"in_progress":return"default";case"resolved":return"secondary";case"open":return"destructive";case"closed":return"secondary";case"new_reply":return"default";case"completed":return"secondary";case"scheduled":return"default";case"no_show":return"destructive";default:return"outline"}},z=()=>{l("/super-admin?tab=support")},D=[...s.map(A=>({...A,activityType:"contact"})),...a.map(A=>({...A,activityType:"support"})),...t.map(A=>({...A,activityType:"feedback"})),...n.map(A=>({...A,activityType:"booking"})),...r.map(A=>({...A,activityType:"social"}))].sort((A,F)=>new Date(F.created_at).getTime()-new Date(A.created_at).getTime()).slice(0,10);return i?e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"h-5 w-5"}),"Recent Activity"]})}),e.jsx(J,{className:"space-y-4",children:[1,2,3].map(A=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(gs,{className:"h-4 w-32"}),e.jsx(gs,{className:"h-3 w-24"})]}),e.jsx(gs,{className:"h-5 w-16"})]},A))})]}):e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"h-5 w-5"}),"Recent Activity"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(R,{variant:"ghost",size:"sm",onClick:()=>p.mutate(),disabled:D.length===0||p.isPending,className:"h-8 px-2 text-xs",children:[e.jsx(Jd,{className:"h-4 w-4 mr-1"}),"Read All"]}),e.jsxs(R,{variant:"ghost",size:"sm",onClick:()=>b(!0),disabled:D.length===0||w.isPending,className:"h-8 px-2 text-xs text-destructive hover:text-destructive",children:[e.jsx(os,{className:"h-4 w-4 mr-1"}),"Delete All"]})]})]}),e.jsx(J,{className:"space-y-4",children:D.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No recent activity"}):D.map(A=>{if(A.activityType==="contact"){const F=A;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>h(F),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:F.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[F.category," • ",Dt(new Date(F.created_at),{addSuffix:!0})]})]})]}),e.jsx(B,{variant:$(F.status),children:F.status})]},`contact-${F.id}`)}else if(A.activityType==="support"){const F=A,q=F.type==="ticket"?Kn:St,E=F.type==="ticket"?"text-orange-500":"text-purple-500";return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",onClick:z,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(q,{className:`h-4 w-4 ${E}`}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:F.title}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[F.user_name," • ",Dt(new Date(F.created_at),{addSuffix:!0})]})]})]}
226),e.jsx(B,{variant:$(F.status),children:F.type==="ticket"?F.status:"reply"})]},`support-${F.id}`)}else if(A.activityType==="feedback"){const F=A;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors group",onClick:()=>K.info(`Survey from ${F.email}
227Price: ${F.suggested_price_per_sport||"N/A"}
228Experience: ${F.overall_experience}/5
229NPS: ${F.likelihood_to_recommend}/10
230Sport: ${F.selected_sport.toUpperCase()}`),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Vi,{className:"h-4 w-4 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Feedback Survey"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[F.email," • ",Dt(new Date(F.created_at),{addSuffix:!0})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:$(F.status),children:F.selected_sport.toUpperCase()}),e.jsx("button",{onClick:q=>{q.stopPropagation(),g(F)},className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(os,{className:"h-4 w-4 text-destructive"})})]})]},`feedback-${F.id}`)}else if(A.activityType==="social"){const F=A,q=F.platform==="instagram"?Ur:F.platform==="facebook"?Ii:St,E=F.platform==="instagram"?"text-pink-500":F.platform==="facebook"?"text-blue-600":F.platform==="tiktok"?"text-foreground":"text-muted-foreground",L=q,H=F.event_type==="comment.received",Z=async se=>{se.stopPropagation();const{error:ie}=await T.from("social_webhook_events").update({processed:!0}).eq("id",F.id);ie?K.error("Failed to dismiss"):(m.invalidateQueries({queryKey:["dashboard-social-activity"]}),K.success("Dismissed"))};return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors group",onClick:()=>c(F),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(L,{className:`h-4 w-4 ${E}`}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium",children:[F.platform?F.platform.charAt(0).toUpperCase()+F.platform.slice(1):"Social"," ",H?"Comment":"Message"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[F.sender_name," • ",Dt(new Date(F.created_at),{addSuffix:!0})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"destructive",children:"new"}),e.jsx("button",{onClick:Z,className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-muted rounded transition-opacity",title:"Dismiss",children:e.jsx(os,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})]},`social-${F.id}`)}else{const F=A,q=new Date(F.booking_date),E=parseInt(F.booking_time.split(":")[0]),L=E>=13?`${E-12}:${F.booking_time.split(":")[1].slice(0,2)} PM`:`${E}:${F.booking_time.split(":")[1].slice(0,2)} PM`;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>u(F),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(kr,{className:"h-4 w-4 text-cyan-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium",children:["Call Booked: ",F.name]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ke(q,"MMM d")," at ",L," • ",Dt(new Date(F.created_at),{addSuffix:!0})]})]})]}),e.jsx(B,{variant:$(F.status),children:F.status})]},`booking-${F.id}`)}})}),e.jsx(Pu,{submission:o,open:!!o,onOpenChange:A=>!A&&h(null),onStatusChange:(A,F)=>{S.mutate({id:A,status:F})},onDelete:()=>{o&&d(o)}}),e.jsx(ws,{open:!!N,onOpenChange:A=>!A&&d(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Submission"}),e.jsxs(Ps,{children:["Are you sure you want to delete this contact submission from ",N==null?void 0:N.name,"? This action cannot be undone."]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>N&&P.mutate(N.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(ws,{open:!!x,onOpenChange:A=>!A&&g(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Feedback Survey"}),e.jsxs(Ps,{children:["Are you sure you want to delete this feedback survey from ",x==null?void 0:x.email,"? This action cannot be undone."]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>x&&C.mutate(x.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(ws,{open:!!f,onOpenChange:A=>!A&&_(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Call Booking"}),e.jsxs(Ps,{children:["Are you sure you want to delete this call booking for ",f==null?void 0:f.name,"? This action cannot be undone."]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>f&&O.mutate(f.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Fu,{booking:y,open:!!y,onOpenChange:A=>!A&&u(null),onDelete:()=>{y&&_(y)}}),e.jsx(ws,{open:k,onOpenChange:b,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete All Activity"}
230),e.jsx(Ps,{children:"This will permanently delete all contact submissions, feedback surveys, and call bookings shown here. Social messages will be marked as read. This action cannot be undone."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>w.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete All"})]})]})}),e.jsx(Au,{item:j,open:!!j,onOpenChange:A=>!A&&c(null)})]})}function Lu({sportStatuses:s,isLoading:a}){const t=r=>{switch(r){case"in_season":return"bg-primary/20 text-primary";case"off_season":return"bg-muted text-muted-foreground";case"coming_soon":return"bg-accent/20 text-accent";default:return"bg-muted text-muted-foreground"}},n=r=>r.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ");return a?e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Sports Status Overview"})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-3",children:[...Array(4)].map((r,i)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(gs,{className:"h-4 w-16"}),e.jsx(gs,{className:"h-6 w-24 rounded-full"})]},i))})})]}):e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Sports Status Overview"})}),e.jsx(J,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sports configured"}):e.jsx("div",{className:"space-y-3",children:s.map(r=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:r.sport_name}),e.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${t(r.status)}`,children:n(r.status)})]},r.id))})})]})}const bl=["bg-primary","bg-blue-500","bg-green-500","bg-purple-500","bg-orange-500","bg-pink-500"];function wl({open:s,onOpenChange:a,title:t,data:n,total:r,scheduledToCancelCount:i}){const l=Math.max(...n.map(m=>m.count),1);return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"sm:max-w-md",children:[e.jsx(ze,{children:e.jsx(Ke,{children:t})}),e.jsx("div",{className:"space-y-4 py-4",children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"No subscription data available"}):e.jsxs(e.Fragment,{children:[n.map((m,o)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:m.packageName}),e.jsxs("span",{className:"text-muted-foreground",children:[m.count," (",m.percentage.toFixed(1),"%)"]})]}),e.jsx("div",{className:"h-2 w-full bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${bl[o%bl.length]} transition-all`,style:{width:`${m.count/l*100}%`}})})]},m.packageId)),e.jsxs("div",{className:"pt-4 border-t space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm font-semibold",children:[e.jsx("span",{children:"Total"}),e.jsx("span",{children:r})]}),i!==void 0&&i>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm text-amber-600 dark:text-amber-400",children:[e.jsx("span",{children:"Scheduled to Cancel"}),e.jsx("span",{children:i})]})]})]})})]})})}const Eu={"24h":24,"7d":24*7,"30d":24*30},rl="America/Chicago";function Du(s){return new Date(s).toLocaleString("en-US",{timeZone:rl,hour:"numeric",hour12:!0})}function Sl(s){return new Date(s).toLocaleDateString("en-CA",{timeZone:rl})}function Mu(s){return new Date(s).toLocaleDateString("en-US",{timeZone:rl,month:"numeric",day:"numeric"})}function Iu(s){return ge({queryKey:["sportapi-usage-hourly",s],refetchInterval:6e4,queryFn:async()=>{const a=Eu[s],t=Date.now(),n=new Date(t-a*36e5).toISOString(),r=new Date(t-a*2*36e5).toISOString(),{data:i,error:l}=await T.from("sportapi_usage_hourly").select("function_name, hour_bucket, call_count").gte("hour_bucket",r).order("hour_bucket",{ascending:!0}).limit(2e4);if(l)throw l;const m=i||[],o=m.filter(b=>b.hour_bucket>=n),h=m.filter(b=>b.hour_bucket<n),N=o.reduce((b,j)=>b+(j.call_count||0),0),d=h.reduce((b,j)=>b+(j.call_count||0),0),y=new Map;for(const b of o)y.set(b.function_name,(y.get(b.function_name)||0)+(b.call_count||0));const u=Array.from(y.entries()).map(([b,j])=>({function_name:b,count:j})).sort((b,j)=>j.count-b.count),x=new Map;if(s==="24h"){for(let b=a-1;b>=0;b--){const j=new Date(t-b*36e5);j.setUTCMinutes(0,0,0),x.set(j.toISOString(),{label:Du(j.toISOString()),value:0})}for(const b of o){const j=new Date(b.hour_bucket).toISOString(),c=x.get(j);c&&(c.value+=b.call_count||0)}}else{const b=Math.round(a/24);for(let j=b-1;j>=0;j--){const c=new Date(t-j*864e5);x.set(Sl(c.toISOString()),{label:Mu(c.toISOString()),value:0})}for(const j of o){const c=Sl(j.hour_bucket),p=x.get(c);
230p&&(p.value+=j.call_count||0)}}const{data:g}=await T.from("sportapi_usage_hourly").select("hour_bucket").order("hour_bucket",{ascending:!0}).limit(1).maybeSingle(),f=(g==null?void 0:g.hour_bucket)??null,_=!f||f>n,k=!!f&&f<=r;return{total:N,previousTotal:d,change:k&&d>0?Math.round((N-d)/d*100):void 0,series:Array.from(x.values()),byFunction:u,trackingSince:f,isPartialWindow:_}}})}function Ru({open:s,onOpenChange:a,rangeLabel:t,total:n,data:r}){const i=r.length>0?r[0].count:0;return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-md",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"SportAPI Calls by Function"}),e.jsxs(Vs,{children:[n.toLocaleString()," calls in the ",t]})]}),r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"No tracked SportAPI calls in this period."}):e.jsx(cs,{className:"max-h-[360px] pr-3",children:e.jsx("div",{className:"space-y-3",children:r.map(l=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-mono text-xs truncate mr-2",children:l.function_name}),e.jsx("span",{className:"font-medium tabular-nums",children:l.count.toLocaleString()})]}),e.jsx(Ct,{value:i>0?l.count/i*100:0,className:"h-1.5"})]},l.function_name))})})]})})}const qu=["24h","7d","30d"],kl={"24h":"last 24 hours","7d":"last 7 days","30d":"last 30 days"};function $u(s){return new Date(s).toLocaleDateString("en-US",{timeZone:"America/Chicago",month:"short",day:"numeric",year:"numeric"})}function Ou(){const[s,a]=v.useState("24h"),[t,n]=v.useState(!1),{data:r,isLoading:i}=Iu(s),l=!!(r!=null&&r.isPartialWindow);return e.jsxs(e.Fragment,{children:[e.jsx(G,{children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[e.jsxs("div",{className:"min-w-[220px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"SportAPI Calls"})]}),i?e.jsx(gs,{className:"h-9 w-32 mt-2"}):e.jsx("div",{className:"text-3xl font-bold mt-2",children:((r==null?void 0:r.total)||0).toLocaleString()}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(r==null?void 0:r.change)!==void 0&&e.jsxs("span",{className:Le(r.change>=0?"text-red-500":"text-green-500"),children:[r.change>=0?"+":"",r.change,"%"," "]}),"in the ",kl[s],(r==null?void 0:r.change)!==void 0&&" vs prior period"]}),!i&&l&&(r==null?void 0:r.trackingSince)&&e.jsxs("p",{className:"text-[11px] text-amber-500 mt-1",children:["Partial — tracking started ",$u(r.trackingSince)]}),!i&&!(r!=null&&r.trackingSince)&&e.jsx("p",{className:"text-[11px] text-amber-500 mt-1",children:"No tracked calls recorded yet"}),e.jsxs("button",{type:"button",onClick:()=>n(!0),className:"text-xs text-primary mt-2 flex items-center gap-1 hover:underline",children:["View by function",e.jsx(st,{className:"h-3 w-3"})]})]}),e.jsxs("div",{className:"flex-1 md:max-w-[70%]",children:[e.jsx("div",{className:"flex items-center justify-end gap-1",children:qu.map(m=>e.jsx(R,{size:"sm",variant:m===s?"default":"ghost",className:"h-6 px-2 text-xs",onClick:()=>a(m),children:m},m))}),e.jsx("div",{className:"h-[120px] mt-2",children:i?e.jsx(gs,{className:"h-full w-full"}):e.jsx(Hi,{width:"100%",height:"100%",children:e.jsxs(td,{data:(r==null?void 0:r.series)||[],margin:{top:4,right:4,bottom:0,left:4},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"sportapiUsageFill",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]})}),e.jsx(Wi,{dataKey:"label",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,interval:"preserveStartEnd",minTickGap:24}),e.jsx(Gi,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12},labelStyle:{color:"hsl(var(--muted-foreground))"},formatter:m=>
230[m.toLocaleString(),"Calls"]}),e.jsx(ad,{type:"monotone",dataKey:"value",stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#sportapiUsageFill)"})]})})})]})]})})}),e.jsx(Ru,{open:t,onOpenChange:n,rangeLabel:kl[s],data:(r==null?void 0:r.byFunction)||[],total:(r==null?void 0:r.total)||0})]})}function Uu(){const{stats:s,activity:a,sportStatuses:t,supportActivity:n,feedbackSubmissions:r,feedbackBookings:i,socialActivity:l,churnBreakdown:m,churnTotal:o,trialBreakdown:h,trialTotal:N,trialScheduledToCancelCount:d,activeBreakdown:y,activeTotal:u,isLoading:x}=Cu(),[g,f]=v.useState(!1),[_,k]=v.useState(!1),[b,j]=v.useState(!1);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ou,{}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsx($t,{title:"Total Users",value:(s==null?void 0:s.totalUsers)||0,change:s==null?void 0:s.userGrowth,icon:hs,isLoading:x}),e.jsx($t,{title:"Free Users",value:(s==null?void 0:s.freeUsers)||0,icon:vu,isLoading:x}),e.jsx($t,{title:"Trial Users",value:(s==null?void 0:s.trialUsers)||0,icon:$s,isLoading:x,onClick:()=>k(!0),clickLabel:"View by package"}),e.jsx($t,{title:"Churn Rate",value:`${(s==null?void 0:s.churnRate)||0}%`,icon:qt,isLoading:x,onClick:()=>f(!0),clickLabel:"View reasons"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx($t,{title:"Cancelled Subs",value:(s==null?void 0:s.cancelledSubscriptions)||0,icon:Is,isLoading:x}),e.jsx($t,{title:"Paused Subs",value:(s==null?void 0:s.pausedSubscriptions)||0,icon:Ri,isLoading:x}),e.jsx($t,{title:"Past Due Subs",value:(s==null?void 0:s.pastDueSubscriptions)||0,icon:ls,isLoading:x})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx($t,{title:"AVG LTV",value:`$${((s==null?void 0:s.avgLtv)||0).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`,icon:La,isLoading:x}),e.jsx($t,{title:"Active Subscriptions",value:(s==null?void 0:s.activeSubscriptions)||0,change:s==null?void 0:s.subscriptionGrowth,icon:ta,isLoading:x,onClick:()=>j(!0),clickLabel:"View by package"}),e.jsx($t,{title:"Monthly Revenue",value:`$${((s==null?void 0:s.potentialRevenue)||0).toLocaleString()}`,secondaryValue:`$${((s==null?void 0:s.currentRevenue)||0).toLocaleString()}`,secondaryLabel:"Current",change:s==null?void 0:s.revenueGrowth,icon:La,isLoading:x})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Tu,{activity:a||[],supportActivity:n||[],feedbackSubmissions:r||[],feedbackBookings:i||[],socialActivity:l||[],isLoading:x}),e.jsx(Lu,{sportStatuses:t||[],isLoading:x})]}),e.jsx(ku,{open:g,onOpenChange:f,data:m,total:o}),e.jsx(wl,{title:"Trial Users by Package",open:_,onOpenChange:k,data:h,total:N,scheduledToCancelCount:d}),e.jsx(wl,{title:"Active Subscriptions by Package",open:b,onOpenChange:j,data:y,total:u})]})}function Cl(s,a){const t=String(s);if(typeof a!="string")throw new TypeError("Expected character");let n=0,r=t.indexOf(a);for(;r!==-1;)n++,r=t.indexOf(a,r+a.length);return n}function Bu(s){if(typeof s!="string")throw new TypeError("Expected a string");return s.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function zu(s,a,t){const r=qi((t||{}).ignore||[]),i=Ku(a);let l=-1;for(;++l<i.length;)lo(s,"text",m);function m(h,N){let d=-1,y;for(;++d<N.length;){const u=N[d],x=y?y.children:void 0;if(r(u,x?x.indexOf(u):void 0,y))return;y=u}if(y)return o(h,N)}function o(h,N){const d=N[N.length-1],y=i[l][0],u=i[l][1];let x=0;const f=d.children.indexOf(h);let _=!1,k=[];y.lastIndex=0;let b=y.exec(h.value);for(;b;){const j=b.index,c={index:b.index,input:b.input,stack:[...N,h]};let p=u(...b,c);if(typeof p=="string"&&(p=p.length>0?{type:"text",value:p}:void 0),p===!1?y.lastIndex=j+1:(x!==j&&k.push({type:"text",value:h.value.slice(x,j)}),Array.isArray(p)?k.push(...p):p&&k.push(p),x=j+b[0].length,_=!0),!y.global)break;b=y.exec(h.value)}return _?(x<h.value.length&&k.push({type:"text",value:h.value.slice(x)}),d.children.splice(f,1,...k)):k=[h],f+k.length}}function Ku(s){const a=[];if(!Array.isArray(s))throw new TypeError("Expected find and replace tuple or list of tuples");const t=!s[0]||Array.isArray(s[0])?s:[s];let n=-1;for(;++n<t.length;){const r=t[n];a.push([Vu(r[0]),Hu(r[1])])}return a}function Vu(s){return typeof s=="string"?new RegExp(Bu(s),"g"):s}function Hu(s){return typeof s=="function"?s:function(){return s}}const jn="phrasing",fn=["autolink","link","image","label"];function Wu(){return{transforms:[em],enter:{literalAutolink:Qu,literalAutolinkEmail:vn,literalAutolinkHttp:vn,literalAutolinkWww:vn},exit:{literalAutolink:Xu,literalAutolinkEmail:Zu,literalAutolinkHttp:Yu,literalAutolinkWww:Ju}}}function Gu(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:jn,notInConstruct:fn},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:jn,notInConstruct:fn},{character:":",before:"[ps]",after:"\\/",inConstruct:jn,notInConstruct:fn}]}}function Qu(s){this.enter({type:"link",title:null,url:"",children:[]},s)}function vn(s){this.config.enter.autolinkProtocol.call(this,s)}function Yu(s){this.config.exit.autolinkProtocol.call(this,s)}function Ju(s){this.config.exit.data.call(this,s);const a=this.stack[this.stack.length-1];$a(a.type==="link"),a.url="http://"+this.sliceSerialize(s)}function Zu(s){this.config.exit.autolinkEmail.call(this,s)}function Xu(s){this.exit(s)}function em(s){zu(s,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,sm],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S}
230)([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),tm]],{ignore:["link","linkReference"]})}function sm(s,a,t,n,r){let i="";if(!gc(r)||(/^w/i.test(a)&&(t=a+t,a="",i="http://"),!am(t)))return!1;const l=rm(t+n);if(!l[0])return!1;const m={type:"link",title:null,url:i+a+l[0],children:[{type:"text",value:a+l[0]}]};return l[1]?[m,{type:"text",value:l[1]}]:m}function tm(s,a,t,n){return!gc(n,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+a+"@"+t,children:[{type:"text",value:a+"@"+t}]}}function am(s){const a=s.split(".");return!(a.length<2||a[a.length-1]&&(/_/.test(a[a.length-1])||!/[a-zA-Z\d]/.test(a[a.length-1]))||a[a.length-2]&&(/_/.test(a[a.length-2])||!/[a-zA-Z\d]/.test(a[a.length-2])))}function rm(s){const a=/[!"&'),.:;<>?\]}]+$/.exec(s);if(!a)return[s,void 0];s=s.slice(0,a.index);let t=a[0],n=t.indexOf(")");const r=Cl(s,"(");let i=Cl(s,")");for(;n!==-1&&r>i;)s+=t.slice(0,n+1),t=t.slice(n+1),n=t.indexOf(")"),i++;return[s,t]}function gc(s,a){const t=s.input.charCodeAt(s.index-1);return(s.index===0||Ea(t)||Vn(t))&&(!a||t!==47)}jc.peek=xm;function nm(){this.buffer()}function lm(s){this.enter({type:"footnoteReference",identifier:"",label:""},s)}function im(){this.buffer()}function cm(s){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},s)}function om(s){const a=this.resume(),t=this.stack[this.stack.length-1];$a(t.type==="footnoteReference"),t.identifier=wr(this.sliceSerialize(s)).toLowerCase(),t.label=a}function dm(s){this.exit(s)}function um(s){const a=this.resume(),t=this.stack[this.stack.length-1];$a(t.type==="footnoteDefinition"),t.identifier=wr(this.sliceSerialize(s)).toLowerCase(),t.label=a}function mm(s){this.exit(s)}function xm(){return"["}function jc(s,a,t,n){const r=t.createTracker(n);let i=r.move("[^");const l=t.enter("footnoteReference"),m=t.enter("reference");return i+=r.move(t.safe(t.associationId(s),{after:"]",before:i})),m(),l(),i+=r.move("]"),i}function hm(){return{enter:{gfmFootnoteCallString:nm,gfmFootnoteCall:lm,gfmFootnoteDefinitionLabelString:im,gfmFootnoteDefinition:cm},exit:{gfmFootnoteCallString:om,gfmFootnoteCall:dm,gfmFootnoteDefinitionLabelString:um,gfmFootnoteDefinition:mm}}}function pm(s){let a=!1;return s&&s.firstLineBlank&&(a=!0),{handlers:{footnoteDefinition:t,footnoteReference:jc},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function t(n,r,i,l){const m=i.createTracker(l);let o=m.move("[^");const h=i.enter("footnoteDefinition"),N=i.enter("label");return o+=m.move(i.safe(i.associationId(n),{before:o,after:"]"})),N(),o+=m.move("]:"),n.children&&n.children.length>0&&(m.shift(4),o+=m.move((a?`
231`:" ")+i.indentLines(i.containerFlow(n,m.current()),a?fc:gm))),h(),o}}function gm(s,a,t){return a===0?s:fc(s,a,t)}function fc(s,a,t){return(t?"":"    ")+s}const jm=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];vc.peek=_m;function fm(){return{canContainEols:["delete"],enter:{strikethrough:ym},exit:{strikethrough:Nm}}}function vm(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:jm}],handlers:{delete:vc}}}function ym(s){this.enter({type:"delete",children:[]},s)}function Nm(s){this.exit(s)}function vc(s,a,t,n){const r=t.createTracker(n),i=t.enter("strikethrough");let l=r.move("~~");return l+=t.containerPhrasing(s,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),i(),l}function _m(){return"~"}function bm(s){return s.length}function wm(s,a){const t=a||{},n=(t.align||[]).concat(),r=t.stringLength||bm,i=[],l=[],m=[],o=[];let h=0,N=-1;for(;++N<s.length;){const g=[],f=[];let _=-1;for(s[N].length>h&&(h=s[N].length);++_<s[N].length;){const k=Sm(s[N][_]);if(t.alignDelimiters!==!1){const b=r(k);f[_]=b,(o[_]===void 0||b>o[_])&&(o[_]=b)}g.push(k)}l[N]=g,m[N]=f}let d=-1;if(typeof n=="object"&&"length"in n)for(;++d<h;)i[d]=Pl(n[d]);else{const g=Pl(n);for(;++d<h;)i[d]=g}d=-1;const y=[],u=[];for(;++d<h;){const g=i[d];let f="",_="";g===99?(f=":",_=":"):g===108?f=":":g===114&&(_=":");let k=t.alignDelimiters===!1?1:Math.max(1,o[d]-f.length-_.length);const b=f+"-".repeat(k)+_;t.alignDelimiters!==!1&&(k=f.length+k+_.length,k>o[d]&&(o[d]=k),u[d]=k),y[d]=b}l.splice(1,0,y),m.splice(1,0,u),N=-1;const x=[];for(;++N<l.length;){const g=l[N],f=m[N];d=-1;const _=[];for(;++d<h;){const k=g[d]||"";let b="",j="";if(t.alignDelimiters!==!1){const c=o[d]-(f[d]||0),p=i[d];p===114?b=" ".repeat(c):p===99?c%2?(b=" ".repeat(c/2+.5),j=" ".repeat(c/2-.5)):(b=" ".repeat(c/2),j=b):j=" ".repeat(c)}t.delimiterStart!==!1&&!d&&_.push("|"),t.padding!==!1&&!(t.alignDelimiters===!1&&k==="")&&(t.delimiterStart!==!1||d)&&_.push(" "),t.alignDelimiters!==!1&&_.push(b),_.push(k),t.alignDelimiters!==!1&&_.push(j),t.padding!==!1&&_.push(" "),(t.delimiterEnd!==!1||d!==h-1)&&_.push("|")}x.push(t.delimiterEnd===!1?_.join("").replace(/ +$/,""):_.join(""))}return x.join(`
232`)}function Sm(s){return s==null?"":String(s)}function Pl(s){const a=typeof s=="string"?s.codePointAt(0):0;return a===67||a===99?99:a===76||a===108?108:a===82||a===114?114:0}function km(s,a,t,n){const r=t.enter("blockquote"),i=t.createTracker(n);i.move("> "),i.shift(2);
vendor: 11,437 bytes, lines 232-243
232const l=t.indentLines(t.containerFlow(s,i.current()),Cm);return r(),l}function Cm(s,a,t){return">"+(t?"":" ")+s}function Pm(s,a){return Fl(s,a.inConstruct,!0)&&!Fl(s,a.notInConstruct,!1)}function Fl(s,a,t){if(typeof a=="string"&&(a=[a]),!a||a.length===0)return t;let n=-1;for(;++n<a.length;)if(s.includes(a[n]))return!0;return!1}function Al(s,a,t,n){let r=-1;for(;++r<t.unsafe.length;)if(t.unsafe[r].character===`
233`&&Pm(t.stack,t.unsafe[r]))return/[ \t]/.test(n.before)?"":" ";return`\\
234`}function Fm(s,a){const t=String(s);let n=t.indexOf(a),r=n,i=0,l=0;if(typeof a!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===r?++i>l&&(l=i):i=1,r=n+a.length,n=t.indexOf(a,r);return l}function Am(s,a){return!!(a.options.fences===!1&&s.value&&!s.lang&&/[^ \r\n]/.test(s.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(s.value))}function Tm(s){const a=s.options.fence||"`";if(a!=="`"&&a!=="~")throw new Error("Cannot serialize code with `"+a+"` for `options.fence`, expected `` ` `` or `~`");return a}function Lm(s,a,t,n){const r=Tm(t),i=s.value||"",l=r==="`"?"GraveAccent":"Tilde";if(Am(s,t)){const d=t.enter("codeIndented"),y=t.indentLines(i,Em);return d(),y}const m=t.createTracker(n),o=r.repeat(Math.max(Fm(i,r)+1,3)),h=t.enter("codeFenced");let N=m.move(o);if(s.lang){const d=t.enter(`codeFencedLang${l}`);N+=m.move(t.safe(s.lang,{before:N,after:" ",encode:["`"],...m.current()})),d()}if(s.lang&&s.meta){const d=t.enter(`codeFencedMeta${l}`);N+=m.move(" "),N+=m.move(t.safe(s.meta,{before:N,after:`
235`,encode:["`"],...m.current()})),d()}return N+=m.move(`
236`),i&&(N+=m.move(i+`
237`)),N+=m.move(o),h(),N}function Em(s,a,t){return(t?"":"    ")+s}function nl(s){const a=s.options.quote||'"';if(a!=='"'&&a!=="'")throw new Error("Cannot serialize title with `"+a+"` for `options.quote`, expected `\"`, or `'`");return a}function Dm(s,a,t,n){const r=nl(t),i=r==='"'?"Quote":"Apostrophe",l=t.enter("definition");let m=t.enter("label");const o=t.createTracker(n);let h=o.move("[");return h+=o.move(t.safe(t.associationId(s),{before:h,after:"]",...o.current()})),h+=o.move("]: "),m(),!s.url||/[\0- \u007F]/.test(s.url)?(m=t.enter("destinationLiteral"),h+=o.move("<"),h+=o.move(t.safe(s.url,{before:h,after:">",...o.current()})),h+=o.move(">")):(m=t.enter("destinationRaw"),h+=o.move(t.safe(s.url,{before:h,after:s.title?" ":`
238`,...o.current()}))),m(),s.title&&(m=t.enter(`title${i}`),h+=o.move(" "+r),h+=o.move(t.safe(s.title,{before:h,after:r,...o.current()})),h+=o.move(r),m()),l(),h}function Mm(s){const a=s.options.emphasis||"*";if(a!=="*"&&a!=="_")throw new Error("Cannot serialize emphasis with `"+a+"` for `options.emphasis`, expected `*`, or `_`");return a}function br(s){return"&#x"+s.toString(16).toUpperCase()+";"}function en(s,a,t){const n=Br(s),r=Br(a);return n===void 0?r===void 0?t==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}yc.peek=Im;function yc(s,a,t,n){const r=Mm(t),i=t.enter("emphasis"),l=t.createTracker(n),m=l.move(r);let o=l.move(t.containerPhrasing(s,{after:r,before:m,...l.current()}));const h=o.charCodeAt(0),N=en(n.before.charCodeAt(n.before.length-1),h,r);N.inside&&(o=br(h)+o.slice(1));const d=o.charCodeAt(o.length-1),y=en(n.after.charCodeAt(0),d,r);y.inside&&(o=o.slice(0,-1)+br(d));const u=l.move(r);return i(),t.attentionEncodeSurroundingInfo={after:y.outside,before:N.outside},m+o+u}function Im(s,a,t){return t.options.emphasis||"*"}function Rm(s,a){let t=!1;return io(s,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return t=!0,co}),!!((!s.depth||s.depth<3)&&$i(s)&&(a.options.setext||t))}function qm(s,a,t,n){const r=Math.max(Math.min(6,s.depth||1),1),i=t.createTracker(n);if(Rm(s,t)){const N=t.enter("headingSetext"),d=t.enter("phrasing"),y=t.containerPhrasing(s,{...i.current(),before:`
239`,after:`
240`});return d(),N(),y+`
241`+(r===1?"=":"-").repeat(y.length-(Math.max(y.lastIndexOf("\r"),y.lastIndexOf(`
242`))+1))}const l="#".repeat(r),m=t.enter("headingAtx"),o=t.enter("phrasing");i.move(l+" ");let h=t.containerPhrasing(s,{before:"# ",after:`
243`,...i.current()});return/^[\t ]/.test(h)&&(h=br(h.charCodeAt(0))+h.slice(1)),h=h?l+" "+h:l,t.options.closeAtx&&(h+=" "+l),o(),m(),h}Nc.peek=$m;function Nc(s){return s.value||""}function $m(){return"<"}_c.peek=Om;function _c(s,a,t,n){const r=nl(t),i=r==='"'?"Quote":"Apostrophe",l=t.enter("image");let m=t.enter("label");const o=t.createTracker(n);let h=o.move("![");return h+=o.move(t.safe(s.alt,{before:h,after:"]",...o.current()})),h+=o.move("]("),m(),!s.url&&s.title||/[\0- \u007F]/.test(s.url)?(m=t.enter("destinationLiteral"),h+=o.move("<"),h+=o.move(t.safe(s.url,{before:h,after:">",...o.current()})),h+=o.move(">")):(m=t.enter("destinationRaw"),h+=o.move(t.safe(s.url,{before:h,after:s.title?" ":")",...o.current()}))),m(),s.title&&(m=t.enter(`title${i}`),h+=o.move(" "+r),h+=o.move(t.safe(s.title,{before:h,after:r,...o.current()})),h+=o.move(r),m()),h+=o.move(")"),l(),h}function Om(){return"!"}bc.peek=Um;function bc(s,a,t,n){const r=s.referenceType,i=t.enter("imageReference");let l=t.enter("label");const m=t.createTracker(n);let o=m.move("![");const h=t.safe(s.alt,{before:o,after:"]",...m.current()});o+=m.move(h+"]["),l();const N=t.stack;t.stack=[],l=t.enter("reference");const d=t.safe(t.associationId(s),{before:o,after:"]",...m.current()});return l(),t.stack=N,i(),r==="full"||!h||h!==d?o+=m.move(d+"]"):r==="shortcut"?o=o.slice(0,-1):o+=m.move("]"),o}function Um(){return"!"}wc.peek=Bm;function wc(s,a,t){let n=s.value||"",r="`",i=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(n);)r+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++i<t.unsafe.length;){const l=t.unsafe[i],m=t.compilePattern(l);let o;if(l.atBreak)for(;o=m.exec(n);){let h=o.index;n.charCodeAt(h)===10&&n.charCodeAt(h-1)===13&&h--,n=n.slice(0,h)+" "+n.slice(o.index+1)}}return r+n+r}function Bm(){return"`"}function Sc(s,a){const t=$i(s);return!!(!a.options.resourceLink&&s.url&&!s.title&&s.children&&s.children.length===1&&s.children[0].type==="text"&&(t===s.url||"mailto:"+t===s.url)&&/^[a-z][a-z+.-]+:/i.test(s.url)&&!/[\0- <>\u007F]/.test(s.url))}kc.peek=zm;function kc(s,a,t,n){const r=nl(t),i=r==='"'?"Quote":"Apostrophe",l=t.createTracker(n);let m,o;if(Sc(s,t)){const N=t.stack;t.stack=[],m=t.enter("autolink");let d=l.move("<");return d+=l.move(t.containerPhrasing(s,{before:d,after:">",...l.current()})),d+=l.move(">"),m(),t.stack=N,d}m=t.enter("link"),o=t.enter("label");let h=l.move("[");return h+=l.move(t.containerPhrasing(s,{before:h,after:"](",...l.current()})),h+=l.move("]("),o(),!s.url&&s.title||/[\0- \u007F]/.test(s.url)?(o=t.enter("destinationLiteral"),h+=l.move("<"),h+=l.move(t.safe(s.url,{before:h,after:">",...l.current()})),h+=l.move(">")):(o=t.enter("destinationRaw"),h+=l.move(t.safe(s.url,{before:h,after:s.title?" ":")",...l.current()}))),o(),s.title&&(o=t.enter(`title${i}`),h+=l.move(" "+r),h+=l.move(t.safe(s.title,{before:h,after:r,...l.current()})),h+=l.move(r),o()),h+=l.move(")"),m(),h}function zm(s,a,t){return Sc(s,t)?"<":"["}Cc.peek=Km;function Cc(s,a,t,n){const r=s.referenceType,i=t.enter("linkReference");let l=t.enter("label");const m=t.createTracker(n);let o=m.move("[");const h=t.containerPhrasing(s,{before:o,after:"]",...m.current()});o+=m.move(h+"]["),l();const N=t.stack;t.stack=[],l=t.enter("reference");const d=t.safe(t.associationId(s),{before:o,after:"]",...m.current()});return l(),t.stack=N,i(),r==="full"||!h||h!==d?o+=m.move(d+"]"):r==="shortcut"?o=o.slice(0,-1):o+=m.move("]"),o}function Km(){return"["}function ll(s){const a=s.options.bullet||"*";if(a!=="*"&&a!=="+"&&a!=="-")throw new Error("Cannot serialize items with `"+a+"` for `options.bullet`, expected `*`, `+`, or `-`");return a}function Vm(s){const a=ll(s),t=s.options.bulletOther;if(!t)return a==="*"?"-":"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(t===a)throw new Error("Expected `bullet` (`"+a+"`) and `bulletOther` (`"+t+"`) to be different");return t}function Hm(s){const a=s.options.bulletOrdered||".";if(a!=="."&&a!==")")throw new Error("Cannot serialize items with `"+a+"` for `options.bulletOrdered`, expected `.` or `)`");return a}function Pc(s){const a=s.options.rule||"*";if(a!=="*"&&a!=="-"&&a!=="_")throw new Error("Cannot serialize rules with `"+a+"` for `options.rule`, expected `*`, `-`, or `_`");return a}function Wm(s,a,t,n){const r=t.enter("list"),i=t.bulletCurrent;let l=s.ordered?Hm(t):ll(t);const m=s.ordered?l==="."?")":".":Vm(t);let o=a&&t.bulletLastUsed?l===t.bulletLastUsed:!1;if(!s.ordered){const N=s.children?s.children[0]:void 0;if((l==="*"||l==="-")&&N&&(!N.children||!N.children[0])&&t.stack[t.stack.length-1]==="list"&&t.stack[t.stack.length-2]==="listItem"&&t.stack[t.stack.length-3]==="list"&&t.stack[t.stack.length-4]==="listItem"&&t.indexStack[t.indexStack.length-1]===0&&t.indexStack[t.indexStack.length-2]===0&&t.indexStack[t.indexStack.length-3]===0&&(o=!0),Pc(t)===l&&N){let d=-1;for(;++d<s.children.length;){const y=s.children[d];if(y&&y.type==="listItem"&&y.children&&y.children[0]&&y.children[0].type==="thematicBreak"){o=!0;break}}}}o&&(l=m),t.bulletCurrent=l;const h=t.containerFlow(s,n);return t.bulletLastUsed=l,t.bulletCurrent=i,r(),h}function Gm(s){const a=s.options.listItemIndent||"one";if(a!=="tab"&&a!=="one"&&a!=="mixed")throw new Error("Cannot serialize items with `"+a+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return a}function Qm(s,a,t,n){const r=Gm(t);let i=t.bulletCurrent||ll(t);a&&a.type==="list"&&a.ordered&&(i=(typeof a.start=="number"&&a.start>-1?a.start:1)+(t.options.incrementListMarker===!1?0:a.children.indexOf(s))+i);let l=i.length+1;(r==="tab"||r==="mixed"&&(a&&a.type==="list"&&a.spread||s.spread))&&(l=Math.ceil(l/4)*4);const m=t.createTracker(n);m.move(i+" ".repeat(l-i.length)),m.shift(l);const o=t.enter("listItem"),h=t.indentLines(t.containerFlow(s,m.current()),N);return o(),h;function N(d,y,u){return y?(u?"":" ".repeat(l))+d:(u?i:i+" ".repeat(l-i.length))+d}}function Ym(s,a,t,n){const r=t.enter("paragraph"),i=t.enter("phrasing"),l=t.containerPhrasing(s,n);return i(),r(),l}const Jm=qi(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Zm(s,a,t,n){return(s.children.some(function(l){return Jm(l)})?t.containerPhrasing:t.containerFlow).call(t,s,n)}function Xm(s){const a=s.options.strong||"*";if(a!=="*"&&a!=="_")throw new Error("Cannot serialize strong with `"+a+"` for `options.strong`, expected `*`, or `_`");return a}Fc.peek=ex;function Fc(s,a,t,n){const r=Xm(t),i=t.enter("strong"),l=t.createTracker(n),m=l.move(r+r);let o=l.move(t.containerPhrasing(s,{after:r,before:m,...l.current()}));const h=o.charCodeAt(0),N=en(n.before.charCodeAt(n.before.length-1),h,r);N.inside&&(o=br(h)+o.slice(1));const d=o.charCodeAt(o.length-1),y=en(n.after.charCodeAt(0),d,r);y.inside&&(o=o.slice(0,-1)+br(d));const u=l.move(r+r);return i(),t.attentionEncodeSurroundingInfo={after:y.outside,before:N.outside},m+o+u}function ex(s,a,t){return t.options.strong||"*"}
vendor: 4,631 bytes, lines 243-245
243function sx(s,a,t,n){return t.safe(s.value,n)}function tx(s){const a=s.options.ruleRepetition||3;if(a<3)throw new Error("Cannot serialize rules with repetition `"+a+"` for `options.ruleRepetition`, expected `3` or more");return a}function ax(s,a,t){const n=(Pc(t)+(t.options.ruleSpaces?" ":"")).repeat(tx(t));return t.options.ruleSpaces?n.slice(0,-1):n}const Ac={blockquote:km,break:Al,code:Lm,definition:Dm,emphasis:yc,hardBreak:Al,heading:qm,html:Nc,image:_c,imageReference:bc,inlineCode:wc,link:kc,linkReference:Cc,list:Wm,listItem:Qm,paragraph:Ym,root:Zm,strong:Fc,text:sx,thematicBreak:ax};function rx(){return{enter:{table:nx,tableData:Tl,tableHeader:Tl,tableRow:ix},exit:{codeText:cx,table:lx,tableData:yn,tableHeader:yn,tableRow:yn}}}function nx(s){const a=s._align;this.enter({type:"table",align:a.map(function(t){return t==="none"?null:t}),children:[]},s),this.data.inTable=!0}function lx(s){this.exit(s),this.data.inTable=void 0}function ix(s){this.enter({type:"tableRow",children:[]},s)}function yn(s){this.exit(s)}function Tl(s){this.enter({type:"tableCell",children:[]},s)}function cx(s){let a=this.resume();this.data.inTable&&(a=a.replace(/\\([\\|])/g,ox));const t=this.stack[this.stack.length-1];$a(t.type==="inlineCode"),t.value=a,this.exit(s)}function ox(s,a){return a==="|"?a:s}function dx(s){const a=s||{},t=a.tableCellPadding,n=a.tablePipeAlign,r=a.stringLength,i=t?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
244`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[	 :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:y,table:l,tableCell:o,tableRow:m}};function l(u,x,g,f){return h(N(u,g,f),u.align)}function m(u,x,g,f){const _=d(u,g,f),k=h([_]);return k.slice(0,k.indexOf(`
245`))}function o(u,x,g,f){const _=g.enter("tableCell"),k=g.enter("phrasing"),b=g.containerPhrasing(u,{...f,before:i,after:i});return k(),_(),b}function h(u,x){return wm(u,{align:x,alignDelimiters:n,padding:t,stringLength:r})}function N(u,x,g){const f=u.children;let _=-1;const k=[],b=x.enter("table");for(;++_<f.length;)k[_]=d(f[_],x,g);return b(),k}function d(u,x,g){const f=u.children;let _=-1;const k=[],b=x.enter("tableRow");for(;++_<f.length;)k[_]=o(f[_],u,x,g);return b(),k}function y(u,x,g){let f=Ac.inlineCode(u,x,g);return g.stack.includes("tableCell")&&(f=f.replace(/\|/g,"\\$&")),f}}function ux(){return{exit:{taskListCheckValueChecked:Ll,taskListCheckValueUnchecked:Ll,paragraph:xx}}}function mx(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:hx}}}function Ll(s){const a=this.stack[this.stack.length-2];$a(a.type==="listItem"),a.checked=s.type==="taskListCheckValueChecked"}function xx(s){const a=this.stack[this.stack.length-2];if(a&&a.type==="listItem"&&typeof a.checked=="boolean"){const t=this.stack[this.stack.length-1];$a(t.type==="paragraph");const n=t.children[0];if(n&&n.type==="text"){const r=a.children;let i=-1,l;for(;++i<r.length;){const m=r[i];if(m.type==="paragraph"){l=m;break}}l===t&&(n.value=n.value.slice(1),n.value.length===0?t.children.shift():t.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,t.position.start=Object.assign({},n.position.start)))}}this.exit(s)}function hx(s,a,t,n){const r=s.children[0],i=typeof s.checked=="boolean"&&r&&r.type==="paragraph",l="["+(s.checked?"x":" ")+"] ",m=t.createTracker(n);i&&m.move(l);let o=Ac.listItem(s,a,t,{...n,...m.current()});return i&&(o=o.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,h)),o;function h(N){return N+l}}function px(){return[Wu(),hm(),fm(),rx(),ux()]}function gx(s){return{extensions:[Gu(),pm(s),vm(),dx(s),mx()]}}const jx={tokenize:bx,partial:!0},Tc={tokenize:wx,partial:!0},Lc={tokenize:Sx,partial:!0},Ec={tokenize:kx,partial:!0},fx={tokenize:Cx,partial:!0},Dc={name:"wwwAutolink",tokenize:Nx,previous:Ic},Mc={name:"protocolAutolink",tokenize:_x,previous:Rc},Qt={name:"emailAutolink",tokenize:yx,previous:qc},Kt={};function vx(){return{text:Kt}}let la=48;for(;la<123;)Kt[la]=Qt,la++,la===58?la=65:la===91&&(la=97);Kt[43]=Qt;Kt[45]=Qt;Kt[46]=Qt;Kt[95]=Qt;Kt[72]=[Qt,Mc];Kt[104]=[Qt,Mc];Kt[87]=[Qt,Dc];Kt[119]=[Qt,Dc];function yx(s,a,t){const n=this;let r,i;return l;function l(d){return!Un(d)||!qc.call(n,n.previous)||il(n.events)?t(d):(s.enter("literalAutolink"),s.enter("literalAutolinkEmail"),m(d))}function m(d){return Un(d)?(s.consume(d),m):d===64?(s.consume(d),o):t(d)}function o(d){return d===46?s.check(fx,N,h)(d):d===45||d===95||Hn(d)?(i=!0,s.consume(d),o):N(d)}function h(d){return s.consume(d),r=!0,o}
vendor: 7,282 bytes, line 245
245function N(d){return i&&r&&fr(n.previous)?(s.exit("literalAutolinkEmail"),s.exit("literalAutolink"),a(d)):t(d)}}function Nx(s,a,t){const n=this;return r;function r(l){return l!==87&&l!==119||!Ic.call(n,n.previous)||il(n.events)?t(l):(s.enter("literalAutolink"),s.enter("literalAutolinkWww"),s.check(jx,s.attempt(Tc,s.attempt(Lc,i),t),t)(l))}function i(l){return s.exit("literalAutolinkWww"),s.exit("literalAutolink"),a(l)}}function _x(s,a,t){const n=this;let r="",i=!1;return l;function l(d){return(d===72||d===104)&&Rc.call(n,n.previous)&&!il(n.events)?(s.enter("literalAutolink"),s.enter("literalAutolinkHttp"),r+=String.fromCodePoint(d),s.consume(d),m):t(d)}function m(d){if(fr(d)&&r.length<5)return r+=String.fromCodePoint(d),s.consume(d),m;if(d===58){const y=r.toLowerCase();if(y==="http"||y==="https")return s.consume(d),o}return t(d)}function o(d){return d===47?(s.consume(d),i?h:(i=!0,o)):t(d)}function h(d){return d===null||oo(d)||bt(d)||Ea(d)||Vn(d)?t(d):s.attempt(Tc,s.attempt(Lc,N),t)(d)}function N(d){return s.exit("literalAutolinkHttp"),s.exit("literalAutolink"),a(d)}}function bx(s,a,t){let n=0;return r;function r(l){return(l===87||l===119)&&n<3?(n++,s.consume(l),r):l===46&&n===3?(s.consume(l),i):t(l)}function i(l){return l===null?t(l):a(l)}}function wx(s,a,t){let n,r,i;return l;function l(h){return h===46||h===95?s.check(Ec,o,m)(h):h===null||bt(h)||Ea(h)||h!==45&&Vn(h)?o(h):(i=!0,s.consume(h),l)}function m(h){return h===95?n=!0:(r=n,n=void 0),s.consume(h),l}function o(h){return r||n||!i?t(h):a(h)}}function Sx(s,a){let t=0,n=0;return r;function r(l){return l===40?(t++,s.consume(l),r):l===41&&n<t?i(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?s.check(Ec,a,i)(l):l===null||bt(l)||Ea(l)?a(l):(s.consume(l),r)}function i(l){return l===41&&n++,s.consume(l),r}}function kx(s,a,t){return n;function n(m){return m===33||m===34||m===39||m===41||m===42||m===44||m===46||m===58||m===59||m===63||m===95||m===126?(s.consume(m),n):m===38?(s.consume(m),i):m===93?(s.consume(m),r):m===60||m===null||bt(m)||Ea(m)?a(m):t(m)}function r(m){return m===null||m===40||m===91||bt(m)||Ea(m)?a(m):n(m)}function i(m){return fr(m)?l(m):t(m)}function l(m){return m===59?(s.consume(m),n):fr(m)?(s.consume(m),l):t(m)}}function Cx(s,a,t){return n;function n(i){return s.consume(i),r}function r(i){return Hn(i)?t(i):a(i)}}function Ic(s){return s===null||s===40||s===42||s===95||s===91||s===93||s===126||bt(s)}function Rc(s){return!fr(s)}function qc(s){return!(s===47||Un(s))}function Un(s){return s===43||s===45||s===46||s===95||Hn(s)}function il(s){let a=s.length,t=!1;for(;a--;){const n=s[a][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){t=!0;break}if(n._gfmAutolinkLiteralWalkedInto){t=!1;break}}return s.length>0&&!t&&(s[s.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),t}const Px={tokenize:Ix,partial:!0};function Fx(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Ex,continuation:{tokenize:Dx},exit:Mx}},text:{91:{name:"gfmFootnoteCall",tokenize:Lx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Ax,resolveTo:Tx}}}}function Ax(s,a,t){const n=this;let r=n.events.length;const i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let l;for(;r--;){const o=n.events[r][1];if(o.type==="labelImage"){l=o;break}if(o.type==="gfmFootnoteCall"||o.type==="labelLink"||o.type==="label"||o.type==="image"||o.type==="link")break}return m;function m(o){if(!l||!l._balanced)return t(o);const h=wr(n.sliceSerialize({start:l.end,end:n.now()}));return h.codePointAt(0)!==94||!i.includes(h.slice(1))?t(o):(s.enter("gfmFootnoteCallLabelMarker"),s.consume(o),s.exit("gfmFootnoteCallLabelMarker"),a(o))}}function Tx(s,a){let t=s.length;for(;t--;)if(s[t][1].type==="labelImage"&&s[t][0]==="enter"){s[t][1];break}s[t+1][1].type="data",s[t+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},s[t+3][1].start),end:Object.assign({},s[s.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},s[t+3][1].end),end:Object.assign({},s[t+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},s[s.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},m=[s[t+1],s[t+2],["enter",n,a],s[t+3],s[t+4],["enter",r,a],["exit",r,a],["enter",i,a],["enter",l,a],["exit",l,a],["exit",i,a],s[s.length-2],s[s.length-1],["exit",n,a]];return s.splice(t,s.length-t+1,...m),s}function Lx(s,a,t){const n=this,r=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i=0,l;return m;function m(d){return s.enter("gfmFootnoteCall"),s.enter("gfmFootnoteCallLabelMarker"),s.consume(d),s.exit("gfmFootnoteCallLabelMarker"),o}function o(d){return d!==94?t(d):(s.enter("gfmFootnoteCallMarker"),s.consume(d),s.exit("gfmFootnoteCallMarker"),s.enter("gfmFootnoteCallString"),s.enter("chunkString").contentType="string",h)}function h(d){if(i>999||d===93&&!l||d===null||d===91||bt(d))return t(d);if(d===93){s.exit("chunkString");const y=s.exit("gfmFootnoteCallString");return r.includes(wr(n.sliceSerialize(y)))?(s.enter("gfmFootnoteCallLabelMarker"),s.consume(d),s.exit("gfmFootnoteCallLabelMarker"),s.exit("gfmFootnoteCall"),a):t(d)}return bt(d)||(l=!0),i++,s.consume(d),d===92?N:h}function N(d){return d===91||d===92||d===93?(s.consume(d),i++,h):h(d)}}function Ex(s,a,t){const n=this,r=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i,l=0,m;return o;function o(x){return s.enter("gfmFootnoteDefinition")._container=!0,s.enter("gfmFootnoteDefinitionLabel"),s.enter("gfmFootnoteDefinitionLabelMarker"),s.consume(x),s.exit("gfmFootnoteDefinitionLabelMarker"),h}function h(x){return x===94?(s.enter("gfmFootnoteDefinitionMarker"),s.consume(x),s.exit("gfmFootnoteDefinitionMarker"),s.enter("gfmFootnoteDefinitionLabelString"),s.enter("chunkString").contentType="string",N):t(x)}function N(x){if(l>999||x===93&&!m||x===null||x===91||bt(x))return t(x);if(x===93){s.exit("chunkString");const g=s.exit("gfmFootnoteDefinitionLabelString");return i=wr(n.sliceSerialize(g)),s.enter("gfmFootnoteDefinitionLabelMarker"),s.consume(x),s.exit("gfmFootnoteDefinitionLabelMarker"),s.exit("gfmFootnoteDefinitionLabel"),y}return bt(x)||(m=!0),l++,s.consume(x),x===92?d:N}function d(x){return x===91||x===92||x===93?(s.consume(x),l++,N):N(x)}function y(x){return x===58?(s.enter("definitionMarker"),s.consume(x),s.exit("definitionMarker"),r.includes(i)||r.push(i),sa(s,u,"gfmFootnoteDefinitionWhitespace")):t(x)}function u(x){return a(x)}}function Dx(s,a,t){return s.check(uo,a,s.attempt(Px,a,t))}function Mx(s){s.exit("gfmFootnoteDefinition")}function Ix(s,a,t){const n=this;return sa(s,r,"gfmFootnoteDefinitionIndent",5);function r(i){const l=n.events[n.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?a(i):t(i)}}function Rx(s){let t=(s||{}).singleTilde;const n={name:"strikethrough",tokenize:i,resolveAll:r};return t==null&&(t=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(l,m){let o=-1;for(;++o<l.length;)if(l[o][0]==="enter"&&l[o][1].type==="strikethroughSequenceTemporary"&&l[o][1]._close){let h=o;for(;h--;
vendor: 5,613 bytes, line 245
245)if(l[h][0]==="exit"&&l[h][1].type==="strikethroughSequenceTemporary"&&l[h][1]._open&&l[o][1].end.offset-l[o][1].start.offset===l[h][1].end.offset-l[h][1].start.offset){l[o][1].type="strikethroughSequence",l[h][1].type="strikethroughSequence";const N={type:"strikethrough",start:Object.assign({},l[h][1].start),end:Object.assign({},l[o][1].end)},d={type:"strikethroughText",start:Object.assign({},l[h][1].end),end:Object.assign({},l[o][1].start)},y=[["enter",N,m],["enter",l[h][1],m],["exit",l[h][1],m],["enter",d,m]],u=m.parser.constructs.insideSpan.null;u&&dn(y,y.length,0,mo(u,l.slice(h+1,o),m)),dn(y,y.length,0,[["exit",d,m],["enter",l[o][1],m],["exit",l[o][1],m],["exit",N,m]]),dn(l,h-1,o-h+3,y),o=h+y.length-2;break}}for(o=-1;++o<l.length;)l[o][1].type==="strikethroughSequenceTemporary"&&(l[o][1].type="data");return l}function i(l,m,o){const h=this.previous,N=this.events;let d=0;return y;function y(x){return h===126&&N[N.length-1][1].type!=="characterEscape"?o(x):(l.enter("strikethroughSequenceTemporary"),u(x))}function u(x){const g=Br(h);if(x===126)return d>1?o(x):(l.consume(x),d++,u);if(d<2&&!t)return o(x);const f=l.exit("strikethroughSequenceTemporary"),_=Br(x);return f._open=!_||_===2&&!!g,f._close=!g||g===2&&!!_,m(x)}}}class qx{constructor(){this.map=[]}add(a,t,n){$x(this,a,t,n)}consume(a){if(this.map.sort(function(i,l){return i[0]-l[0]}),this.map.length===0)return;let t=this.map.length;const n=[];for(;t>0;)t-=1,n.push(a.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),a.length=this.map[t][0];n.push(a.slice()),a.length=0;let r=n.pop();for(;r;){for(const i of r)a.push(i);r=n.pop()}this.map.length=0}}function $x(s,a,t,n){let r=0;if(!(t===0&&n.length===0)){for(;r<s.map.length;){if(s.map[r][0]===a){s.map[r][1]+=t,s.map[r][2].push(...n);return}r+=1}s.map.push([a,t,n])}}function Ox(s,a){let t=!1;const n=[];for(;a<s.length;){const r=s[a];if(t){if(r[0]==="enter")r[1].type==="tableContent"&&n.push(s[a+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(s[a-1][1].type==="tableDelimiterMarker"){const i=n.length-1;n[i]=n[i]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(t=!0);a+=1}return n}function Ux(){return{flow:{null:{name:"table",tokenize:Bx,resolveAll:zx}}}}function Bx(s,a,t){const n=this;let r=0,i=0,l;return m;function m(C){let O=n.events.length-1;for(;O>-1;){const D=n.events[O][1].type;if(D==="lineEnding"||D==="linePrefix")O--;else break}const $=O>-1?n.events[O][1].type:null,z=$==="tableHead"||$==="tableRow"?p:o;return z===p&&n.parser.lazy[n.now().line]?t(C):z(C)}function o(C){return s.enter("tableHead"),s.enter("tableRow"),h(C)}function h(C){return C===124||(l=!0,i+=1),N(C)}function N(C){return C===null?t(C):mr(C)?i>1?(i=0,n.interrupt=!0,s.exit("tableRow"),s.enter("lineEnding"),s.consume(C),s.exit("lineEnding"),u):t(C):ka(C)?sa(s,N,"whitespace")(C):(i+=1,l&&(l=!1,r+=1),C===124?(s.enter("tableCellDivider"),s.consume(C),s.exit("tableCellDivider"),l=!0,N):(s.enter("data"),d(C)))}function d(C){return C===null||C===124||bt(C)?(s.exit("data"),N(C)):(s.consume(C),C===92?y:d)}function y(C){return C===92||C===124?(s.consume(C),d):d(C)}function u(C){return n.interrupt=!1,n.parser.lazy[n.now().line]?t(C):(s.enter("tableDelimiterRow"),l=!1,ka(C)?sa(s,x,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):x(C))}function x(C){return C===45||C===58?f(C):C===124?(l=!0,s.enter("tableCellDivider"),s.consume(C),s.exit("tableCellDivider"),g):c(C)}function g(C){return ka(C)?sa(s,f,"whitespace")(C):f(C)}function f(C){return C===58?(i+=1,l=!0,s.enter("tableDelimiterMarker"),s.consume(C),s.exit("tableDelimiterMarker"),_):C===45?(i+=1,_(C)):C===null||mr(C)?j(C):c(C)}function _(C){return C===45?(s.enter("tableDelimiterFiller"),k(C)):c(C)}function k(C){return C===45?(s.consume(C),k):C===58?(l=!0,s.exit("tableDelimiterFiller"),s.enter("tableDelimiterMarker"),s.consume(C),s.exit("tableDelimiterMarker"),b):(s.exit("tableDelimiterFiller"),b(C))}function b(C){return ka(C)?sa(s,j,"whitespace")(C):j(C)}function j(C){return C===124?x(C):C===null||mr(C)?!l||r!==i?c(C):(s.exit("tableDelimiterRow"),s.exit("tableHead"),a(C)):c(C)}function c(C){return t(C)}function p(C){return s.enter("tableRow"),w(C)}function w(C){return C===124?(s.enter("tableCellDivider"),s.consume(C),s.exit("tableCellDivider"),w):C===null||mr(C)?(s.exit("tableRow"),a(C)):ka(C)?sa(s,w,"whitespace")(C):(s.enter("data"),S(C))}function S(C){return C===null||C===124||bt(C)?(s.exit("data"),w(C)):(s.consume(C),C===92?P:S)}function P(C){return C===92||C===124?(s.consume(C),S):S(C)}}function zx(s,a){let t=-1,n=!0,r=0,i=[0,0,0,0],l=[0,0,0,0],m=!1,o=0,h,N,d;const y=new qx;for(;++t<s.length;){const u=s[t],x=u[1];u[0]==="enter"?x.type==="tableHead"?(m=!1,o!==0&&(El(y,a,o,h,N),N=void 0,o=0),h={type:"table",start:Object.assign({},x.start),end:Object.assign({},x.end)},y.add(t,0,[["enter",h,a]])):x.type==="tableRow"||x.type==="tableDelimiterRow"?(n=!0,d=void 0,i=[0,0,0,0],l=[0,t+1,0,0],m&&(m=!1,N={type:"tableBody",start:Object.assign({},x.start),end:Object.assign({},x.end)},y.add(t,0,[["enter",N,a]])),r=x.type==="tableDelimiterRow"?2:N?3:1):r&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")?(n=!1,l[2]===0&&(i[1]!==0&&(l[0]=l[1],d=Fr(y,a,i,r,void 0,d),i=[0,0,0,0]),l[2]=t)):x.type==="tableCellDivider"&&(n?n=!1:(i[1]!==0&&(l[0]=l[1],d=Fr(y,a,i,r,void 0,d)),i=l,l=[i[1],t,0,0])):x.type==="tableHead"?(m=!0,o=t):x.type==="tableRow"||x.type==="tableDelimiterRow"?(o=t,i[1]!==0?(l[0]=l[1],d=Fr(y,a,i,r,t,d)):l[1]!==0&&(
245d=Fr(y,a,l,r,t,d)),r=0):r&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")&&(l[3]=t)}for(o!==0&&El(y,a,o,h,N),y.consume(a.events),t=-1;++t<a.events.length;){const u=a.events[t];u[0]==="enter"&&u[1].type==="table"&&(u[1]._align=Ox(a.events,t))}return s}function Fr(s,a,t,n,r,i){const l=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",m="tableContent";t[0]!==0&&(i.end=Object.assign({},Ca(a.events,t[0])),s.add(t[0],0,[["exit",i,a]]));const o=Ca(a.events,t[1]);if(i={type:l,start:Object.assign({},o),end:Object.assign({},o)},s.add(t[1],0,[["enter",i,a]]),t[2]!==0){const h=Ca(a.events,t[2]),N=Ca(a.events,t[3]),d={type:m,start:Object.assign({},h),end:Object.assign({},N)};if(s.add(t[2],0,[["enter",d,a]]),n!==2){const y=a.events[t[2]],u=a.events[t[3]];if(y[1].end=Object.assign({},u[1].end),y[1].type="chunkText",y[1].contentType="text",t[3]>t[2]+1){const x=t[2]+1,g=t[3]-t[2]-1;s.add(x,g,[])}}s.add(t[3]+1,0,[["exit",d,a]])}return r!==void 0&&(i.end=Object.assign({},Ca(a.events,r)),s.add(r,0,[["exit",i,a]]),i=void 0),i}function El(s,a,t,n,r){const i=[],l=Ca(a.events,t);r&&(r.end=Object.assign({},l),i.push(["exit",r,a])),n.end=Object.assign({},l),i.push(["exit",n,a]),s.add(t+1,0,i)}function Ca(s,a){const t=s[a],n=t[0]==="enter"?"start":"end";return t[1][n]}const Kx={name:"tasklistCheck",tokenize:Hx};function Vx(){return{text:{91:Kx}}}function Hx(s,a,t){const n=this;return r;function r(o){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?t(o):(s.enter("taskListCheck"),s.enter("taskListCheckMarker"),s.consume(o),s.exit("taskListCheckMarker"),i)}function i(o){return bt(o)?(s.enter("taskListCheckValueUnchecked"),s.consume(o),s.exit("taskListCheckValueUnchecked"),l):o===88||o===120?(s.enter("taskListCheckValueChecked"),s.consume(o),s.exit("taskListCheckValueChecked"),l):t(o)}function l(o){return o===93?(s.enter("taskListCheckMarker"),s.consume(o),s.exit("taskListCheckMarker"),s.exit("taskListCheck"),m):t(o)}function m(o){return mr(o)?a(o):ka(o)?s.check({tokenize:Wx},a,t)(o):t(o)}}function Wx(s,a,t){return sa(s,n,"whitespace");function n(r){return r===null?t(r):a(r)}}function Gx(s){return xo([vx(),Fx(),Rx(s),Ux(),Vx()])}const Qx={};function Yx(s){const a=this,t=s||Qx,n=a.data(),r=n.micromarkExtensions||(n.micromarkExtensions=[]),i=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),l=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);r.push(Gx(t)),i.push(px()),l.push(gx(t))}const Jx=[{label:"Daily audit",prompt:"Run a complete KLUTCH audit for the last 7 days. Check tier WR, trigger health, engine drift, v3 diagnostics. Highlight anything below threshold and propose fixes.",icon:ft},{label:"CORE health",prompt:"How is CORE performing in the last 7 days? Break down by sport and market. Compare to the last 30 days.",icon:_t},{label:"Trigger drift",prompt:"Show me trigger types with the worst win-rates over the last 14 days (min n=20). Propose overlay fixes for the worst offenders.",icon:ls},{label:"v3 gate report",prompt:"Pull the last 10 v3 diagnostics rows. Tell me why v3 is dropping candidates and recommend gate adjustments.",icon:Yn},{label:"Module overlays",prompt:"List all active and shadow module overlays. Tell me which ones look outdated or wrong based on current trigger health.",icon:xr},{label:"Confidence bands",prompt:"Show win-rate by 1pt confidence band for the last 14 days. Should we change the CORE confidence floor?",icon:it},{label:"Spread readiness",prompt:"Is the spread module ready for re-enable? Compare paused spread_v1.0 module performance to legacy spread WR over the last 14 days.",icon:Sr}];function Zx({onPick:s}){return e.jsx("div",{className:"flex flex-wrap gap-2",children:Jx.map(({label:a,prompt:t,icon:n})=>e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>s(t),className:"text-xs h-8",children:[e.jsx(n,{className:"h-3.5 w-3.5 mr-1.5"}),a]},a))})}function Xx({conversationId:s,messages:a,isStreaming:t,streamingText:n,activeTools:r,send:i,stop:l,onNewChat:m}){const[o,h]=v.useState(""),[N,d]=v.useState(!1),y=v.useRef(null),u=v.useRef(!1),x=v.useRef(0);v.useEffect(()=>{u.current=!1,x.current=0},[s]),v.useEffect(()=>{const f=y.current;if(!f)return;const _=!u.current&&a.length>0,k=Math.abs(a.length-x.current)>1,b=_||k?"auto":"smooth";f.scrollTo({top:f.scrollHeight,behavior:b}),a.length>0&&(u.current=!0),x.current=a.length},[a,n]);const g=()=>{!o.trim()||t||(i(o.trim()),h(""))};return e.jsxs("div",{className:"flex flex-col h-full min-h-[400px]",children:[m&&e.jsx("div",{className:"flex items-center justify-end pb-2 shrink-0",children:e.jsxs(R,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:m,disabled:t,children:[e.jsx(Zs,{className:"h-3.5 w-3.5 mr-1"}),"New chat"]})}),e.jsx("div",{ref:y,className:"flex-1 overflow-y-auto pr-3",children:e.jsxs("div",{className:"space-y-4 py-2",children:[a.length===0&&!n&&e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx("p",{className:"text-sm",children:"Ask the KLUTCH Analyst anything about pick performance, trigger drift, engine health, or module overlays."}),e.jsx("p",{className:"text-xs mt-2",children:"Or open Quick prompts below."})]}),a.filter(f=>f.role!=="tool"&&(f.content||f.tool_calls)).map((f,_)=>e.jsx(Ml,{role:f.role,content:f.content||"",toolCalls:f.tool_calls},_)),t&&r.length>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground pl-2",children:[e.jsx(ne,{className:"h-3.5 w-3.5 animate-spin"}),e.jsx("span",{children:"Running tools:"}),r.map(f=>e.jsxs(B,{variant:"outline",className:"text-[10px]",children:[e.jsx(ga,{className:"h-2.5 w-2.5 mr-1"}),f]},f))]}),n&&e.jsx(Ml,{role:"assistant",content:n,streaming:!0})]})}),e.jsxs("div",{className:"border-t pt-3 space-y-2 shrink-0",children:[e.jsxs(vs,{open:N,onOpenChange:d,children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(ft,{className:"h-3.5 w-3.5 mr-1.5"}),"Quick prompts",e.jsx(Ns,{className:Le("h-3.5 w-3.5 ml-1 transition-transform",N&&"rotate-180")}
245)]})}),e.jsx(_s,{className:"pt-2",children:e.jsx(Zx,{onPick:f=>{h(f),d(!1)}})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Xs,{value:o,onChange:f=>h(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),g())},placeholder:"Ask about KLUTCH performance, trigger health, overlays...",rows:2,className:"resize-none text-sm",disabled:t||!s}),t?e.jsx(R,{onClick:l,variant:"outline",size:"icon",className:"h-auto",children:e.jsx(To,{className:"h-4 w-4"})}):e.jsx(R,{onClick:g,disabled:!o.trim()||!s,size:"icon",className:"h-auto",children:e.jsx(ut,{className:"h-4 w-4"})})]})]})]})}function Nn(s){let a=s.trim();return a.startsWith("|")&&(a=a.slice(1)),a.endsWith("|")&&(a=a.slice(0,-1)),a.split("|").map(t=>t.trim())}function eh(s){if(!s)return[];const a=s.split(`
246`),t=[];for(let n=0;n<a.length-1;n++){const r=a[n],i=a[n+1];if(!r.includes("|")||!i.includes("|"))continue;const l=Nn(i);if(!(l.length>=1&&l.every(d=>/^:?-{2,}:?$/.test(d))))continue;const o=Nn(r);if(o.length!==l.length)continue;const h=[];let N=n+2;for(;N<a.length;){const d=a[N];if(!d.trim()||!d.includes("|"))break;const y=Nn(d);for(;y.length<o.length;)y.push("");h.push(y.slice(0,o.length)),N++}t.push({headers:o,rows:h}),n=N-1}return t}function Dl(s){if(s==null)return"";const a=String(s);return/[",\r\n]/.test(a)?`"${a.replace(/"/g,'""')}"`:a}function sh(s){const a=[s.headers.map(Dl).join(",")];for(const t of s.rows)a.push(t.map(Dl).join(","));return a.join(`\r
247`)}function th(s,a){const t=new Blob([a],{type:"text/csv;charset=utf-8;"}),n=URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=s,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),0)}function Ml({role:s,content:a,toolCalls:t,streaming:n}){const r=s==="user",i=s==="system",m=!r&&!i&&!n?eh(a):[],o=m.length>0;return e.jsx("div",{className:Le("flex",r?"justify-end":"justify-start"),children:e.jsxs("div",{className:Le("rounded-lg px-3 py-2 text-sm min-w-0",r?"max-w-[88%] bg-primary/15 border border-primary/40 text-foreground":i?"w-full max-w-full bg-accent/50 border border-accent":o?"w-full max-w-full bg-muted":"max-w-[88%] bg-muted"),children:[i&&e.jsx("div",{className:"text-xs uppercase text-muted-foreground mb-1",children:"System"}),e.jsx("div",{className:Le("prose prose-sm dark:prose-invert max-w-none","[&_p]:my-1 [&_ul]:my-1 [&_ol]:my-1 [&_pre]:text-xs","[&_table]:block [&_table]:w-max [&_table]:min-w-full [&_table]:overflow-x-auto","[&_table]:text-xs [&_th]:px-2 [&_td]:px-2 [&_th]:py-1 [&_td]:py-1","[&_th]:border-b [&_td]:border-b [&_thead]:bg-muted/40 [&_th]:text-left [&_th]:font-semibold","[&_td]:whitespace-nowrap [&_th]:whitespace-nowrap"),children:e.jsx(ho,{remarkPlugins:[Yx],children:a||(n?"…":"")})}),o&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:m.map((h,N)=>{const d=m.length===1?"Download CSV":`Download table ${N+1}`,y=`klutch-analyst-table-${N+1}-${Date.now()}.csv`;return e.jsxs(R,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>th(y,sh(h)),children:[e.jsx(Gt,{className:"h-3.5 w-3.5 mr-1.5"}),d]},N)})}),t&&t.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:t.map((h,N)=>{var d;return e.jsxs(B,{variant:"outline",className:"text-[10px]",children:[e.jsx(ga,{className:"h-2.5 w-2.5 mr-1"}),(d=h.function)==null?void 0:d.name]},N)})})]})})}function ah(s){const a=Date.now(),t=new Date(s).getTime(),n=Math.max(0,a-t),r=Math.floor(n/6e4);if(r<1)return"now";if(r<60)return`${r}m`;const i=Math.floor(r/60);if(i<24)return`${i}h`;const l=Math.floor(i/24);return l<7?`${l}d`:new Date(s).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Il({conversations:s,activeId:a,onSelect:t,onNew:n,onRename:r,onDelete:i}){const[l,m]=v.useState(null),[o,h]=v.useState(""),[N,d]=v.useState(null),y=x=>{m(x),h(x.title)},u=()=>{l&&r(l.id,o),m(null)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pb-3 border-b shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"text-sm font-semibold",children:"Chats"})]}),e.jsxs(R,{size:"sm",variant:"default",className:"h-7 text-xs",onClick:n,children:[e.jsx(Zs,{className:"h-3.5 w-3.5 mr-1"}),"New"]})]}),e.jsx(cs,{className:"flex-1 -mr-2 pr-2",children:s.length===0?e.jsx("div",{className:"text-center py-8 text-xs text-muted-foreground",children:"No chats yet."}):e.jsx("div",{className:"space-y-1",children:s.map(x=>e.jsxs("div",{className:Le("group relative rounded-md border border-transparent hover:bg-accent/60 transition-colors",x.id===a&&"bg-accent border-border"),children:[e.jsxs("button",{type:"button",onClick:()=>t(x.id),className:"w-full text-left px-2 py-2 pr-8 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium truncate",title:x.title,children:x.title||"Untitled"}),e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:ah(x.last_message_at)})]}),e.jsxs(zr,{children:[e.jsx(Kr,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"icon",className:"absolute right-1 top-1 h-6 w-6 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100",onClick:g=>g.stopPropagation(),children:e.jsx(Yr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Vr,{align:"end",className:"w-36",children:[e.jsxs(ht,{onClick:()=>y(x),children:[e.jsx(va,{className:"h-3.5 w-3.5 mr-2"}),"Rename"]}),e.jsxs(ht,{onClick:()=>d(x),className:"text-destructive focus:text-destructive",children:[e.jsx(os,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]},x.id))})})]}),e.jsx(Ue,{open:!!l,onOpenChange:x=>!x&&m(null),children:e.jsxs(Be,{className:"sm:max-w-sm",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Rename chat"})}),e.jsx(pe,{value:o,onChange:x=>h(x.target.value),onKeyDown:x=>{x.key==="Enter"&&u()},autoFocus:!0,maxLength:80}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(R,{onClick:u,children:"Save"})]})]})}),e.jsx(ws,{open:!!N,onOpenChange:x=>!x&&d(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete chat?"}),e.jsxs(Ps,{children:['This permanently deletes "',N==null?void 0:N.title,'" and all of its messages. Proposals already created from this chat are preserved.']})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>{N&&i(N.id),d(null)},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function Rl(s="pending",a="analyst"){return ge({queryKey:["klutch-ai-proposals",s,a],queryFn:async()=>{let t=T.from("klutch_policy_proposals").select("*").order("created_at",{ascending:!1}).limit(50);s!=="all"&&(t=t.eq("status",s)),a!=="all"&&(t=t.eq("source_loop",a));const{data:n,error:r}=await t;if(r)throw r;return n||[]},refetchInterval:3e4})}function rh(){const s=Me();return _e({mutationFn:async({proposal_id:a,action:t,note:n})=>{const{data:r,error:i}=await T.functions.invoke("klutch-apply-proposal",{body:{proposal_id:a,action:t,note:n}});if(i)throw i;if(r!=null&&r.error)throw new Error(r.error);return r},onSuccess:(a,t)=>{K.success(t.action==="apply"?"Proposal applied":"Proposal dismissed"),s.invalidateQueries({queryKey:["klutch-ai-proposals"]}),s.invalidateQueries({queryKey:["policy-lab-proposals"]})},onError:a=>K.error((a==null?void 0:a.message)||"Failed")})}const nh={add_overlay:"Add Overlay",update_overlay:"Update Overlay",toggle_module:"Toggle Module",update_engine_rule:"Update Engine Rule",gate_tuning:"Gate Tuning",signal_weight:"Signal Weight",note_only:"Note O
247nly"},lh={high:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",medium:"bg-amber-500/10 text-amber-600 border-amber-500/20",low:"bg-muted text-muted-foreground border-muted"};function ql({proposal:s}){const a=rh(),t=s.status==="pending";return e.jsxs(G,{className:"p-3 space-y-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx(B,{variant:"secondary",className:"text-[10px]",children:nh[s.proposal_type]||s.proposal_type}),e.jsx(ih,{status:s.status}),s.confidence&&e.jsx(B,{variant:"outline",className:`text-[10px] ${lh[s.confidence]||""}`,children:s.confidence})]}),e.jsx("p",{className:"text-sm font-medium leading-tight",children:s.title})]})}),s.rationale&&e.jsx("p",{className:"text-xs text-muted-foreground leading-snug line-clamp-3",children:s.rationale}),e.jsxs("details",{className:"text-xs",children:[e.jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground",children:"View payload"}),e.jsx("pre",{className:"mt-1 p-2 bg-muted rounded overflow-auto text-[10px]",children:JSON.stringify(s.payload,null,2)})]}),t&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(R,{size:"sm",className:"h-7 text-xs flex-1",onClick:()=>a.mutate({proposal_id:s.id,action:"apply"}),disabled:a.isPending,children:[e.jsx(rs,{className:"h-3.5 w-3.5 mr-1"})," Apply"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>a.mutate({proposal_id:s.id,action:"dismiss"}),disabled:a.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Dismiss"]})]}),s.apply_result&&Object.keys(s.apply_result).length>0&&e.jsxs("div",{className:"text-[10px] text-muted-foreground border-t pt-1",children:["Applied: ",e.jsx("code",{className:"text-[10px]",children:Object.keys(s.apply_result)[0]})]}),s.dismissed_note&&e.jsxs("div",{className:"text-[10px] text-muted-foreground border-t pt-1",children:["Note: ",e.jsx("span",{className:"italic",children:s.dismissed_note})]})]})}function ih({status:s}){const a={pending:{icon:$s,cls:"bg-amber-500/10 text-amber-600 border-amber-500/20"},simulating:{icon:$s,cls:"bg-blue-500/10 text-blue-600 border-blue-500/20"},approved:{icon:rs,cls:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20"},applied:{icon:rs,cls:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20"},dismissed:{icon:Is,cls:"bg-muted text-muted-foreground"},rejected:{icon:Is,cls:"bg-red-500/10 text-red-600 border-red-500/20"},superseded:{icon:xs,cls:"bg-muted text-muted-foreground"}},{icon:t,cls:n}=a[s]||a.pending;return e.jsxs(B,{variant:"outline",className:`text-[10px] ${n}`,children:[e.jsx(t,{className:"h-3 w-3 mr-1"}),s]})}const sr="KLUTCH Analyst";function ch(s){const[a,t]=v.useState([]),[n,r]=v.useState(null),[i,l]=v.useState([]),[m,o]=v.useState(!1),[h,N]=v.useState(""),[d,y]=v.useState([]),u=v.useRef(null),x=Me(),g=v.useCallback(async()=>{if(!s)return[];const{data:p}=await T.from("klutch_ai_conversations").select("id, title, last_message_at, created_at").eq("super_admin_id",s).order("last_message_at",{ascending:!1}).limit(100),w=p||[];return t(w),w},[s]);v.useEffect(()=>{s&&(async()=>{const p=await g();if(p.length>0)r(w=>w??p[0].id);else{const{data:w}=await T.from("klutch_ai_conversations").insert({super_admin_id:s,title:sr}).select("id, title, last_message_at, created_at").single();w&&(t([w]),r(w.id))}})()},[s,g]),v.useEffect(()=>{if(!n){l([]);return}(async()=>{const{data:p}=await T.from("klutch_ai_messages").select("*").eq("conversation_id",n).order("created_at").limit(200);l(p||[])})()},[n]);const f=v.useCallback(p=>{var w;m&&((w=u.current)==null||w.abort()),l([]),N(""),y([]),r(p)},[m]),_=v.useCallback(async p=>{if(!s)return null;const{data:w,error:S}=await T.from("klutch_ai_conversations").insert({super_admin_id:s,title:p||sr}).select("id, title, last_message_at, created_at").single();return S||!w?(K.error("Failed to create new chat"),null):(t(P=>[w,...P]),l([]),N(""),y([]),r(w.id),w.id)},[s]),k=v.useCallback(async(p,w)=>{const S=w.trim().slice(0,80)||sr,{error:P}=await T.from("klutch_ai_conversations").update({title:S}).eq("id",p);if(P){K.error("Rename failed");return}t(C=>C.map(O=>O.id===p?{...O,title:S}:O))},[]),b=v.useCallback(async p=>{const{error:w}=await T.from("klutch_ai_conversations").delete().eq("id",p);if(w){K.error("Delete failed");return}t(S=>{const P=S.filter(C=>
247C.id!==p);return p===n&&(P.length>0?(l([]),r(P[0].id)):(r(null),s&&T.from("klutch_ai_conversations").insert({super_admin_id:s,title:sr}).select("id, title, last_message_at, created_at").single().then(({data:C})=>{C&&(t([C]),r(C.id))}))),P}),K.success("Chat deleted")},[n,s]),j=v.useCallback(async p=>{if(!n||!p.trim()||m)return;const w=i.length===0,S=a.find(C=>C.id===n);if(w&&S&&(!S.title||S.title===sr)){const C=p.trim().slice(0,60);T.from("klutch_ai_conversations").update({title:C}).eq("id",n).then(()=>{t(O=>O.map($=>$.id===n?{...$,title:C}:$))})}l(C=>[...C,{role:"user",content:p}]),o(!0),N(""),y([]);const P=new AbortController;u.current=P;try{const{data:{session:C}}=await T.auth.getSession();if(!C)throw new Error("Not authenticated");const $=await fetch("https://qqamfojeypfnjezyofqc.supabase.co/functions/v1/klutch-analyst-chat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.access_token}`},body:JSON.stringify({conversation_id:n,message:p}),signal:P.signal});if(!$.ok||!$.body){const E=await $.text();throw new Error(`Stream failed: ${$.status} ${E.slice(0,200)}`)}const z=$.body.getReader(),D=new TextDecoder;let A="",F="";for(;;){const{done:E,value:L}=await z.read();if(E)break;A+=D.decode(L,{stream:!0});let H;for(;(H=A.indexOf(`
248`))!==-1;){let Z=A.slice(0,H);if(A=A.slice(H+1),Z.endsWith("\r")&&(Z=Z.slice(0,-1)),!!Z.startsWith("data: "))try{const se=JSON.parse(Z.slice(6).trim());se.type==="token"?(F+=se.content,N(F)):se.type==="tools_start"?y(se.tools||[]):se.type==="tool_result"?y(ie=>ie.filter(Y=>Y!==se.name)):se.type==="error"?K.error(se.message):se.type}catch{}}}const{data:q}=await T.from("klutch_ai_messages").select("*").eq("conversation_id",n).order("created_at").limit(200);l(q||[]),N(""),y([]),x.invalidateQueries({queryKey:["klutch-ai-proposals"]}),g()}catch(C){C.name!=="AbortError"&&K.error((C==null?void 0:C.message)||"Chat failed")}finally{o(!1),u.current=null}},[n,m,i.length,a,x,g]),c=v.useCallback(()=>{var p;return(p=u.current)==null?void 0:p.abort()},[]);return{conversationId:n,conversations:a,messages:i,isStreaming:m,streamingText:h,activeTools:d,send:j,stop:c,selectConversation:f,newConversation:_,renameConversation:k,deleteConversation:b}}function oh(){var d,y,u,x;const[s,a]=v.useState(null),[t,n]=v.useState(!0),[r,i]=v.useState(!1),l=Rl("pending"),m=Rl("all"),o=ch(s);if(v.useEffect(()=>{(async()=>{const{data:{user:g}}=await T.auth.getUser();if(!g){n(!1);return}const{data:f}=await T.from("user_roles").select("role").eq("user_id",g.id).eq("role","super_admin").maybeSingle();f&&a(g.id),n(!1)})()},[]),t)return e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(ne,{className:"h-6 w-6 animate-spin"})});if(!s)return e.jsx("div",{className:"p-6 text-center text-muted-foreground",children:"Super admin role required."});const h=()=>{o.newConversation(),i(!1)},N=g=>{o.selectConversation(g),i(!1)};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[220px_1fr_340px] gap-4 h-[calc(100vh-220px)] min-h-[600px]",children:[e.jsx(G,{className:"hidden lg:flex p-3 flex-col overflow-hidden",children:e.jsx(Il,{conversations:o.conversations,activeId:o.conversationId,onSelect:N,onNew:h,onRename:o.renameConversation,onDelete:o.deleteConversation})}),e.jsxs(G,{className:"p-4 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 pb-3 border-b",children:[e.jsxs(rd,{open:r,onOpenChange:i,children:[e.jsx(nd,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"icon",className:"h-8 w-8 lg:hidden",children:e.jsx(St,{className:"h-4 w-4"})})}),e.jsxs(ld,{side:"left",className:"w-72 p-4",children:[e.jsx(id,{className:"mb-3",children:e.jsx(cd,{className:"text-sm",children:"Chats"})}),e.jsx("div",{className:"h-[calc(100vh-100px)]",children:e.jsx(Il,{conversations:o.conversations,activeId:o.conversationId,onSelect:N,onNew:h,onRename:o.renameConversation,onDelete:o.deleteConversation})})]})]}),e.jsx(it,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"KLUTCH Analyst"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto hidden sm:inline",children:"AI-powered diagnostic chat"})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Xx,{conversationId:o.conversationId,messages:o.messages,isStreaming:o.isStreaming,streamingText:o.streamingText,activeTools:o.activeTools,send:o.send,stop:o.stop,onNewChat:h})})]}),e.jsxs(G,{className:"p-4 flex flex-col overflow-hidden",children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Insights & Actions"}),e.jsxs(js,{defaultValue:"pending",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(fs,{className:"grid grid-cols-2 mb-3",children:[e.jsxs(Ne,{value:"pending",children:["Pending ",(d=l.data)!=null&&d.length?`(${l.data.length})`:""]}),e.jsx(Ne,{value:"history",children:"History"})]}),e.jsx(we,{value:"pending",className:"flex-1 overflow-hidden mt-0",children:e.jsx(cs,{className:"h-full pr-2",children:l.isLoading?e.jsx("div",{className:"text-center py-8",children:e.jsx(ne,{className:"h-4 w-4 animate-spin mx-auto"})}):((y=l.data)==null?void 0:y.length)===0?e.jsxs("div",{className:"text-center py-8 text-xs text-muted-foreground",children:["No pending proposals.",e.jsx("br",{}),"Ask the AI for recommendations."]}):e.jsx("div",{className:"space-y-2",children:(u=l.data)==null?void 0:u.map(g=>e.jsx(ql,{proposal:g},g.id))})})}),e.jsx(we,{value:"history",className:"flex-1 overflow-hidden mt-0",children:e.jsx(cs,{className:"h-full pr-2",children:m.isLoading?e.jsx("div",{className:"text-center py-8",children:e.jsx(ne,{className:"h-4 w-4 animate-spin mx-auto"})}):e.jsx("div",{className:"space-y-2",children:(x=m.data)==null?void 0:x.filter(g=>g.status!=="pending").map(g=>e.jsx(ql,{proposal:g},g.id))})})})]})]})]})}const dh=[{value:7,label:"7d"},{value:30,label:"30d"},{value:90,label:"90d"},{value:"all",label:"All"}];function $c(s){return s==="all"?null:new Date(Date.now()-s*24*60*60*1e3).toISOString()}const uh=new Set(["v1","v1a","v2.5","v2.5a","v3","v3a"]);function mh({windowDays:s="all"}={}){var le,ve;const[a,t]=v.useState("all"),[n,r]=v.useState("all");v.useState(!1),v.useState("v3"),v.useState("core"),v.useState("module_moneyline"),v.useState("lab");const[i,l]=v.useState(!1),[m,o]=v.useState(!1),h=$c(s),N=h?h.slice(0,10):null,d=s!=="all"||a!=="all"||n!=="all",{data:y,isLoading:u,refetch:x,isRefetching:g}=ge({queryKey:["klutch-performance-tracking",m],queryFn:async()=>{const{data:te,error:X}=await T.from("klutch_performance_tracking").select("*");if(X)throw X;const ae=te||[];return m?ae.map(W=>({...W,total_picks:W.total_picks_all??W.total_picks,wins:W.wins_all??W.wins,losses:W.losses_all??W.losses,pushes:W.pushes_all??W.pushes,units_wagered:W.units_wagered_all??W.units_wagered,net_units:W.net_units_all??W.net_units,roi_eligible_picks:W.roi_eligible_picks_all??W.roi_eligible_picks,missing_odds_picks:W.missing_odds_picks_all??W.missing_odds_picks})):ae}}),f=te=>a==="all"?te:a.startsWith("module_")?te.eq("engine_id",a.replace("module_","")):te.eq("generation_version",a),{data:_,isLoading:k,refetch:b,isRefetching:j}=ge({queryKey:["klutch-performance-by-version",a,n,s,m],queryFn:async()=>
248{if(!d)return null;const te=uh.has(a),X=[];let ae=0;const W=1e3;if(te){const ce=new Set;let Pe=0;for(;;){let Ae=T.from("klutch_picks").select("id, sport, pick_type, status, confidence_score, suggested_units, original_odds, settled_at").eq("generation_version",a).in("status",["won","lost","push"]).range(Pe,Pe+W-1);n!=="all"&&(Ae=Ae.eq("tier",n)),N&&(Ae=Ae.gte("game_date",N));const{data:Ve,error:as}=await Ae;if(as)throw as;for(const Oe of Ve||[])ce.add(Oe.id),X.push({sport:Oe.sport,pick_type:Oe.pick_type,status:Oe.status,confidence_score:Number(Oe.confidence_score??0),suggested_units:Number(Oe.suggested_units??1),original_odds:Oe.original_odds,settled_at:Oe.settled_at,_source:!0});if(!Ve||Ve.length<W)break;Pe+=W}let Fe=0;for(;;){let Ae=T.from("klutch_module_finalized_picks").select("sport, pick_type, settled_status, settled_at, candidate, source_version, promoted_pick_id").eq("source_version",a).eq("dropped",!1).in("settled_status",["won","lost","push"]).range(Fe,Fe+W-1);N&&(Ae=Ae.gte("game_date",N));const{data:Ve,error:as}=await Ae;if(as)throw as;for(const Oe of Ve||[]){const Ie=Oe.promoted_pick_id;if(Ie&&ce.has(Ie))continue;const ds=Oe.candidate||{};X.push({sport:Oe.sport??ds.sport,pick_type:Oe.pick_type??ds.pick_type,status:Oe.settled_status,confidence_score:Number(ds.confidence_score??ds.confidence??0),suggested_units:Number(ds.suggested_units??1),original_odds:ds.original_odds,settled_at:Oe.settled_at,_source:!0})}if(!Ve||Ve.length<W)break;Fe+=W}}else for(;;){let ce=T.from("klutch_picks").select("sport, pick_type, status, confidence_score, suggested_units, original_odds, generation_version, engine_id, tier, settled_at").in("status",["won","lost","push"]).range(ae,ae+W-1);ce=f(ce),n!=="all"&&(ce=ce.eq("tier",n)),N&&(ce=ce.gte("game_date",N)),m||(ce=ce.gte("confidence_score",90));const{data:Pe,error:Fe}=await ce;if(Fe)throw Fe;if(X.push(...Pe||[]),!Pe||Pe.length<W)break;ae+=W}const re={};for(const ce of X){if(!ce._source&&!m&&(ce.confidence_score??0)<90)continue;const Pe=ce.sport==="ice-hockey"?"hockey":ce.sport,Fe=`${Pe}|${ce.pick_type}`;re[Fe]||(re[Fe]={id:Fe,sport:Pe,pick_type:ce.pick_type,total_picks:0,wins:0,losses:0,pushes:0,units_wagered:0,net_units:0,roi_eligible_picks:0,missing_odds_picks:0,picks_90_92:0,wins_90_92:0,picks_93_95:0,wins_93_95:0,picks_96_98:0,wins_96_98:0,picks_99_plus:0,wins_99_plus:0,updated_at:new Date().toISOString()});const Ae=re[Fe],Ve=Number(ce.suggested_units||1),as=Wn(ce.status,Ve,ce.original_odds);Ae.total_picks++,ce.status==="won"?Ae.wins++:ce.status==="lost"?Ae.losses++:ce.status==="push"&&Ae.pushes++,as==null?Ae.missing_odds_picks++:(Ae.roi_eligible_picks++,Ae.units_wagered+=Ve,Ae.net_units+=as);const Oe=ce.confidence_score;Oe>=99?(Ae.picks_99_plus++,ce.status==="won"&&Ae.wins_99_plus++):Oe>=96?(Ae.picks_96_98++,ce.status==="won"&&Ae.wins_96_98++):Oe>=93?(Ae.picks_93_95++,ce.status==="won"&&Ae.wins_93_95++):Oe>=90&&(Ae.picks_90_92++,ce.status==="won"&&Ae.wins_90_92++)}return Object.values(re)},enabled:d}),{data:c}=ge({queryKey:["klutch-confidence-trend-picks",a,n,s],queryFn:async()=>{let te=T.from("klutch_picks").select("confidence_score, status, settled_at, game_date, tier, engine_id, generation_version").in("status",["won","lost"]).not("confidence_score","is",null).order("game_date",{ascending:!1}).limit(500);te=f(te),n!=="all"&&(te=te.eq("tier",n)),N&&(te=te.gte("game_date",N));const{data:X,error:ae}=await te;if(ae)throw ae;return X||[]}}),p=v.useMemo(()=>{if(!c)return null;const te={"90-92%":{wins:0,total:0},"93-95%":{wins:0,total:0},"96-98%":{wins:0,total:0},"99+%":{wins:0,total:0}},X={"90-92%":0,"93-95%":0,"96-98%":0,"99+%":0};for(const ae of c){const W=ae.confidence_score;let re=null;W>=99?re="99+%":W>=96?re="96-98%":W>=93?re="93-95%":W>=90&&(re="90-92%"),!(!re||X[re]>=50)&&(X[re]++,te[re].total++,ae.status==="won"&&te[re].wins++)}return te},[c]),{data:w,refetch:S}=ge({queryKey:["klutch-performance-snapshots",a],queryFn:async()=>{let te=T.from("klutch_performance_snapshots").select("*").order("snapshot_date",{ascending:!1}).limit(500);a!=="all"&&(te=te.eq("generation_version",a));const{data:X,error:ae}=await te;if(ae)throw ae;if(!X||X.length===0)return[];const W=X[0].snapshot_date;return X.filter(re=>re.snapshot_date===W)}}),P=v.useMemo(()=>{const te={};
248if(!w)return te;for(const X of w){const ae=X.sport==="ice-hockey"?"hockey":X.sport,W=`${ae}|${X.pick_type}`;te[W]?a==="all"&&(te[W].last_n_wins+=X.last_n_wins,te[W].last_n_losses+=X.last_n_losses,te[W].last_n_pushes+=X.last_n_pushes,te[W].last_n_net_units+=X.last_n_net_units,te[W].last_n_size+=X.last_n_size):te[W]={...X,sport:ae}}return te},[w,a]),O=v.useMemo(()=>d?k||!_?[]:_:y||[],[d,y,k,_]).filter(te=>te.sport!=="mma"),$=!d,z=$?u:k,D=$?g:j,A=()=>{$?x():b(),S(),K.success("Refreshed KLUTCH performance data")},F=async()=>{l(!0);try{const{data:te,error:X}=await T.functions.invoke("snapshot-klutch-performance");if(X)throw X;K.success(`Snapshot taken: ${(te==null?void 0:te.combos_tracked)||0} combos tracked`),S()}catch(te){K.error(`Snapshot failed: ${te.message}`)}finally{l(!1)}},q=O.reduce((te,X)=>({totalPicks:te.totalPicks+(X.total_picks||0),wins:te.wins+(X.wins||0),losses:te.losses+(X.losses||0),pushes:te.pushes+(X.pushes||0),unitsWagered:te.unitsWagered+Number(X.units_wagered||0),netUnits:te.netUnits+Number(X.net_units||0),roiEligiblePicks:te.roiEligiblePicks+Number(X.roi_eligible_picks||0),missingOddsPicks:te.missingOddsPicks+Number(X.missing_odds_picks||0),picks_90_92:te.picks_90_92+(X.picks_90_92||0),wins_90_92:te.wins_90_92+(X.wins_90_92||0),picks_93_95:te.picks_93_95+(X.picks_93_95||0),wins_93_95:te.wins_93_95+(X.wins_93_95||0),picks_96_98:te.picks_96_98+(X.picks_96_98||0),wins_96_98:te.wins_96_98+(X.wins_96_98||0),picks_99_plus:te.picks_99_plus+(X.picks_99_plus||0),wins_99_plus:te.wins_99_plus+(X.wins_99_plus||0)}),{totalPicks:0,wins:0,losses:0,pushes:0,unitsWagered:0,netUnits:0,roiEligiblePicks:0,missingOddsPicks:0,picks_90_92:0,wins_90_92:0,picks_93_95:0,wins_93_95:0,picks_96_98:0,wins_96_98:0,picks_99_plus:0,wins_99_plus:0}),E=q.totalPicks>0?(q.wins/(q.wins+q.losses)*100).toFixed(1):"0.0",L=q.unitsWagered>0?(q.netUnits/q.unitsWagered*100).toFixed(1):"0.0",H=O.reduce((te,X)=>{const ae=X.sport==="ice-hockey"?"hockey":X.sport==="ufc"?"mma":X.sport;return te[ae]||(te[ae]={wins:0,losses:0,pushes:0,unitsWagered:0,netUnits:0}),te[ae].wins+=X.wins||0,te[ae].losses+=X.losses||0,te[ae].pushes+=X.pushes||0,te[ae].unitsWagered+=Number(X.units_wagered||0),te[ae].netUnits+=Number(X.net_units||0),te},{}),Z=O.reduce((te,X)=>(te[X.pick_type]||(te[X.pick_type]={wins:0,losses:0,pushes:0,unitsWagered:0,netUnits:0}),te[X.pick_type].wins+=X.wins||0,te[X.pick_type].losses+=X.losses||0,te[X.pick_type].pushes+=X.pushes||0,te[X.pick_type].unitsWagered+=Number(X.units_wagered||0),te[X.pick_type].netUnits+=Number(X.net_units||0),te),{}),se=O.reduce((te,X)=>{const ae=X.sport==="ice-hockey"?"hockey":X.sport==="ufc"?"mma":X.sport;te[ae]||(te[ae]=[]);const W=te[ae].find(re=>re.pickType===X.pick_type);return W?(W.wins+=X.wins||0,W.losses+=X.losses||0,W.pushes+=X.pushes||0,W.netUnits+=Number(X.net_units||0)):te[ae].push({pickType:X.pick_type,wins:X.wins||0,losses:X.losses||0,pushes:X.pushes||0,netUnits:Number(X.net_units||0)}),te},{});se&&Object.values(se).forEach(te=>{te.sort((X,ae)=>ae.netUnits-X.netUnits)});const ie=(te,X)=>{if(te+X===0)return e.jsx(B,{variant:"outline",children:"N/A"});const ae=te/(te+X)*100;return ae>=60?e.jsxs(B,{className:"bg-green-500/20 text-green-400 border-green-500/30",children:[ae.toFixed(1),"%"]}):ae>=50?e.jsxs(B,{className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",children:[ae.toFixed(1),"%"]}):e.jsxs(B,{className:"bg-red-500/20 text-red-400 border-red-500/30",children:[ae.toFixed(1),"%"]})},Y=(te,X,ae)=>{if(!te||te.last_n_size===0)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});const W=te.last_n_wins+te.last_n_losses>0?te.last_n_wins/(te.last_n_wins+te.last_n_losses)*100:0,re=X+ae>0?X/(X+ae)*100:0,ce=W-re,Pe=ce>0,Fe=W>=60?"text-green-400":W>=50?"text-yellow-400":"text-red-400";return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("span",{className:`text-xs font-medium ${Fe}`,children:[W.toFixed(0),"%"]}),Math.abs(ce)>=1&&e.jsx("span",{className:`text-xs ${Pe?"text-green-400":"text-red-400"}`,children:Pe?"↑":"↓"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(L",te.last_n_size,")"]})]})},I=te=>{if(!te||te.active_learned_adjustment===null||te.active_learned_adjustment===void 0)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});const X=Number(te.active_learned_adjustment);if(X===0)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"0%"});const ae=X>0?"text-green-400":"text-red-400";return e.jsxs("span",{className:`text-xs font-medium ${ae}`,children:[X>0?"+":"",(X*100).toFixed(1),"%"]})},ee=[{label:"90-92%",picks:q.picks_90_92,wins:q.wins_90_92},{label:"93-95%",picks:q.picks_93_95,wins:q.wins_93_95},{label:"96-98%",picks:q.picks_96_98,wins:q.wins_96_98},{label:"99+%",picks:q.picks_99_plus,wins:q.wins_99_plus}];return z?e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-5 w-5"}),"KLUTCH Performance Dashboard"]})}),e.jsx(J,{children:e.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:"Loading performance data..."})})]}):e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between",children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-5 w-5 text-primary"}),"KLUTCH Performance Dashboard"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(oe,{value:a,onValueChange:te=>t(te),children:[e.jsx(de,{className:"w-[120px]",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All"}),e.jsx(V,{value:"v1",children:"v1"}),e.jsx(V,{value:"v1a",children:"v1a · Opus 4.8"}),e.jsx(V,{value:"v2.5",children:"v2.5"}),e.jsx(V,{value:"v2.5a",children:"v2.5a · GPT-5.5"}),e.jsx(V,{value:"v3",children:"v3"}),e.jsx(V,{value:"v3a",children:"v3a · Gemini 3.5"}),e.jsx(V,{value:"v4",children:"v4"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 border rounded-md",children:[e.jsx(Ge,{id:"include-shadow",checked:m,onCheckedChange:o}),e.jsx(Q,{htmlFor:"include-shadow",className:"text-xs cursor-pointer whitespace-nowrap",children:"Include shadow (<90)"}),m&&e.jsx(B,{variant:"outline",className:"text-[10px] h-4 px-1",children:"SHADOW ON"})]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:F,disabled:i,children:[e.jsx(_d,{className:`h-4 w-4 mr-2 ${i?"animate-pulse":""}`}),"Snapshot"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:A,disabled:D,children:[e.jsx(He,{className:`h-4 w-4 mr-2 ${D?"animate-spin":""}`}),"Refresh"]})]})]}),e.jsx(J,{className:"space-y-6",children:q.totalPicks===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(As,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsxs("p",{className:"text-lg font-medium",children:["No KLUTCH picks settled yet",a!=="all"?` for ${a}`:""]}),e.jsx("p",{className:"text-sm mt-2",children:"Performance data will appear here once picks are generated and settled."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(G,{children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Js,{className:"h-4 w-4"}),"Total Picks"]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:q.totalPicks}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[q.wins,"W - ",q.losses,"L - ",q.pushes,"P"]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Jn,{className:"h-4 w-4"}),"Win Rate"]}),e.jsxs("p",{className:`text-2xl font-bold mt-1 ${Number(E)>=55?"text-green-400":Number(E)>=50?"text-yellow-400":"text-red-400"}`,children:[E,"%"]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(La,{className:"h-4 w-4"}),"Net Units"]}),e.jsxs("p",{className:`text-2xl font-bold mt-1 flex items-center gap-1 ${q.netUnits>=0?"text-green-400":"text-red-400"}`,children:[q.netUnits>=0?e.jsx(Ds,{className:"h-5 w-5"}):e.jsx(qt,{className:"h-5 w-5"}),q.netUnits>=0?"+":"",q.netUnits.toFixed(1),"u"]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Ds,{className:"h-4 w-4"}),"ROI"]}),e.jsxs("p",{className:`text-2xl font-bold mt-1 ${Number(L)>=0?"text-green-400":"text-red-400"}`,children:[Number(L)>=0?"+":"",L,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Recorded odds · ",q.roiEligiblePicks.toLocaleStr
248ing()," eligible",q.missingOddsPicks>0?` · ${q.missingOddsPicks.toLocaleString()} missing odds excluded`:""]})]})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"Confidence Band Performance"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:ee.map(te=>{const X=p==null?void 0:p[te.label],ae=te.picks>0?te.wins/te.picks*100:0,W=X&&X.total>0?X.wins/X.total*100:null,re=W!==null?W-ae:null,ce=te.label==="99+%"?65:te.label==="96-98%"?60:te.label==="93-95%"?55:50,Pe=te.picks>0?te.wins/te.picks*100:0,Fe=te.picks>=20?Pe-ce:null;return e.jsx(G,{className:"bg-muted/30",children:e.jsxs(J,{className:"pt-4 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:te.label}),e.jsxs("p",{className:"text-xl font-bold mt-1",children:[te.picks," picks"]}),e.jsx("div",{className:"mt-1",children:ie(te.wins,te.picks-te.wins)}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["Target: ",ce,"%",Fe!==null&&e.jsxs("span",{className:`ml-1 ${Fe>=-2?"text-green-400":"text-red-400"}`,children:["(",Fe>=0?"+":"",Fe.toFixed(0),")"]})]}),W!==null&&X.total>=5&&e.jsxs("div",{className:"mt-2 flex items-center justify-center gap-1",children:[e.jsxs("span",{className:`text-xs font-medium ${W>=60?"text-green-400":W>=50?"text-yellow-400":"text-red-400"}`,children:["L",X.total,": ",W.toFixed(0),"%"]}),re!==null&&Math.abs(re)>=1&&e.jsx("span",{className:`text-xs ${re>0?"text-green-400":"text-red-400"}`,children:re>0?"↑":"↓"})]})]})},te.label)})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"By Sport"}),e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Record"}),e.jsx(U,{children:"Win %"}),e.jsx(U,{children:"Net Units"})]})}),e.jsx($e,{children:H&&Object.entries(H).map(([te,X])=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium uppercase",children:te}),e.jsxs(M,{children:[X.wins,"-",X.losses,"-",X.pushes]}),e.jsx(M,{children:ie(X.wins,X.losses)}),e.jsxs(M,{className:X.netUnits>=0?"text-green-400":"text-red-400",children:[X.netUnits>=0?"+":"",X.netUnits.toFixed(1),"u"]})]},te))})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"By Pick Type"}),e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Type"}),e.jsx(U,{children:"Record"}),e.jsx(U,{children:"Win %"}),e.jsx(U,{children:"Net Units"})]})}),e.jsx($e,{children:Z&&Object.entries(Z).map(([te,X])=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium capitalize",children:te.replace(/_/g," ")}),e.jsxs(M,{children:[X.wins,"-",X.losses,"-",X.pushes]}),e.jsx(M,{children:ie(X.wins,X.losses)}),e.jsxs(M,{className:X.netUnits>=0?"text-green-400":"text-red-400",children:[X.netUnits>=0?"+":"",X.netUnits.toFixed(1),"u"]})]},te))})]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"By Sport & Pick Type"}),e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Pick Type"}),e.jsx(U,{children:"Record"}),e.jsx(U,{children:"Win %"}),e.jsx(U,{children:"Recent Form"}),e.jsx(U,{children:"Adj"}),e.jsx(U,{children:"Net Units"})]})}),e.jsx($e,{children:se&&Object.entries(se).map(([te,X])=>X.map((ae,W)=>{const re=`${te}|${ae.pickType}`,ce=P[re];return e.jsxs(he,{children:[W===0?e.jsx(M,{className:"font-medium uppercase align-top",rowSpan:X.length,children:te}):null,e.jsx(M,{className:"capitalize",children:ae.pickType.replace(/_/g," ")}),e.jsxs(M,{children:[ae.wins,"-",ae.losses,"-",ae.pushes]}),e.jsx(M,{children:ie(ae.wins,ae.losses)}),e.jsx(M,{children:Y(ce,ae.wins,ae.losses)}),e.jsx(M,{children:I(ce)}),e.jsxs(M,{className:ae.netUnits>=0?"text-green-400":"text-red-400",children:[ae.netUnits>=0?"+":"",ae.netUnits.toFixed(1),"u"]})]},`${te}-${ae.pickType}`)}))})]}),w&&w.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Snapshot: ",(le=w[0])==null?void 0:le.snapshot_date," · Recent Form = last ",((ve=w[0])==null?void 0:ve.last_n_size)||50," settled picks"]})]})]})})]})}const xh=s=>new Promise((a,t)=>{const n={};Bi.parse(s,{header:!0,dynamicTyping:!0,skipEmptyLines:!0,transformHeader:r=>{let i=r.trim();
248return i.charCodeAt(0)===65279&&(i=i.slice(1)),i=i.replace(/^\uFEFF/,""),n[i]!==void 0?(n[i]++,`${i}_${n[i]}`):(n[i]=0,i)},complete:r=>{const i=r.meta.fields||[],l=r.data,m=l.slice(0,50);a({headers:i,rows:l,preview:m})},error:r=>{t(r)}})}),hh=s=>new Promise((a,t)=>{const n=new FileReader;n.onload=r=>{var i;try{const l=JSON.parse((i=r.target)==null?void 0:i.result),m=Array.isArray(l)?l:[l],o=m.length>0?Object.keys(m[0]):[],h=m.slice(0,50);a({headers:o,rows:m,preview:h})}catch(l){t(l)}},n.onerror=()=>t(n.error),n.readAsText(s)}),cl=(s,a)=>{const t=Bi.unparse(s),n=new Blob([t],{type:"text/csv;charset=utf-8;"}),r=document.createElement("a"),i=URL.createObjectURL(n);r.setAttribute("href",i),r.setAttribute("download",a),r.style.visibility="hidden",document.body.appendChild(r),r.click(),document.body.removeChild(r)},$l=(s,a)=>{const t={"Player Name":"Name",player:"Name",player_name:"Name","Projected FP":"Projected",Projection:"Projected",FPTS:"Projected",fpts:"Projected",projection:"Projected",TeamAbbrev:"Team",team:"Team",Pos:"Position",pos:"Position",position:"Position",Name_1:"Name",Salary_1:"Salary",Projected_1:"Projected",Projection_1:"Projected",Team_1:"Team",Position_1:"Position",Pos_1:"Position"},n={};return Object.entries(t).forEach(([r,i])=>{n[r.toLowerCase()]=i}),s.map(r=>{const i={},l=new Set;return Object.entries(r).forEach(([m,o])=>{const h=n[m.toLowerCase()]||t[m]||m;if(l.has(h)){const N=i[h];(N==null||N==="")&&o!==null&&o!==void 0&&o!==""&&(i[h]=o)}else i[h]=o,l.add(h)}),i})},Ol=s=>s.map(a=>{if(a.Salary&&typeof a.Salary=="string"){const t=parseInt(a.Salary.replace(/[$,]/g,""),10);isNaN(t)||(a.Salary=t)}return a}),ph=(s,a)=>{const t=JSON.stringify(s,null,2),n=new Blob([t],{type:"application/json"}),r=document.createElement("a"),i=URL.createObjectURL(n);r.setAttribute("href",i),r.setAttribute("download",a),r.style.visibility="hidden",document.body.appendChild(r),r.click(),document.body.removeChild(r)};function gh(s,a){return ge({queryKey:["clv-dashboard-stats",s,a],queryFn:async()=>{const{data:t,error:n}=await T.rpc("get_clv_dashboard_stats",{p_trusted_only:s,p_window_days:a==="all"?null:a});if(n)throw n;return t},staleTime:6e4})}function jh(){return ge({queryKey:["clv-capture-monitor"],queryFn:async()=>{const{data:s,error:a}=await T.rpc("get_clv_capture_monitor");if(a)throw a;return s},staleTime:3e4})}function Et({label:s,value:a,subtitle:t,trend:n}){return e.jsxs(G,{className:"glassmorphism p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:s}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-2xl font-bold",children:a}),n==="up"&&e.jsx(Ds,{className:"h-4 w-4 text-green-400"}),n==="down"&&e.jsx(qt,{className:"h-4 w-4 text-red-400"}),n==="neutral"&&e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"})]}),t&&e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:t})]})}function tr({title:s,data:a,trustedOnly:t,benchmarkKey:n}){const r=Object.entries(a||{}).sort((i,l)=>l[1].count-i[1].count);return r.length===0?null:e.jsxs(G,{className:"glassmorphism p-4",children:[e.jsx("h4",{className:"text-sm font-medium mb-3",children:s}),e.jsx("div",{className:"space-y-2",children:r.map(([i,l])=>{const m=t&&n===i,o=t&&(i==="total"||i==="totals")&&l.count<10;return e.jsxs("div",{className:Le("flex items-center justify-between text-xs",o&&"opacity-50"),children:[e.jsxs("span",{className:"capitalize text-muted-foreground flex items-center gap-1.5",children:[i.replace("_"," "),m&&e.jsx(B,{variant:"default",className:"text-[9px] px-1 py-0 h-3.5 bg-green-600/80 hover:bg-green-600/80 border-0",children:"Benchmark"}),o&&e.jsx("span",{className:"text-[9px] text-muted-foreground italic",children:"insufficient data"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:l.count}),e.jsxs(B,{variant:"outline",className:Le("text-[10px] px-1.5 py-0 h-4 font-mono",l.beat_pct>=55?"text-green-400 border-green-500/30":l.beat_pct<45?"text-red-400 border-red-500/30":"text-muted-foreground"),children:[l.beat_pct,"%"]}),e.jsxs(B,{variant:"outline",className:Le("text-[10px] px-1.5 py-0 h-4 font-mono",l.avg_clv>0?"text-green-400 border-green-500/30":l.avg_clv<0?"text-red-400 border-red-500/30":"text-muted-foreground"),children:[l.avg_clv>0?"+":"",l.avg_clv]}),l.net_units!==void 0&&e.jsxs(B,{variant:"outline",className:Le("text-[10px] px-1.5 py-0 h-4 font-mono",l.net_units>0?"text-green-400 border-green-500/30":l.net_units<0?"text-red-400 border-red-500/30":"text-muted-foreground"),children:[l.net_units>0?"+":"",l.net_units,"u"]})]})]},i)})})]})}function fh(){const{data:s,isLoading:a}=jh();return a||!s?null:e.jsxs(G,{className:"glassmorphism p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(_t,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"text-sm font-medium",children:"Capture Monitor (Today)"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-xs",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-muted-foreground",children:"Games Today"}),e.jsx("div",{className:"text-lg font-bold",children:s.games_today})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(rs,{className:"h-3 w-3 text-green-400"})," Captured"]}),e.jsx("div",{className:"text-lg font-bold text-green-400",children:s.games_captured})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ls,{className:"h-3 w-3 text-red-400"})," Missed"]}),e.jsx("div",{className:"text-lg font-bold text-red-400",children:s.games_missed})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-muted-foreground",children:"Snapshots"}),e.jsx("div",{className:"text-lg font-bold",children:s.total_snapshots_today})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-muted-foreground",children:"Avg Books/Game"}),e.jsx("div",{className:"font-semibold",children:s.avg_books_per_game??"—"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-muted-foreground",children:"Avg Min Before Start"}),e.jsx("div",{className:"font-semibold",children:s.avg_closest_snapshot_min??"—"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-muted-foreground",children:"Awaiting Capture"}),e.jsx("div",{className:"font-semibold",children:s.games_needing_capture})]})]})]})}function vh(s){if(!s)return null;let a=null,t=0;for(const[n,r]of Object.entries(s))r.beat_pct>50&&r.count>
248t&&(a=n,t=r.count);return a}function yh({windowDays:s="all"}={}){const[a,t]=v.useState(!0),[n,r]=v.useState(!1),{data:i,isLoading:l}=gh(a,s),m=$c(s),o=async()=>{r(!0);try{let u=0;const x=[];for(;;){let k=T.from("klutch_picks").select("id,generation_version,engine_id,engine_version,tier,source_type,pick_type,sport,league,market_name,market_side,picked_side,pick_sign,pick,player_name,game_id,game_date,home_team,away_team,matchup,original_line,original_odds,closing_line,closing_odds,closing_book,closing_confidence,closing_captured_at,consensus_book_count,close_latency_seconds,snapshot_source_count,clv_line,clv_odds,clv_implied_prob,beat_close,clv_status,clv_calculated_at,confidence_score,edge_pct,suggested_units,status,actual_result,settled_at,created_at,line_history").in("status",["won","lost","push"]).not("pick_type","in","(prop,player_prop)").in("clv_status",["positive","negative","neutral","review"]).order("created_at",{ascending:!1}).range(u,u+1e3-1);a&&(k=k.eq("closing_confidence","fresh_close").gte("consensus_book_count",3)),m&&(k=k.gte("settled_at",m));const{data:b,error:j}=await k;if(j)throw j;if(!b||b.length===0||(x.push(...b),b.length<1e3))break;u+=1e3}if(x.length===0){K.error("No CLV rows match the current filter");return}const g=x.map(k=>({...k,line_history:k.line_history?JSON.stringify(k.line_history):""})),f=new Date().toISOString().slice(0,10),_=s==="all"?"all-time":`${s}d`;cl(g,`klutch-clv-${a?"trusted":"all"}-${_}-${f}.csv`),K.success(`Exported ${g.length} picks`)}catch(y){K.error((y==null?void 0:y.message)||"Export failed")}finally{r(!1)}};if(l)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})});if(!i||!i.summary||i.summary.total_picks===0)return e.jsxs(G,{className:"glassmorphism p-6 text-center",children:[e.jsx(ml,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a?'No trusted CLV data yet (fresh_close + 3+ books). Try "All Historical" mode.':"No CLV data available yet. CLV will be computed as picks are settled."}),a&&e.jsx("button",{onClick:()=>t(!1),className:"text-xs text-primary underline mt-2",children:"Switch to All Historical"})]});const h=i.summary,N=(h.avg_clv_line??0)>.5?"up":(h.avg_clv_line??0)<-.5?"down":"neutral",d=a?vh(i.by_type):null;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ml,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold",children:"CLV Analytics"}),e.jsxs(B,{variant:"outline",className:"text-[10px]",children:[h.total_picks," picks"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"ml-auto h-7 text-xs",onClick:o,disabled:n,children:[n?e.jsx(ne,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Gt,{className:"h-3.5 w-3.5 mr-1.5"}),"Export CSV"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex rounded-md border border-border overflow-hidden",children:[e.jsxs("button",{onClick:()=>t(!0),className:Le("flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors",a?"bg-primary text-primary-foreground":"bg-transparent text-muted-foreground hover:text-foreground"),children:[e.jsx(Zn,{className:"h-3.5 w-3.5"}),"Trusted CLV"]}),e.jsx("button",{onClick:()=>t(!1),className:Le("flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors",a?"bg-transparent text-muted-foreground hover:text-foreground":"bg-primary text-primary-foreground"),children:"All Historical"})]}),e.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-muted-foreground",children:[e.jsx(Ys,{className:"h-3 w-3"}),a?"fresh_close snapshots, 3+ books consensus":"includes stale_proxy and low-book consensus"]})]}),e.jsx(fh,{}),e.jsxs(js,{defaultValue:"final",className:"w-full",children:[e.jsxs(fs,{className:"h-8",children:[e.jsx(Ne,{value:"final",className:"text-xs",children:"Final Signal"}),e.jsx(Ne,{value:"first",className:"text-xs",children:"First Signal"}),e.jsx(Ne,{value:"weighted",className:"text-xs",children:"Weighted"})]}),e.jsx(we,{value:"final",className:"mt-3",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Et,{label:"% Beat Close",value:`${h.beat_close_pct}%`,subtitle:`${h.beat_close_count} / ${h.total_picks}`,trend:h.beat_close_pct>=55?"up":h.beat_close_pct<45?"down":"neutral"}),e.jsx(Et,{label:"Avg Line CLV",value:h.avg_clv_line!=null?`${h.avg_clv_line>0?"+":""}${h.avg_clv_line}`:"N/A",subtitle:"Final Signal vs Close",trend:N}),e.jsx(Et,{label:"Avg ML CLV",value:h.avg_clv_implied!=null?`${(h.avg_clv_implied*100).toFixed(1)}%`:"N/A",subtitle:"Implied prob delta",trend:h.avg_clv_implied!=null?h.avg_clv_implied>.01?"up":h.avg_clv_implied<-.01?"down":"neutral":"neutral"}),e.jsx(Et,{label:"Net Units",value:h.net_units!=null?`${h.net_units>0?"+":""}${h.net_units}`:"N/A",trend:h.net_units!=null?h.net_units>0?"up":h.net_units<0?"down":"neutral":"neutral"})]})}),e.jsx(we,{value:"first",className:"mt-3",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Et,{label:"% Beat Close",value:`${h.beat_close_pct}%`,subtitle:`${h.beat_close_count} / ${h.total_picks}`,trend:h.beat_close_pct>=55?"up":h.beat_close_pct<45?"down":"neutral"}),e.jsx(Et,{label:"First Signal Line CLV",value:h.avg_first_signal_clv_line!=null?`${h.avg_first_signal_clv_line>0?"+":""}${h.avg_first_signal_clv_line}`:"N/A",subtitle:"Earliest entry vs Close",trend:(h.avg_first_signal_clv_line??0)>.5?"up":(h.avg_first_signal_clv_line??0)<-.5?"down":"neutral"}),e.jsx(Et,{label:"First Signal ML CLV",value:h.avg_first_signal_clv_implied!=null?`${(h.avg_first_signal_clv_implied*100).toFixed(1)}%`:"N/A",subtitle:"Earliest entry implied delta",trend:h.avg_first_signal_clv_implied!=null?h.avg_first_signal_clv_implied>.01?"up":h.avg_first_signal_clv_implied<-.01?"down":"neutral":"neutral"}),e.jsx(Et,{label:"Net Units",value:h.net_units!=null?`${h.net_units>0?"+":""}${h.net_units}`:"N/A",trend:h.net_units!=null?h.net_units>0?"up":h.net_units<0?"down":"neutral":"neutral"})]})}),e.jsx(we,{value:"weighted",className:"mt-3",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Et,{label:"% Beat Close",value:`${h.beat_close_pct}%`,subtitle:`${h.beat_close_count} / ${h.total_picks}`,trend:h.beat_close_pct>=55?"up":h.beat_close_pct<45?"down":"neutral"}),e.jsx(Et,{label:"Weighted Avg CLV",value:h.weighted_avg_clv_line!=null?`${h.weighted_avg_clv_line>0?"+":""}${h.weighted_avg_clv_line}`:"N/A",subtitle:"Weighted by suggested units",trend:(h.weighted_avg_clv_line??0)>.5?"up":(h.weighted_avg_clv_line??0)<-.5?"down":"neutral"}),e.jsx(Et,{label:"Net Units",value:h.net_units!=null?`${h.net_units>0?"+":""}${h.net_units}`:"N/A",trend:h.net_units!=null?h.net_units>0?"up":h.net_units<0?"down":"neutral":"neutral"})]})})]}),i.by_closing_confidence&&Object.keys(i.by_closing_confidence).length>0&&e.jsxs(G,{className:"glassmorphism p-4",children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Close Data Quality"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(i.by_closing_confidence).map(([y,u])=>e.jsxs(B,{variant:"outline",className:Le("text-[10px]",y==="fresh_close"||y==="real_close"?"text-green-400 border-green-500/30":y==="inferred_close"?"text-yellow-400 border-yellow-500/30":y==="opening_proxy"||y==="stale_proxy"?"text-orange-400 border-orange-500/30":"text-muted-foreground"),children:[y,": ",u.count," (",u.beat_pct,"% beat)"]},y))})]}),i.by_market_scorecard&&Object.keys(i.by_market_scorecard).length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-3",children:"Market Scorecards"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:Object.entries(i.by_market_scorecard).sort((y,u)=>u[1].count-y[1].count).map(([y,u])=>{const x=u.beat_close_pct>=55?"up":u.beat_close_pct<45?"down":"neutral",g=u.net_units>0?"up":u.net_units<0?"down":"neutral";return e.jsxs(G,{className:"glassmorphism p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-sm font-semibold capitalize",children:y}),e.jsxs(B,{variant:"outline",className:"text-[10px]",children:[u.count," picks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground mb-0.5",children:"Beat Close"}),e.jsxs("div",{className:Le("text-lg font-bold",x==="up"?"text-green-400":x==="down"?"text-red-400":""),children:[u.beat_close_pct,"%"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:[u.beat_close_count," / ",u.count]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground mb-0.5",children:"Net Units"}),e.jsxs("div",{className:Le("text-lg font-bold",g==="up"?"text-green-400":g==="down"?"text-red-400":""),children:[u.net_units>0?"+":"",u.net_units,"u"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground mb-0.5",children:"Avg CLV Line"}),e.jsx("div",{className:"font-semibold",children:u.avg_clv_line!=null?`${u.avg_clv_line>0?"+":""}${u.avg_clv_line}`:"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground mb-0.5",children:"Avg CLV Implied"}),e.jsx("div",{className:"font-semibold",children:u.avg_clv_implied!=null?`${(u.avg_clv_implied*100).toFixed(1)}%`:"—"})]}),u.avg_first_signal_clv_line!=null&&e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground mb-0.5",children:"1st Signal CLV"}),e.jsxs("div",{className:"font-semibold",children:[u.avg_first_signal_clv_line>0?"+":"",u.avg_first_signal_clv_line]})]}),u.weighted_avg_clv_line!=null&&e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground mb-0.5",children:"Weighted CLV"}),e.jsxs("div",{className:"font-semibold",children:[u.weighted_avg_clv_line>0?"+":"",u.weighted_avg_clv_line]})]})]})]},y)})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsx(tr,{title:"By Market Type",data:i.by_type,trustedOnly:a,benchmarkKey:d}),e.jsx(tr,{title:"By Odds Range",data:i.by_odds_range}),e.jsx(tr,{title:"By Sport",data:i.by_sport}),e.jsx(tr,{title:"By Version",data:i.by_version}),e.jsx(tr,{title:"By Confidence",data:i.by_confidence})]})]})}function Oc(){return ge({queryKey:["klutch-engine-module-settings"],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_engine_module_settings").select("engine_key, enabled, updated_at, updated_by").order("engine_key");if(a)throw a;return s||[]},refetchInterval:3e4})}function Nh(){const s=Me();return _e({mutationFn:async({engine_key:a,enabled:t})=>{const{data:n,error:r}=await T.functions.invoke("toggle-engine-module",{body:{engine_key:a,enabled:t}});if(r)throw r;if(n!=null&&n.error)throw new Error(n.error);return n},onSuccess:(a,t)=>{K.success(`${t.engine_key} → ${t.enabled?"Module":"Monolith"}`),s.invalidateQueries({queryKey:["klutch-engine-module-settings"]})},onError:a=>{K.error(`Toggle failed: ${(a==null?void 0:a.message)||"unknown error"}`)}})}function Uc(){var y;const s=new Date,a=new Intl.DateTimeFormat("en-CA",{timeZone:"America/Chicago",year:"numeric",month:"2-digit",day:"2-digit"}).format(s),i=(((y=new Intl.DateTimeFormat("en-US",{timeZone:"America/Chicago",timeZoneName:"shortOffset",hour:"numeric"}).formatToParts(s).find(u=>u.type==="timeZoneName"))==null?void 0:y.value)||"GMT-6").match(/GMT([+-]\d{1,2})(?::?(\d{2}))?/),l=i?parseInt(i[1],10):-6,m=i&&i[2]?parseInt(i[2],10):0,o=l<0?"-":"+",h=String(Math.abs(l)).padStart(2,"0"),N=String(m).padStart(2,"0"),d=`${a}T00:00:00${o}${h}:${N}`;return new Date(d).toISOString()}function _h(){const s=new Date(Uc());return new Date(s.getTime()+24*60*60*1e3).toISOString()}function bh(){return ge({queryKey:["engine-pipeline-snapshot"],queryFn:async()=>{var _,k;const s=Uc(),a=_h(),[t,n,r,i]=await Promise.all([T.from("master_games").select("sport, commence_time").gte("commence_time",s).lt("commence_time",a).limit(2e3),T.from("klutch_picks").select("sport, pick_type, created_at").gte("created_at",s).lt("created_at",a).limit(5e3),T.from("klutch_picks").select("created_at").order("created_at",{ascending:!1}).limit(1).maybeSingle(),T.from("klutch_pipeline_runs").select("started_at").order("started_at",{ascending:!1}).limit(1).maybeSingle()]);if(t.error)throw t.error;if(n.error)throw n.error;const l=t.data||[],m=n.data||[],o=new Map;for(const b of l){const j=(b.sport||"unknown").toString();o.set(j,(o.get(j)||0)+1)}const h=new Map,N=new Map;for(const b of m){const j=(b.sport||"unknown").toString();h.set(j,(h.get(j)||0)+1);const c=(b.pick_type||"unknown").toString();N.set(c,(N.get(c)||0)+1)}const d=(b,j)=>[...b.entries()].map(([c,p])=>({[j]:c,count:p})).sort((c,p)=>p.count-c.count),y=((_=r.data)==null?void 0:_.created_at)||null,u=y?Math.max(0,Math.floor((Date.now()-new Date(y).getTime())/6e4)):null,x=((k=i.data)==null?void 0:k.started_at)||y;let g=null,f="stale";return x&&(g=Math.max(0,Math.floor((Date.now()-new Date(x).getTime())/6e4)),g<20?f="healthy":g<35?f="warning":f="stale"),{totalGames:l.length,gamesPerSport:d(o,"sport"),totalPicks:m.length,picksPerSport:d(h,"sport"),picksPerBetType:d(N,"pick_type"),lastPick:y,lastPickMinutesAgo:u,lastRun:x,lastRunMinutesAgo:g,pipelineStatus:f}},refetchInterval:6e4,staleTime:3e4})}function wh(s){if(!s)return"—";try{const a=new Date(s);return`${new Intl.DateTimeFormat("en-US",{timeZone:"America/Chicago",hour:"numeric",minute:"2-digit",hour12:!0}).format(a)} CT`}catch{return"—"}}function Sh(s={}){const{enabled:a=!0,limit:t=10}=s;return ge({queryKey:["klutch-pipeline-errors",t],enabled:a,queryFn:async()=>{const n=new Date(Date.now()-72e5).toISOString(),{data:r,error:i}=await T.from("klutch_pipeline_errors").select("id, function_name, severity, message, metadata, created_at").gte("created_at",n).in("severity",["error","warning"]).order("created_at",{ascending:!1}).limit(t);if(i)throw i;return r||[]},refetchInterval:6e4,staleTime:3e4})}const Ul=85,_n={core:105,plus:92,lab:85};function wt(s,a=2){return s==null||isNaN(s)?"—":s.toFixed(a)}function ar(s){switch((s||"").toLowerCase()){case"core":return"bg-emerald-500/15 text-emerald-400 border-emerald-500/40";case"plus":return"bg-sky-500/15 text-sky-400 border-sky-500/40";case"lab":return"bg-violet-500/15 text-violet-400 border-violet-500/40";case"dropped":case"rejected":return"bg-destructive/15 text-destructive border-destructive/40";case"shadow":case"suppressed":return"bg-muted text-muted-foreground border-muted-foreground
248/30";default:return"bg-muted/40 text-muted-foreground border-muted-foreground/20"}}function kh(s){return{core:(s==null?void 0:s.min_confidence_core)??(s==null?void 0:s.min_confidence)??_n.core,plus:(s==null?void 0:s.min_confidence_plus)??(s==null?void 0:s.min_confidence)??_n.plus,lab:(s==null?void 0:s.min_confidence_lab)??(s==null?void 0:s.min_confidence)??_n.lab}}function Ch(){const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState(!1),[l,m]=v.useState({}),{data:o,isLoading:h}=ge({queryKey:["policy-lab-finalized",s,r],queryFn:async()=>{let f=T.from("klutch_module_finalized_picks").select("*, candidate, applied_overlays, applied_signal_overlays").order("created_at",{ascending:!1}).limit(200);s==="promoted"&&(f=f.not("promoted_pick_id","is",null)),s==="pending"&&(f=f.is("promoted_pick_id",null).eq("dropped",!1)),r||(f=f.eq("dropped",!1));const{data:_,error:k}=await f;if(k)throw k;return _||[]},refetchInterval:3e4}),N=(o||[]).map(f=>f.promoted_pick_id).filter(f=>!!f),{data:d}=ge({queryKey:["policy-lab-finalized-tiers",N.sort().join(",")],enabled:N.length>0,queryFn:async()=>{const{data:f,error:_}=await T.from("klutch_picks").select("id, tier, router_score, edge_pct").in("id",N);if(_)throw _;const k=new Map;for(const b of f||[])k.set(b.id,{tier:b.tier??null,router_score:b.router_score??null,edge_pct:b.edge_pct??null});return k},staleTime:3e4}),{data:y}=ge({queryKey:["policy-lab-engine-rules"],queryFn:async()=>{const{data:f,error:_}=await T.from("klutch_engine_rules").select("engine_id, engine_version, allowed_tiers, allowed_sports, allowed_bet_types, min_confidence, min_confidence_core, min_confidence_plus, min_confidence_lab, status");if(_)throw _;return f||[]},staleTime:5*6e4}),u=(f,_)=>{if(!f||!y)return null;const k=y.find(b=>b.engine_id===f&&b.engine_version===(_||"v1.0"));return k||y.find(b=>b.engine_id===f)||null},x=f=>m(_=>({..._,[f]:!_[f]})),g=v.useMemo(()=>o?t==="all"?o:t==="none"?o.filter(f=>!f.promoted_pick_id):o.filter(f=>{var k;return f.promoted_pick_id?(((k=d==null?void 0:d.get(f.promoted_pick_id))==null?void 0:k.tier)||"").toLowerCase()===t:!1}):[],[o,t,d]);return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{className:"text-base",children:"Module Finalized Picks (SSOT)"}),e.jsx(De,{children:"The new authoritative staging table. Engines write every calibrated pick here — including dropped ones (with reason) — so we have full provenance from candidate → finalized → published. Click any row to expand the calibration math."})]}),e.jsxs(J,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(oe,{value:s,onValueChange:f=>a(f),children:[e.jsx(de,{className:"w-44 h-8 text-xs",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All statuses"}),e.jsx(V,{value:"promoted",children:"Promoted (any tier)"}),e.jsx(V,{value:"pending",children:"Pending router"})]})]}),e.jsxs(oe,{value:t,onValueChange:f=>n(f),children:[e.jsx(de,{className:"w-44 h-8 text-xs",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All tiers"}),e.jsx(V,{value:"core",children:"Core"}),e.jsx(V,{value:"plus",children:"Plus"}),e.jsx(V,{value:"lab",children:"Lab"}),e.jsx(V,{value:"none",children:"No tier (pending)"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{id:"show-dropped",checked:r,onCheckedChange:i}),e.jsx(Q,{htmlFor:"show-dropped",className:"text-xs cursor-pointer",children:"Show Dropped"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[g.length," ",g.length===1?"row":"rows"]})]}),h?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(ne,{className:"h-5 w-5 animate-spin mr-2"}),"Loading finalized picks…"]}):!g||g.length===0?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-6",children:[e.jsx(xs,{className:"h-4 w-4"}),"No finalized picks match the current filters."]}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-6"}),e.jsx(U,{children:"Created"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Market"}),e.jsx(U,{children:"Side"}),e.jsx(U,{children:"Engine"}),e.jsx(U,{className:"text-right",children:"Confidence"}),e.jsx(U,{className:"text-right",children:"Trust"}),e.jsx(U,{className:"text-right",children:"NTS"}),e.jsx(U,{children:"Tier"})]})}),e.jsx($e,{children:g.map(f=>{var E,L,H;const _=!!l[f.id],k=((E=f.candidate)==null?void 0:E.engine_metadata)||{},b=k.raw_adjusted_confidence,j=!!k.clamped,c=k.overlay_reason||null,p=f.signal_overlay_multiplier??k.signal_overlay_multiplier??1,w=f.overlay_weight??k.overlay_weight??1,S=f.original_confidence??k.original_confidence??null,P=f.adjusted_confidence??null,C=Array.isArray(f.applied_overlays)?f.applied_overlays:[],O=Array.isArray(f.applied_signal_overlays)?f.applied_signal_overlays:[],$=f.promoted_pick_id?d==null?void 0:d.get(f.promoted_pick_id):null,z=u(f.module_engine_id,f.module_engine_version),D=kh(z),A=(z==null?void 0:z.allowed_tiers)??["core","plus","lab"],F=($==null?void 0:$.t
248ier)??null,q=($==null?void 0:$.router_score)??null;return e.jsxs(v.Fragment,{children:[e.jsxs(he,{className:"cursor-pointer hover:bg-muted/30",onClick:()=>x(f.id),children:[e.jsx(M,{className:"px-2",children:_?e.jsx(Ns,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(st,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx(M,{className:"text-[10px] text-muted-foreground",children:new Date(f.created_at).toLocaleString()}),e.jsx(M,{className:"text-xs capitalize",children:f.sport}),e.jsx(M,{className:"text-xs capitalize",children:f.pick_type}),e.jsx(M,{className:"text-xs",children:f.picked_side||f.player_name||"—"}),e.jsx(M,{className:"text-xs",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx(B,{variant:"outline",className:"text-[10px] w-fit",children:f.module_engine_id||"—"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[f.source_version||"",f.module_engine_version?` · ${f.module_engine_version}`:""]})]})}),e.jsxs(M,{className:"text-xs text-right",children:[e.jsx("span",{className:"font-medium",title:`Confidence = the version's pick strength after market signal multipliers only.${p!=null&&Number(p)!==1?` (signal × ${Number(p).toFixed(2)})`:""}${j?` · clamped from ${wt(b,1)}`:""} Trust is shown separately and only affects the router's NTS — it never multiplies confidence.`,children:P!=null?P.toFixed(0):S!=null?S.toFixed(0):"—"}),S!=null&&P!=null&&Math.abs(S-P)>=1&&e.jsxs("span",{className:"ml-1 text-[10px] text-muted-foreground",children:["(raw ",S.toFixed(0),")"]})]}),e.jsxs(M,{className:"text-xs text-right",title:f.trust_source==="bootstrap"?"Trust = how much the router trusts the source version's track record. BOOTSTRAP: no learned history yet — neutral 1.00 trust, tier capped at LAB.":"Trust = how much the router trusts the source version's track record on this sport+market. Higher trust → larger NTS bonus → higher tier eligibility.",children:[e.jsx("span",{className:Le("font-medium",f.trust_source==="bootstrap"&&"text-amber-400"),children:w!=null?Number(w).toFixed(2):"—"}),f.trust_source==="bootstrap"&&e.jsx("span",{className:"ml-1 text-[9px] uppercase text-amber-400/80 tracking-wide",children:"boot"})]}),e.jsx(M,{className:"text-xs text-right",title:"Net Trust Score assigned by the meta-router. Tier gates: Core ≥105, Plus ≥92, Lab ≥85.",children:q!=null?e.jsx("span",{className:Le("font-mono font-medium",q>=105&&"text-emerald-400",q>=92&&q<105&&"text-blue-400",q>=85&&q<92&&"text-amber-400",q<85&&"text-destructive"),children:wt(q,1)}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(M,{children:f.dropped?e.jsx(B,{variant:"outline",className:`text-[10px] uppercase ${ar("dropped")}`,title:f.drop_reason||"Dropped pre-router",children:"dropped"}):f.promoted_pick_id?F?e.jsx(B,{variant:"outline",className:`text-[10px] uppercase ${ar(F)}`,title:`Assigned by meta-router · NTS ${wt(q,1)}${f.trust_source==="bootstrap"?" · capped at LAB (bootstrap trust)":""}`,children:F}):e.jsx(B,{variant:"outline",className:"text-[10px] uppercase bg-emerald-500/10 text-emerald-400 border-emerald-500/30",title:"Promoted, tier not yet stamped",children:"promoted"}):e.jsx(B,{variant:"outline",className:"text-[10px] uppercase bg-yellow-500/10 text-yellow-400 border-yellow-500/30",title:"Awaiting next meta-router run",children:"pending"})})]}),_&&e.jsxs(he,{className:"bg-muted/20",children:[e.jsx(M,{}),e.jsx(M,{colSpan:9,className:"py-3",children:e.jsxs("div",{className:"space-y-3 text-xs",children:[(()=>{const Z=Number(p??1),se=S!=null?S*Z:null,ie=S!=null&&P!=null&&se!=null&&S>0&&Math.abs(P-se)>Math.max(1,se*.1);return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Confidence"}),e.jsxs("code",{className:"text-xs",children:["Raw ",wt(S,1)," × Signal multiplier ",wt(p,2)," = Final ",wt(P,1),j&&b!=null&&e.jsxs("span",{className:"ml-1 text-amber-400",children:["(clamped from ",wt(b,1),")"]})]}),ie&&e.jsx(B,{variant:"outline",className:"text-[9px] uppercase bg-amber-500/10 text-amber-400 border-amber-500/30",title:"Legacy row written before the overlay-pipeline fix. Trust was multiplied into adjusted_confidence, which the new model does not do. Kept for history.",children:"legacy multiply"})]}),e.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Trust (router-only)"}),e.jsxs("code",{className:"text-xs",children:["overlay_weight ",wt(w,2),f.trust_source?` · ${f.trust_source}`:"",f.source_version?` · ${f.source_version}`:"",f.module_engine_id?` · ${f.sport}/${f.module_engine_id}`:"",e.jsx("span",{className:"ml-1 text-muted-foreground",children:"→ applied at router as NTS bonus (capped ±10); never multiplies confidence"})]})]})]})})(),e.jsxs("div",{className:"rounded border border-border/60 bg-background/40 p-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Tier assignment"}),F?e.jsxs(B,{variant:"outline",className:`text-[10px] uppercase ${ar(F)}`,children:["Final tier: ",F]}):f.dropped?e.jsx(B,{variant:"outline",className:`text-[10px] uppercase ${ar("dropped")}`,children:"Dropped"}):e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Awaiting next router run"}),q!=null&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["NTS (router_score):"," ",e.jsx("span",{className:"font-mono text-foreground",children:wt(q,1)})]}),($==null?void 0:$.edge_pct)!=null&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Edge:"," ",e.jsxs("span",{className:"font-mono text-foreground",children:[$.edge_pct>0?"+":"",wt($.edge_pct,1),"%"]})]})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground font-mono leading-relaxed",children:"NTS = confidence + overlay_trust(±10) + health(±6) + clv(±3) − instability(0..−5) + edge_bonus(0/+2)"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 text-[11px]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Engine rule"}),z?e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-mono",children:z.engine_id}),e.jsxs("span",{className:"text-muted-foreground",children:[" ","· ",z.engine_version||"v1.0"," · ",z.status]})]}),e.jsxs("div",{className:"text-muted-foreground",children:["Allowed tiers: ",(z.allowed_tiers||[]).join(", ")||"—"]}
248),(((L=z.allowed_sports)==null?void 0:L.length)??0)>0&&e.jsxs("div",{className:"text-muted-foreground",children:["Sports: ",z.allowed_sports.join(", ")]}),(((H=z.allowed_bet_types)==null?void 0:H.length)??0)>0&&e.jsxs("div",{className:"text-muted-foreground",children:["Markets: ",z.allowed_bet_types.join(", ")]})]}):e.jsxs("div",{className:"text-muted-foreground italic",children:["No matching rule — legacy fallback to ",e.jsx("code",{children:"lab"})," if NTS ≥ ",Ul]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Tier thresholds (NTS)"}),e.jsxs("div",{className:"font-mono space-y-0.5",children:[e.jsxs("div",{className:A.includes("core")?"":"opacity-40 line-through",children:["Core ≥ ",D.core]}),e.jsxs("div",{className:A.includes("plus")?"":"opacity-40 line-through",children:["Plus ≥ ",D.plus]}),e.jsxs("div",{className:A.includes("lab")?"":"opacity-40 line-through",children:["Lab ≥ ",D.lab]}),e.jsxs("div",{className:"text-destructive",children:["Drop < ",Ul," (hard floor)"]})]})]})]}),F&&q!=null&&e.jsxs("div",{className:"text-[11px]",children:["Result:"," ",e.jsxs("span",{className:"font-mono",children:["NTS ",wt(q,1)]})," → ",e.jsx("span",{className:`uppercase font-semibold ${ar(F).split(" ").find(Z=>Z.startsWith("text-"))||""}`,children:F})]}),!F&&f.dropped&&e.jsxs("div",{className:"text-[11px] text-destructive",children:["Did not reach meta-router — dropped pre-promote",f.drop_reason?` · ${f.drop_reason}`:"","."]}),!F&&!f.dropped&&e.jsx("div",{className:"text-[11px] text-muted-foreground italic",children:"Awaiting next router run. Will be tiered using NTS = confidence + trust bonus + health/CLV/edge — no preview shown because router bonuses depend on live health stats."})]}),c&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1",children:"Sport overlay"}),e.jsx("code",{className:"text-[11px] text-muted-foreground",children:c})]}),C.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1",children:"Active sport-version overlay"}),e.jsx("pre",{className:"text-[10px] bg-background/40 p-2 rounded overflow-x-auto",children:JSON.stringify(C,null,2)})]}),O.length>0?e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground mb-1",children:"Applied signal overlays"}),e.jsx("div",{className:"space-y-1",children:O.map((Z,se)=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx(B,{variant:"outline",className:"text-[10px]",children:Z.signal_key||Z.key||`overlay ${se+1}`}),e.jsxs("span",{className:"text-muted-foreground",children:["weight ",wt(Z.weight,2)]}),Z.status&&e.jsx(B,{variant:"outline",className:"text-[10px]",children:Z.status})]},se))})]}):e.jsx("div",{className:"text-[10px] text-muted-foreground italic",children:"No signal overlays matched."}),f.dropped&&f.drop_reason&&e.jsxs("div",{className:"text-[11px] text-destructive",children:["Drop reason: ",e.jsx("code",{children:f.drop_reason})]}),!f.promoted_pick_id&&!f.dropped&&P!=null&&P<60&&e.jsx("div",{className:"text-[11px] text-amber-400",children:"Below 60% calibrated confidence — promote will skip this pick (module floor)."})]})})]})]},f.id)})})]})})]})]})}function Bc(s){if(!s)return{picks_with_line_mismatch:0,picks_with_market_mismatch:0,picks_with_true_mismatch:0};try{const a=JSON.parse(s);return{picks_with_line_mismatch:Number((a==null?void 0:a.picks_with_line_mismatch)??0),picks_with_market_mismatch:Number((a==null?void 0:a.picks_with_market_mismatch)??0),picks_with_true_mismatch:Number((a==null?void 0:a.picks_with_true_mismatch)??0)}}catch{return{picks_with_line_mismatch:0,picks_with_market_mismatch:0,picks_with_true_mismatch:0}}}function Ph(s=50){return ge({queryKey:["klutch-parity-runs",s],queryFn:async()=>{const{data:a,error:t}=await T.from("klutch_engine_module_parity_runs").select("*").order("run_at",{ascending:!1}).limit(s);if(t)throw t;return a||[]},refetchInterval:6e4})}function Fh(s){return ge({queryKey:["klutch-parity-diffs",s],queryFn:async()=>
248{if(!s)return[];const{data:a,error:t}=await T.from("klutch_engine_module_parity_diffs").select("*").eq("run_id",s).order("created_at",{ascending:!0}).limit(500);if(t)throw t;return a||[]},enabled:!!s})}function Ah(){return ge({queryKey:["klutch-parity-rollup"],queryFn:async()=>{const s=new Date(Date.now()-864e5).toISOString(),{data:a,error:t}=await T.from("klutch_engine_module_parity_runs").select("passed, picks_with_side_flip, picks_with_confidence_diff, monolith_pick_count, module_pick_count, version, notes").gte("run_at",s).limit(1e3);if(t)throw t;const n=a||[],r=n.length,i=n.filter(d=>d.passed).length,l=n.reduce((d,y)=>d+(y.picks_with_side_flip||0),0),m=n.reduce((d,y)=>d+(y.picks_with_confidence_diff||0),0),o=n.reduce((d,y)=>d+Bc(y.notes).picks_with_true_mismatch,0),h=n.reduce((d,y)=>d+(y.monolith_pick_count||0),0),N=n.reduce((d,y)=>d+(y.module_pick_count||0),0);return{runs_24h:r,pass_rate_pct:r?Math.round(i/r*100):0,total_side_flips:l,total_true_mismatches:o,total_calibration_drift:m,monolith_total:h,module_total:N,count_delta_pct:h>0?Math.abs(N-h)/h*100:0}},refetchInterval:6e4})}function Th(s){return s?s==="moneyline"?"moneyline":s==="spread"?"spread":s==="totals"?"totals":s==="props"?"props":null:null}function Lh(s,a){return a>0||(s.picks_with_side_flip||0)>0?"mismatch":s.passed?"match":"calibrated"}const Eh={side_flip:"bg-destructive text-destructive-foreground",line_mismatch:"bg-destructive/80 text-destructive-foreground",market_mismatch:"bg-destructive/80 text-destructive-foreground",only_monolith:"bg-blue-500/20 text-blue-700 dark:text-blue-400",only_module:"bg-purple-500/20 text-purple-700 dark:text-purple-400",calibration_drift:"bg-amber-500/15 text-amber-700 dark:text-amber-400",confidence_drift:"bg-amber-500/15 text-amber-700 dark:text-amber-400"};function Dh(){const{data:s}=Ah(),{data:a,isLoading:t}=Ph(50),[n,r]=v.useState(null),{data:i}=Fh(n),{data:l}=Oc();new Set((l||[]).filter(o=>o.enabled).map(o=>o.engine_key));const m=(a==null?void 0:a.find(o=>o.id===n))||null;return e.jsx(zt,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(rr,{label:"Runs / 24h",value:(s==null?void 0:s.runs_24h)??"—",icon:e.jsx(_t,{className:"h-4 w-4"})}),e.jsx(rr,{label:"True mismatches",value:(s==null?void 0:s.total_true_mismatches)??"—",good:s?s.total_true_mismatches===0:void 0}),e.jsx(rr,{label:"Side flips",value:(s==null?void 0:s.total_side_flips)??"—",good:s?s.total_side_flips===0:void 0}),e.jsx(rr,{label:"Calibration drift",value:(s==null?void 0:s.total_calibration_drift)??"—"}),e.jsx(rr,{label:"Mono / Mod",value:s?`${s.monolith_total} / ${s.module_total}`:"—"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs(G,{children:[e.jsx(je,{className:"pb-3",children:e.jsxs(fe,{className:"text-sm flex items-center gap-2",children:["Recent Parity Runs",e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground cursor-help"})}),e.jsxs(zs,{className:"max-w-xs text-xs",children:[e.jsx("strong",{children:"Match"})," = monolith and module produced the same picks.",e.jsx("br",{}),e.jsx("strong",{children:"Calibrated"})," = same picks, module re-scored confidence via overlays/dynamic weights (expected).",e.jsx("br",{}),e.jsx("strong",{children:"Mismatch"})," = real divergence: side flip, line/market drift, or missing pick — investigate."]})]})]})}),e.jsx(J,{className:"p-0",children:t?e.jsx("div",{className:"p-4 text-xs text-muted-foreground",children:"Loading…"}):!a||a.length===0?e.jsx("div",{className:"p-4 text-xs text-muted-foreground",children:"No parity runs yet. They appear after the next generation cycle."}):e.jsx("div",{className:"max-h-[480px] overflow-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"text-xs",children:"When"}),e.jsx(U,{className:"text-xs",children:"Ver"}),e.jsx(U,{className:"text-xs",children:"Mono / Mod"}),e.jsx(U,{className:"text-xs",children:"Δ Conf"}),e.jsx(U,{className:"text-xs",children:"Status"}),e.jsx(U,{})]})}),e.jsx($e,{children:a.map(o=>e.jsx(Mh,{run:o,selected:n===o.id,onSelect:()=>r(o.id)},o.id))})]})})})]}),e.jsxs(G,{children:[e.jsx(je,{className:"pb-3",children:e.jsx(fe,{className:"text-sm",children:n?"Per-pick diffs":"Select a run to inspect diffs"})}),e.jsx(J,{className:"p-0",children:n?!i||i.length===0?e.jsx("div",{className:"p-4 text-xs text-muted-foreground",children:"Perfect parity — no divergent picks for this run."}):e.jsx("div",{className:"max-h-[480px] overflow-auto divide-y divide-border",children:i.map(o=>
248e.jsx(Ih,{diff:o,activeModules:(m==null?void 0:m.active_modules)||[]},o.id))}):e.jsx("div",{className:"p-4 text-xs text-muted-foreground",children:"Click a run on the left to see every divergent pick."})})]})]})]})})}function Mh({run:s,selected:a,onSelect:t}){const r=Bc(s.notes).picks_with_true_mismatch,i=Lh(s,r),l=s.picks_with_side_flip>0,m=s.picks_with_confidence_diff||0;return e.jsxs(he,{className:`cursor-pointer ${a?"bg-muted/60":""}`,onClick:t,children:[e.jsx(M,{className:"text-xs whitespace-nowrap",children:Dt(new Date(s.run_at),{addSuffix:!0})}),e.jsx(M,{className:"text-xs font-mono",children:s.version}),e.jsxs(M,{className:"text-xs",children:[s.monolith_pick_count," / ",s.module_pick_count]}),e.jsx(M,{className:"text-xs",children:e.jsxs("span",{className:Math.abs(s.confidence_delta_avg)>1?"text-amber-500":"text-muted-foreground",children:[s.confidence_delta_avg>=0?"+":"",s.confidence_delta_avg.toFixed(2)]})}),e.jsx(M,{children:i==="match"?e.jsxs(B,{variant:"outline",className:"text-[10px] border-primary/40 text-primary gap-1",children:[e.jsx(rs,{className:"h-3 w-3"}),"match"]}):i==="calibrated"?e.jsxs(B,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-600 dark:text-amber-400 gap-1",children:[e.jsx(mc,{className:"h-3 w-3"}),"calibrated",m>0?` (${m})`:""]}):e.jsxs(B,{variant:"destructive",className:"text-[10px] gap-1",children:[e.jsx(ls,{className:"h-3 w-3"}),"mismatch",l?` (${s.picks_with_side_flip} flip${s.picks_with_side_flip>1?"s":""})`:""]})}),e.jsx(M,{children:e.jsx(st,{className:"h-3 w-3 text-muted-foreground"})})]})}function Ih({diff:s,activeModules:a}){const t=Eh[s.diff_type]||"",n=Th(s.engine_id),r=n?a.includes(n):!1;return e.jsxs("div",{className:"p-3 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{className:`text-[10px] ${t}`,children:s.diff_type.replace(/_/g," ")}),r&&e.jsx(B,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-600 dark:text-amber-400",children:"expected (module mode)"}),e.jsx("span",{className:"font-mono text-muted-foreground",children:s.sport??"—"}),e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{children:s.pick_type??"—"}),s.engine_id&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{className:"text-muted-foreground",children:s.engine_id})]})]}),s.delta&&e.jsx("code",{className:"text-[10px] text-muted-foreground",children:JSON.stringify(s.delta)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[e.jsx(Bl,{label:"Monolith",pick:s.monolith_pick}),e.jsx(Bl,{label:"Module",pick:s.module_pick})]})]})}function Bl({label:s,pick:a}){return a?e.jsxs("div",{className:"rounded border border-border p-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground mb-1",children:s}),e.jsx("div",{className:"font-medium truncate",title:a.pick,children:a.pick??"—"}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["conf ",a.confidence_score??"—"," · ",a.pick_direction??a.picked_side??"—",a.engine_id?` · ${a.engine_id}`:""]})]}):e.jsxs("div",{className:"rounded border border-dashed border-border p-2 text-[10px] text-muted-foreground",children:[s,": ",e.jsx("span",{className:"italic",children:"absent"})]})}function rr({label:s,value:a,icon:t,good:n}){return e.jsx(G,{children:e.jsxs(J,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-1",children:[t,s]}),e.jsx("div",{className:`text-lg font-semibold ${n===!0?"text-primary":n===!1?"text-destructive":""}`,children:a})]})})}const Rh=["moneyline","spread","totals","props"],bn="__null__",qh=30;function $h(s,a){const t=new Date(`${s}T12:00:00Z`);return t.setUTCDate(t.getUTCDate()+a),t.toISOString().slice(0,10)}function Oh(){const s=v.useMemo(()=>new Intl.DateTimeFormat("en-CA",{timeZone:"America/Chicago"}).format(new Date),[]),[a,t]=v.useState({day:s,sport:"all",market:"all",version:"all"}),n=v.useMemo(()=>Array.from({length:qh},(p,w)=>$h(s,-w)),[s]),r=v.useMemo(()=>({start:a.day==="all"?n[n.length-1]:a.day,end:a.day==="all"?s:a.day}),[n,a.day,s]),{data:i,isLoading:l,isError:m,error:o}=ge({queryKey:["policy-lab-funnel",r.start,r.end],queryFn:async()=>{var C;const p=T,w=a.day==="all"?n:[a.day],S=await Promise.all(w.map(O=>p.rpc("get_klutch_pipeline_funnel",{p_start_day:O,p_end_day:O}))),P=(C=S.find(({error:O})=>O))==null?void 0:C.error;if(P)throw P;return S.flatMap(({data:O})=>O||[])},refetchInterval:a.day==="all"?3e5:3e4}),{data:h}=Oc(),N=Nh(),{data:d,isLoading:y}=bh(),u=v.useMemo(()=>{const p=new Set,w=new Set,S=new Set;for(const P of i||[])P.sport&&p.add(P.sport),P.pick_type&&w.add(P.pick_type),S.add(P.source_version||bn);return{sports:[...p].sort(),markets:[...w].sort(),versions:[...S].sort()}},[i]),x=v.useMemo(()=>(i||[]).filter(p=>!(a.day!=="all"&&p.day!==a.day||a.sport!=="all"&&p.sport!==a.sport||a.market!=="all"&&p.pick_type!==a.market||a.version!=="all"&&(p.source_version||bn)!==a.version)),[i,a]),g=x.reduce((p,w)=>(p.candidates+=w.candidate_count||0,p.published+=w.published_count||0,p.core+=w.core_count||0,p.plus+=w.plus_count||0,p.lab+=w.lab_count||0,p.dropped+=w.dropped_count||0,p),{candidates:0,published:0,core:0,plus:0,lab:0,dropped:0}),f=new Map((h||[]).map(p=>[p.engine_key,p])),_=a.day!=="all"||a.sport!=="all"||a.market!=="all"||a.version!=="all",k=()=>t({day:s,sport:"all",market:"all",version:"all"}),b=((d==null?void 0:d.gamesPerSport)||[]).slice(0,4).map(p=>`${p.sport.toUpperCase()} ${p.count}`).join(" · "),j=((d==null?void 0:d.picksPerSport)||[]).slice(0,4).map(p=>`${p.sport.toUpperCase()} ${p.count}`).join(" · "),c=((d==null?void 0:d.picksPerBetType)||[]).map(p=>`${p.pick_type} ${p.count}`).join(" · ");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{className:"text-base",children:"Engine Module Toggles"}),e.jsxs(De,{children:["Per-engine kill switches. When OFF the legacy monolith handles that bet type. When ON the federated specialist engine writes calibrated picks to ",e.jsx("code",{children:"klutch_module_finalized_picks"}),"."]})]}),e.jsx(J,{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Rh.map(p=>{const w=f.get(p);return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-card/40 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium capitalize",children:p}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:w!=null&&w.enabled?"Module":"Monolith"})]}),e.jsx(Ge,{checked:!!(w!=null&&w.enabled),disabled:N.isPending,onCheckedChange:S=>N.mutate({engine_key:p,enabled:S})})]},p)})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(wn,{icon:e.jsx($s,{className:"h-4 w-4 text-muted-foreground"}),label:"Last Run",value:y?"—":wh((d==null?void 0:d.lastRun)||null),subtext:(d==null?void 0:d.lastRunMinutesAgo)==null?"Dispatcher has not fired yet":e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"truncate",children:["Dispatcher fired · ",d.lastRunMinutesAgo," min ago"]}),e.jsx("div",{className:"truncate text-[10px] opacity-80",children:d.lastPickMinutesAgo==null?"No published picks yet":`Last published pick · ${d.lastPickMinutesAgo} min ago`})]}),status:d==null?void 0:d.pipelineStatus,statusTooltip:(d==null?void 0:d.pipelineStatus)==="healthy"?`Dispatcher firing on schedule (last attempt ${d.lastRunMinutesAgo} min ago)`:(d==null?void 0:d.pipelineStatus)==="warning"?`Slow — dispatcher last fired ${d.lastRunMinutesAgo}
248 min ago (expected every 15 min)`:`Stale — ${(d==null?void 0:d.lastRunMinutesAgo)??"?"} min since dispatcher fired. Cron may be failing. Check edge function logs.`}),e.jsx(wn,{icon:e.jsx(zi,{className:"h-4 w-4 text-muted-foreground"}),label:"Today's Games",value:y?"—":((d==null?void 0:d.totalGames)??0).toLocaleString(),subtext:b||"No games scheduled today"}),e.jsx(wn,{icon:e.jsx(As,{className:"h-4 w-4 text-muted-foreground"}),label:"Today's Picks",value:y?"—":((d==null?void 0:d.totalPicks)??0).toLocaleString(),subtext:e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"truncate",children:j||"—"}),e.jsx("div",{className:"truncate text-[10px] opacity-80",children:c||"—"})]})})]}),e.jsx(Uh,{status:d==null?void 0:d.pipelineStatus,minutesAgo:(d==null?void 0:d.lastRunMinutesAgo)??null}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3",children:[e.jsx(Na,{label:"Candidates",value:m?null:g.candidates}),e.jsx(Na,{label:"Pub",value:m?null:g.published,accent:"primary"}),e.jsx(Na,{label:"Core",value:m?null:g.core,accent:"primary"}),e.jsx(Na,{label:"Plus",value:m?null:g.plus,accent:"primary"}),e.jsx(Na,{label:"Lab",value:m?null:g.lab}),e.jsx(Na,{label:"Drop",value:m?null:g.dropped,accent:"destructive"})]}),e.jsxs(js,{defaultValue:"funnel",className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-1 h-auto p-1 justify-start",children:[e.jsxs(Ne,{value:"funnel",className:"text-xs gap-1.5",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"Funnel by Day"]}),e.jsxs(Ne,{value:"finalized",className:"text-xs gap-1.5",children:[e.jsx(tt,{className:"h-3.5 w-3.5"}),"Finalized Picks"]}),e.jsxs(Ne,{value:"parity",className:"text-xs gap-1.5",children:[e.jsx(mc,{className:"h-3.5 w-3.5"}),"Parity"]})]}),e.jsx(we,{value:"funnel",className:"mt-4",children:e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{className:"text-base",children:"Funnel by Day · Sport · Market · Version"}),e.jsxs(De,{children:[e.jsx("code",{children:"Cand"})," = candidates the engines evaluated. ",e.jsx("code",{children:"Pub"})," = picks promoted to users. ",e.jsx("code",{children:"Core"})," / ",e.jsx("code",{children:"Plus"})," / ",e.jsx("code",{children:"Lab"})," = NTS tier of each published pick (Core = top trust, Plus = above average, Lab = experimental or locked engines like Spread). ",e.jsx("code",{children:"Drop"})," = picks explicitly rejected by a module engine or by the meta-router. The legacy monolith pipeline filters silently and is not counted in ",e.jsx("code",{children:"Drop"}),", so legacy rows commonly show ",e.jsx("code",{children:"Drop = 0"})," by design."]})]}),e.jsxs(J,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs(oe,{value:a.day,onValueChange:p=>t(w=>({...w,day:p})),children:[e.jsx(de,{className:"h-8 text-xs",children:e.jsx(ue,{placeholder:"Date"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All days"}),n.map(p=>e.jsx(V,{value:p,children:p},p))]})]}),e.jsxs(oe,{value:a.sport,onValueChange:p=>t(w=>({...w,sport:p})),children:[e.jsx(de,{className:"h-8 text-xs",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All sports"}),u.sports.map(p=>e.jsx(V,{value:p,className:"capitalize",children:p},p))]})]}),e.jsxs(oe,{value:a.market,onValueChange:p=>t(w=>({...w,market:p})),children:[e.jsx(de,{className:"h-8 text-xs",children:e.jsx(ue,{placeholder:"Market"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All markets"}),u.markets.map(p=>e.jsx(V,{value:p,className:"capitalize",children:p},p))]})]}),e.jsxs(oe,{value:a.version,onValueChange:p=>t(w=>({...w,version:p})),children:[e.jsx(de,{className:"h-8 text-xs",children:e.jsx(ue,{placeholder:"Version"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All versions"}),u.versions.map(p=>e.jsx(V,{value:p,children:p===bn?"— (none)":p},p))]})]})]}),_&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:k,children:[e.jsx(rt,{className:"h-3 w-3 mr-1"}),"Reset filters"]})})]}),l?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(ne,{className:"h-5 w-5 animate-spin mr-2"}),"Loading funnel…"]}):m?e.jsxs("div",{className:"flex items-start gap-2 text-sm text-destructive py-6",children:[e.jsx(xs,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Pipeline activity could not be loaded."}),e.jsx("div",{className:"text-xs mt-1 opacity-80",children:o instanceof Error?o.message:"Unknown database error"})]})]}):!i||i.length===0?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-6",children:[e.jsx(xs,{className:"h-4 w-4"}),"No pipeline activity yet."]}):x.length===0?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-6",children:[e.jsx(xs,{className:"h-4 w-4"}),"No pipeline activity for the selected filters."]}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Day"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Market"}),e.jsx(U,{children:"Version"}),e.jsx(U,{className:"text-right",children:"Cand"}),e.jsx(U,{className:"text-right",children:"Pub"}),e.jsx(U,{className:"text-right",children:"Core"}),e.jsx(U,{className:"text-right",children:"Plus"}),e.jsx(U,{className:"text-right",children:"Lab"}),e.jsx(U,{className:"text-right",children:"Drop"})]})}),e.jsx($e,{children:x.map((p,w)=>{const S=p.pick_type==="spread",P=p.day===s,C=p.candidate_count>=50&&p.published_count===0&&p.dropped_count===0&&!S&&!P;return e.jsxs(he,{className:C?"bg-destructive/5":void 0,children:[e.jsx(M,{className:"text-xs",children:p.day}),e.jsx(M,{className:"text-xs capitalize",children:p.sport}),e.jsx(M,{className:"text-xs capitalize",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[p.pick_type,C&&e.jsx("span",{className:"inline-flex items-center text-destructive",title:"Past day with 50+ candidates and no pub/drop activity — investigate whether promote ran for this slice.",children:e.jsx(xs,{className:"h-3 w-3"})})]})}),e.jsx(M,{className:"text-xs",children:e.jsx(B,{variant:"outline",className:"text-[10px]",children:p.source_version||"—"})}),e.jsx(M,{className:"text-xs text-right",children:p.candidate_count}),e.jsx(M,{className:"text-xs text-right text-primary font-semibold",children:p.published_count}),e.jsx(M,{className:"text-xs text-right text-primary font-semibold",children:p.core_count}),e.jsx(M,{className:"text-xs text-right text-primary",children:p.plus_count}),e.jsx(M,{className:"text-xs text-right text-muted-foreground",children:p.lab_count}),e.jsx(M,{className:"text-xs text-right text-destructive",children:p.dropped_count})]},w)})})]})})]})]})}),e.jsx(we,{value:"finalized",className:"mt-4",children:e.jsx(Ch,{})}),e.jsx(we,{value:"parity",className:"mt-4",children:e.jsx(Dh,{})})]})]})}function wn({icon:s,label:a,value:t,subtext:n,status:r,statusTooltip:i}){const l=r==="healthy"?"bg-green-500":r==="warning"?"bg-amber-500":r==="stale"?"bg-destructive animate-pulse":"";return e.jsx(G,{children:e.jsxs(J,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[s,e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:a}),r&&e.jsx("span",{className:`ml-auto inline-block h-2 w-2 rounded-full ${l}`,title:i})]}),e.jsx("div",{className:"text-2xl font-bold mt-1 text-foreground truncate",children:t}),e.jsx("div",{className:"text-[11px] text-muted-foreground mt-1",children:n})]})})}function Uh({status:s,minutesAgo:a}){const t=s==="stale"||s==="warning",{data:n}=Sh({enabled:t,limit:5});if(!t)return null;const r=s==="stale",i=r?"border-destructive/60 bg-destructive/10 text-destructive":"border-amber-500/60 bg-amber-500/10 text-amber-600 dar
248k:text-amber-400",m="https://supabase.com/dashboard/project/qqamfojeypfnjezyofqc/functions";return e.jsx("div",{className:`rounded-md border p-3 ${i}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(xs,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[e.jsx("div",{className:"text-sm font-semibold",children:r?`KLUTCH generation appears stalled — last pick ${a??"?"} min ago`:`KLUTCH generation is slow — last pick ${a} min ago`}),e.jsxs("div",{className:"text-xs opacity-90",children:["sync-orchestrator runs every 5 min and triggers generation every 15 min. Healthy: < 15 min."," ",e.jsxs("a",{href:`${m}/sync-orchestrator/logs`,target:"_blank",rel:"noreferrer",className:"underline inline-flex items-center gap-0.5",children:["sync-orchestrator logs ",e.jsx(Ma,{className:"h-3 w-3"})]})," · ",e.jsxs("a",{href:`${m}/generate-klutch-picks/logs`,target:"_blank",rel:"noreferrer",className:"underline inline-flex items-center gap-0.5",children:["generate-klutch-picks logs ",e.jsx(Ma,{className:"h-3 w-3"})]})]}),n&&n.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide opacity-80",children:"Recent errors (last 2 hrs)"}),e.jsx("ul",{className:"space-y-1",children:n.map(o=>e.jsxs("li",{className:"text-[11px] font-mono bg-background/40 rounded px-2 py-1 break-all",children:[e.jsxs("span",{className:"opacity-70",children:[new Date(o.created_at).toLocaleTimeString()," · ",o.function_name,o.severity!=="error"?` (${o.severity})`:""," ·"]})," ",o.message]},o.id))})]}),n&&n.length===0&&e.jsx("div",{className:"text-[11px] opacity-80",children:"No errors recorded in the last 2 hours — cron may not be firing at all. Check Supabase cron and the orchestrator logs above."})]})]})})}function Na({label:s,value:a,accent:t}){const n=t==="primary"?"text-primary":t==="destructive"?"text-destructive":"text-foreground";return e.jsx(G,{children:e.jsxs(J,{className:"p-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:`text-2xl font-bold mt-1 ${n}`,children:a==null?"—":a.toLocaleString()})]})})}function Bh(){return ge({queryKey:["klutch-version-specialization"],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_version_specialization").select("*").order("sport").order("pick_type").order("roi_pct",{ascending:!1});if(a)throw a;return s||[]},staleTime:6e4,refetchInterval:6e4})}function zh(){return ge({queryKey:["klutch-calibration-health"],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_calibration_runs").select("id,status,started_at,completed_at,evidence_rows,calibration_rows,error_message,details,mode,checkpoint_from,checkpoint_to,source_rows_processed,backlog_rows").order("started_at",{ascending:!1}).limit(1).maybeSingle();if(a)throw a;return s},staleTime:6e4,refetchInterval:6e4})}function Kh(){return ge({queryKey:["klutch-evidence-health"],queryFn:async()=>{const[s,a]=await Promise.all([T.from("klutch_evidence_checkpoint").select("last_status,last_success_at,last_error,backlog_rows").eq("pipeline","klutch_v4_evidence").maybeSingle(),T.from("klutch_evidence_reconciliation").select("settled_source_evaluations,promoted_evaluations,unpublished_evaluations,credited_source_outcomes,router_outcomes,duplicates_removed,unattributable_records,eligible_outcomes,excluded_outcomes,exclusion_reasons,created_at").order("created_at",{ascending:!1}).limit(1).maybeSingle()]);if(s.error)throw s.error;if(a.error)throw a.error;return{checkpoint:s.data,reconciliation:a.data}},staleTime:6e4,refetchInterval:6e4})}const Vh=["dominant","competitive","fallback","muted","insufficient_sample"],zc={dominant:{label:"Dominant",icon:Gn,className:"bg-emerald-500/15 text-emerald-400 border-emerald-500/40"},competitive:{label:"Competitive",icon:rs,className:"bg-sky-500/15 text-sky-400 border-sky-500/40"},fallback:{label:"Fallback",icon:uu,className:"bg-amber-500/15 text-amber-400 border-amber-500/40"},muted:{label:"Muted",icon:Qi,className:"bg-red-500/15 text-red-400 border-red-500/40"},insufficient_sample:{label:"Insufficient",icon:cu,className:"bg-muted text-muted-foreground border-border"}};function _a({status:s}){const a=zc[s],t=a.icon;return e.jsxs(B,{variant:"outline",className:Le("gap-1 text-[10px]",a.className),children:[e.jsx(t,{className:"h-3 w-3"}),a.label]})}function Hh(s){return s==="confidence_90_or_lower"?"≤90 conf":s==="v5_candidate_ineligible"?"v5 ineligible":s==="clv_blind"?"CLV blind":s==="prop_juice_too_heavy"?"Heavy juice":s==="prop_juice_too_long"?"Long juice":s==="sport_overlay_zero_weight"?"Sport gated":s==="signal_overlay_zero_weight"?"Signal gated":s==="extreme_juice"?"Extreme juice":s==="negative_ev"?"Negative EV":s.split("_").join(" ")}function Wh(s){if((s.sample_size??0)>0||(s.settled_sample_size??0)===0)return null;const a=s.excluded_reason_summary??{},[t,n]=Object.entries(a).sort((r,i)=>Number(i[1])-Number(r[1]))[0]??[];return t?`${Hh(t)} (${n})`:(s.dropped_sample_size??0)>0?`Dropped (${s.dropped_sample_size})`:(s.low_confidence_sample_size??0)>0?s.generation_version==="v5"?`Not eligible (${s.low_confidence_sample_size})`:`≤90 conf (${s.low_confidence_sample_size})`:"Excluded"}function Gh(){const{data:s,isLoading:a,refetch:t}=Bh(),{data:n,refetch:r}=zh(),{data:i,refetch:l}=Kh(),[m,o]=v.useState(!1),{toast:h}
248=Ws(),[N,d]=v.useState("all"),[y,u]=v.useState("all"),[x,g]=v.useState("all"),[f,_]=v.useState(new Set),[k,b]=v.useState(new Set),[j,c]=v.useState(!1),p=v.useMemo(()=>{const D=new Set,A=new Set,F=new Set,q=new Set;for(const L of s??[])D.add(L.sport),A.add(L.pick_type),F.add(L.engine_id),q.add(L.generation_version);const E=(L,H)=>L.localeCompare(H,void 0,{numeric:!0});return{sports:Array.from(D).sort(),pickTypes:Array.from(A).sort(),engines:Array.from(F).sort(),versions:Array.from(q).sort(E)}},[s]),w=v.useMemo(()=>(s??[]).filter(D=>!(N!=="all"&&D.sport!==N||y!=="all"&&D.pick_type!==y||x!=="all"&&D.engine_id!==x||f.size>0&&!f.has(D.generation_version)||k.size>0&&!k.has(D.status)||j&&(D.sample_size??0)===0)),[s,N,y,x,f,k,j]),S=v.useMemo(()=>{const D=new Map;for(const A of w){const F=`${A.sport} • ${A.pick_type}`,q=D.get(F)??[];q.push(A),D.set(F,q)}for(const A of D.values())A.sort((F,q)=>(q.roi_pct??-999)-(F.roi_pct??-999));return Array.from(D.entries()).sort(([A],[F])=>A.localeCompare(F))},[w]),P=v.useMemo(()=>{const D={dominant:0,competitive:0,fallback:0,muted:0,insufficient_sample:0};for(const A of w)D[A.status]++;return D},[w]),C=(D,A,F)=>{const q=new Set(D);q.has(F)?q.delete(F):q.add(F),A(q)},O=N!=="all"||y!=="all"||x!=="all"||f.size>0||k.size>0||j,$=()=>{d("all"),u("all"),g("all"),_(new Set),b(new Set),c(!1)};async function z(){var D,A;o(!0);try{const F=await T.functions.invoke("process-klutch-v4-specialization",{body:{}});if(F.error||((D=F.data)==null?void 0:D.ok)!==!0)throw F.error??new Error(((A=F.data)==null?void 0:A.error)??"Specialization failed");h({title:"v4 evidence refreshed",description:"Incremental attribution, calibration, and lifetime specialization completed."}),await Promise.all([t(),r(),l()])}catch(F){h({title:"Recompute failed",description:(F==null?void 0:F.message)??"Unknown error",variant:"destructive"})}finally{o(!1)}}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-base",children:"v4 Specialization Matrix"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 max-w-3xl",children:["Per (sport × market × version) routing classification over lifetime history. Status uses only non-dropped finalized rows with adjusted confidence ",e.jsx("span",{className:"font-medium text-foreground",children:"greater than 90%"}),"; The legacy score is a publication gate—not a probability. Settled/dropped diagnostics show the wider audit history behind zero routing samples. The v4 router publishes from ",e.jsx("span",{className:"text-emerald-400",children:"dominant"})," versions first, can use ",e.jsx("span",{className:"text-sky-400",children:"competitive"})," fallback when allowed, and filters",e.jsx("span",{className:"text-red-400",children:" muted"})," or ",e.jsx("span",{className:"text-muted-foreground",children:"insufficient"})," slices."]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsxs(R,{size:"sm",variant:"outline",onClick:z,disabled:m,children:[m?e.jsx(ne,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(He,{className:"h-3.5 w-3.5 mr-1.5"}),"Recompute"]}),e.jsx(Yh,{run:n})]})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(_a,{status:"dominant"})," ",e.jsx("span",{className:"text-xs text-muted-foreground self-center",children:P.dominant}),e.jsx(_a,{status:"competitive"})," ",e.jsx("span",{className:"text-xs text-muted-foreground self-center",children:P.competitive}),e.jsx(_a,{status:"fallback"})," ",e.jsx("span",{className:"text-xs text-muted-foreground self-center",children:P.fallback}),e.jsx(_a,{status:"muted"})," ",e.jsx("span",{className:"text-xs text-muted-foreground self-center",children:P.muted}),e.jsx(_a,{status:"insufficient_sample"})," ",e.jsx("span",{className:"text-xs text-muted-foreground self-center",children:P.insufficient_sample})]}),e.jsx(Qh,{health:i}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 pt-3 border-t",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Q,{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Sport"}),e.jsxs(oe,{value:N,onValueChange:d,children:[e.jsx(de,{className:"h-8 w-[140px] text-xs capitalize",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All sports"}),p.sports.map(D=>e.jsx(V,{value:D,className:"capitalize",children:D},D))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Q,{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Bet type"}),e.jsxs(oe,{value:y,onValueChange:u,children:[e.jsx(de,{className:"h-8 w-[140px] text-xs capitalize",children:e.jsx(ue,{})}
248),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All bet types"}),p.pickTypes.map(D=>e.jsx(V,{value:D,className:"capitalize",children:D},D))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Q,{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Engine"}),e.jsxs(oe,{value:x,onValueChange:g,children:[e.jsx(de,{className:"h-8 w-[160px] text-xs",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All engines"}),p.engines.map(D=>e.jsx(V,{value:D,children:D},D))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Q,{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Version"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:p.versions.map(D=>{const A=f.has(D);return e.jsx(R,{type:"button",size:"sm",variant:A?"default":"outline",className:"h-7 px-2 text-[11px] font-mono",onClick:()=>C(f,_,D),children:D},D)})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Q,{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Vh.map(D=>{const A=k.has(D);return e.jsx(R,{type:"button",size:"sm",variant:A?"default":"outline",className:"h-7 px-2 text-[11px]",onClick:()=>C(k,b,D),children:zc[D].label},D)})})]}),e.jsxs("div",{className:"flex items-center gap-2 h-8",children:[e.jsx(Ge,{id:"hide-zero",checked:j,onCheckedChange:c}),e.jsx(Q,{htmlFor:"hide-zero",className:"text-xs cursor-pointer",children:"Hide zero-routing"})]}),O&&e.jsxs(R,{size:"sm",variant:"ghost",className:"h-8 text-xs",onClick:$,children:[e.jsx(rt,{className:"h-3.5 w-3.5 mr-1"})," Reset"]})]})]})]}),a?e.jsxs("div",{className:"flex items-center justify-center py-10 text-sm text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"})," Loading matrix…"]}):S.length===0?e.jsx(G,{children:e.jsx(J,{className:"py-10 text-center text-sm text-muted-foreground",children:O?e.jsxs(e.Fragment,{children:["No rows match the current filters. ",e.jsx("button",{onClick:$,className:"underline",children:"Reset filters"}),"."]}):e.jsxs(e.Fragment,{children:["No classification rows yet. Click ",e.jsx("span",{className:"font-medium",children:"Recompute"})," to populate from lifetime settled evidence."]})})}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:S.map(([D,A])=>e.jsxs(G,{children:[e.jsx(je,{className:"pb-2",children:e.jsx(fe,{className:"text-sm capitalize",children:D})}),e.jsx(J,{className:"pt-0",children:e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted/30",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-1.5 font-medium",children:"Version"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Routing n"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Settled"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Dropped"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Not pickable"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"WR"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"ROI"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Units"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Season n"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Season WR"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Attributed"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-medium",children:"Excluded by"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Status"})]})}),e.jsx("tbody",{children:A.map(F=>{var E;const q=Wh(F);return e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"px-2 py-1.5 font-mono",children:F.generation_version}),e.jsx("td",{className:"px-2 py-1.5 text-right tabular-nums font-medium",children:F.sample_size}),e.jsx("td",{className:"px-2 py-1.5 text-right tabular-nums text-muted-foreground",children:F.settled_sample_size??0}),e.jsx("td",{className:"px-2 py-1.5 text-right tabular-nums text-muted-foreground",children:F.dropped_sample_size??0}),e.jsx("td",{className:"px-2 py-1.5 text-right tabular-nums text-muted-foreground",children:F.low_confidence_sample_size??0}),e.jsxs("td",{className:"px-2 py-1.5 text-right tabular-nums",children:[((E=F.win_rate)==null?void 0:E.toFixed(1))??"—","%"]}),e.jsx("td",{className:Le("px-2 py-1.5 text-right tabular-nums",(F.roi_pct??0)>0?"text-emerald-400":(F.roi_pct??0)<0?"text-red-400":""),children:F.roi_pct!=null?`${F.roi_pct>0?"+":""}${F.roi_pct.toFixed(1)}%`:"—"}),e.jsx("td",{className:Le("px-2 py-1.5 text-right tabular-nums",(F.net_units??0)>0?"text-emerald-400":(F.net_units??0)<0?"text-red-400":""),children:F.net_units!=null?`${F.net_units>0?"+":""}${F.net_units.toFixed(1)}u`:"—"}),e.jsx("td",{className:"px-2 py-1.5 text-right tabular-nums",children:F.current_season_sample_size??0}),e.jsx("td",{className:"px-2 py-1.5 text-right tabular-nums",children:F.current_season_win_rate!=null?`${F.
248current_season_win_rate.toFixed(1)}%`:"—"}),e.jsxs("td",{className:"px-2 py-1.5 text-right tabular-nums",children:[(F.attribution_completeness_pct??0).toFixed(1),"%"]}),e.jsx("td",{className:"px-2 py-1.5 text-left",children:q?e.jsx(B,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-400 border-amber-500/40 whitespace-nowrap",children:q}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"px-2 py-1.5 text-right",children:e.jsx(_a,{status:F.status})})]},F.id)})})]})})})]},D))})]})}function Qh({health:s}){var r,i;const a=s==null?void 0:s.checkpoint,t=s==null?void 0:s.reconciliation,n=!a||a.last_status!=="healthy"||a.backlog_rows>0;return e.jsxs("div",{className:Le("grid gap-2 rounded-md border p-3 text-xs sm:grid-cols-4",n?"border-red-500/40":"border-border"),children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Pipeline"}),e.jsx("div",{className:n?"text-red-400":"text-emerald-400",children:(a==null?void 0:a.last_status)??"unverified"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Backlog"}),e.jsx("div",{className:"tabular-nums",children:((r=a==null?void 0:a.backlog_rows)==null?void 0:r.toLocaleString())??"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Attribution"}),e.jsx("div",{className:"tabular-nums",children:t?`${t.credited_source_outcomes.toLocaleString()} / ${t.settled_source_evaluations.toLocaleString()}`:"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Quarantined"}),e.jsx("div",{className:t!=null&&t.unattributable_records?"text-amber-400 tabular-nums":"tabular-nums",children:((i=t==null?void 0:t.unattributable_records)==null?void 0:i.toLocaleString())??"—"})]}),(a==null?void 0:a.last_error)&&e.jsx("div",{className:"sm:col-span-4 text-red-400",children:a.last_error})]})}function Yh({run:s}){if(!s)return e.jsx(B,{variant:"outline",className:"text-[10px] text-amber-400 border-amber-500/40",children:"Calibration unverified"});const a=s.completed_at?Date.parse(s.completed_at):NaN,t=Number.isFinite(a)?(Date.now()-a)/36e5:null,n=s.status==="succeeded"&&(t==null||t>36),r=s.status==="failed"||n?"text-red-400 border-red-500/40":s.status==="succeeded"?"text-emerald-400 border-emerald-500/40":"text-amber-400 border-amber-500/40",i=s.status==="failed"?`Calibration failed${s.error_message?`: ${s.error_message}`:""}`:n?`Calibration stale · ${Math.floor(t)}h`:s.status==="succeeded"?`Calibration current · ${s.evidence_rows.toLocaleString()} results`:`Calibration ${s.status}`;return e.jsx(B,{variant:"outline",className:Le("max-w-[360px] truncate text-[10px]",r),title:i,children:i})}const Jh=[{value:30,label:"30d"},{value:90,label:"90d"},{value:9999,label:"All"}];function Sn({pts:s,minN:a=20,n:t=0}){if(s==null||t<a)return e.jsxs(B,{variant:"outline",className:"gap-1 text-[10px] bg-muted text-muted-foreground border-border",children:[e.jsx(Da,{className:"h-3 w-3"})," n/a"]});const n=s>.5,r=s<-.5,i=n?Ds:r?qt:Da;return e.jsxs(B,{variant:"outline",className:Le("gap-1 text-[10px] font-mono",n&&"bg-emerald-500/15 text-emerald-400 border-emerald-500/40",r&&"bg-red-500/15 text-red-400 border-red-500/40",!n&&!r&&"bg-muted text-muted-foreground border-border"),children:[e.jsx(i,{className:"h-3 w-3"}),s>0?"+":"",s.toFixed(1)," pts"]})}function nr(s){return s==null?"—":`${s.toFixed(1)}%`}function Zh(){var d;const[s,a]=v.useState(90),[t,n]=v.useState(!1),{toast:r}=Ws(),{data:i,isLoading:l,refetch:m}=ge({queryKey:["klutch_engine_lift_audit",s],queryFn:async()=>{const{data:y,error:u}=await T.from("klutch_engine_lift_audit").select("*").eq("window_days",s).order("computed_at",{ascending:!1}).limit(500);if(u)throw u;const x=new Set,g=[];for(const f of y??[]){const _=`${f.module_engine_id}|${f.source_version}|${f.sport}`;x.has(_)||(x.add(_),g.push(f))}return g},staleTime:6e4}),o=v.useMemo(()=>{const y=new Map;for(const u of i??[]){const x=u.module_engine_id,g=y.get(x)??[];g.push(u),y.set(x,g)}for(const u of y.values())u.sort((x,g)=>
248x.sport!==g.sport?x.sport.localeCompare(g.sport):x.source_version.localeCompare(g.source_version));return Array.from(y.entries()).sort(([u],[x])=>u.localeCompare(x))},[i]),h=async()=>{n(!0);try{const{error:y}=await T.functions.invoke("recompute-engine-lift");if(y)throw y;r({title:"Engine lift audit recomputed",description:"Fresh numbers loaded."}),await m()}catch(y){r({title:"Recompute failed",description:(y==null?void 0:y.message)??String(y),variant:"destructive"})}finally{n(!1)}},N=(d=i==null?void 0:i[0])!=null&&d.computed_at?new Date(i[0].computed_at).toLocaleString():null;return e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-start justify-between gap-3 pb-3",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-base",children:"Engine Lift Audit"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Per-engine lift measured on the ",e.jsx("strong",{children:"full finalized pool"}),", not just promoted picks. Compares engine BET/PASS decisions against what the monolith would have said on the same candidate. Positive net_lift = engine picks the correct BET pool; add_value / veto_value use −110 break-even (52.4%). Cells with fewer than 20 settled bets show n/a."]}),N&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Last computed: ",N]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("div",{className:"flex items-center gap-1 rounded-md border bg-card p-1",role:"group",children:Jh.map(y=>e.jsx(R,{type:"button",size:"sm",variant:s===y.value?"default":"ghost",className:Le("h-7 px-2.5 text-xs",s===y.value&&"shadow"),onClick:()=>a(y.value),children:y.label},y.value))}),e.jsxs(R,{size:"sm",variant:"outline",onClick:h,disabled:t,className:"gap-1.5",children:[t?e.jsx(ne,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(He,{className:"h-3.5 w-3.5"}),"Recompute"]})]})]}),e.jsx(J,{children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-8 justify-center",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"})," Loading lift audit…"]}):o.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground py-8 text-center",children:["No lift data yet for this window. Click ",e.jsx("strong",{children:"Recompute"})," to run the first pass."]}):e.jsx("div",{className:"space-y-6",children:o.map(([y,u])=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-semibold capitalize",children:[y," engine"]}),e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted/40 text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-2 py-1.5 font-medium",children:"Sport"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-medium",children:"Version"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Finalized"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Settled"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Engine BET WR"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Monolith BET WR"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-medium",children:"Net Lift"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Agree BET (n / WR)"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Engine-only (n / WR)"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-medium",children:"Add value"}),e.jsx("th",{className:"text-right px-2 py-1.5 font-medium",children:"Engine veto (n / WR)"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-medium",children:"Veto value"})]})}),e.jsx("tbody",{children:u.map(x=>e.jsxs("tr",{className:"border-t hover:bg-muted/20",children:[e.jsx("td",{className:"px-2 py-1.5 capitalize",children:x.sport}),e.jsx("td",{className:"px-2 py-1.5 font-mono",children:x.source_version}),e.jsx("td",{className:"px-2 py-1.5 text-right font-mono",children:x.finalized_n.toLocaleString()}),e.jsx("td",{className:"px-2 py-1.5 text-right font-mono",children:x.settled_n.toLocaleStr
248ing()}),e.jsx("td",{className:"px-2 py-1.5 text-right font-mono",children:nr(x.engine_bet_wr)}),e.jsx("td",{className:"px-2 py-1.5 text-right font-mono",children:nr(x.monolith_bet_wr)}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsx(Sn,{pts:x.net_lift_pts,n:x.agree_bet_n+x.engine_only_bet_n+x.engine_veto_n})}),e.jsxs("td",{className:"px-2 py-1.5 text-right font-mono",children:[x.agree_bet_n," / ",nr(x.agree_bet_wr)]}),e.jsxs("td",{className:"px-2 py-1.5 text-right font-mono",children:[x.engine_only_bet_n," / ",nr(x.engine_only_bet_wr)]}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsx(Sn,{pts:x.add_value_pts,n:x.engine_only_bet_n})}),e.jsxs("td",{className:"px-2 py-1.5 text-right font-mono",children:[x.engine_veto_n," / ",nr(x.engine_veto_wr)]}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsx(Sn,{pts:x.veto_value_pts,n:x.engine_veto_n})})]},x.id))})]})})]},y))})})]})}const sn="engine_auto_promotion_enabled";function Xh(){return ge({queryKey:["klutch-system-flag",sn],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_system_flags").select("flag_value, updated_at, updated_by").eq("flag_key",sn).maybeSingle();if(a)throw a;return s},refetchInterval:3e4})}function ep(){const s=Me();return _e({mutationFn:async a=>{var r;const{data:t}=await T.auth.getUser(),{error:n}=await T.from("klutch_system_flags").update({flag_value:a,updated_at:new Date().toISOString(),updated_by:((r=t.user)==null?void 0:r.id)??null}).eq("flag_key",sn);if(n)throw n;return{enabled:a}},onSuccess:({enabled:a})=>{K.success(`Auto-promotion ${a?"ENABLED":"DISABLED"}`),s.invalidateQueries({queryKey:["klutch-system-flag",sn]})},onError:a=>{K.error(`Toggle failed: ${(a==null?void 0:a.message)||"unknown error"}`)}})}const sp={sharp_money:[/sharp/i,/professional\s*money/i,/smart\s*money/i,/wiseguy/i],team_form:[/form/i,/streak/i,/momentum/i,/recent\s*performance/i,/hot/i,/cold/i,/slump/i],matchup:[/matchup/i,/head.to.head/i,/h2h/i,/vs\./i,/versus/i],injury:[/injur/i,/questionable/i,/doubtful/i,/out\b/i,/health/i,/return/i],weather:[/weather/i,/wind/i,/rain/i,/temperature/i,/outdoor/i,/dome/i],rest_schedule:[/rest/i,/back.to.back/i,/b2b/i,/schedule/i,/fatigue/i,/travel/i],pitching:[/pitch/i,/starter/i,/bullpen/i,/ERA/i,/WHIP/i,/arm/i],public_fade:[/public/i,/fade/i,/contrarian/i,/square/i,/sharp.vs.public/i],value:[/value/i,/edge/i,/overlay/i,/mispriced/i,/EV/i,/expected\s*value/i]};function tp(s){if(!s)return[];const a=[];for(const[t,n]of Object.entries(sp))n.some(r=>r.test(s))&&a.push(t);return a.length>0?a:["unclassified"]}function ap(){const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState("total"),[l,m]=v.useState("desc"),[o,h]=v.useState(null),{data:N,isLoading:d}=ge({queryKey:["klutch-reasoning-performance"],queryFn:async()=>{const{data:j,error:c}=await T.from("klutch_picks").select("reasoning, status, sport, trigger_type, suggested_units, original_odds").in("status",["won","lost","push"]).in("pick_type",["moneyline","spread","total"]);if(c)throw c;return j||[]}}),{themeMap:y,sports:u,triggers:x}=v.useMemo(()=>{const j={},c=new Set,p=new Set;if(!N)return{themeMap:j,sports:[],triggers:[]};for(const w of N){const S=tp(w.reasoning),P=w.sport||"unknown",C=w.trigger_type||"unknown",O=w.suggested_units||1;c.add(P),p.add(C);const $=w.status==="won",z=w.status==="lost",D=w.status==="push",A=Wn(w.status,O,w.original_odds)??0;for(const F of S){j[F]||(j[F]={wins:0,losses:0,pushes:0,netUnits:0,bySport:{},byTrigger:{}});const q=j[F];$?(q.wins++,q.netUnits+=A):z?(q.losses++,q.netUnits+=A):D&&q.pushes++,q.bySport[P]||(q.bySport[P]={wins:0,losses:0,pushes:0,netUnits:0});const E=q.bySport[P];$?(E.wins++,E.netUnits+=A):z?(E.losses++,E.netUnits+=A):D&&E.pushes++,q.byTrigger[C]||(q.byTrigger[C]={wins:0,losses:0,pushes:0,netUnits:0});const L=q.byTrigger[C];$?(L.wins++,L.netUnits+=A):z?(L.losses++,L.netUnits+=A):D&&L.pushes++}}return{themeMap:j,sports:Array.from(c).sort(),triggers:Array.from(p).sort()}},[N]),g=v.useMemo(()=>Object.entries(y).map(([j,c])=>{let p=c.wins,w=c.losses,S=c.pushes,P=c.netUnits;if(s!=="all"){const $=c.bySport[s];if(!$)return null;p=$.wins,w=$.losses,S=$.pushes,P=$.netUnits}if(t!=="all"){const $=c.byTrigger[t];if(!$)return null;p=$.wins,w=$.losses,S=$.pushes,P=$.netUnits}const C=p+w,O=C>0?p/C*100:null;return{theme:j,wins:p,losses:w,pushes:S,netUnits:P,total:p+w+S,winRate:O,stats:c}}
248).filter(Boolean),[y,s,t]),f=v.useMemo(()=>[...g].sort((j,c)=>{let p=0;return r==="theme"?p=j.theme.localeCompare(c.theme):r==="total"?p=j.total-c.total:r==="winRate"?p=(j.winRate??0)-(c.winRate??0):r==="netUnits"&&(p=j.netUnits-c.netUnits),l==="desc"?-p:p}),[g,r,l]),_=j=>{r===j?m(c=>c==="asc"?"desc":"asc"):(i(j),m("desc"))},k=(j,c)=>c<10?e.jsx(B,{variant:"outline",className:"text-muted-foreground text-xs",children:"n/a"}):j===null?null:c<50?e.jsxs(B,{variant:"outline",className:"text-xs",children:[j.toFixed(1),"%"]}):j>=55?e.jsxs(B,{className:"bg-green-500/20 text-green-400 border-green-500/30 text-xs",children:[j.toFixed(1),"%"]}):j>=50?e.jsxs(B,{className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30 text-xs",children:[j.toFixed(1),"%"]}):e.jsxs(B,{className:"bg-red-500/20 text-red-400 border-red-500/30 text-xs",children:[j.toFixed(1),"%"]}),b=(j,c)=>c>=50&&j!==null&&j<47?e.jsx(B,{variant:"destructive",className:"text-xs ml-1",children:"Suppress"}):null;return d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-medium",children:"Reasoning Performance"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-[120px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),u.map(j=>e.jsx(V,{value:j,children:j.toUpperCase()},j))]})]}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-[150px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Trigger"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Triggers"}),x.map(j=>e.jsx(V,{value:j,children:j.replace(/_/g," ")},j))]})]})]})]}),f.length===0?e.jsx("div",{className:"text-center py-6 text-muted-foreground text-sm",children:"No settled gameline picks found."}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"cursor-pointer",onClick:()=>_("theme"),children:"Theme"}),e.jsx(U,{children:"Record"}),e.jsx(U,{className:"cursor-pointer",onClick:()=>_("winRate"),children:"Win %"}),e.jsx(U,{className:"cursor-pointer",onClick:()=>_("netUnits"),children:"Net Units"}),e.jsx(U,{className:"cursor-pointer",onClick:()=>_("total"),children:"Picks"}),e.jsx(U,{children:"Status"})]})}),e.jsx($e,{children:f.map(j=>e.jsx(vs,{open:o===j.theme,onOpenChange:c=>h(c?j.theme:null),asChild:!0,children:e.jsxs(e.Fragment,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(he,{className:"cursor-pointer",children:[e.jsx(M,{className:"font-medium capitalize",children:e.jsxs("span",{className:"flex items-center gap-1",children:[o===j.theme?e.jsx(Ns,{className:"h-3 w-3"}):e.jsx(st,{className:"h-3 w-3"}),j.theme.replace(/_/g," ")]})}),e.jsxs(M,{className:"text-sm",children:[j.wins,"-",j.losses,"-",j.pushes]}),e.jsx(M,{children:k(j.winRate,j.total)}),e.jsxs(M,{className:`text-sm ${j.netUnits>=0?"text-green-400":"text-red-400"}`,children:[j.netUnits>=0?"+":"",j.netUnits.toFixed(1),"u"]}),e.jsx(M,{className:"text-sm",children:j.total}),e.jsxs(M,{children:[b(j.winRate,j.total),j.total>=50&&j.winRate!==null&&j.winRate>=55&&e.jsx(B,{className:"bg-green-500/20 text-green-400 border-green-500/30 text-xs",children:"Strong"})]})]})}),e.jsx(_s,{asChild:!0,children:e.jsxs(e.Fragment,{children:[Object.entries(j.stats.bySport).map(([c,p])=>{const w=p.wins+p.losses>0?p.wins/(p.wins+p.losses)*100:null;return e.jsxs(he,{className:"bg-muted/30",children:[e.jsx(M,{className:"pl-10 text-xs text-muted-foreground uppercase",children:c}),e.jsxs(M,{className:"text-xs",children:[p.wins,"-",p.losses,"-",p.pushes]}),e.jsx(M,{children:k(w,p.wins+p.losses+p.pushes)}),e.jsxs(M,{className:`text-xs ${p.netUnits>=0?"text-green-400":"text-red-400"}`,children:[p.netUnits>=0?"+":"",p.netUnits.toFixed(1),"u"]}),e.jsx(M,{className:"text-xs",children:p.wins+p.losses+p.pushes}),e.jsx(M,{})]},`${j.theme}-${c}`)}),Object.entries(j.stats.byTrigger).map(([c,p])=>{const w=p.wins+p.losses>0?p.wins/(p.wins+p.losses)*100:null;return e.jsxs(he,{className:"bg-muted/20",children:[e.jsx(M,{className:"pl-10 text-xs text-muted-foreground italic",children:c.replace(/_/g," ")}),e.jsxs(M,{className:"text-xs",children:[p.wins,"-",p.losses,"-",p.pushes]}),e.jsx(M,{children:k(w,p.wins+p.losses+p.pushes)}),e.jsxs(M,{className:`text-xs ${p.netUnits>=0?"text-green-400":"text-red-400"}`,children:[p.netUnits>=0?"+":"",p.netUnits.toFixed(1),"u"]}),e.jsx(M,{className:"text-xs",children:p.wins+p.losses+p.pushes}),e.jsx(M,{})]},`${j.theme}-trigger-${c}`)})]})})]})},j.theme))})]}),f.some(j=>j.total>=50&&j.winRate!==null&&j.winRate<47)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-md bg-destructive/10 border border-destructive/20 text-sm",children:[e.jsx(ls,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-destructive",children:'Themes flagged as "Suppress" have 50+ picks with <47% win rate — consider downweighting in the analytical prompt.'})]})]})}function rp(){return ge({queryKey:["klutch-version-settings"],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_version_settings").select("version, enabled, tier, notes, updated_at, updated_by").order("version");if(a)throw a;return s||[]},refetchInterval:3e4})}function np(s){const{data:a,...t}=rp();return{...t,data:(a==null?void 0:a.find(n=>n.version===s))??null}}function lp(){const s=Me();return _e({mutationFn:async a=>{var i;const{data:t}=await T.auth.getUser(),n={updated_at:new Date().toISOString(),updated_by:((i=t.user)==null?void 0:i.id)??null};typeof a.enabled=="boolean"&&(n.enabled=a.enabled),a.tier&&(n.tier=a.tier);const{error:r}=await T.from("klutch_version_settings").update(n).eq("version",a.version);if(r)throw r;return a},onSuccess:a=>{const t=[];typeof a.enabled=="boolean"&&t.push(a.enabled?"ENABLED":"PAUSED"),a.tier&&t.push(`tier=${a.tier.toUpperCase()}`),K.success(`${a.version} → ${t.join(" · ")}`),s.invalidateQueries({queryKey:["klutch-version-settings"]})},onError:a=>K.error(`Update failed: ${(a==null?void 0:a.message)||"unknown"}`)})}function Bn({version:s,description:a}){const{data:t,isLoading:n}=np(s),r=lp(),i=(t==null?void 0:t.enabled)??!0;return e.jsx(G,{className:Le("border",i?"border-emerald-500/30 bg-emerald-500/[0.03]":"border-amber-500/40 bg-amber-500/[0.05]"),children:e.jsxs(J,{className:"py-4 flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[i?e.jsx(Lo,{className:"h-5 w-5 mt-0.5 text-emerald-400 shrink-0"}):e.jsx(Ri,{className:"h-5 w-5 mt-0.5 text-amber-400 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-sm font-semibold uppercase tracking-wide",children:["KLUTCH ",s]}),e.jsx(B,{variant:i?"default":"destructive",className:"text-[10px]",children:i?"GENERATING":"PAUSED"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 max-w-2xl",children:a??"When paused, this version stops generating new picks immediately. Existing picks settle normally and learning continues from history."})]})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(Ge,{checked:i,disabled:n||r.isPending,onCheckedChange:l=>r.mutate({version:s,enabled:l})})})]})})}function ip({version:s="v1"}={}){const a=Me(),[t,n]=v.useState(!1),{data:r,isLoading:i,error:l}=ge({queryKey:["klutch-gameline-learning"],queryFn:async()=>{const{data:u,error:x}=await T.from("klutch_gameline_learning").select("*").order("sample_size",{ascending:!1});if(x)throw x;return(u||[]).map(g=>({...g,reasoning_factors:g.reasoning_factors}))}}),m=_e({mutationFn:async()=>{n(!0);const{data:u,error:x}=await T.functions.invoke("process-klutch-gameline-learning");if(x)throw x;return u},onSuccess:u=>{K.success(`Learning complete: ${u.stats.patterns_updated} patterns updated`),a.invalidateQueries({queryKey:["klutch-gameline-learning"]})},onError:u=>{K.error(`Learning failed: ${u.message}`)},onSettled:()=>{n(!1)}}),o=(u,x)=>x<50?e.jsx(B,{variant:"outline",className:"text-muted-foreground",children:"Insufficient data"}):u===null?null:u>=55?e.jsxs(B,{className:"bg-green-500/20 text-green-400 border-green-500/30",children:[u.toFixed(1),"%"]}):u>=50?e.jsxs(B,{className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",children:[u.toFixed(1),"%"]}):e.jsxs(B,{className:"bg-red-500/20 text-red-400 border-red-500/30",children:[u.toFixed(1),"%"]}),h=(u,x)=>{if(x<50)return e.jsx("span",{className:"text-muted-foreground",children:"—"});const g=(u*100).toFixed(1);return u>0?e.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[e.jsx(Ds,{className:"h-3 w-3"}),"+",g,"%"]}
248):u<0?e.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[e.jsx(qt,{className:"h-3 w-3"}),g,"%"]}):e.jsx("span",{className:"text-muted-foreground",children:"0%"})},N=(u,x)=>x<50?e.jsx(B,{variant:"outline",children:"Learning"}):u?e.jsx(B,{variant:"default",children:"Active"}):e.jsx(B,{variant:"destructive",children:"Suppressed"}),d=(r==null?void 0:r.filter(u=>u.sport!=="mma").reduce((u,x)=>(u[x.sport]||(u[x.sport]=[]),u[x.sport].push(x),u),{}))||{},y=Object.entries(d).map(([u,x])=>{const g=x.reduce((j,c)=>j+c.wins,0),f=x.reduce((j,c)=>j+c.losses,0),_=x.reduce((j,c)=>j+c.net_units,0),k=x.reduce((j,c)=>j+c.sample_size,0),b=g+f>0?g/(g+f)*100:0;return{sport:u,totalSamples:k,winRate:b,totalNet:_,patterns:x}}).sort((u,x)=>x.totalSamples-u.totalSamples);return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-5 w-5 text-primary"}),e.jsxs(fe,{children:["KLUTCH ",s," Gameline Learning"]})]}),e.jsx(R,{onClick:()=>m.mutate(),disabled:t,size:"sm",children:t?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 mr-2"}),"Run Learning"]})})]}),e.jsxs(De,{className:"flex items-center gap-2",children:["Learns from historical gameline performance to calibrate future pick confidence",r&&r.length>0&&(()=>{const u=Math.max(...r.map(_=>new Date(_.last_updated).getTime())),x=(Date.now()-u)/(1e3*60*60),g=x<24?"bg-green-500":x<48?"bg-yellow-500":"bg-red-500",f=new Date(u).toLocaleString("en-US",{timeZone:"America/Chicago",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})+" CT";return e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${g}`}),"Last synced: ",f]})})()]})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(Bn,{version:s,description:`When paused, KLUTCH ${s} stops generating new gameline picks. Existing picks settle normally and learning patterns continue to update from history.`}),l&&e.jsxs(ss,{variant:"destructive",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsxs(ts,{children:["Failed to load learning patterns: ",l.message]})]}),e.jsxs(ss,{children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsx(ts,{children:"Patterns require 50+ samples to generate adjustments. Adjustments are clamped to ±10% and patterns with <45% win rate are suppressed."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"Performance by Sport"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:y.map(({sport:u,totalSamples:x,winRate:g,totalNet:f})=>e.jsx(G,{className:"bg-card/50",children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"font-medium uppercase text-sm",children:u}),o(g,x)]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsxs("span",{children:[x," picks"]}),e.jsx("span",{className:"mx-2",children:"•"}),e.jsxs("span",{className:f>=0?"text-green-400":"text-red-400",children:[f>=0?"+":"",f.toFixed(1),"u"]})]})]})},u))})]}),e.jsx(ap,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:"Learned Patterns"}),i?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):!r||r.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No learning patterns found. Run the learning process to analyze historical picks."}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Type"}),e.jsx(U,{children:"Direction"}),e.jsx(U,{children:"Sharp Score"}),e.jsx(U,{children:"Record"}),e.jsx(U,{children:"Win %"}),e.jsx(U,{children:"Net Units"}),e.jsx(U,{children:"Adjustment"}),e.jsx(U,{children:"Status"})]})}),e.jsx($e,{children:r.map(u=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium uppercase",children:u.sport}),e.jsx(M,{className:"capitalize",children:u.pick_type}),e.jsx(M,{className:"capitalize",children:u.movement_direction.replace(/_/g," ")}),e.jsx(M,{children:u.sharp_score_bucket}),e.jsxs(M,{children:[u.wins,"-",u.losses,"-",u.pushes]}),e.jsx(M,{children:o(u.win_rate,u.sample_size)}),e.jsxs(M,{className:u.net_units>=0?"text-green-400":"text-red-400",children:[u.net_units>=0?"+":"",u.net_units.toFixed(1),"u"]}),e.jsx(M,{children:h(u.learned_adjustment,u.sample_size)}),e.jsx(M,{children:N(u.is_active,u.sample_size)})]},u.id))})]})]})]})]})}const cp=new Set(["scoring_trend","team_form_home","team_form_away","historical","historical_matchup","historical_pattern","injury_impact"]),op=new Set(["sharp_movement","public_consensus","reverse_line","sharp_public_divergence","public_vs_sharp"]);function dp(s){const a=s.indexOf(":");return a===-1?s:s.slice(0,a)}function up(s){if(!s||s==="unknown")return"other";
248const a=s.split("+").map(dp).filter(Boolean);return a.length===0?"other":a.some(t=>op.has(t))?"market":a.every(t=>cp.has(t))?"core":"other"}function kn(s){const a=s.filter(h=>["won","lost","push"].includes(h.status)),t=a.filter(h=>h.status==="won").length,n=a.filter(h=>h.status==="lost").length,r=a.filter(h=>h.status==="push").length,i=s.filter(h=>h.status==="pending").length,l=a.reduce((h,N)=>{const d=N.suggested_units||1;return N.status==="won"?h+d:N.status==="lost"?h-d:h},0),m={core:{wins:0,losses:0,pushes:0,units:0},market:{wins:0,losses:0,pushes:0,units:0},other:{wins:0,losses:0,pushes:0,units:0}},o=new Map;for(const h of a){const N=h.trigger_data,d=(N==null?void 0:N.signal_combo_key)||"unknown",y=up(d),u=m[y],x=h.suggested_units||1;h.status==="won"?(u.wins++,u.units+=x):h.status==="lost"?(u.losses++,u.units-=x):h.status==="push"&&u.pushes++;const g=o.get(d)||{wins:0,losses:0,pushes:0,total:0};g.total++,h.status==="won"?g.wins++:h.status==="lost"?g.losses++:h.status==="push"&&g.pushes++,o.set(d,g)}return{wins:t,losses:n,pushes:r,pending:i,total:s.length,netUnits:l,winRate:t+n>0?(t/(t+n)*100).toFixed(1):"N/A",buckets:m,combos:o}}function zl({version:s}={}){const[a,t]=v.useState(!1),[n,r]=v.useState("comparison"),[i,l]=v.useState("all"),[m,o]=v.useState("all"),[h,N]=v.useState("sample_size"),[d,y]=v.useState("desc"),u=F=>{h===F?y(q=>q==="desc"?"asc":"desc"):(N(F),y("desc"))},x=s??"v2.5",g=s?null:"v3",f=[],{data:_,isLoading:k}=ge({queryKey:["klutch-v2lab-primary-picks",x],queryFn:async()=>{const{data:F,error:q}=await T.from("klutch_picks").select("id, sport, pick_type, status, trigger_type, trigger_data, confidence_score, suggested_units, generation_version, created_at").eq("generation_version",x).order("created_at",{ascending:!1}).limit(500);if(q)throw q;return F||[]}}),{data:b,isLoading:j}=ge({queryKey:["klutch-v2lab-secondary-picks",g??"none"],queryFn:async()=>{if(!g)return[];const{data:F,error:q}=await T.from("klutch_picks").select("id, sport, pick_type, status, trigger_type, trigger_data, confidence_score, suggested_units, generation_version, created_at").eq("generation_version",g).order("created_at",{ascending:!1}).limit(500);if(q)throw q;return F||[]}}),{data:c,isLoading:p,refetch:w}=ge({queryKey:["klutch-v2-signal-learning"],queryFn:async()=>{const{data:F,error:q}=await T.from("klutch_v2_signal_learning").select("*").order("sample_size",{ascending:!1});if(q)throw q;return F||[]}}),S=async()=>{t(!0);try{const{data:F,error:q}=await T.functions.invoke("process-klutch-v2-learning");if(q)throw q;K.success(`Learning processed: ${F.unique_combos} combos analyzed, ${F.unique_buckets} buckets evaluated, ${F.proposals_created} proposals created`),w()}catch(F){K.error(`Failed to process learning: ${F instanceof Error?F.message:"Unknown error"}`)}finally{t(!1)}};kn(f||[]);const P=kn(_||[]),C=kn(b||[]),O=k||j||p,$=!!s,z=x,D=g??"",A=$?`Single-version drilldown — ${z}`:"v2.5 = clean baseline · v3 = bucket-weighted engine (legacy v2 collapsed into v2.5)";return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-5 w-5 text-primary"}),e.jsxs(fe,{children:["KLUTCH ",$?z:"Version"," Lab"]})]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:S,disabled:a,children:[a?e.jsx(ne,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(He,{className:"h-4 w-4 mr-1"}),"Process Learning"]})]}),e.jsxs(De,{className:"flex items-center gap-2",children:[A,c&&c.length>0&&(()=>{const F=Math.max(...c.map(H=>new Date(H.last_calculated_at).getTime())),q=(Date.now()-F)/(1e3*60*60),E=q<24?"bg-green-500":q<48?"bg-yellow-500":"bg-red-500",L=new Date(F).toLocaleString("en-US",{timeZone:"America/Chicago",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})+" CT";return e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${E}`}),"Last synced: ",L]})})()]})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:`grid gap-3 ${$?"md:grid-cols-1":"md:grid-cols-2"}`,children:[e.jsx(Bn,{version:x,description:`Pause to halt new ${z} picks immediately.`}
248),g&&e.jsx(Bn,{version:g,description:`Pause to halt new ${D} picks immediately.`})]}),O?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(js,{value:n,onValueChange:r,children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsx(Ne,{value:"comparison",children:$?"Performance":"Version Comparison"}),e.jsx(Ne,{value:"signals",children:"Signal Combos"}),e.jsx(Ne,{value:"learning",children:"Learned Adjustments"})]}),e.jsxs(we,{value:"comparison",className:"mt-4 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Overall Performance"}),e.jsxs("div",{className:`grid ${$?"grid-cols-1":"grid-cols-2"} gap-4`,children:[e.jsxs("div",{className:"rounded-lg border border-primary/50 p-4 space-y-3",children:[e.jsx(B,{className:"text-xs bg-violet-500/10 text-violet-400 border-violet-500/30",children:z}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-2xl font-bold text-primary",children:[P.winRate,"%"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[P.wins,"W-",P.losses,"L-",P.pushes,"P"]}),e.jsxs("p",{className:`text-sm font-medium ${P.netUnits>=0?"text-green-500":"text-red-500"}`,children:[P.netUnits>=0?"+":"",P.netUnits.toFixed(1),"u"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[P.total," total · ",P.pending," pending"]})]})]}),g&&e.jsxs("div",{className:"rounded-lg border border-emerald-500/50 p-4 space-y-3",children:[e.jsx(B,{className:"text-xs bg-emerald-500/10 text-emerald-400 border-emerald-500/30",children:D}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-2xl font-bold text-emerald-400",children:[C.winRate,"%"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[C.wins,"W-",C.losses,"L-",C.pushes,"P"]}),e.jsxs("p",{className:`text-sm font-medium ${C.netUnits>=0?"text-green-500":"text-red-500"}`,children:[C.netUnits>=0?"+":"",C.netUnits.toFixed(1),"u"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[C.total," total · ",C.pending," pending"]})]})]})]}),!$&&P.wins+P.losses>0&&C.wins+C.losses>0&&(()=>{const F=P.wins/(P.wins+P.losses)*100,E=C.wins/(C.wins+C.losses)*100-F,L=C.netUnits-P.netUnits;return e.jsxs("div",{className:"mt-3 flex items-center gap-4 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Δ Win Rate (",D," vs ",z,"):"]}),e.jsxs("span",{className:E>=0?"text-green-500 font-semibold":"text-red-500 font-semibold",children:[E>=0?"+":"",E.toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:"Δ Units:"}),e.jsxs("span",{className:L>=0?"text-green-500 font-semibold":"text-red-500 font-semibold",children:[L>=0?"+":"",L.toFixed(1),"u"]})]})})()]}),e.jsx(is,{}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold mb-3",children:["Signal Bucket ",$?"Breakdown":"Comparison"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Bucket"}),e.jsxs(U,{className:"text-right",children:[z," W-L-P"]}),e.jsxs(U,{className:"text-right",children:[z," WR"]}),e.jsxs(U,{className:"text-right",children:[z," Units"]}),g&&e.jsxs(U,{className:"text-right",children:[D," W-L-P"]}),g&&e.jsxs(U,{className:"text-right",children:[D," WR"]}),g&&e.jsxs(U,{className:"text-right",children:[D," Units"]})]})}),e.jsx($e,{children:["core","market","other"].map(F=>{const q=P.buckets[F],E=C.buckets[F],L=q.wins+q.losses,H=E.wins+E.losses,Z=L>0?(q.wins/L*100).toFixed(1):"N/A",se=H>0?(E.wins/H*100).toFixed(1):"N/A",ie=q.wins+q.losses+q.pushes,Y=E.wins+E.losses+E.pushes;return($?ie:ie+Y)===0?null:e.jsxs(he,{children:[e.jsx(M,{className:"capitalize font-medium",children:F==="core"?"🔵 Core":F==="market"?"🟡 Market":"⚪ Other"}),e.jsxs(M,{className:"text-right",children:[q.wins,"-",q.losses,"-",q.pushes]}),e.jsxs(M,{className:"text-right",children:[Z,"%"]}),e.jsxs(M,{className:`text-right ${q.units>=0?"text-green-500":"text-red-500"}`,children:[q.units>=0?"+":"",q.units.toFixed(1),"u"]}),g&&e.jsxs(M,{className:"text-right",children:[E.wins,"-",E.losses,"-",E.pushes]}),g&&e.jsxs(M,{className:"text-right",children:[se,"%"]}),g&&e.jsxs(M,{className:`text-right ${E.units>=0?"text-green-500":"text-red-500"}`,children:[E.units>=0?"+":"",E.units.toFixed(1),"u"]})]},F)})})]})})]})]}),e.jsx(we,{value:"signals",className:"mt-4 space-y-6",children:(g?[z,D]:[z]).map((F,q,E)=>{const L=F===z?P:C;return e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold mb-3",children:["Signal Combos — ",F]}),L.combos.size===0?e.jsxs("p",{className:"text-sm text-muted-foreground py-4",children:["No settled ",F," picks yet."]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Signal Combo"}),e.jsx(U,{className:"text-right",children:"W"}),e.jsx(U,{className:"text-right",children:"L"}),e.jsx(U,{className:"text-right",children:"Win Rate"}),e.jsx(U,{className:"text-right",children:"Total"})]})}),e.jsx($e,{children:[...L.combos.entries()].sort((H,Z)=>Z[1].total-H[1].total).map(([H,Z])=>{const se=Z.wins+Z.losses,ie=se>0?(Z.wins/se*100).toFixed(1):"N/A",Y=se>0?Z.wins/se:.5;return e.jsxs(he,{children:[e.jsx(M,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:H.split("+").map(I=>e.jsx(B,{variant:"secondary",className:"text-xs",children:I.replace(/_/g," ")},I))})}),e.jsx(M,{className:"text-right font-medium text-green-500",children:Z.wins}),e.jsx(M,{className:"text-right font-medium text-red-500",children:Z.losses}),e.jsx(M,{className:"text-right",children:e.jsxs("span",{className:Y>=.55?"text-green-500 font-semibold":Y<.47?"text-red-500 font-semibold":"",children:[ie,"%"]})}),e.jsx(M,{className:"text-right text-muted-foreground",children:Z.total})]},H)})})]})}),q<E.length-1&&e.jsx(is,{className:"my-4"})]},F)})}),e.jsx(we,{value:"learning",className:"mt-4",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Learned Signal Adjustments"}),e.jsxs(oe,{value:i,onValueChange:l,children:[e.jsx(de,{className:"w-[140px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),e.jsx(V,{value:"baseball",children:"Baseball"}),e.jsx(V,{value:"basketball",children:"Basketball"}),e.jsx(V,{value:"hockey",children:"Hockey"}),e.jsx(V,{value:"soccer",children:"Soccer"})]})]}),e.jsxs(oe,{value:m,onValueChange:o,children:[e.jsx(de,{className:"w-[140px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Type"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Types"}),e.jsx(V,{value:"moneyline",children:"Moneyline"}),e.jsx(V,{value:"spread",children:"Spread"}),e.jsx(V,{value:"total",children:"Total"})]})]})]}),(c||[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:'No learning data yet — run "Process Learning" after picks settle.'}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Combo"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Type"}),e.jsx(U,{className:"text-right cursor-pointer select-none",onClick:()=>u("sample_size"),children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["Samples ",e.jsx(Jt,{className:"h-3 w-3"})]})}),e.jsx(U,{className:"text-right cursor-pointer select-none",onClick:()=>u("win_rate"),children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["Win Rate ",e.jsx(Jt,{className:"h-3 w-3"})]})}),e.jsx(U,{className:"text-right",children:"Adjustment"}),e.jsx(U,{children:"Status"})]})}),e.jsx($e,{children:(c||[]).filter(F=>i==="all"||F.sport===i).filter(F=>m==="all"||F.pick_type===m).sort((F,q)=>{const E=Number(F[h])||0,L=Number(q[h])||0;return d==="desc"?L-E:E-L}).map(F=>e.jsxs(he,{children:[e.jsx(M,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:F.signal_combo_key.split("+").map(q=>e.jsx(B,{variant:"secondary",className:"text-xs",children:q.replace(/_/g," ")},q))})}),e.jsx(M,{className:"capitalize",children:F.sport}),e.jsx(M,{className:"capitalize",children:F.pick_type}),e.jsx(M,{className:"text-right",children:F.sample_size}),e.jsx(M,{className:"text-right",children:e.jsxs("span",{className:Number(F.win_rate)>=.55?"text-green-500 font-semibold":Number(F.win_rate)<.47?"text-red-500 font-semibold":"",children:[(Number(F.win_rate)*100).toFixed(1),"%"]})}),e.jsx(M,{className:"text-right",children:Number(F.learned_adjustment)>0?e.jsxs("span",{className:"text-green-500 flex items-center justify-end gap-1",children:[e.jsx(Ds,{className:"h-3 w-3"}),"+",(Number(F.learned_adjustment)*100).toFixed(1),"%"]}):Number(F.learned_adjustment)<0?e.jsxs("span",{className:"text-red-500 flex items-center justify-end gap-1",children:[e.jsx(qt,{className:"h-3 w-3"}),(Number(F.learned_adjustment)*100).toFixed(1),"%"]}):e.jsx("span",{className:"text-muted-foreground",children:"0%"})}),e.jsx(M,{children:F.is_suppressed?e.jsx(B,{variant:"destructive",className:"text-xs",children:"Suppressed"}):F.is_active?e.jsx(B,{variant:"default",className:"text-xs",children:"Active"}):e.jsx(B,{variant:"secondary",className:"text-xs",children:"Inactive"})})]},F.id))})]})})]})})]})]})]})}async function mp(){const{data:s,error:a}=await T.from("klutch_v5_corpus_snapshots").select("*").order("created_at",{ascending:!1}).limit(1).maybeSingle();if(a)throw a;return s??null}async function xp(s){const{data:a,error:t}=await T.from("klutch_v5_corpus_coverage").select("*").eq("snapshot_id",s).order("sport").order("league").order("market_type").order("season_type").order("horizon_seconds");if(t)throw t;return a??[]}async function hp(s){const{data:a,error:t}=await T.from("klutch_v5_model_summary").select("*").eq("snapshot_id",s).order("sport").order("league").order("market_type").order("status",{ascending:!1});if(t)throw t;return a??[]}async function pp(){const{data:s,error:a}=await T.from("klutch_v5_runtime_summary").select("*").maybeSingle();if(a)throw a;return s??null}async function gp(){const{data:s,error:a}=await T.from("klutch_version_specialization").select("sport,pick_type,generation_version,status,sample_size,settled_sample_size,win_rate,roi_pct,net_units,last_evaluated_at").eq("generation_version","v5").order("sport").order("pick_type");if(a)throw a;return s??[]}async function jp(){const{data:s,error:a}
248=await T.from("klutch_v5_independent_validation").select("*").order("sport").order("league").order("market_type");if(a)throw a;return s??[]}async function fp(){const{data:s,error:a}=await T.from("canonical_sports_identity_coverage").select("*").maybeSingle();if(a)throw a;return s??null}function vp(){var m,o,h,N,d;const s=ge({queryKey:["klutch-v5-corpus-latest"],queryFn:mp,refetchInterval:6e4,refetchOnWindowFocus:!0}),a=ge({queryKey:["klutch-v5-corpus-coverage",(m=s.data)==null?void 0:m.id],queryFn:()=>xp(s.data.id),enabled:!!((o=s.data)!=null&&o.id),refetchInterval:((h=s.data)==null?void 0:h.status)==="building"?15e3:6e4,refetchOnWindowFocus:!0}),t=ge({queryKey:["klutch-v5-models",(N=s.data)==null?void 0:N.id],queryFn:()=>hp(s.data.id),enabled:!!((d=s.data)!=null&&d.id),refetchInterval:6e4,refetchOnWindowFocus:!0,retry:!1}),n=ge({queryKey:["klutch-v5-runtime"],queryFn:pp,refetchInterval:3e4,retry:!1}),r=ge({queryKey:["klutch-v5-specialization"],queryFn:gp,refetchInterval:6e4,retry:!1}),i=ge({queryKey:["klutch-v5-independent-validation"],queryFn:jp,refetchInterval:6e4,retry:!1}),l=ge({queryKey:["canonical-sports-identity-coverage"],queryFn:fp,refetchInterval:6e4,retry:!1});return{snapshot:s,coverage:a,models:t,runtime:n,matrix:r,validation:i,identity:l}}const at=new Intl.NumberFormat("en-US"),lr=s=>s?new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(s)):"—",Cn=s=>s%86400===0?`${s/86400}d`:s%3600===0?`${s/3600}h`:`${s/60}m`,Vt=(s,a)=>a>0?`${(s/a*100).toFixed(1)}%`:"—",ct=s=>s.replace(/[-_]/g," ").replace(/\b\w/g,a=>a.toUpperCase());function ir({label:s,value:a,options:t,onChange:n}){return e.jsxs("label",{className:"grid gap-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:[s,e.jsxs("select",{value:a,onChange:r=>n(r.target.value),className:"min-w-32 rounded-md border border-border/60 bg-background px-2 py-1.5 text-xs font-normal normal-case tracking-normal text-foreground",children:[e.jsx("option",{value:"all",children:"All"}),t.map(r=>e.jsx("option",{value:r,children:ct(r)},r))]})]})}const yp=(s,a)=>s.reduce((t,n)=>t+Number(n[a]??0),0);function Np(){var A,F,q,E;const{snapshot:s,coverage:a,models:t,runtime:n,matrix:r,validation:i,identity:l}=vp(),[m,o]=v.useState("all"),[h,N]=v.useState("all"),[d,y]=v.useState("all"),[u,x]=v.useState("all"),[g,f]=v.useState("all"),_=a.data??[],k=L=>[...new Set(_.map(H=>String(H[L])))].sort(),b=v.useMemo(()=>_.filter(L=>(m==="all"||L.sport===m)&&(h==="all"||L.league===h)&&(d==="all"||L.market_type===d)&&(u==="all"||L.season_type===u)&&(g==="all"||String(L.horizon_seconds)===g)),[_,m,h,d,u,g]),j=()=>{s.refetch(),a.refetch(),t.refetch(),n.refetch(),r.refetch(),i.refetch(),l.refetch()};if(s.isLoading)return e.jsxs("div",{className:"flex items-center gap-2 py-12 text-sm text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"})," Loading KLUTCH v5 corpus evidence…"]});if(s.error)return e.jsx(G,{className:"border-red-500/40 bg-red-500/[0.05]",children:e.jsxs(J,{className:"flex items-start gap-3 py-5 text-sm",role:"alert",children:[e.jsx(Is,{className:"mt-0.5 h-4 w-4 shrink-0 text-red-400"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Corpus evidence unavailable"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"The Admin read failed. This state is not treated as healthy."})]})]})});if(!s.data)return e.jsx(G,{className:"border-amber-500/40 bg-amber-500/[0.04]",children:e.jsxs(J,{className:"flex items-start gap-3 py-5 text-sm",role:"status",children:[e.jsx(ls,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-400"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"No KLUTCH v5 corpus snapshot"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"The schema is readable, but no immutable training snapshot has been recorded."})]})]})});const c=s.data,p=c.status==="building",w=c.status==="failed",S=p?ne:w?Is:rs,P=w?"border-red-500/40 bg-red-500/[0.04]":p?"border-amber-500/40 bg-amber-500/[0.04]":"border-emerald-500/30 bg-emerald-500/[0.025]",C=yp(b,"rows"),O=Object.entries(c.exclusions??{}).sort((L,H)=>Number(H[1])-Number(L[1])),D=(n.data?Date.now()-Date.parse(n.data.completed_at??n.data.started_at):1/0)>30*60*1e3&&((A=n.data)==null?void 0:A.status)==="succeeded"?"stale":(F=n.data)==null?void 0:F.status;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("section",{"aria-labelledby":"klutch-v5-runtime-title",className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h3",{id:"klutch-v5-runtime-title",className:"flex items-center gap-2 font-semibold",children:[e.jsx(rs,{className:"h-4 w-4 text-primary"})," First-class v5 evaluation and scoring"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Observed source-model activity and normal specialization results. This display does not control Admin strategy or trader enablement."})]}),n.error?e.jsx("div",{className:"rounded-lg border border-red-500/40 bg-red-500/[0.04] p-4 text-sm",role:"alert",children:"Runtime evidence could not be read; v5 health is unverified."}):n.data?e.jsx(G,{className:D==="failed"?"border-red-500/40":D==="degraded"||D==="stale"?"border-amber-500/40":"border-emerald-500/30",children:e.jsxs(J,{className:"grid gap-4 py-4 text-xs sm:grid-cols-3 lg:grid-cols-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Observed run"}),e.jsx("div",{className:"mt-1 font-semibold uppercase",children:D}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:lr(n.data.completed_at??n.data.started_at)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Qualified artifacts"}),e.jsx("div",{className:"mt-1 text-lg font-semibold tabular-nums",children:at.format(n.data.artifacts_loaded)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Inputs / evaluations"}),e.jsxs("div",{className:"mt-1 font-semibold tabular-nums",children:[at.format(n.data.inputs_scanned)," / ",at.format(n.data.evaluations_recorded)]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Eligible / finalized"}),e.jsxs("div",{className:"mt-1 font-semibold tabular-nums",children:[at.format(n.data.eligible_evaluations)," / ",at.format(n.data.finalized_sources_recorded)]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"24h evaluations"}),e.jsxs("div",{className:"mt-1 font-semibold tabular-nums",children:[at.format(n.data.evaluations_24h)," (",at.format(n.data.eligible_24h)," eligible)"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Settled / pending"}),e.jsxs("div",{className:"mt-1 font-semibold tabular-nums",children:[at.format(n.data.settled_total)," / ",at.format(n.data.unsettled_total)]})]}),n.data.error&&e.jsx("div",{className:"sm:col-span-3 lg:col-span-6 text-red-300",children:n.data.error})]})}):e.jsx("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/[0.04] p-4 text-sm",children:"No v5 runtime evaluation has been recorded yet."}),i.error?e.jsx("div",{className:"rounded-lg border border-red-500/40 bg-red-500/[0.04] p-4 text-sm",role:"alert",children:"Settled v5 model validation could not be read."}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"Settled runtime calibration"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"One independent result per artifact, game and market; repeated evaluations are retained separately."})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border/60",children:e.jsxs("table",{className:"w-full min-w-[900px] text-left text-xs",children:[e.jsx("thead",{className:"bg-muted/30 text-[10px] uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"League / bet type"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Independent n"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"W / L / P"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Win rate"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Brier"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Raw edge"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Tradable edge"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Last settled"})]})}),e.jsxs("tbody",{children:[(i.data??[]).map(L=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"px-3 py-2",children:[e.jsxs("div",{className:"font-medium",children:[ct(L.league)," · ",ct(L.market_type)]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:ct(L.sport)})]}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:at.format(L.independent_events)}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[L.wins," / ",L.losses," / ",L.pushes]}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:L.win_rate==null?"—":`${(Number(L.win_rate)*100).toFixed(1)}%`}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:cr(L.brier_score)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:L.raw_model_edge==null?"—":`${or(Number(L.raw_model_edge)*100)}pp`}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:L.net_tradable_edge==null?"—":`${or(Number(L.net_tradable_edge)*100)}pp`}),e.jsx("td",{className:"px-3 py-2 text-right text-muted-foreground",children:lr(L.last_settled_at)})]},`${L.artifact_id}|${L.market_type}`)),(i.data??[]).length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-8 text-center text-muted-foreground",children:"No settled independent v5 evaluations yet. Pregame observations will appear here after their games receive canonical final scores."})})]})]})})]}),r.error?e.jsx("div",{className:"rounded-lg border border-red-500/40 p-4 text-sm",children:"The v5 specialization slice could not be read."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border/60",children:e.jsxs("table",{className:"w-full min-w-[800px] text-left text-xs",children:[e.jsx("thead",{className:"bg-muted/30 text-[10px] uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"Sport / bet type"}),e.jsx("th",{className:"px-3 py-2",children:"Matrix status"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Eligible n"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Settled n"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Win rate"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"ROI"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Units"})]})}),e.jsxs("tbody",{children:[(r.data??[]).map(L=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"px-3 py-2 font-medium",children:[ct(L.sport)," · ",ct(L.pick_type)]}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(B,{variant:"outline",children:ct(L.status)})}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:L.sample_size}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:L.settled_sample_size}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[Number(L.win_rate).toFixed(1),"%"]}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[Number(L.roi_pct).toFixed(1),"%"]}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[Number(L.net_units).toFixed(1),"u"]})]},`${L.sport}|${L.pick_type}`)),(r.data??[]).length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-3 py-8 text-center text-muted-foreground",children:"No settled v5 specialization rows yet. v5 remains insufficient until ordinary sample floors are met."})})]})]})})]}
248),e.jsxs("section",{"aria-labelledby":"canonical-sports-identity-title",className:"space-y-2",children:[e.jsxs("div",{children:[e.jsxs("h3",{id:"canonical-sports-identity-title",className:"flex items-center gap-2 font-semibold",children:[e.jsx(tt,{className:"h-4 w-4 text-primary"})," Canonical provider identity"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Exact league and team reconciliation across sportsbook, prediction-market, and game-data providers. Unresolved or ambiguous identities fail closed."})]}),l.error?e.jsx("div",{className:"rounded-lg border border-red-500/40 bg-red-500/[0.04] p-4 text-sm",role:"alert",children:"Identity coverage could not be read. Provider reconciliation is unverified."}):l.data?e.jsxs("div",{className:`rounded-lg border p-4 ${l.data.status==="healthy"?"border-emerald-500/30":"border-amber-500/40 bg-amber-500/[0.025]"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[l.data.status==="healthy"?e.jsx(rs,{className:"h-4 w-4 text-emerald-400"}):e.jsx(ls,{className:"h-4 w-4 text-amber-400"}),l.data.status==="healthy"?"Recent identities resolved":"Identity coverage degraded"]}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Latest game update ",lr(l.data.latest_game_update)]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-x-8 gap-y-3 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"All games"}),e.jsx("strong",{className:"ml-2 tabular-nums",children:at.format(l.data.games)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"League resolved"}),e.jsx("strong",{className:"ml-2 tabular-nums",children:Vt(l.data.league_resolved,l.data.games)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Both teams resolved"}),e.jsx("strong",{className:"ml-2 tabular-nums",children:Vt(l.data.both_teams_resolved,l.data.games)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Backfill pending"}),e.jsx("strong",{className:"ml-2 tabular-nums",children:at.format(l.data.identity_check_pending)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Recent unresolved"}),e.jsxs("strong",{className:"ml-2 tabular-nums",children:[at.format(l.data.recent_identity_unresolved)," / ",at.format(l.data.recent_games)]})]})]}),l.data.status_reason&&e.jsxs("p",{className:"mt-3 text-xs text-amber-200",children:["Reason: ",ct(l.data.status_reason)]})]}):e.jsx("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/[0.04] p-4 text-sm",role:"status",children:"No canonical identity coverage has been recorded."})]}),e.jsxs(G,{className:P,children:[e.jsx(je,{className:"pb-3",children:e.jsxs(fe,{className:"flex flex-wrap items-start justify-between gap-3 text-base",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4 text-primary"})," KLUTCH v5 point-in-time corpus"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsxs(B,{className:w?"bg-red-600":p?"bg-amber-600":"bg-emerald-700",children:[e.jsx(S,{className:`mr-1 h-3 w-3 ${p?"animate-spin":""}`}),w?"BUILD FAILED":p?"BUILDING":"SNAPSHOT AVAILABLE"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:j,disabled:s.isFetching||a.isFetching,children:[e.jsx(He,{className:`mr-1 h-3.5 w-3.5 ${s.isFetching||a.isFetching?"animate-spin":""}`})," Refresh"]})]})]})}),e.jsxs(J,{className:"space-y-4 text-xs",children:[e.jsxs("div",{className:"grid gap-x-6 gap-y-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Snapshot cutoff"}),e.jsx("div",{className:"mt-0.5 font-medium",children:lr(c.cutoff_at)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Completed"}),e.jsx("div",{className:"mt-0.5 font-medium",children:lr(c.completed_at)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Training rows"}),e.jsx("div",{className:"mt-0.5 font-medium tabular-nums",children:at.format(c.row_count)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Independent events"}),e.jsx("div",{className:"mt-0.5 font-medium tabular-nums",children:at.format(c.event_count)}
248)]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Corpus / features"}),e.jsxs("div",{className:"mt-0.5 font-medium",children:[c.corpus_version," · ",c.feature_schema_version]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Decision horizons"}),e.jsx("div",{className:"mt-0.5 font-medium",children:c.horizons_seconds.map(Cn).join(" · ")})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Quote policy"}),e.jsxs("div",{className:"mt-0.5 font-medium",children:["≤ ",Cn(c.quote_max_age_seconds)," old · ",c.minimum_book_count,"+ book"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Content hash"}),e.jsxs("div",{className:"mt-0.5 truncate font-mono",title:c.content_sha256??void 0,children:[((q=c.content_sha256)==null?void 0:q.slice(0,16))??"pending",c.content_sha256?"…":""]})]})]}),w&&e.jsx("p",{className:"rounded-md border border-red-500/30 bg-red-500/[0.06] p-3 text-red-200",role:"alert",children:c.error_message||"The snapshot build failed without a recorded reason."}),e.jsx("p",{className:"border-t border-border/50 pt-3 text-muted-foreground",children:"Snapshot availability proves the immutable corpus was recorded. Production model readiness remains unverified until leakage, reproducibility, calibration, and end-to-end release evidence pass."})]})]}),e.jsxs("section",{"aria-labelledby":"klutch-v5-models-title",className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h3",{id:"klutch-v5-models-title",className:"flex items-center gap-2 font-semibold",children:[e.jsx(Eo,{className:"h-4 w-4 text-primary"})," Chronological model validation"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Candidate-only artifacts. These results do not publish picks or change strategy/trader enablement."})]}),t.error?e.jsxs("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/[0.04] p-4 text-sm",role:"status",children:[e.jsx("div",{className:"font-semibold",children:"No Phase 4 model evidence is available"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"The immutable corpus remains available, but model training has not produced a readable completed run."})]}):t.isLoading?e.jsxs("div",{className:"flex items-center gap-2 py-8 text-sm text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"})," Loading model evidence…"]}):(E=t.data)!=null&&E.length?e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border/60",children:e.jsxs("table",{className:"w-full min-w-[1220px] text-left text-xs",children:[e.jsx("thead",{className:"bg-muted/30 text-[10px] uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"Sport / market"}),e.jsx("th",{className:"px-3 py-2",children:"Artifact"}),e.jsx("th",{className:"px-3 py-2",children:"Evidence"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Train / cal / test events"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Brier model / market"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Log loss model / market"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Brier Δ 95% CI"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Pick ROI"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Avg CLV"})]})}),e.jsx("tbody",{children:t.data.map(L=>{var ee,le,ve,te,X,ae,W;const H=(ee=L.metrics)==null?void 0:ee.test,Z=(le=L.baseline_metrics)==null?void 0:le.test,se=((ve=L.sample_counts)==null?void 0:ve.events)??{},ie=(te=L.uncertainty)==null?void 0:te.clusterBootstrapBrierDelta,Y=(X=L.metrics)==null?void 0:X.simulatedPicks,I=((W=(ae=L.metrics)==null?void 0:ae.qualification)==null?void 0:W.eligible)===!0;return e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"px-3 py-2",children:[e.jsxs("div",{className:"font-medium",children:[ct(L.league)," · ",ct(L.market_type)]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:[ct(L.sport)," · ",L.version]})]}),e.jsx("td",{className:"px-3 py-2",children:ct(L.algorithm_kind)}),e.jsx("td",{className:"px-3 py-2",children:e.jsx(B,{variant:"outline",title:(L.validation_reasons??[]).join(" · "),className:I?"border-emerald-500/50 text-emerald-400":"border-amber-500/50 text-amber-300",children:L.status==="insufficient"?"Insufficient":I?"Prelim qualified":"Not proven"})}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[se.train??"—"," / ",se.calibration??"—"," / ",se.test??"—"]}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[cr(H==null?void 0:H.brier)," / ",cr(Z==null?void 0:Z.brier)]}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[cr(H==null?void 0:H.log_loss)," / ",cr(Z==null?void 0:Z.log_loss)]}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:ie?`${or(ie.lower95)}…${or(ie.upper95)}`:"—"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:(Y==null?void 0:Y.roi)==null?"—":`${(Number(Y.roi)*100).toFixed(1)}%`}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:(Y==null?void 0:Y.average_probability_clv)==null?"—":`${or(Number(Y.average_probability_clv)*100)}pp`})]},L.id)})})]})}):e.jsx("div",{className:"rounded-lg border border-border/60 bg-card/20 p-4 text-sm text-muted-foreground",children:"No completed Phase 4 artifacts exist for this corpus snapshot."})]}),e.jsxs("section",{"aria-labelledby":"klutch-v5-coverage-title",className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"klutch-v5-coverage-title",className:"font-semibold",children:"Coverage by modeling slice"}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Filters change the table only; they do not rebuild or alter the snapshot."})]}),e.jsxs("div",{className:"text-right text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground tabular-nums",children:at.format(C)}
248)," rows across ",at.format(b.length)," slices"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 rounded-lg border border-border/60 bg-card/30 p-3",children:[e.jsx(ir,{label:"Sport",value:m,options:k("sport"),onChange:o}),e.jsx(ir,{label:"League",value:h,options:k("league"),onChange:N}),e.jsx(ir,{label:"Bet type",value:d,options:k("market_type"),onChange:y}),e.jsx(ir,{label:"Season",value:u,options:k("season_type"),onChange:x}),e.jsx(ir,{label:"Horizon",value:g,options:k("horizon_seconds"),onChange:f})]}),a.error?e.jsx("div",{className:"rounded-lg border border-red-500/40 bg-red-500/[0.04] p-4 text-sm",role:"alert",children:"Coverage rows could not be loaded. Snapshot metadata above may still be current; detailed coverage is unverified."}):a.isLoading?e.jsxs("div",{className:"flex items-center gap-2 py-8 text-sm text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"})," Loading coverage…"]}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border/60",children:e.jsxs("table",{className:"w-full min-w-[1260px] text-left text-xs",children:[e.jsx("thead",{className:"bg-muted/30 text-[10px] uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"Sport / league"}),e.jsx("th",{className:"px-3 py-2",children:"Bet type"}),e.jsx("th",{className:"px-3 py-2",children:"Season"}),e.jsx("th",{className:"px-3 py-2",children:"Horizon"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Events"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Rows"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"W / L / P"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Books"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Pace"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"ATS"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Injury"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Lineup array"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Lineup status"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Weather"}),e.jsx("th",{className:"px-3 py-2 text-right",children:"Starters"})]})}),e.jsxs("tbody",{children:[b.map(L=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:ct(L.league)}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:ct(L.sport)})]}),e.jsx("td",{className:"px-3 py-2",children:ct(L.market_type)}),e.jsx("td",{className:"px-3 py-2",children:ct(L.season_type)}),e.jsx("td",{className:"px-3 py-2 tabular-nums",children:Cn(L.horizon_seconds)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:at.format(L.events)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:at.format(L.rows)}),e.jsxs("td",{className:"px-3 py-2 text-right tabular-nums",children:[L.wins," / ",L.losses," / ",L.pushes]}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:L.average_book_count==null?"—":Number(L.average_book_count).toFixed(1)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Vt(L.pace_history_rows,L.rows)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Vt(L.ats_history_rows,L.rows)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Vt(L.injury_rows,L.rows)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Vt(L.lineup_rows,L.rows)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Vt(L.lineup_status_rows,L.rows)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Vt(L.weather_rows,L.rows)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums",children:Vt(L.starter_rows,L.rows)})]},`${L.sport}|${L.league}|${L.market_type}|${L.season_type}|${L.horizon_seconds}`)),b.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:15,className:"px-3 py-10 text-center text-muted-foreground",children:"No coverage matches these filters."})})]})]})})]}),e.jsxs("section",{"aria-labelledby":"klutch-v5-exclusions-title",className:"space-y-2",children:[e.jsx("h3",{id:"klutch-v5-exclusions-title",className:"font-semibold",children:"Build exclusions"}),e.jsx("div",{className:"grid gap-px overflow-hidden rounded-lg border border-border/60 bg-border/60 sm:grid-cols-2 lg:grid-cols-4",children:O.map(([L,H])=>e.jsxs("div",{className:"bg-background p-3 text-xs",children:[e.jsx("div",{className:"text-muted-foreground",children:ct(L)}),e.jsx("div",{className:"mt-1 text-base font-semibold tabular-nums",children:at.format(Number(H))})]},L))})]})]})}function cr(s){const a=Number(s);return Number.isFinite(a)?a.toFixed(4):"—"}function or(s){const a=Number(s);return Number.isFinite(a)?`${a>=0?"+":""}${a.toFixed(4)}`:"—"}const _p=[{key:"v1",label:"v1"},{key:"v1a",label:"v1a"},{key:"v2.5",label:"v2.5"},{key:"v2.5a",label:"v2.5a"},{key:"v3",label:"v3"},{key:"v3a",label:"v3a"},{key:"v5",label:"v5"},{key:"compare",label:"v2.5 vs v3"}];function bp(){const[s,a]=v.useState("v1");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Version:"}),_p.map(t=>e.jsx(R,{size:"sm",variant:s===t.key?"default":"outline",className:Le("h-7 px-3 text-xs"),onClick:()=>a(t.key),children:t.label},t.key))]}),s==="v5"?e.jsx(Np,{}
248):s==="v1"||s==="v1a"?e.jsx(ip,{version:s}):s==="compare"?e.jsx(zl,{}):e.jsx(zl,{version:s})]})}function wp(s,a,t=30){return ge({queryKey:["klutch-module-version-trust",s,a,t],queryFn:async()=>{let n=T.from("klutch_module_version_trust").select("*").eq("window_days",t).order("picks_promoted",{ascending:!1});s!=="all"&&(n=n.eq("module_engine_id",s)),a!=="all"&&(n=n.eq("sport",a));const{data:r,error:i}=await n;if(i)throw i;return r||[]},refetchInterval:6e4})}const Kl={moneyline:"Moneyline",totals:"Totals",spread:"Spread",props:"Props"};function Sp({engines:s,sports:a}){const t=s.filter(u=>["moneyline","spread","totals","props"].includes(u)),[n,r]=v.useState("all"),[i,l]=v.useState("all"),[m,o]=v.useState(30),{data:h,isLoading:N}=wp(n,i,m),d=u=>u===null?"—":`${u.toFixed(1)}%`,y=u=>u===null?"—":`${u>0?"+":""}${u.toFixed(1)}pp`;return e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:["Module Trust by Version",e.jsx(zt,{delayDuration:150,children:e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(Ys,{className:"h-3.5 w-3.5 text-muted-foreground cursor-help"})}),e.jsx(zs,{side:"bottom",className:"max-w-sm text-xs",children:"Versions (v1, v2.5, v3) self-adjust their own signal weights based on raw win rates. This view measures whether the module/overlay layer's adjustment on top of those versions actually helps. Lift = Module Win Rate − Version Baseline Win Rate."})]})})]}),e.jsxs(De,{className:"text-xs",children:["Per-(module · sport · source version) lift over the version's raw baseline. Populated by"," ",e.jsx("code",{className:"text-[10px]",children:"process-module-overlay-calibration"}),"."]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(oe,{value:n,onValueChange:r,children:[e.jsx(de,{className:"w-[140px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Engine"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Engines"}),t.map(u=>e.jsx(V,{value:u,children:Kl[u]||u},u))]})]}),e.jsxs(oe,{value:i,onValueChange:l,children:[e.jsx(de,{className:"w-[130px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),a.map(u=>e.jsx(V,{value:u,children:u.charAt(0).toUpperCase()+u.slice(1)},u))]})]}),e.jsxs(oe,{value:String(m),onValueChange:u=>o(Number(u)),children:[e.jsx(de,{className:"w-[100px] h-8 text-xs",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"7",children:"7d"}),e.jsx(V,{value:"30",children:"30d"}),e.jsx(V,{value:"90",children:"90d"})]})]})]})]})}),e.jsx(J,{children:N?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):!h||h.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground py-8 text-center space-y-2",children:[e.jsx("div",{children:"No module trust data yet."}),e.jsxs("div",{className:"text-xs",children:["The module-overlay calibration job has not produced rows yet for this window. Once ",e.jsx("code",{children:"process-module-overlay-calibration"})," runs against settled module-finalized picks, per-version trust scores will appear here."]})]}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Module"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Source Version"}),e.jsx(U,{className:"text-right",children:"Promoted"}),e.jsx(U,{className:"text-right",children:"Dropped"}),e.jsx(U,{className:"text-right",children:"Module WR"}),e.jsx(U,{className:"text-right",children:"Version WR"}),e.jsx(U,{className:"text-right",children:"Lift"}),e.jsx(U,{className:"text-right",children:"Trust ×"}),e.jsx(U,{className:"text-right",children:"Recommended ×"})]})}),e.jsx($e,{children:h.map(u=>{const x=u.module_lift,f=u.wins+u.losses>=30&&x!==null&&Math.abs(x)>=3,_=u.recommended_trust_multiplier,k=u.current_trust_multiplier??1,b=_!==null&&Math.abs((_??k)-k)>=.05;return e.jsxs(he,{children:[e.jsx(M,{className:"font-medium text-xs",children:Kl[u.module_engine_id]||u.module_engine_id}),e.jsx(M,{className:"capitalize text-xs",children:u.sport}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:"text-[10px]",children:u.source_version})}),e.jsx(M,{className:"text-right text-xs font-mono",children:u.picks_promoted}),e.jsx(M,{className:"text-right text-xs font-mono text-muted-foreground",children:u.picks_dropped}),e.jsx(M,{className:"text-right text-xs font-mono",children:d(u.module_promoted_win_rate)}),e.jsx(M,{className:"text-right text-xs font-mono text-muted-foreground",children:d(u.version_baseline_win_rate)}),e.jsx(M,{className:Le("text-right text-xs font-mono font-medium",x!==null&&x>0&&"text-emerald-400",x!==null&&x<0&&"text-red-400"),children:e.jsxs("span",{className:"inline-flex items-center gap-1 justify-end",children:[f&&x!==null&&x>0&&e.jsx(Ds,{className:"h-3 w-3"}),f&&x!==null&&x<0&&e.jsx(qt,{className:"h-3 w-3"}),y(x)]})}),e.jsx(M,{className:"text-right text-xs font-mono",children:k.toFixed(2)}),e.jsx(M,{className:Le("text-right text-xs font-mono",b&&"text-amber-400 font-medium"),children:_!==null?_.toFixed(2):"—"})]},u.id)})})]})})]})}const Vl={moneyline:"Moneyline",totals:"Totals",spread:"Spread",props:"Props"},Hl={active:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",shadow:"bg-amber-500/15 text-amber-400 border-amber-500/30",retired:"bg-muted text-muted-foreground border-muted"},kp={active:"ACTIVE",shadow:"STAGED",retired:"RETIRED"};function Cp({engines:s=[],sports:a=[]}){const[t,n]=v.useState("all"),[r,i]=v.useState("all"),[l,m]=v.useState(30),[o,h]=v.useState(!1),{data:N,isLoading:d}=ge({queryKey:["policy-lab-overlays",t,r,l,o],queryFn:async()=>{const u=new Date(Date.now()-l*24*60*60*1e3).toISOString();let x=T.from("klutch_module_sport_overlays").select("*").gte("updated_at",u).order("updated_at",{ascending:!1}).limit(500);t!=="all"&&(x=x.eq("engine_id",t)),r!=="all"&&(x=x.in("sport",[r,"*"])),o||(x=x.neq("status","retired"));const{data:g,error:f}=await x;if(f)throw f;return g||[]},refetchInterval:6e4}),y=(N==null?void 0:N.filter(u=>(u.status||"").toLowerCase()==="retired").length)??0;return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(fe,{className:"text-base",children:"Module Sport Overlays"}),e.jsxs(De,{className:"text-xs",children:["Module-native multipliers learned standalone from post-adjustment outcomes. Weight ","<"," 1 dampens · ",">"," 1 amplifies · = 0 drops the candidate. Lifecycle: ",e.jsx("span",{className:"text-amber-400 font-medium",children:"STAGED"})," = proposed ·"," ",e.jsx("span",{className:"text-emerald-400 font-medium",children:"ACTIVE"})," = applied ·"," ",e.jsx("span",{className:"text-muted-foreground font-medium",children:"RETIRED"})," = removed."]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 mr-2",children:[e.jsx(Ge,{id:"show-retired",checked:o,onCheckedChange:h}),e.jsx(Q,{htmlFor:"show-retired",className:"text-xs cursor-pointer",children:"Show retired"})]}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-[140px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Engine"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Engines"}),s.map(u=>e.jsx(V,{value:u,children:Vl[u]||u},u))]})]}),e.jsxs(oe,{value:r,onValueChange:i,children:[e.jsx(de,{className:"w-[130px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),a.map(u=>e.jsx(V,{value:u,children:u.charAt(0).toUpperCase()+u.slice(1)},u))]})]}),e.jsxs(oe,{value:String(l),onValueChange:u=>m(Number(u)),children:[e.jsx(de,{className:"w-[100px] h-8 text-xs",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"7",children:"7d"}),e.jsx(V,{value:"30",children:"30d"}),e.jsx(V,{value:"90",children:"90d"})]})]})]})]}),o&&y>0&&e.jsxs("div",{className:"mt-3 rounded-md border border-amber-500/30 bg-amber-500/10 p-2 text-xs flex items-start gap-2",children:[e.jsx(ls,{className:"h-3.5 w-3.5 text-amber-400 mt-0.5 shrink-0"}),e.jsx("span",{className:"text-amber-200/90",children:"Retired rows include legacy contamination quarantined Apr 2026 — overlays that were auto-imported from version learning tables and never represented standalone module learning. They are not applied at pick time."})]})]}),e.jsx(J,{children:d?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(ne,{className:"h-5 w-5 animate-spin mr-2"}),"Loading overlays…"]}):!N||N.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground py-6 text-center space-y-1",children:[e.jsx("div",{children:"No overlays in the selected window."}),e.jsx("div",{className:"text-xs",children:"The standalone module-overlay calibration job will populate this as settled module-finalized picks accumulate."})]}):e.jsx(zt,{delayDuration:150,children:e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Engine"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Signal"}),e.jsx(U,{className:"text-right",children:"Weight"}),e.jsx(U,{className:"text-right",children:"N w/"}),e.jsx(U,{className:"text-right",children:"WR w/"}),e.jsx(U,{className:"text-right",children:"WR w/o"}),e.jsx(U,{className:"text-right",children:"Lift"}),e.jsx(U,{className:"text-right",children:"Recommended"}),e.jsx(U,{children:"Status"})]})}),e.jsx($e,{children:[...N].sort((u,x)=>{if(u.engine_id!==x.engine_id)return u.engine_id.localeCompare(x.engine_id);const g=u.sport==="*"||u.sport==="any"?0:1,f=x.sport==="*"||x.sport==="any"?0:1;if(g!==f)return g-f;const _=(u.sport||"").localeCompare(x.sport||"");if(_!==0)return _;
248const k=u.signal_key==="*"?0:1,b=x.signal_key==="*"?0:1;return k!==b?k-b:(u.signal_key||"").localeCompare(x.signal_key||"")}).map(u=>{var S,P;const x=(u.status||"active").toLowerCase(),g=Hl[x]||Hl.active,f=kp[x]||x.toUpperCase(),_=u.overlay_lift,b=(u.picks_with_overlay??0)>=30&&_!==null&&Math.abs(_)>=3,j=u.recommended_weight,c=u.weight??1,p=j!=null&&Math.abs(j-c)>=.1,w=e.jsx(B,{variant:"outline",className:Le("text-[10px] uppercase",g),children:f});return e.jsxs(he,{className:x==="retired"?"opacity-60":"",children:[e.jsx(M,{className:"text-xs capitalize",children:Vl[u.engine_id]||u.engine_id}),e.jsx(M,{className:"text-xs capitalize",children:u.sport==="*"||u.sport==="any"?e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(B,{variant:"outline",className:"text-[10px] uppercase bg-sky-500/10 text-sky-300 border-sky-500/30 cursor-help",children:"All sports"})}),e.jsx(zs,{side:"top",className:"max-w-xs text-xs",children:"Wildcard rule — fans out to every sport for this engine at pick time. Multiplies on top of any sport-specific rows."})]}):u.sport}),e.jsx(M,{className:"text-xs font-mono max-w-[220px] truncate",title:u.signal_key||"",children:u.signal_key==="*"?e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(B,{variant:"outline",className:"text-[10px] uppercase bg-violet-500/10 text-violet-300 border-violet-500/30 cursor-help font-sans",children:"Baseline (all signals)"})}),e.jsx(zs,{side:"top",className:"max-w-xs text-xs",children:"Baseline weight — applied once to every candidate in this (engine, sport) bucket, regardless of which specific signals fired."})]}):u.signal_key||"—"}),e.jsx(M,{className:Le("text-xs text-right font-medium font-mono",(u.weight??1)>1&&"text-primary",(u.weight??1)<1&&"text-destructive"),children:((S=u.weight)==null?void 0:S.toFixed(2))??"—"}),e.jsx(M,{className:"text-xs text-right font-mono text-muted-foreground",children:u.picks_with_overlay??"—"}),e.jsx(M,{className:"text-xs text-right font-mono",children:u.with_overlay_win_rate!==null&&u.with_overlay_win_rate!==void 0?`${u.with_overlay_win_rate.toFixed(1)}%`:"—"}),e.jsx(M,{className:"text-xs text-right font-mono text-muted-foreground",children:u.without_overlay_win_rate!==null&&u.without_overlay_win_rate!==void 0?`${u.without_overlay_win_rate.toFixed(1)}%`:"—"}),e.jsx(M,{className:Le("text-xs text-right font-mono font-medium",_!=null&&_>0&&"text-emerald-400",_!=null&&_<0&&"text-red-400"),children:_!=null?`${_>0?"+":""}${_.toFixed(1)}pp${b?" *":""}`:"—"}),e.jsx(M,{className:Le("text-xs text-right font-mono",p&&"text-amber-400 font-medium"),children:j!=null?j.toFixed(2):"—"}),e.jsx(M,{children:x==="retired"&&((P=u.notes)!=null&&P.includes("QUARANTINED"))?e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx("span",{children:w})}),e.jsx(zs,{side:"top",className:"max-w-xs text-xs",children:"Quarantined: legacy-sourced contamination. Originally auto-imported from version learning tables. Not applied at pick time."})]}):x==="shadow"?e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx("span",{children:w})}),e.jsx(zs,{side:"top",className:"max-w-xs text-xs",children:"Proposed by Loop A. Not applied to live picks. Promote to ACTIVE to use."})]}):w})]},u.id)})})]})})})})]})}function Pp(){return ge({queryKey:["klutch-engine-versions"],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_engine_versions").select("*").order("created_at",{ascending:!1});if(a)throw a;return s||[]},staleTime:6e4})}function Kc(s,a,t){return ge({queryKey:["klutch-engine-health",s,a,t],queryFn:async()=>{let n=T.from("klutch_engine_health").select("*").order("engine_id").order("sport").order("window_days");s&&s!=="all"&&(n=n.eq("engine_id",s)),a&&a!=="all"&&(n=n.eq("sport",a)),t!=null&&(n=n.eq("window_days",t));const{data:r,error:i}=await n;if(i)throw i;return r||[]},staleTime:6e4,refetchInterval:6e4})}function Fp(){return ge({queryKey:["klutch-overlay-calibration"],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_overlay_calibration").select("*");if(a)throw a;return s||[]},staleTime:6e4,refetchInterval:6e4})}function Ap(){const{data:s}=Pp(),{data:a}=Kc("all","all"),t=[...new Set((s==null?void 0:s.map(r=>r.engine_id))||[])],n=[...new Set((a==null?void 0:a.map(r=>r.sport))||[])];return e.jsxs(js,{defaultValue:"reasoning",className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-1 h-auto p-1 justify-start",children:[e.jsxs(Ne,{value:"reasoning",className:"text-xs gap-1.5",children:[e.jsx(_t,{className:"h-3.5 w-3.5"}),"Engine Signal Reasoning"]}),e.jsxs(Ne,{value:"overlays",className:"text-xs gap-1.5",children:[e.jsx(hc,{className:"h-3.5 w-3.5"}),"Sport Overlays"]})]}),e.jsx(we,{value:"reasoning",className:"mt-4",children:e.jsx(Sp,{engines:t,sports:n})}),e.jsx(we,{value:"overlays",className:"mt-4",children:e.jsx(Cp,{engines:t,sports:n})})]})}function Tp(){return ge({queryKey:["klutch-active-shadow-rules"],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_rule_applied").select("id, proposal_id, rollout_scope, status, shadow_start, shadow_end, shadow_results, model_version_before, model_version_after, klutch_rule_proposals(scope, reason, target_table, target_key, current_value, proposed_value, change_type)").eq("rollout_scope","shadow").eq("status","active").order("shadow_start",{ascending:!1}).limit(50);if(a)throw a;return s||[]},staleTime:3e4})}function Lp(){const s=Me();return _e({mutationFn:async({applied_id:a,force:t=!1})=>{const{data:n,error:r}=await T.functions.invoke("evaluate-shadow-rule",{body:{applied_id:a,force:t}});if(r)throw r;if(n!=null&&n.error)throw new Error(n.error);return n},onSuccess:async a=>{var n;await s.invalidateQueries({queryKey:["klutch-active-shadow-rules"]}),await s.refetchQueries({queryKey:["klutch-active-shadow-rules"]});const t=((n=a==null?void 0:a.result)==null?void 0:n.total_window_picks)??0;t===0?K.message("No settled picks in shadow window yet — nothing to compare."):K.success(`Shadow comparison computed (${t} picks)`)},onError:a=>K.error(`Compare failed: ${(a==null?void 0:a.message)||"unknown error"}`)})}function Ep(){const s=Me();return _e({mutationFn:async({applied_id:a,proposal_id:t})=>{const{error:n}=await T.from("klutch_rule_applied").update({status:"rolled_back",rolled_back_at:new Date().toISOString()}).eq("id",a);if(n)throw n;const{data:r,error:i}=await T.functions.invoke("apply-klutch-rule",{body:{proposal_id:t,rollout_scope:"full",applied_by:"manual_promote_from_shadow"}});if(r!=null&&r.error)throw new Error(r.error);if(i){const l=i==null?void 0:i.context;let m=null;try{if(l&&typeof l.json=="function"){const o=await l.json();m=(o==null?void 0:o.error)||(o==null?void 0:o.message)||null}}catch{}throw new Error(m||i.message||"Edge function error")}return r},onSuccess:async()=>{const a=[["klutch-active-shadow-rules"],["klutch-applied"],["klutch-proposals"],["klutch-simulations"],["klutch-versions"],["policy-lab-proposals"],["policy-lab-sim-map"]];await Promise.all(a.map(t=>s.invalidateQueries({queryKey:t}))),await Promise.all(a.map(t=>s.refetchQueries({queryKey:t,type:"active"}))),K.success("Promoted to production — rule is now live")},onError:a=>K.error(`Promote failed: ${(a==null?void 0:a.message)||"unknown error"}`)})}function Dp(s){switch(s){case"klutch_gameline_learning":return{label:"Legacy v1",tone:"outline"};case"klutch_v2_signal_learning":return{label:"Legacy v2",tone:"outline"};case"klutch_engine_module_settings":return{label:"Module",tone:"secondary"};case"klutch_engine_rules":return{label:"Module Rules",tone:"secondary"};default:return{label:s||"unknown",tone:"outline"}}}const Pn=new Set(["simulated","approved","applied"]),Wl={loop_a:"Loop A · Module Learning",loop_b:"Loop B · Signal Promotion",analyst:"KLUTCH Analyst",rule_proposal:"Rule Proposal",engine_promotion:"Engine Promotion",ai_proposal:"AI Proposal"};function Mp(){const[s,a]=v.useState("all"),[t,n]=v.useState(null),r=Me(),{data:i,isLoading:l}=ge({queryKey:["policy-lab-proposals","pending",s],queryFn:async()=>{let _=T.from("klutch_policy_proposals").select("*").eq("status","pen
248ding").order("created_at",{ascending:!1}).limit(200);s!=="all"&&(_=_.eq("source_loop",s));const{data:k,error:b}=await _;if(b)throw b;const j=k||[],c=j.filter(w=>w.legacy_source_table==="klutch_rule_proposals"&&w.legacy_source_id).map(w=>w.legacy_source_id);let p=new Set;if(c.length>0){const[{data:w},{data:S}]=await Promise.all([T.from("klutch_rule_proposals").select("id, status").in("id",c),T.from("klutch_rule_applied").select("proposal_id").in("proposal_id",c).eq("rollout_scope","shadow").eq("status","active")]),P=new Map;for(const C of w||[])P.set(C.id,C.status);for(const C of S||[])p.add(C.proposal_id);for(const C of j)C.legacy_source_id&&(C.legacy_status=P.get(C.legacy_source_id)||null)}return j.filter(w=>w.legacy_source_table!=="klutch_rule_proposals"||!w.legacy_source_id?!0:!(w.legacy_status==="applied"||p.has(w.legacy_source_id)))},refetchInterval:3e4}),{data:m}=ge({queryKey:["policy-lab-sim-map"],queryFn:async()=>{const{data:_,error:k}=await T.from("klutch_rule_simulations").select("proposal_id, passed_gates, simulation_confidence_score, created_at").eq("simulation_type","replay").order("created_at",{ascending:!1}).limit(1e3);if(k)throw k;const b=new Map;for(const j of _||[]){const c=j.proposal_id;!c||b.has(c)||b.set(c,{passed_gates:j.passed_gates,score:j.simulation_confidence_score})}return b},placeholderData:_=>_,staleTime:15e3});m&&new Set(Array.from(m.keys()));const o=async()=>{const _=[["policy-lab-proposals"],["policy-lab-sim-map"],["policy-lab-sim-ids"],["policy-lab-applied-map"],["klutch-proposals"],["klutch-simulations"],["klutch-applied"],["klutch-versions"],["klutch-active-shadow-rules"],["klutch-ai-proposals"]];await Promise.all(_.map(k=>
248r.invalidateQueries({queryKey:k}))),await Promise.all(_.map(k=>r.refetchQueries({queryKey:k,type:"active"})))};async function h(_,k,b){const j={status:k},c=new Date().toISOString();k==="applied"&&(j.applied_at=c),(k==="rejected"||k==="dismissed")&&(j.dismissed_at=c,b&&(j.dismissed_note=b));const{error:p}=await T.from("klutch_policy_proposals").update(j).eq("id",_.id);if(p)throw new Error(`Failed to update unified proposal: ${p.message}`);if(_.legacy_source_table==="klutch_rule_proposals"&&_.legacy_source_id){await T.from("klutch_policy_proposals").update(j).eq("legacy_source_table","klutch_rule_proposals").eq("legacy_source_id",_.legacy_source_id);const w=k==="rejected"||k==="dismissed"?"rejected":"applied";await T.from("klutch_rule_proposals").update({status:w}).eq("id",_.legacy_source_id)}}function N(_){r.setQueriesData({queryKey:["policy-lab-proposals"]},k=>Array.isArray(k)?k.filter(b=>!(b.id===_.id||_.legacy_source_id&&b.legacy_source_table==="klutch_rule_proposals"&&b.legacy_source_id===_.legacy_source_id)):k)}function d(_,k){k&&r.setQueryData(["policy-lab-sim-map"],b=>{const j=new Map(b||[]);return j.set(_,{passed_gates:k.gates_passed??null,score:k.simulation_confidence??null}),j})}async function y(_){const{data:k,error:b}=await T.functions.invoke("simulate-klutch-rule",{body:{proposal_id:_}});if(b)throw new Error(x(b,k,"Simulation failed"));if(k&&k.success===!1)throw new Error(k.error||"Simulation failed");return d(_,k),k}async function u(_){const{data:k}=await T.from("klutch_rule_proposals").select("status").eq("id",_).maybeSingle();return(k==null?void 0:k.status)??null}function x(_,k,b){var c,p,w;if(k&&typeof k=="object"&&k.error)return String(k.error);const j=((c=_==null?void 0:_.context)==null?void 0:c.body)||((w=(p=_==null?void 0:_.context)==null?void 0:p.response)==null?void 0:w.body);if(typeof j=="string")try{const S=JSON.parse(j);if(S!=null&&S.error)return String(S.error)}catch{return j}return(_==null?void 0:_.message)||b}const g=_e({mutationFn:async({proposal:_,action:k})=>{const b=_.legacy_source_table==="klutch_rule_proposals"&&!!_.legacy_source_id,j=_.legacy_source_id;switch(k){case"simulate":{if(!b||!j)throw new Error("Simulate is only available for rule proposals.");return{kind:"simulate",sim:await y(j)}}case"shadow":{if(!b||!j)throw new Error("Shadow promotion is only available for rule proposals.");let c=_.legacy_status??await u(j),p=null;if(!c||!Pn.has(c)){if(p=await y(j),c=await u(j),(p==null?void 0:p.gates_passed)===!1)throw new Error(`Simulation gates failed (confidence ${Math.round(p.simulation_confidence??0)}%). Review Simulations tab before shadowing.`);if(!c||!Pn.has(c))throw new Error(`Cannot shadow: proposal status is "${c||"unknown"}" after simulation. Picks may be missing or insufficient.`)}const{data:w,error:S}=await T.functions.invoke("apply-klutch-rule",{body:{proposal_id:j,rollout_scope:"shadow"}});if(S)throw new Error(x(S,w,"Shadow apply failed"));if(w&&w.success===!1)throw new Error(w.error||"Shadow apply failed");return await h(_,"applied","shadow_promoted"),{kind:"shadow",sim:p}}case"apply":{if(b&&j){let w=_.legacy_status??await u(j),S=null,P=!1;if((!w||!Pn.has(w))&&(S=await y(j),w=await u(j),(S==null?void 0:S.gates_passed)===!1&&(P=!0),!w||!["simulated","approved","applied"].includes(w)))throw new Error(`Cannot apply: proposal status is "${w||"unknown"}" after simulation.`);const{data:C,error:O}=await T.functions.invoke("apply-klutch-rule",{body:{proposal_id:j,rollout_scope:"full"}});if(O)throw new Error(x(O,C,"Apply failed"));if(C&&C.success===!1)throw new Error(C.error||"Apply failed");return await h(_,"applied","applied_full"),{kind:"apply",sim:S,gatesWarn:P}}const{data:c,error:p}=await T.functions.invoke("klutch-apply-proposal",{body:{proposal_id:_.id,action:"apply"}});if(p)throw new Error(x(p,c,"Apply failed"));return{kind:"apply"}}case"reject":return await h(_,"rejected","manual_reject"),{kind:"reject"};case"dismiss":return await h(_,"dismissed","manual_dismiss"),{kind:"dismiss"}}},onSuccess:(_,k)=>{k!=null&&k.proposal&&(_!=null&&_.kind)&&_.kind!=="simulate"&&N(k.proposal);const b=j=>{if(!j)return"";const c=j.gates_passed?"✓ Gates Passed":"✗ Gates Failed",p=j.simulation_confidence!=null?`${Math.round(j.simulation_confidence)}%`:"n/a",w=j.picks_tested??0;return`${c} · Confidence ${p} · ${w} picks tested`};if((_==null?void 0:_.kind)==="simulate"&&_.sim){const j=`Simulation: ${b(_.sim)}`;_.sim.gates_passed?K.success(j):K.error(j)}else(_==null?void 0:_.kind)==="shadow"?K.success(_.sim?`Promoted to Shadow (sim ${b(_.sim)})`:"Promoted to Shadow"):(_==null?void 0:_.kind)==="apply"?_.gatesWarn?K.warning(`Applied (override) — ${b(_.sim)}`):K.success(_.sim?`Applied (sim ${b(_.sim)})`:"Applied to active rules / overlays"):(_==null?void 0:_.kind)==="reject"?K.success("Proposal rejected"):(_==null?void 0:_.kind)==="dism
248iss"?K.success("Proposal dismissed"):K.success("Proposal updated");o(),n(null)},onError:_=>K.error((_==null?void 0:_.message)||"Action failed")}),f=(i||[]).reduce((_,k)=>{const b=k.source_loop||k.proposal_type||"unknown";return _[b]=(_[b]||0)+1,_},{});return e.jsx(zt,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs(G,{children:[e.jsxs(je,{className:"pb-3",children:[e.jsx(fe,{className:"text-base",children:"Unified Proposals Queue"}),e.jsx(De,{children:"Single queue for every governance signal: Loop A (module learning rebalances), Loop B (legacy signal promotion), KLUTCH Analyst, and rule proposals. Simulate, Shadow-test, Apply (to sport overlays / active rules), or Reject — actions remove the row from the pending queue and route it to the right tab below."})]}),e.jsxs(J,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-56 h-8 text-xs",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sources"}),e.jsx(V,{value:"loop_a",children:"Loop A · Module Learning"}),e.jsx(V,{value:"loop_b",children:"Loop B · Signal Promotion"}),e.jsx(V,{value:"analyst",children:"KLUTCH Analyst"}),e.jsx(V,{value:"rule_proposal",children:"Rule Proposal (legacy)"}),e.jsx(V,{value:"engine_promotion",children:"Engine Promotion (legacy)"}),e.jsx(V,{value:"ai_proposal",children:"AI Proposal (legacy)"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1 text-[10px] text-muted-foreground",children:Object.entries(f).map(([_,k])=>e.jsxs(B,{variant:"outline",className:"text-[10px]",children:[_,": ",k]},_))})]}),l?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(ne,{className:"h-5 w-5 animate-spin mr-2"}),"Loading proposals…"]}):!i||i.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No proposals match the current filters."}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Source"}),e.jsx(U,{children:"Type"}),e.jsx(U,{children:"Title"}),e.jsx(U,{children:"Sim"}),e.jsx(U,{children:"Sim Score"}),e.jsx(U,{children:"Created"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:i.map(_=>{var S;const k=_.legacy_source_id,b=k?m==null?void 0:m.get(k):void 0,j=!!b,c=_.legacy_source_table==="klutch_rule_proposals"&&!!_.legacy_source_id,p=_.status==="pending",w={sim:j,shadowed:!1,active:!1};return e.jsxs(he,{children:[e.jsx(M,{className:"text-xs",children:e.jsx(B,{variant:"outline",className:"text-[10px]",children:Wl[_.source_loop||""]||_.source_loop||"—"})}),e.jsx(M,{className:"text-xs",children:_.proposal_type||"—"}),e.jsx(M,{className:"text-xs max-w-md truncate",children:_.title||((S=_.rationale)==null?void 0:S.slice(0,80))||"—"}),e.jsx(M,{children:(b==null?void 0:b.passed_gates)===!0?e.jsx(B,{variant:"outline",className:"text-[10px] bg-emerald-500/15 text-emerald-400 border-emerald-500/30",children:"Pass"}):(b==null?void 0:b.passed_gates)===!1?e.jsx(B,{variant:"outline",className:"text-[10px] bg-red-500/15 text-red-400 border-red-500/30",children:"Fail"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Not simulated"})}),e.jsx(M,{className:"text-xs",children:(b==null?void 0:b.score)!=null?Math.round(Number(b.score)):"—"}),e.jsx(M,{className:"text-[10px] text-muted-foreground",children:new Date(_.created_at).toLocaleString()}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 px-2",onClick:()=>n(_),children:e.jsx(us,{className:"h-3.5 w-3.5"})})}),e.jsx(zs,{children:"View details"})]}),p&&c&&!w.sim&&e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 px-2 text-blue-400 hover:text-blue-300",disabled:g.isPending,onClick:()=>g.mutate({proposal:_,action:"simulate"}),children:e.jsx(Rt,{className:"h-3.5 w-3.5"})})}),e.jsx(zs,{children:"Simulate"})]}),p&&c&&!w.shadowed&&!w.active&&e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 px-2 text-cyan-400 hover:text-cyan-300",disabled:g.isPending,onClick:()=>g.mutate({proposal:_,action:"shadow"}),children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})}),e.jsx(zs,{children:"Shadow-test"})]}),p&&e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 px-2 text-emerald-400 hover:text-emerald-300",disabled:g.isPending,onClick:()=>g.mutate({proposal:_,action:"apply"}),children:e.jsx(pr,{className:"h-3.5 w-3.5"})})}),e.jsx(zs,{children:"Apply (push to overlay / active rules)"})]}),p&&e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsx(R,{size:"sm",variant:"ghost",className:"h-7 px-2 text-destructive hover:text-destructive",disabled:g.isPending,onClick:()=>g.mutate({proposal:_,action:"reject"}),children:e.jsx(Is,{className:"h-3.5 w-3.5"})})}),e.jsx(zs,{children:"Reject (remove from queue)"})]})]})})]},_.id)})})]})})]})]}),e.jsx(Ue,{open:!!t,onOpenChange:_=>!_&&n(null),children:e.jsxs(Be,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:(t==null?void 0:t.t
248itle)||"Proposal"}),e.jsxs(Vs,{children:[Wl[(t==null?void 0:t.source_loop)||""]||(t==null?void 0:t.source_loop)," · ",t==null?void 0:t.proposal_type]})]}),t&&(()=>{const _=t.legacy_source_id,k={sim:!!(_&&(m!=null&&m.get(_))),shadowed:!1,active:!1},b=t.legacy_source_table==="klutch_rule_proposals"&&!!t.legacy_source_id,j=t.status==="pending";return e.jsxs("div",{className:"space-y-3 text-sm",children:[t.rationale&&e.jsx(dr,{title:"Rationale",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.rationale})}),e.jsx(dr,{title:"Target",children:e.jsx("pre",{className:"text-[11px] bg-muted/40 p-2 rounded overflow-x-auto",children:JSON.stringify(t.target,null,2)})}),e.jsx(dr,{title:"Current Value",children:e.jsx("pre",{className:"text-[11px] bg-muted/40 p-2 rounded overflow-x-auto",children:JSON.stringify(t.current_value,null,2)})}),e.jsx(dr,{title:"Proposed Change",children:e.jsx("pre",{className:"text-[11px] bg-muted/40 p-2 rounded overflow-x-auto",children:JSON.stringify(t.payload,null,2)})}),e.jsx(dr,{title:"Evidence",children:e.jsx("pre",{className:"text-[11px] bg-muted/40 p-2 rounded overflow-x-auto",children:JSON.stringify(t.evidence,null,2)})}),j&&e.jsxs("div",{className:"flex flex-wrap gap-2 pt-3 border-t",children:[b&&!k.sim&&e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>g.mutate({proposal:t,action:"simulate"}),disabled:g.isPending,children:[e.jsx(Rt,{className:"h-3.5 w-3.5 mr-1"})," Simulate"]}),b&&!k.shadowed&&!k.active&&e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>g.mutate({proposal:t,action:"shadow"}),disabled:g.isPending,children:[e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1"})," Shadow-test"]}),e.jsxs(R,{size:"sm",onClick:()=>g.mutate({proposal:t,action:"apply"}),disabled:g.isPending,children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1"})," Apply"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"text-destructive",onClick:()=>g.mutate({proposal:t,action:"reject"}),disabled:g.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Reject"]}),e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>g.mutate({proposal:t,action:"dismiss"}),disabled:g.isPending,children:"Dismiss"})]})]})})()]})})]})})}function dr({title:s,children:a}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:s}),a]})}const Ip={pending:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",simulating:"bg-blue-500/20 text-blue-400 border-blue-500/30",simulated:"bg-purple-500/20 text-purple-400 border-purple-500/30",approved:"bg-green-500/20 text-green-400 border-green-500/30",rejected:"bg-red-500/20 text-red-400 border-red-500/30",applied:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",expired:"bg-muted text-muted-foreground border-muted",rolled_back:"bg-orange-500/20 text-orange-400 border-orange-500/30",watchlist:"bg-cyan-500/20 text-cyan-400 border-cyan-500/30",insufficient_samples:"bg-muted text-muted-foreground border-muted"};function Rp(s){if(!s)return"—";if(typeof s=="string")try{s=JSON.parse(s)}catch{return s.replace(/__/g,"").substring(0,30)}const a=[];return s.signal_combo_key&&a.push(s.signal_combo_key.replace(/__BUCKET_/g,"").replace(/__/g,"")),s.sharp_score_bucket&&a.push(`sharp ${s.sharp_score_bucket}`),s.movement_direction&&a.push(s.movement_direction),s.confidence_bucket&&a.push(`conf ${s.confidence_bucket}`),a.length>0?a.join(" · "):JSON.stringify(s).substring(0,30)}function qp(){const[s,a]=v.useState("proposals"),{toast:t}=Ws(),n=Me();ge({queryKey:["klutch-proposals"],queryFn:async()=>{const{data:S,error:P}=await T.from("klutch_rule_proposals").select("*, klutch_rule_simulations(passed_gates)").order("created_at",{ascending:!1}).limit(200);if(P)throw P;const C=new Map;for(const O of S||[]){const $=typeof O.target_key=="string"?O.target_key:JSON.stringify(O.target_key),z=`${O.scope}||${$}||${O.change_type}`;C.has(z)||C.set(z,O)}return Array.from(C.values())}});const{data:r,isLoading:i}=ge({queryKey:["klutch-simulations"],queryFn:async()=>{const{data:S,error:P}=await T.from("klutch_rule_simulations").select("*, klutch_rule_proposals(id, scope, reason, status)").order("created_at",{ascending:!1}).limit(50);if(P)throw P;return S}}),{data:l,isLoading:m}=ge({queryKey:["klutch-applied"],queryFn:async()=>{const{data:S,error:P}=await T.from("klutch_rule_applied").select("*, klutch_rule_proposals(scope, reason, change_type)").order("applied_at",{ascending:!1}).limit(50);if(P)throw P;return S}}),{data:o,isLoading:h}=ge({queryKey:["klutch-versions"],queryFn:async()=>{const{data:S,error:P}=await T.from("klutch_model_versions").select("*").order("created_at",{ascending:!1}).limit(20);if(P)throw P;return S}}),{data:N,isLoading:d}=ge({queryKey:["klutch-chief-reviews"],queryFn:async()=>{const{data:S,error:P}=await T.from("klutch_chief_reviews").select("*").order("review_date",{ascending:!1}).limit(10);if(P)throw P;return S}}),{data:y}=ge({queryKey:["klutch-policy-caps"],queryFn:async()=>{const{data:S,error:P}=await T.from("klutch_policy_caps").select("*").limit(1).single();if(P)throw P;return S}}),{data:u,isLoading:x}=Tp(),g=Lp(),f=Ep(),_=(()=>{const S=new Map;for(const P of l||[]){if(P.status!=="active")continue;const C=S.get(P.proposal_id);(!C||C==="shadow"&&P.rollout_scope!=="shadow")&&S.set(P.proposal_id,P.rollout_scope)}return S})();_e({mutationFn:async S=>{const{data:P,error:C}=await T.functions.invoke("simulate-klutch-rule",{body:{proposal_id:S}});if(C)throw C;return P},onSuccess:S=>{t({title:"Simulation complete",description:`Confidence: ${S.simulation_confidence}% | Gates: ${S.gates_passed?"PASSED":"FAILED"}`}),n.invalidateQueries({queryKey:["klutch-proposals"]}),n.invalidateQueries({queryKey:["klutch-simulations"]})},onError:S=>t({title:"Simulation failed",description:S.message,variant:"destructive"})});const k=_e({mutationFn:async({proposalId:S,rolloutScope:P})=>{const{data:C,error:O}=await T.functions.invoke("apply-klutch-rule",{body:{proposal_id:S,rollout_scope:P}});if(O)throw O;const $=P==="shadow"?"shadow_promoted":"applied_full";return await T.from("klutch_policy_proposals").update({status:"applied",applied_at:new Date().toISOString(),dismissed_note:$}).eq("legacy_source_id",S),C},onSuccess:async S=>{const P=(S==null?void 0:S.rollout_scope)==="shadow";t({title:P?"Rule shadowed":"Rule applied",description:`Version: ${S==null?void 0:S.new_version} | Scope: ${S==null?void 0:S.rollout_scope}`});const C=[["klutch-proposals"],["klutch-simulations"],["klutch-applied"],["klutch-versions"],["klutch-active-shadow-rules"],["policy-lab-proposals"],["policy-lab-sim-map"]];await Promise.all(C.map(O=>n.invalidateQueries({queryKey:O}))),await Promise.all(C.map(O=>n.refetchQueries({queryKey:O,type:"active"})))},onError:S=>
248t({title:"Apply failed",description:(S==null?void 0:S.message)||"Edge function error",variant:"destructive"})});_e({mutationFn:async({id:S,status:P})=>{const{error:C}=await T.from("klutch_rule_proposals").update({status:P}).eq("id",S);if(C)throw C;if(P==="rejected"||P==="dismissed"||P==="applied"){const O={status:P==="dismissed"?"rejected":P},$=new Date().toISOString();P==="applied"?O.applied_at=$:(O.dismissed_at=$,O.dismissed_note=`mirrored_${P}`),await T.from("klutch_policy_proposals").update(O).eq("legacy_source_id",S)}},onSuccess:async()=>{const S=[["klutch-proposals"],["klutch-simulations"],["klutch-applied"],["policy-lab-proposals"],["policy-lab-sim-map"]];await Promise.all(S.map(P=>n.invalidateQueries({queryKey:P}))),await Promise.all(S.map(P=>n.refetchQueries({queryKey:P,type:"active"}))),t({title:"Status updated"})}});const b=_e({mutationFn:async S=>{const{error:P}=await T.from("klutch_rule_applied").update({status:"rolled_back",rolled_back_at:new Date().toISOString()}).eq("id",S);if(P)throw P},onSuccess:()=>{n.invalidateQueries({queryKey:["klutch-applied"]}),t({title:"Rule rolled back"})}}),j=_e({mutationFn:async({appliedId:S,proposalId:P})=>{const{data:C,error:O}=await T.functions.invoke("end-shadow-rule",{body:{applied_id:S,proposal_id:P}});if(O)throw O;if(C!=null&&C.error)throw new Error(C.error);if(!(C!=null&&C.applied_rolled_back))throw new Error("Shadow row was not active — nothing to end.");return{...C,appliedId:S,proposalId:P}},onSuccess:async S=>{n.setQueriesData({queryKey:["klutch-active-shadow-rules"]},C=>Array.isArray(C)?C.filter(O=>(O==null?void 0:O.id)!==S.appliedId):C);const P=[["klutch-active-shadow-rules"],["klutch-applied"],["klutch-proposals"],["klutch-simulations"],["policy-lab-proposals"],["policy-lab-sim-map"]];await Promise.all(P.map(C=>n.invalidateQueries({queryKey:C}))),await Promise.all(P.map(C=>n.refetchQueries({queryKey:C,type:"active"}))),t({title:"Shadow ended",description:"Proposal rejected and removed from queue."})},onError:S=>t({title:"End Shadow failed",description:S==null?void 0:S.message,variant:"destructive"})}),c=_e({mutationFn:async S=>{const{error:P}=await T.from("klutch_rule_proposals").update({status:"rejected"}).eq("id",S);if(P)throw P;await T.from("klutch_policy_proposals").update({status:"rejected",dismissed_at:new Date().toISOString(),dismissed_note:"rejected_from_simulation"}).eq("legacy_source_id",S)},onSuccess:async()=>{t({title:"Proposal rejected"});const S=[["klutch-proposals"],["klutch-simulations"],["policy-lab-proposals"],["policy-lab-sim-map"]];await Promise.all(S.map(P=>n.invalidateQueries({queryKey:P}))),await Promise.all(S.map(P=>n.refetchQueries({queryKey:P,type:"active"})))},onError:S=>t({title:"Reject failed",description:S==null?void 0:S.message,variant:"destructive"})}),p=_e({mutationFn:async()=>{const{data:S,error:P}=await T.functions.invoke("weekly-klutch-chief-review",{body:{}});if(P)throw P;return S},onSuccess:S=>{t({title:"Chief Review generated",description:`Health: ${S.health_score}/100`}),n.invalidateQueries({queryKey:["klutch-chief-reviews"]})},onError:S=>t({title:"Review failed",description:S.message,variant:"destructive"})}),w=_e({mutationFn:async()=>{const{data:S,error:P}=await T.functions.invoke("monitor-klutch-rules",{body:{}});if(P)throw P;return S},onSuccess:S=>{var P;t({title:"Monitor complete",description:`${((P=S.actions)==null?void 0:P.length)||0} actions taken`}),n.invalidateQueries({queryKey:["klutch-applied"]}),n.invalidateQueries({queryKey:["klutch-proposals"]})},onError:S=>t({title:"Monitor failed",description:S.message,variant:"destructive"})});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-bold",children:"KLUTCH Policy Lab"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Simulation, validation & governed rule deployment"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>w.mutate(),disabled:w.isPending,children:[w.isPending?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(Sr,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-1",children:"Run Monitor"})]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>p.mutate(),disabled:p.isPending,children:[p.isPending?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(kt,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-1",children:"Chief Review"})]})]})]}),e.jsxs(js,{value:s,onValueChange:a,children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsx(Ne,{value:"proposals",children:"Proposals"}),e.jsx(Ne,{value:"simulations",children:"Simulations"}),e.jsxs(Ne,{value:"shadow",children:["Shadow (",(u==null?void 0:u.length)||0,")"]}),e.jsx(Ne,{value:"active",children:"Active Rules"}),e.jsx(Ne,{value:"versions",children:"Versions"}),e.jsx(Ne,{value:"chief",children:"Chief Review"}),e.jsx(Ne,{value:"settings",children:"Settings"})]}),e.jsx(we,{value:"proposals",className:"mt-4",children:e.jsx(Mp,{})}),e.jsx(we,{value:"simulations",className:"mt-4",children:e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Simulation Results"})}),e.jsx(J,{children:i?e.jsx(ne,{className:"h-6 w-6 animate-spin mx-auto"}):e.jsx("div",{className:"space-y-4",children:(()=>{const S=(r||[]).filter(O=>O.simulation_type==="replay"),P=new Set,C=[];for(const O of S){const $=O.proposal_id;!$||P.has($)||(P.add($),C.push(O))}return C})().map(S=>{var P,C,O,$,z,D,A,F,q,E,L,H,Z,se,ie,Y;return e.jsx(G,{className:"border",children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-mono text-sm font-bold",children:(P=S.klutch_rule_proposals)==null?void 0:P.scope}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:(C=S.klutch_rule_proposals)==null?void 0:C.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[S.passed_gates!=null&&e.jsx(B,{className:S.passed_gates?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400",children:S.passed_gates?"Gates Passed":"Gates Failed"}),S.simulation_confidence_score!=null&&e.jsxs(B,{variant:"outline",children:["Confidence: ",Math.round(S.simulation_confidence_score),"%"]})]})]}
248),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3 text-sm",children:[e.jsx(Ar,{label:"Win Rate",before:(O=S.before_stats)==null?void 0:O.win_rate,after:($=S.after_stats)==null?void 0:$.win_rate,format:"pct"}),e.jsx(Ar,{label:"ROI",before:(z=S.before_stats)==null?void 0:z.roi,after:(D=S.after_stats)==null?void 0:D.roi,format:"pct"}),e.jsx(Ar,{label:"Volume",before:(A=S.before_stats)==null?void 0:A.volume,after:(F=S.after_stats)==null?void 0:F.volume,format:"num"}),e.jsx(Ar,{label:"Net Units",before:(q=S.before_stats)==null?void 0:q.net_units,after:(E=S.after_stats)==null?void 0:E.net_units,format:"num"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Picks Tested"}),e.jsx("p",{className:"font-bold",children:S.picks_tested})]})]}),S.regret_analysis&&e.jsxs("div",{className:"mt-3 grid grid-cols-2 md:grid-cols-4 gap-2 text-xs border-t pt-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Missed Winners:"})," ",S.regret_analysis.missed_winners]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Avoided Losers:"})," ",S.regret_analysis.avoided_losers]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Missed ROI:"})," ",(L=S.regret_analysis.missed_roi)==null?void 0:L.toFixed(2)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Net Regret:"})," ",(H=S.regret_analysis.net_regret)==null?void 0:H.toFixed(2)]})]}),S.gate_results&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-1",children:S.gate_results.map((I,ee)=>e.jsxs(B,{variant:"outline",className:`text-xs ${I.passed?"border-green-500/50 text-green-400":"border-red-500/50 text-red-400"}`,children:[I.gate,": ",I.value," ",I.passed?"✓":"✗"]},ee))}),S.passed_gates===!0&&((((Z=S.after_stats)==null?void 0:Z.roi)??0)<0||(((se=S.after_stats)==null?void 0:se.win_rate)??0)<.5)&&e.jsxs("div",{className:"mt-3 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-300",children:["⚠ Bucket is unprofitable on its own (ROI ",((((ie=S.after_stats)==null?void 0:ie.roi)??0)*100).toFixed(1),"%, WR ",((((Y=S.after_stats)==null?void 0:Y.win_rate)??0)*100).toFixed(1),"%) — proposal passes legacy gates but doesn't fix the underlying bucket. Consider rejecting or reworking."]}),(()=>{const I=S.klutch_rule_proposals,ee=I==null?void 0:I.id,le=I==null?void 0:I.status;if(!ee)return null;const ve=_.get(ee),te=ve==="shadow",X=!!ve&&ve!=="shadow",ae=le==="rejected",W=S.passed_gates===!1;return e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-2 border-t pt-3",children:X?e.jsx(B,{variant:"outline",className:"text-emerald-400 border-emerald-500/40",children:"Applied"}):te?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"text-cyan-400 border-cyan-500/40",children:"Shadowed"}),e.jsxs(R,{size:"sm",disabled:k.isPending||W,onClick:()=>k.mutate({proposalId:ee,rolloutScope:"full"}),title:W?"Cannot apply — gates failed":"Promote shadow rule to full rollout",children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1"})," Apply"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",disabled:c.isPending,onClick:()=>c.mutate(ee),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Reject"]})]}):ae?e.jsx(B,{variant:"outline",className:"text-red-400 border-red-500/40",children:"Rejected"}):e.jsxs(e.Fragment,{children:[e.jsxs(R,{size:"sm",variant:"outline",disabled:k.isPending,onClick:()=>k.mutate({proposalId:ee,rolloutScope:"shadow"}),children:[e.jsx(us,{className:"h-3.5 w-3.5 mr-1"})," Shadow"]}),e.jsxs(R,{size:"sm",disabled:k.isPending||W,onClick:()=>k.mutate({proposalId:ee,rolloutScope:"full"}),title:W?"Cannot apply — gates failed":void 0,children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1"})," Apply"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",disabled:c.isPending,onClick:()=>c.mutate(ee),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Reject"]})]})})})()]})},S.id)})})})]})}),e.jsx(we,{value:"shadow",className:"mt-4",children:e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(us,{className:"h-5 w-5"}),"Active Shadow Rules"]}),e.jsxs(De,{children:["Proposals applied in shadow mode — counterfactual scoring against picks settled inside the shadow window. These do ",e.jsx("span",{className:"font-semibold",children:"not"})," affect production until promoted."]})]}),e.jsx(J,{children:x?e.jsx(ne,{className:"h-6 w-6 animate-spin mx-auto"}):((u==null?void 0:u.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No active shadow rules."}):e.jsx("div",{className:"space-y-3",children:u.map(S=>{var q,E,L,H,Z,se,ie,Y;const P=S.klutch_rule_proposals,C=Dp(P==null?void 0:P.target_table),O=S.shadow_start?new Date(S.shadow_start).getTime():0,$=S.shadow_end?new Date(S.shadow_end).getTime():0,z=Date.now(),D=$?Math.max(0,Math.ceil(($-z)/864e5)):null,A=O?Math.max(0,Math.floor((z-O)/864e5)):0,F=S.shadow_results;return e.jsx(G,{className:"border",children:e.jsxs(J,{className:"pt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-mono text-sm font-bold",children:(P==null?void 0:P.scope)||"—"}),e.jsx(B,{variant:"outline",className:"text-xs",children:C.label}),e.jsxs(B,{variant:"outline",className:"text-xs",children:["v ",S.model_version_after]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:(P==null?void 0:P.reason)||"—"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono",children:Rp(P==null?void 0:P.target_key)})]}),e.jsxs("div",{className:"text-right text-xs text-muted-foreground shrink-0",children:[e.jsxs("div",{children:["Started ",A,"d ago"]}),e.jsx("div",{children:D!=null?`${D}d remaining`:"—"})]})]}),F?(F.total_window_picks??0)===0?e.jsx("p",{className:"text-xs text-muted-foreground italic border-t pt-3",children:"No settled picks in the shadow window yet — nothing to compare. Re-run after picks settle."}
248):e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3 text-sm border-t pt-3",children:[e.jsx(Tr,{label:"Sample",baseline:(q=F.baseline)==null?void 0:q.sample,proposed:(E=F.proposed)==null?void 0:E.sample,format:"num"}),e.jsx(Tr,{label:"Win Rate",baseline:(L=F.baseline)==null?void 0:L.win_rate,proposed:(H=F.proposed)==null?void 0:H.win_rate,format:"pct"}),e.jsx(Tr,{label:"ROI",baseline:(Z=F.baseline)==null?void 0:Z.roi,proposed:(se=F.proposed)==null?void 0:se.roi,format:"pct"}),e.jsx(Tr,{label:"Profit",baseline:(ie=F.baseline)==null?void 0:ie.profit,proposed:(Y=F.proposed)==null?void 0:Y.profit,format:"num"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Window picks"}),e.jsx("p",{className:"font-bold",children:F.total_window_picks??0})]})]}):e.jsxs("p",{className:"text-xs text-muted-foreground italic",children:["No comparison yet — click ",e.jsx("strong",{children:"Compare"})," to score the same settled picks under the current vs proposed rule."]}),e.jsx(zt,{children:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>g.mutate({applied_id:S.id,force:!0}),disabled:g.isPending,children:[g.isPending?e.jsx(ne,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(da,{className:"h-3 w-3 mr-1"}),F?"Recompute":"Compare"]})}),e.jsx(zs,{children:"Score settled picks in the shadow window under both the current and proposed rule."})]}),e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{size:"sm",variant:"default",onClick:()=>f.mutate({applied_id:S.id,proposal_id:S.proposal_id}),disabled:f.isPending,children:[f.isPending?e.jsx(ne,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(pr,{className:"h-3 w-3 mr-1"}),"Promote to Production"]})}),e.jsx(zs,{children:"Apply this rule to live production scoring."})]}),e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsxs(R,{size:"sm",variant:"ghost",onClick:()=>j.mutate({appliedId:S.id,proposalId:S.proposal_id}),disabled:j.isPending,children:[j.isPending?e.jsx(ne,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(qn,{className:"h-3 w-3 mr-1"}),"End Shadow"]})}),e.jsx(zs,{children:"Stop the shadow rollout and reject the underlying proposal."})]})]})})]})},S.id)})})})]})}),e.jsx(we,{value:"active",className:"mt-4",children:e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{children:"Active Rules"}),e.jsxs(De,{children:[(l==null?void 0:l.filter(S=>S.status==="active").length)||0," active"]})]}),e.jsx(J,{children:m?e.jsx(ne,{className:"h-6 w-6 animate-spin mx-auto"}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Scope"}),e.jsx(U,{children:"Rollout"}),e.jsx(U,{children:"Version"}),e.jsx(U,{children:"Applied"}),e.jsx(U,{children:"Review Due"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Actions"})]})}),e.jsx($e,{children:l==null?void 0:l.map(S=>{var P;return e.jsxs(he,{children:[e.jsx(M,{className:"font-mono text-sm",children:((P=S.klutch_rule_proposals)==null?void 0:P.scope)||"—"}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:"text-xs",children:S.rollout_scope})}),e.jsxs(M,{className:"text-sm font-mono",children:[S.model_version_before," → ",S.model_version_after]}),e.jsx(M,{className:"text-sm",children:new Date(S.applied_at).toLocaleDateString()}),e.jsx(M,{className:"text-sm",children:S.review_due?new Date(S.review_due).toLocaleDateString():"—"}),e.jsx(M,{children:e.jsx(B,{className:`${Ip[S.status]||""} text-xs`,children:S.status})}),e.jsx(M,{children:S.status==="active"&&e.jsx(R,{size:"sm",variant:"outline",onClick:()=>b.mutate(S.id),disabled:b.isPending,children:e.jsx(qn,{className:"h-3 w-3"})})})]},S.id)})})]})})]})}),e.jsx(we,{value:"versions",className:"mt-4",children:e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-5 w-5"}),"Version History"]})}),e.jsx(J,{children:h?e.jsx(ne,{className:"h-6 w-6 animate-spin mx-auto"}):e.jsx("div",{className:"space-y-2",children:o==null?void 0:o.map(S=>e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg",children:[e.jsx(B,{className:S.status==="active"?"bg-green-500/20 text-green-400":"bg-muted text-muted-foreground",children:S.version_code}),e.jsx("span",{className:"text-sm flex-1",children:S.description||"No description"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(S.created_at).toLocaleDateString()}),e.jsx(B,{variant:"outline",className:"text-xs",children:S.status})]},S.id))})})]})}),e.jsx(we,{value:"chief",className:"mt-4",children:e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Weekly Chief Reviews"})}),e.jsx(J,{children:d?e.jsx(ne,{className:"h-6 w-6 animate-spin mx-auto"}):(N==null?void 0:N.length)===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:'No reviews yet. Click "Chief Review" to generate one.'}):e.jsx("div",{className:"space-y-4",children:N==null?void 0:N.map(S=>e.jsx(G,{className:"border",children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-bold",children:S.review_date}),e.jsxs("span",{className:"ml-2 text-sm text-muted-foreground",children:["Version: ",S.model_version]})]}),e.jsxs(B,{className:(S.version_health_score||0)>=70?"bg-green-500/20 text-green-400":(S.version_health_score||0)>=50?"bg-yellow-500/20 text-yellow-400":"bg-red-500/20 text-red-400",children:["Health: ",Math.round(S.version_health_score||0),"/100"]})]}),S.recommended_actions&&S.recommended_actions.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground mb-1",children:"Recommended Actions:"}),S.recommended_actions.map((P,C)=>e.jsxs("div",{className:"text-xs flex items-center gap-2 py-1",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:P.action}),e.jsx("span",{className:"font-mono",children:P.scope}),e.jsx("span",{className:"text-muted-foreground",children:P.reason})]},C))]})]})},S.id))})})]})}),e.jsx(we,{value:"settings",className:"mt-4",children:e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-5 w-5"}),"Policy Caps"]}),e.jsx(De,{children:"Over-optimization guardrails"})]}),e.jsx(J,{children:y?e.jsx($p,{policyCaps:y}):e.jsx(ne,{className:"h-6 w-6 animate-spin mx-auto"})})]})})]})]})}function Ar({label:s,before:a,after:t,format:n}){const r=(t||0)-(a||0),i=l=>l==null?"—":n==="pct"?`${(l*100).toFixed(1)}%`:typeof l=="number"?l.toFixed(2):l;return e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:s}),e.jsx("p",{className:"font-bold",children:i(t)}),e.jsxs("p",{className:`text-xs ${r>0?"text-green-400":r<0?"text-red-400":"text-muted-foreground"}`,children:[r>0?"+":"",i(r)," from ",i(a)]})]})}function Tr({label:s,baseline:a,proposed:t,format:n}){const r=(t||0)-(a||0),i=l=>l==null?"—":n==="pct"?`${(l*100).toFixed(1)}%`:typeof l=="number"?l.toFixed(2):l;return e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:s}),e.jsx("p",{className:"font-bold",children:i(t)}),e.jsxs("p",{className:`text-xs ${r>0?"text-green-400":r<0?"text-red-400":"text-muted-foreground"}`,children:[r>0?"+":"",i(r)," vs ",i(a)]})]})}function $p({policyCaps:s}){const a=Me(),{toast:t}=Ws(),[n,r]=v.useState(s.max_live_experimental_rules),[i,l]=v.useState(s.max_simultaneous_per_sport),[m,o]=v.useState(s.cooldown_hours_between_global_edits);v.useEffect(()=>{r(s.max_live_experimental_rules),l(s.max_simultaneous_per_sport),o(s.cooldown_hours_between_global_edits)},[s.id,s.max_live_experimental_rules,s.max_simultaneous_per_sport,s.cooldown_hours_between_global_edits]);const h=n!==s.max_live_experimental_rules||i!==s.max_simultaneous_per_sport||m!==s.cooldown_hours_between_global_edits,N=_e({mutationFn:async()=>{const{data:y,error:u}=await T.from("klutch_policy_caps").update({max_live_experimental_rules:n,max_simultaneous_per_sport:i,cooldown_hours_between_global_edits:m,updated_at:new Date().toISOString()}).eq("id",s.id).select();if(u)throw u;if(!y||y.length===0)throw new Error("No row updated — your role may not have permission to edit policy caps.");
248return y[0]},onSuccess:()=>{t({title:"Policy caps updated"}),a.invalidateQueries({queryKey:["klutch-policy-caps"]})},onError:y=>{t({title:"Update failed",description:(y==null?void 0:y.message)||"unknown error",variant:"destructive"})}}),d=(y,u)=>{const x=parseInt(y,10);return Number.isNaN(x)?u:Math.max(u,x)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"p-4 border rounded-lg space-y-2",children:[e.jsx(Q,{className:"text-sm text-muted-foreground",children:"Max Live Experimental Rules"}),e.jsx(pe,{type:"number",min:1,value:n,onChange:y=>r(d(y.target.value,1)),className:"text-2xl font-bold h-12"})]}),e.jsxs("div",{className:"p-4 border rounded-lg space-y-2",children:[e.jsx(Q,{className:"text-sm text-muted-foreground",children:"Max Simultaneous Per Sport"}),e.jsx(pe,{type:"number",min:1,value:i,onChange:y=>l(d(y.target.value,1)),className:"text-2xl font-bold h-12"})]}),e.jsxs("div",{className:"p-4 border rounded-lg space-y-2",children:[e.jsx(Q,{className:"text-sm text-muted-foreground",children:"Cooldown Between Global Edits (hours)"}),e.jsx(pe,{type:"number",min:0,value:m,onChange:y=>o(d(y.target.value,0)),className:"text-2xl font-bold h-12"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(R,{variant:"ghost",disabled:!h||N.isPending,onClick:()=>{r(s.max_live_experimental_rules),l(s.max_simultaneous_per_sport),o(s.cooldown_hours_between_global_edits)},children:"Reset"}),e.jsxs(R,{disabled:!h||N.isPending,onClick:()=>N.mutate(),children:[N.isPending?e.jsx(ne,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})}function Op(s){return ge({queryKey:["klutch-shadow-picks",s],queryFn:async()=>{let a=T.from("klutch_engine_shadow_picks").select("*").order("created_at",{ascending:!1}).limit(500);s&&s!=="all"&&(a=a.eq("engine_id",s));const{data:t,error:n}=await a;if(n)throw n;return t||[]},staleTime:6e4})}function Up(){return ge({queryKey:["klutch-shadow-summaries"],queryFn:async()=>{const{data:s,error:a}=await T.from("klutch_engine_shadow_picks").select("engine_id, engine_version, status").limit(5e3);if(a)throw a;const t=new Map;for(const n of s||[]){const r=`${n.engine_id}|${n.engine_version}`;t.has(r)||t.set(r,{engine_id:n.engine_id,engine_version:n.engine_version,total:0,won:0,lost:0,push:0,pending:0,win_rate:0});const i=t.get(r);i.total+=1,n.status==="won"?i.won+=1:n.status==="lost"?i.lost+=1:n.status==="push"?i.push+=1:i.pending+=1}for(const n of t.values()){const r=n.won+n.lost;n.win_rate=r>0?n.won/r*100:0}return Array.from(t.values()).sort((n,r)=>r.total-n.total)},staleTime:6e4})}function Bp(){const[s,a]=v.useState("all"),{data:t,isLoading:n}=Up(),{data:r,isLoading:i}=Op(s);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(fe,{className:"text-lg",children:"Shadow Mode Engines"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Engines running in shadow mode generate picks that are tracked but never published to users. Use this to validate experimental versions before promoting them live."}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2 italic",children:["Note: this tab only covers engine-version shadow mode (toggled per engine on the Engine Rules tab). Signal-level overlays staged on ",e.jsx("span",{className:"font-medium",children:"Engine Learning → Sport Overlays"})," do not appear here — they are weight proposals, not pick generators."]})]}),e.jsx(J,{children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Engine"}),e.jsx(U,{children:"Version"}),e.jsx(U,{className:"text-right",children:"Total"}),e.jsx(U,{className:"text-right",children:"Won"}),e.jsx(U,{className:"text-right",children:"Lost"}),e.jsx(U,{className:"text-right",children:"Pending"}),e.jsx(U,{className:"text-right",children:"Win Rate"})]})}
248),e.jsxs($e,{children:[(t||[]).map(l=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium capitalize",children:l.engine_id}),e.jsx(M,{className:"font-mono text-xs",children:l.engine_version}),e.jsx(M,{className:"text-right",children:l.total}),e.jsx(M,{className:"text-right text-green-400",children:l.won}),e.jsx(M,{className:"text-right text-red-400",children:l.lost}),e.jsx(M,{className:"text-right text-muted-foreground",children:l.pending}),e.jsxs(M,{className:Le("text-right font-mono",l.win_rate>52?"text-green-400":l.win_rate<48?"text-red-400":""),children:[l.win_rate.toFixed(1),"%"]})]},`${l.engine_id}|${l.engine_version}`)),(!t||t.length===0)&&e.jsx(he,{children:e.jsx(M,{colSpan:7,className:"text-center text-muted-foreground py-8",children:"No shadow engines active. Toggle 'Shadow' on the Rules tab to start."})})]})]})})]}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{className:"text-lg",children:"Recent Shadow Picks"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-[140px] h-8 text-xs",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Engines"}),(t||[]).map(l=>e.jsx(V,{value:l.engine_id,className:"capitalize",children:l.engine_id},l.engine_id))]})]})]})}),e.jsx(J,{children:i?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Engine"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Type"}),e.jsx(U,{children:"Selection"}),e.jsx(U,{className:"text-right",children:"Conf"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Created"})]})}),e.jsxs($e,{children:[(r||[]).slice(0,100).map(l=>{var m;return e.jsxs(he,{children:[e.jsx(M,{className:"capitalize text-xs",children:l.engine_id}),e.jsx(M,{className:"capitalize text-xs",children:l.sport}),e.jsx(M,{className:"capitalize text-xs",children:l.pick_type}),e.jsx(M,{className:"text-xs",children:l.selection}),e.jsx(M,{className:"text-right font-mono text-xs",children:(m=l.confidence_score)==null?void 0:m.toFixed(0)}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:"text-[10px]",children:l.status})}),e.jsx(M,{className:"text-xs text-muted-foreground",children:new Date(l.created_at).toLocaleString()})]},l.id)}),(!r||r.length===0)&&e.jsx(he,{children:e.jsx(M,{colSpan:7,className:"text-center text-muted-foreground py-8",children:"No shadow picks yet"})})]})]})})]})]})}function zp(){return e.jsxs(js,{defaultValue:"rules",className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-1 h-auto p-1 justify-start",children:[e.jsxs(Ne,{value:"rules",className:"text-xs gap-1.5",children:[e.jsx(hu,{className:"h-3.5 w-3.5"}),"Engine Rules"]}),e.jsxs(Ne,{value:"overlays",className:"text-xs gap-1.5",children:[e.jsx(hc,{className:"h-3.5 w-3.5"}),"Sport Overlays"]}),e.jsxs(Ne,{value:"shadow",className:"text-xs gap-1.5",children:[e.jsx(Ht,{className:"h-3.5 w-3.5"}),"Engine Shadow"]})]}),e.jsx(we,{value:"rules",className:"mt-4",children:e.jsx(Kp,{})}),e.jsx(we,{value:"overlays",className:"mt-4",children:e.jsx(Vp,{})}),e.jsx(we,{value:"shadow",className:"mt-4",children:e.jsx(Bp,{})})]})}function Kp(){const{data:s,isLoading:a}=ge({queryKey:["engine-governance-rules"],queryFn:async()=>{const{data:t,error:n}=await T.from("klutch_engine_rules").select("id, engine_id, engine_version, status, shadow_mode, allowed_sports, allowed_bet_types, updated_at").order("updated_at",{ascending:!1}).limit(100);if(n)throw n;return t||[]}});return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{className:"text-base",children:"Engine Rules — Recent Changes"}),e.jsxs(De,{children:["Current state of ",e.jsx("code",{children:"klutch_engine_rules"})," ordered by last update. Tracks shadow/active flips and scope edits per engine version."]})]}),e.jsx(J,{children:a?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin mr-2"}),"Loading…"]}):s!=null&&s.length?e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Engine"}),e.jsx(U,{children:"Version"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Mode"}),e.jsx(U,{children:"Sports"}),e.jsx(U,{children:"Bet Types"}),e.jsx(U,{className:"text-right",children:"Updated"})]})}),e.jsx($e,{children:s.map(t=>e.jsxs(he,{children:[e.jsx(M,{className:"text-xs font-medium",children:t.engine_id}),e.jsx(M,{className:"text-xs",children:t.engine_version}),e.jsx(M,{children:e.jsx(B,{variant:t.status==="active"?"default":"secondary",className:"text-[10px]",children:t.status})}),e.jsx(M,{children:e.jsx(B,{variant:t.shadow_mode?"outline":"default",className:"text-[10px]",children:t.shadow_mode?"shadow":"live"})}),e.jsx(M,{className:"text-[11px] text-muted-foreground",children:(t.allowed_sports||[]).join(", ")||"all"}),e.jsx(M,{className:"text-[11px] text-muted-foreground",children:(t.allowed_bet_types||[]).join(", ")||"all"}),e.jsx(M,{className:"text-[11px] text-muted-foreground text-right",children:t.updated_at?new Date(t.updated_at).toLocaleStr
248ing():"—"})]},t.id))})]}):e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No engine rules found."})})]})}function Vp(){const{data:s,isLoading:a}=ge({queryKey:["engine-governance-overlays"],queryFn:async()=>{const{data:t,error:n}=await T.from("klutch_module_sport_overlays").select("*").order("updated_at",{ascending:!1}).limit(100);if(n)throw n;return t||[]}});return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{className:"text-base",children:"Sport Overlays — Recent Changes"}),e.jsxs(De,{children:["Current state of ",e.jsx("code",{children:"klutch_module_sport_overlays"}),", ordered by last update."]})]}),e.jsx(J,{children:a?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin mr-2"}),"Loading…"]}):s!=null&&s.length?e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Module"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Status"}),e.jsx(U,{className:"text-right",children:"Updated"})]})}),e.jsx($e,{children:s.map(t=>e.jsxs(he,{children:[e.jsx(M,{className:"text-xs font-medium",children:t.module_id||t.engine_id||"—"}),e.jsx(M,{className:"text-xs",children:t.sport||"—"}),e.jsx(M,{children:e.jsx(B,{variant:t.status==="active"?"default":"secondary",className:"text-[10px]",children:t.status||(t.enabled?"enabled":"disabled")})}),e.jsx(M,{className:"text-[11px] text-muted-foreground text-right",children:t.updated_at?new Date(t.updated_at).toLocaleString():"—"})]},t.id))})]}):e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No sport overlays found."})})]})}function Hp(){return e.jsxs(js,{defaultValue:"versions",className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-1 h-auto p-1 justify-start",children:[e.jsxs(Ne,{value:"versions",className:"text-xs gap-1.5",children:[e.jsx(xr,{className:"h-3.5 w-3.5"}),"Versions"]}),e.jsxs(Ne,{value:"engines",className:"text-xs gap-1.5",children:[e.jsx(Ha,{className:"h-3.5 w-3.5"}),"Engines"]})]}),e.jsx(we,{value:"versions",className:"mt-4",children:e.jsx(qp,{})}),e.jsx(we,{value:"engines",className:"mt-4",children:e.jsx(zp,{})})]})}function Wp(){const[s,a]=v.useState("version-learning"),{data:t,isLoading:n}=Xh(),r=ep(),i=!!(t!=null&&t.flag_value);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(G,{className:Le("border",i?"border-green-500/40 bg-green-500/5":"border-red-500/40 bg-red-500/5"),children:e.jsxs(J,{className:"py-4 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ls,{className:Le("h-5 w-5 mt-0.5",i?"text-green-500":"text-red-500")}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold",children:"Engine Auto-Promotion"}),e.jsx(B,{variant:i?"default":"destructive",className:"text-[10px]",children:i?"ENABLED":"DISABLED"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 max-w-2xl",children:["Master kill switch for engine version promotion/demotion. While disabled,"," ",e.jsx("code",{className:"text-[10px]",children:"evaluate-engine-promotions"})," exits early and no versions will be promoted, demoted, or auto-suppressed regardless of health metrics."]})]})]}),e.jsx(Ge,{checked:i,disabled:n||r.isPending,onCheckedChange:l=>r.mutate(l)})]})}),e.jsxs(js,{value:s,onValueChange:a,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-1 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"version-learning",className:"text-xs gap-1.5",children:[e.jsx(it,{className:"h-3.5 w-3.5"}),"Version Learning"]}),e.jsxs(Ne,{value:"engine-learning",className:"text-xs gap-1.5",children:[e.jsx(Ha,{className:"h-3.5 w-3.5"}),"Engine Learning"]}),e.jsxs(Ne,{value:"governance",className:"text-xs gap-1.5",children:[e.jsx(au,{className:"h-3.5 w-3.5"}),"Governance"]})]}),e.jsx(we,{value:"version-learning",className:"mt-4",children:e.jsx(bp,{})}),e.jsx(we,{value:"engine-learning",className:"mt-4",children:e.jsx(Ap,{})}),e.jsx(we,{value:"governance",className:"mt-4",children:e.jsx(Hp,{})})]})]})}const Gl={moneyline:"moneyline",totals:"total",spread:"spread",props:"prop"},Fn=["core","plus","lab"];function Gp(s){let a=0,t=0;for(const n of s){if(!n.status||n.status==="pending")continue;const r=n.suggested_units||1,i=Wn(n.status,r,n.original_odds);i!=null&&(a+=r,t+=i)}return a>0?t/a*100:0}function Qp(s,a,t=90){return ge({queryKey:["engine-health-tier-breakdown",s,a,t],queryFn:async()=>{const n=new Date("2026-04-27T17:00:00Z").getTime(),r=Date.now()-t*864e5,i=new Date(Math.max(r,n)).toISOString(),l=1e3,m=2e4,o=[];for(let d=0;d<m;d+=l){let y=T.from("klutch_picks").select("status, tier, original_odds, suggested_units").in("tier",Fn).gte("created_at",i).range(d,d+l-1);if(s!=="all"){const f=Gl[s];f&&(y=y.eq("pick_type",f)),y=y.eq("engine_id",s)}else y=y.in("engine_id",Object.keys(Gl));a!=="all"&&(y=y.eq("sport",a));const{data:u,error:x}=await y;if(x)throw x;const g=u||[];if(o.push(...g),g.length<l)break}const h={core:{tier:"core",total:0,won:0,lost:0,push:0,pending:0,winRate:0,roi:0},plus:{tier:"plus",total:0,won:0,lost:0,push:0,pending:0,winRate:0,roi:0},lab:{tier:"lab",total:0,won:0,lost:0,push:0,pending:0,winRate:0,roi:0}},N={core:[],plus:[],lab:[]};for(const d of o){const y=(d.tier||"").toLowerCase();if(!Fn.includes(y))continue;N[y].push(d);const u=h[y];u.total+=1,d.status==="won"?u.won+=1:d.status==="lost"?u.lost+=1:d.status==="push"?u.push+=1:u.pending+=1}for(const d of Fn){const y=h[d],u=y.won+y.lost;y.winRate=u>0?y.won/u*100:0,y.roi=Gp(N[d])}return h},staleTime:6e4})}const Yp={core:{label:"CORE",accent:"text-primary",border:"border-primary/40"},plus:{label:"PLUS",accent:"text-blue-400",border:"border-blue-500/40"},lab:{label:"LAB",accent:"text-purple-400",border:"border-purple-500/40"}};function Jp({stats:s,loading:a}){const t=Yp[s.tier],n=s.won+s.lost,r=n===0?"text-muted-foreground":s.winRate>52?"text-green-400":s.winRate<48?"text-red-400":"text-foreground",i=s.total===0?"text-muted-foreground":s.roi>0?"text-green-400":s.roi<0?"text-red-400":"text-foreground";return e.jsxs("div",{className:Le("rounded-lg border bg-card/50 p-3 flex flex-col gap-1.5",t.border),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:Le("text-xs font-bold tracking-wider",t.accent),children:t.label}),a?e.jsx(ne,{className:"h-3 w-3 animate-spin text-muted-foreground"}):e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[s.total," picks"]})]}),e.jsxs("div",{className:"font-mono text-sm",children:[e.jsx("span",{className:"text-green-400",children:s.won}),e.jsx("span",{className:"text-muted-foreground",children:"–"}),e.jsx("span",{className:"text-red-400",children:s.lost}),s.push>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"–"}),e.jsx("span",{className:"text-muted-foreground",children:s.push})]}),s.pending>0&&e.jsxs("span",{className:"ml-1 text-[10px] text-muted-foreground",children:["(",s.pending," pend)"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs font-mono",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Win "}),e.jsx("span",{className:r,children:n>0?`${s.winRate.toFixed(1)}%`:"—"})]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"ROI "}),e.jsx("span",{className:i,children:s.total>0?`${s.roi>0?"+":""}${s.roi.toFixed(1)}%`:"—"})]})]})]})}const Zp=new Intl.DateTimeFormat("en-US",{timeZone:"America/Chicago",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});function Ql(s){if(!s)return"never";const a=new Date(s);return isNaN(a.getTime())?"never":`${Zp.format(a)} CT`}function An(s){let a=null;for(const t of s)t&&(!a||t>a)&&(a=t);return a}const Yl={moneyline:"Moneyline",totals:"Totals",spread:"Spread",props:"Props"},Jl=["moneyline","spread","totals","props"],Xp={moneyline:"moneyline",totals:"total",spread:"spread",props:"prop"};
248function eg({windowDays:s=7}={}){const[a,t]=v.useState("all"),[n,r]=v.useState("all"),[i,l]=v.useState(!1),m=Me(),o=s==="all"?90:s,{data:h,isLoading:N}=Kc(a,n,o),{data:d}=Fp(),{data:y,isLoading:u}=Qp(a,n,o),x=(h||[]).filter(w=>Jl.includes(w.engine_id)),g=[...new Set(x.map(w=>w.sport))],f=new Map((d||[]).map(w=>[`${w.sport}|${w.pick_type}`,w])),_=(w,S)=>f.get(`${S.toLowerCase()}|${Xp[w]??w}`),k=An((h||[]).map(w=>w.updated_at)),b=An((d||[]).map(w=>w.last_recomputed_at)),j=An([k,b]),c=j?Date.now()-new Date(j).getTime()>90*6e4:!0,p=async()=>{l(!0);try{const{data:w,error:S}=await T.functions.invoke("trigger-engine-learning");if(S)throw S;if(w!=null&&w.error)throw new Error(w.error);K.success("Engine health recompute queued"),setTimeout(()=>{m.invalidateQueries({queryKey:["klutch-engine-health"]}),m.invalidateQueries({queryKey:["klutch-overlay-calibration"]})},3e3)}catch(w){K.error((w==null?void 0:w.message)||"Failed to trigger recompute")}finally{l(!1)}};return e.jsx(zt,{children:e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{className:"text-lg",children:"Engine Health"}),e.jsxs(Us,{children:[e.jsx(Bs,{children:e.jsx(Ys,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs(zs,{className:"max-w-xs",children:["Measures module + sport-overlay effectiveness. Only picks the module finalized AND that were published to users are counted (joined via ",e.jsx("code",{children:"klutch_module_finalized_picks.promoted_pick_id"}),"). Dropped candidates that never reached the UI are tracked separately as ",e.jsx("strong",{children:"Drop %"}),"."]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(oe,{value:a,onValueChange:t,children:[e.jsx(de,{className:"w-[140px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Module"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Modules"}),Jl.map(w=>e.jsx(V,{value:w,children:Yl[w]},w))]})]}),e.jsxs(oe,{value:n,onValueChange:r,children:[e.jsx(de,{className:"w-[130px] h-8 text-xs",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),g.map(w=>e.jsx(V,{value:w,children:w.charAt(0).toUpperCase()+w.slice(1)},w))]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2 mt-2",children:[e.jsxs("div",{className:Le("text-xs font-mono",c?"text-amber-400":"text-muted-foreground"),children:["Last refresh: ",Ql(k),e.jsx("span",{className:"mx-2 opacity-50",children:"·"}),"Overlay: ",Ql(b)]}),e.jsxs(R,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:p,disabled:i,children:[i?e.jsx(ne,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(He,{className:"h-3 w-3 mr-1"}),"Refresh now"]})]})]}),e.jsxs(J,{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4",children:["core","plus","lab"].map(w=>e.jsx(Jp,{stats:(y==null?void 0:y[w])??{tier:w,total:0,won:0,lost:0,push:0,pending:0,winRate:0,roi:0},loading:u},w))}),N?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Module"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Window"}),e.jsx(U,{className:"text-right",children:"ROI%"}),e.jsx(U,{className:"text-right",children:"Win Rate%"}),e.jsx(U,{className:"text-right",children:e.jsxs(Us,{children:[e.jsxs(Bs,{className:"inline-flex items-center gap-1",children:["Overlay Signal ",e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"})]}),e.jsxs(zs,{className:"max-w-xs",children:["Average confidence shift the overlay ",e.jsx("em",{children:"suggested"})," on shipped picks (adjusted − original). This is observational — actual influence on the published score is governed by Overlay Weight."]})]})}),e.jsx(U,{className:"text-right",children:e.jsxs(Us,{children:[e.jsxs(Bs,{className:"inline-flex items-center gap-1",children:["Overlay Weight ",e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"})]}),e.jsx(zs,{className:"max-w-xs",children:"Learned per (sport, market). 0 = overlay ignored (publish original confidence). 1 = overlay trusted fully. Weight rises only when the overlay's Brier score beats the original's, with a sample haircut: 0 below 30 settled picks, ramps to full at 100. Recomputed by process-klutch-engine-learning."})]})}),e.jsx(U,{className:"text-right",children:e.jsxs(Us,{children:[e.jsxs(Bs,{className:"inline-flex items-center gap-1",children:["Drop % ",e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"})]}),e.jsx(zs,{children:"Share of candidates the overlay killed before users saw them. High Drop % + high Win Rate = overlay is doing its job."})]})}),e.jsx(U,{className:"text-right",children:e.jsxs(Us,{children:[e.jsxs(Bs,{className:"inline-flex items-center gap-1",children:["Avg CLV ",e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"})]}),e.jsx(zs,{children:"CLV integration pending — values currently null until CLV snapshot wiring is complete."})]})}),e.jsx(U,{className:"text-right",children:e.jsxs(Us,{children:[e.jsxs(Bs,{className:"inline-flex items-center gap-1",children:["Max Loss Streak ",e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"})]}
248),e.jsx(zs,{children:"Longest consecutive losing streak in this window (count, not %)."})]})}),e.jsx(U,{className:"text-right",children:"Sample"})]})}),e.jsxs($e,{children:[x.map(w=>{const S=_(w.engine_id,w.sport),P=S?Number(S.overlay_weight):null,C=P!==null?(P*100).toFixed(0):"—";return e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:Yl[w.engine_id]||w.engine_id}),e.jsx(M,{className:"capitalize",children:w.sport}),e.jsxs(M,{children:[w.window_days,"d"]}),e.jsx(M,{className:Le("text-right font-mono",w.roi!==null&&w.roi>0?"text-green-400":w.roi!==null&&w.roi<0?"text-red-400":""),children:w.roi!==null?`${w.roi.toFixed(1)}%`:"—"}),e.jsx(M,{className:Le("text-right font-mono",w.win_rate!==null&&w.win_rate>52?"text-green-400":w.win_rate!==null&&w.win_rate<48?"text-red-400":""),children:w.win_rate!==null?`${w.win_rate.toFixed(1)}%`:"—"}),e.jsx(M,{className:Le("text-right font-mono",w.avg_confidence_lift!==null&&w.avg_confidence_lift>0?"text-green-400":w.avg_confidence_lift!==null&&w.avg_confidence_lift<0?"text-red-400":"text-muted-foreground"),children:w.avg_confidence_lift!==null?`${w.avg_confidence_lift>0?"+":""}${w.avg_confidence_lift.toFixed(1)}`:"—"}),e.jsxs(M,{className:Le("text-right font-mono",P===null?"text-muted-foreground":P>=.5?"text-green-400":P>0?"text-amber-400":"text-muted-foreground"),children:[P!==null?`${C}%`:"—",S&&e.jsxs("span",{className:"ml-1 text-[10px]",children:["(n=",S.sample_n,")"]})]}),e.jsxs(M,{className:"text-right font-mono text-muted-foreground",children:[w.drop_rate!==null?`${w.drop_rate.toFixed(1)}%`:"—",w.dropped_count>0&&e.jsxs("span",{className:"ml-1 text-[10px]",children:["(",w.dropped_count,"/",w.dropped_count+w.promoted_count,")"]})]}),e.jsx(M,{className:"text-right font-mono text-muted-foreground",children:w.avg_clv!==null?w.avg_clv.toFixed(2):"—"}),e.jsx(M,{className:Le("text-right font-mono",w.drawdown!==null&&w.drawdown>5?"text-red-400":""),children:w.drawdown!==null?w.drawdown.toFixed(0):"—"}),e.jsx(M,{className:"text-right",children:w.sample_size})]},w.id)}),x.length===0&&e.jsx(he,{children:e.jsx(M,{colSpan:11,className:"text-center text-muted-foreground py-8",children:"No published picks have passed through this module/overlay yet for the selected window. Health rows appear once a module ships ≥3 (7d) or ≥5 (30d/90d) settled picks to users."})})]})]})]})]})})}function sg(){var m,o;const[s,a]=v.useState(!1),[t,n]=v.useState(!0),[r,i]=v.useState(null),l=async()=>{a(!0),i(null);try{const{data:h,error:N}=await T.functions.invoke("settle-klutch-picks",{body:{dryRun:t}});if(N)throw N;i(h),t?K.info(`Dry run complete: ${h.picksSettled} picks would be settled`):K.success(`Settled ${h.picksSettled} KLUTCH picks`)}catch(h){console.error("Settlement error:",h),K.error(h.message||"Failed to settle KLUTCH picks"),i({picksSettled:0,picksSkipped:0,errors:[h.message||"Unknown error"]})}finally{a(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-5 w-5 text-primary"}),"Settle KLUTCH Picks"]}),e.jsx(De,{children:"Manually settle pending KLUTCH picks and their linked user bets & tracked recommendations"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ge,{id:"dry-run",checked:t,onCheckedChange:n}),e.jsx(Q,{htmlFor:"dry-run",className:"text-sm",children:"Dry Run (preview only, no changes)"})]}),e.jsx(R,{onClick:l,disabled:s,variant:t?"outline":"default",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),t?"Previewing...":"Settling..."]}):t?"Preview Settlement":"Run Settlement"})]}),r&&e.jsxs("div",{className:"mt-4 p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r.errors.length===0?e.jsx(rs,{className:"h-5 w-5 text-green-500"}):e.jsx(xs,{className:"h-5 w-5 text-yellow-500"}),e.jsx("span",{className:"font-medium",children:t?"Preview Results":"Settlement Results"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Picks Settled:"}),e.jsx("span",{className:"font-medium text-green-600",children:r.picksSettled})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Picks Skipped:"}),e.jsx("span",{className:"font-medium",children:r.picksSkipped})]}),((m=r.details)==null?void 0:m.props)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Props Settled:"}),e.jsx("span",{className:"font-medium",children:r.details.props.settled})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Props Skipped:"}),e.jsx("span",{className:"font-medium",children:r.details.props.skipped})]})]}),((o=r.details)==null?void 0:o.gamelines)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Gamelines Settled:"}),e.jsx("span",{className:"font-medium",children:r.details.gamelines.settled})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Gamelines Skipped:"}),e.jsx("span",{className:"font-medium",children:r.details.gamelines.skipped})]})]})]}),r.errors.length>0&&e.jsxs("div",{className:"mt-3 p-3 rounded bg-destructive/10 border border-destructive/20",children:[e.jsxs("div",{className:"flex items-center gap-2 text-destructive mb-2",children:[e.jsx(Is,{className:"h-4 w-4"}),e.jsxs("span",{className:"font-medium text-sm",children:["Errors (",r.errors.length,")"]})]}),e.jsxs("ul",{className:"text-xs text-destructive/80 space-y-1",children:[r.errors.slice(0,5).map((h,N)=>e.jsxs("li",{children:["• ",h]},N)),r.errors.length>5&&e.jsxs("li",{className:"text-muted-foreground",children:["...and ",r.errors.length-5," more errors"]})]})]})]})]})]})}function tg(){const[s,a]=v.useState(!1),[t,n]=v.useState(!0),[r,i]=v.useState(3),[l,m]=v.useState(null),o=async()=>{a(!0),m(null);try{const{data:h,error:N}=await T.functions.invoke("cleanup-klutch-unsettleable",{body:{dryRun:t,daysOld:r}});if(N)throw N;m(h),h.success?K.success(h.message||"Cleanup completed"):K.error("Cleanup completed with errors")}catch(h){console.error("Cleanup error:",h),K.error("Failed to run cleanup")}finally{a(!1)}};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(os,{className:"h-5 w-5 text-orange-400"}),"Cleanup Unsettleable Picks"]}
248),e.jsx(De,{children:"Auto-void past picks with no settlement data, flag those with user interactions for manual review"})]})})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{id:"dryRun",checked:t,onCheckedChange:n}),e.jsx(Q,{htmlFor:"dryRun",className:"text-sm",children:"Dry Run (preview only)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Q,{htmlFor:"daysOld",className:"text-sm whitespace-nowrap",children:"Days old:"}),e.jsx(pe,{id:"daysOld",type:"number",min:1,max:30,value:r,onChange:h=>i(parseInt(h.target.value)||3),className:"w-20"})]}),e.jsx(R,{onClick:o,disabled:s,variant:t?"outline":"destructive",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Processing..."]}):t?"Preview Cleanup":"Run Cleanup"})]}),l&&e.jsxs("div",{className:"space-y-4 mt-4 p-4 rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.success?e.jsx(rs,{className:"h-5 w-5 text-green-400"}):e.jsx(ls,{className:"h-5 w-5 text-yellow-400"}),e.jsx("span",{className:"font-medium",children:l.message})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center p-3 rounded-lg bg-background",children:[e.jsx("div",{className:"text-2xl font-bold",children:l.totalChecked}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Checked"})]}),e.jsxs("div",{className:"text-center p-3 rounded-lg bg-background",children:[e.jsx("div",{className:"text-2xl font-bold text-red-400",children:l.autoVoided}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Auto-Voided"})]}),e.jsxs("div",{className:"text-center p-3 rounded-lg bg-background",children:[e.jsx("div",{className:"text-2xl font-bold text-yellow-400",children:l.flaggedForReview}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Flagged"})]}),e.jsxs("div",{className:"text-center p-3 rounded-lg bg-background",children:[e.jsx("div",{className:"text-2xl font-bold text-orange-400",children:l.errors.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Errors"})]})]}),l.details&&l.details.length>0&&e.jsxs("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:[e.jsx("div",{className:"text-sm font-medium",children:"Details (first 20):"}),l.details.slice(0,20).map(h=>e.jsxs("div",{className:"flex items-center gap-2 text-xs p-2 rounded bg-background",children:[h.action==="voided"?e.jsx(B,{variant:"destructive",className:"text-[10px]",children:"VOID"}):e.jsxs(B,{variant:"outline",className:"text-[10px] border-yellow-400 text-yellow-400",children:[e.jsx(Zi,{className:"h-3 w-3 mr-1"}),"REVIEW"]}),e.jsx("span",{className:"flex-1 truncate",children:h.pick}),h.userInteractions&&e.jsxs("span",{className:"text-muted-foreground",children:[h.userInteractions.trackedCount>0&&`${h.userInteractions.trackedCount} tracked`,h.userInteractions.trackedCount>0&&h.userInteractions.betCount>0&&", ",h.userInteractions.betCount>0&&`${h.userInteractions.betCount} bet(s)`]})]},h.id))]}),l.errors.length>0&&e.jsx("div",{className:"text-xs text-red-400 space-y-1",children:l.errors.map((h,N)=>e.jsxs("div",{children:["• ",h]},N))})]})]})]})}function ag(){const s=Me(),[a,t]=v.useState(null),[n,r]=v.useState(null),[i,l]=v.useState(null),{data:m,isLoading:o,refetch:h}=ge({queryKey:["klutch-picks-manual-review"],queryFn:async()=>{const{data:g,error:f}=await T.from("klutch_picks").select("id, pick, pick_type, sport, game_date, player_name, review_reason, confidence_score, original_line, pick_details").eq("needs_manual_review",!0).eq("status","pending").order("game_date",{ascending:!1}).limit(100);if(f)throw f;return g}}),N=async g=>{const[f,_]=await Promise.all([T.from("user_bets").select("id",{count:"exact"}).eq("source","klutch").contains("recommendation_context",{klutch_pick_id:g}),T.from("saved_betting_recommendations").select("id",{count:"exact"}).eq("tracking_status","tracked").contains("game_details",{klutch_pick_id:g})]);return{betCount:f.count||0,trackedCount:_.count||0}},d=_e({mutationFn:async({pickId:g,action:f})=>{const{data:_,error:k}=await T.functions.invoke("manual-settle-klutch-pick",{body:{pickId:g,action:f}});if(k)throw k;if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Settlement failed");return{pickId:g,action:f}},onSuccess:({action:g})=>{K.success(`Pick settled as ${g}`),s.invalidateQueries({queryKey:["klutch-picks-manual-review"]}),t(null),r(null),l(null)},onError:g=>{console.error("Settlement error:",g),K.error("Failed to settle pick")}}),y=async(g,f)=>{t(g),r(f);const _=await N(g.id);l(_)},u=()=>{a&&n&&d.mutate({pickId:a.id,action:n})},x=g=>e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(R,{size:"sm",variant:"outline",className:"h-7 px-2 text-green-400 border-green-400/50 hover:bg-green-400/10",onClick:()=>y(g,"won"),children:[e.jsx(Js,{className:"h-3 w-3 mr-1"}),"Won"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"h-7 px-2 text-red-400 border-red-400/50 hover:bg-red-400/10",onClick:()=>y(g,"lost"),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"Lost"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"h-7 px-2 text-yellow-400 border-yellow-400/50 hover:bg-yellow-400/10",onClick:()=>y(g,"push"),children:[e.jsx(Da,{className:"h-3 w-3 mr-1"}),"Push"]}),e.jsxs(R,{size:"sm",variant:"outline",className:"h-7 px-2 text-muted-foreground",onClick:()=>y(g,"cancelled"),children:[e.jsx(Fa,{className:"h-3 w-3 mr-1"}),"Void"]})]});return e.jsxs(e.Fragment,{children:[e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Zi,{className:"h-5 w-5 text-yellow-400"}),"Manual Settlement Queue",m&&m.length>0&&e.jsx(B,{variant:"secondary",children:m.length})]}),e.jsx(De,{children:"Review and settle KLUTCH picks that have user interactions but couldn't be auto-settled"})]}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>h(),children:e.jsx(He,{className:"h-4 w-4"})})]})}),e.jsx(J,{children:o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):!m||m.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No picks requiring manual review"}):e.jsx("div",{className:"space-y-3 max-h-[500px] overflow-y-auto",children:m.map(g=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",className:"text-[10px]",children:g.sport.toUpperCase()}),e.jsx(B,{variant:"secondary",className:"text-[10px]",children:g.pick_type}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ke(new Date(g.game_date),"MMM d, yyyy")})]}),e.jsx("div",{className:"font-medium text-sm",children:g.pick}),g.review_reason&&e.jsxs("div",{className:"text-xs text-yellow-400",children:["⚠️ ",g.review_reason]})]}),x(g)]},g.id))})})]}
248),e.jsx(ws,{open:!!a&&!!n,onOpenChange:()=>{t(null),r(null),l(null)},children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsxs(Cs,{children:["Confirm Settlement: ",n==null?void 0:n.toUpperCase()]}),e.jsxs(Ps,{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Pick:"})," ",a==null?void 0:a.pick]}),i&&e.jsxs("div",{className:"p-3 rounded-lg bg-muted",children:[e.jsx("div",{className:"text-sm font-medium mb-2",children:"Users Affected:"}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-lg font-bold",children:i.trackedCount}),e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"tracked"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-lg font-bold",children:i.betCount}),e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"bet(s) placed"})]})]})]}),e.jsx("div",{className:"text-sm",children:"This will update the KLUTCH pick status and settle all linked user bets and tracked recommendations."})]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsxs(Ls,{onClick:u,disabled:d.isPending,className:n==="won"?"bg-green-600 hover:bg-green-700":n==="lost"?"bg-red-600 hover:bg-red-700":n==="push"?"bg-yellow-600 hover:bg-yellow-700":"",children:[d.isPending?e.jsx(ne,{className:"h-4 w-4 animate-spin mr-2"}):null,"Confirm ",n]})]})]})})]})}const Lr={generation_version:"v2.5",sports:["baseball"],pick_types:["moneyline"],min_confidence:90},Zl=[{version:"v2.5",sport:"baseball",pick_type:"moneyline",n:16,w:12,l:4,p:0,win_rate:75,net_units:10.38,eligible:!0},{version:"v1",sport:"baseball",pick_type:"total",n:22,w:9,l:11,p:2,win_rate:45,net_units:-4.22,eligible:!1},{version:"v1",sport:"basketball",pick_type:"total",n:134,w:57,l:74,p:3,win_rate:43.5,net_units:-44.76,eligible:!1}];function rg(s,a){const t=(s||"").toUpperCase().trim();if(t.startsWith("OVER")||t.startsWith("UNDER"))return"total";const n=(s||"").match(/([+-]\d+\.?\d*)/);return n?Math.abs(parseFloat(n[1]))>=100?"moneyline":"spread":/\bML\b/.test(t)?"moneyline":(a||"").toLowerCase()}const ng={"1x1":"1:1 — Instagram / LinkedIn / Threads","9x16":"9:16 — TikTok / Stories / Snapchat","16x9":"16:9 — Facebook / X / YouTube"};function lg({todayStr:s}){const[a,t]=v.useState(!1),[n,r]=v.useState(null),[i,l]=v.useState(null),[m,o]=v.useState(null),[h,N]=v.useState(null),[d,y]=v.useState(null),{data:u,isLoading:x}=ge({queryKey:["social-potd-recommendation",s],queryFn:async()=>{const{data:c}=await T.from("klutch_picks").select("id, pick, sport, pick_type, confidence_score, home_team, away_team, current_odds, original_odds, generation_version, status, tier, player_name").eq("game_date",s).eq("generation_version",Lr.generation_version).in("sport",Lr.sports).gte("confidence_score",Lr.min_confidence).is("player_name",null).order("confidence_score",{ascending:!1}).limit(20),p=(c||[]).find(S=>{if(["cancelled","invalidated","stale"].includes((S.status||"").toLowerCase())||["rejected","shadow","suppressed"].includes((S.tier||"").toLowerCase()))return!1;const P=rg(S.pick,S.pick_type);return Lr.pick_types.includes(P)}),{data:w}=await T.from("social_auto_post_log").select("status, late_post_id, created_at").eq("content_type","klutch_potd").eq("post_date",s).maybeSingle();return{pick:p||null,log:w||null}},staleTime:30*1e3}),g=Zl.find(c=>c.eligible),f=c=>({id:c.id,away_team:c.away_team,home_team:c.home_team,pick:c.pick,confidence_score:c.confidence_score,pick_type:c.pick_type,current_odds:c.current_odds,original_odds:c.original_odds,generation_version:c.generation_version,trigger_type:"KLUTCH POTD"}),_=async(c,p)=>{const{data:w,error:S}=await T.functions.invoke("render-potd-image",{body:{pick:f(c),ratios:["1x1","9x16","16x9"],useStadiumBg:p,sport:c.sport,postDate:s}});if(S)throw S;return w.urls},k=async c=>{y(c),t(!0),l(null),o(null),N(null),r("flat");try{l(await _(c,!1))}catch(p){K.error(`Flat preview failed: ${(p==null?void 0:p.message)||p}`)}finally{r(null)}},b=async()=>{if(!(!d||m||n)){r("stadium");try{o(await _(d,!0))}catch(c){K.error(`Stadium preview failed: ${(c==null?void 0:c.message)||c}`)}finally{r(null)}}},j=async()=>
248{if(!(!d||h||n)){r("video");try{const{data:c,error:p}=await T.functions.invoke("render-potd-video",{body:{pick:f(d),useStadiumBg:!1,sport:d.sport,postDate:s}});if(p)throw p;N(c.url)}catch(c){K.error(`Video preview failed: ${(c==null?void 0:c.message)||c}`)}finally{r(null)}}};return e.jsxs(e.Fragment,{children:[e.jsx(G,{className:"border-primary/30 bg-primary/5",children:e.jsxs(J,{className:"p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(_r,{className:"h-4 w-4 text-primary"}),"Social POTD Recommendation"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Auto-posts the highest-confidence pick matching the only profitable POTD slot."})]}),e.jsxs(B,{variant:"outline",className:"text-xs",children:[g.version," · ",g.sport," · ",g.pick_type," · ",g.win_rate,"% (n=",g.n,")"]})]}),x?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ne,{className:"h-3.5 w-3.5 animate-spin"})," Checking today's eligible pick…"]}):u!=null&&u.pick?e.jsxs("div",{className:"rounded bg-background/60 p-2 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium flex-1 truncate",children:[u.pick.away_team," @ ",u.pick.home_team," — ",u.pick.pick]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u.pick.confidence_score,"%"]})]}),e.jsxs("div",{className:"flex items-center justify-between text-[11px] text-muted-foreground gap-2 flex-wrap",children:[e.jsx("span",{children:"Eligible to auto-post when toggle is on."}),e.jsxs("div",{className:"flex items-center gap-2",children:[u.log&&e.jsxs("span",{children:["Today: ",e.jsx("strong",{className:"text-foreground",children:u.log.status})]}),e.jsxs(R,{size:"sm",variant:"outline",className:"h-6 text-[10px] px-2",onClick:()=>k(u.pick),children:[e.jsx(Ot,{className:"h-3 w-3 mr-1"}),"Preview images"]})]})]})]}):e.jsxs("div",{className:"flex items-start gap-2 text-xs text-muted-foreground rounded bg-background/60 p-2",children:[e.jsx(xs,{className:"h-3.5 w-3.5 mt-0.5"}),e.jsxs("div",{children:["No qualifying pick today — auto-post will be skipped.",(u==null?void 0:u.log)&&e.jsxs(e.Fragment,{children:[" Last run logged as ",e.jsx("strong",{children:u.log.status}),"."]})]})]}),e.jsxs("div",{className:"border-t pt-2",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground mb-1",children:"Audit basis (settled POTD picks, n≥10):"}),e.jsx("div",{className:"space-y-0.5",children:Zl.map(c=>e.jsxs("div",{className:`flex items-center gap-2 text-[11px] ${c.eligible?"text-foreground":"text-muted-foreground line-through"}`,children:[e.jsx("span",{className:"font-mono",children:c.version}),e.jsx("span",{className:"capitalize",children:c.sport}),e.jsx("span",{className:"capitalize",children:c.pick_type}),e.jsxs("span",{className:"ml-auto",children:[c.w,"-",c.l,"-",c.p]}),e.jsxs("span",{className:"w-12 text-right",children:[c.win_rate,"%"]}),e.jsxs("span",{className:`w-16 text-right ${c.net_units>=0?"text-primary":""}`,children:[c.net_units>=0?"+":"",c.net_units,"u"]})]},`${c.version}-${c.sport}-${c.pick_type}`))})]})]})}),e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-3xl",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Social POTD — Preview"})}),e.jsxs(js,{defaultValue:"flat",onValueChange:c=>{c==="stadium"&&b(),c==="video"&&j()},children:[e.jsxs(fs,{children:[e.jsx(Ne,{value:"flat",children:"Flat"}),e.jsx(Ne,{value:"stadium",children:"Stadium (AI bg)"}),e.jsx(Ne,{value:"video",children:"Animated 9:16"})]}),e.jsx(we,{value:"flat",children:e.jsx(Xl,{urls:i,loading:n==="flat"})}),e.jsx(we,{value:"stadium",children:e.jsx(Xl,{urls:m,loading:n==="stadium",loadingLabel:"Generating stadium scenes via Nano Banana…"})}),e.jsx(we,{value:"video",children:n==="video"?e.jsxs("div",{className:"flex items-center gap-2 py-12 justify-center text-sm text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"})," Rendering 6s MP4 (this can take 30-60s)…"]}
248):h?e.jsx("video",{src:h,controls:!0,autoPlay:!0,loop:!0,muted:!0,className:"w-full max-w-sm mx-auto rounded border border-border bg-black"}):e.jsx("div",{className:"text-xs text-muted-foreground py-8 text-center",children:"Click the Animated tab to render."})})]})]})})]})}function Xl({urls:s,loading:a,loadingLabel:t="Rendering branded images…"}){return a?e.jsxs("div",{className:"flex items-center gap-2 py-12 justify-center text-sm text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"})," ",t]}):s?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:["1x1","9x16","16x9"].map(n=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:ng[n]}),s[n]?e.jsx("a",{href:s[n],target:"_blank",rel:"noreferrer",children:e.jsx("img",{src:s[n],alt:`POTD ${n}`,className:"w-full rounded border border-border bg-black object-contain"})}):e.jsx("div",{className:"text-xs text-muted-foreground",children:"Not rendered"})]},n))}):e.jsx("div",{className:"text-xs text-muted-foreground py-8 text-center",children:"No preview yet."})}function Tn({status:s}){const a=(s||"").toLowerCase();return a==="won"?e.jsx(B,{variant:"default",className:"text-xs",children:"W"}):a==="lost"?e.jsx(B,{variant:"destructive",className:"text-xs",children:"L"}):a==="push"?e.jsx(B,{variant:"secondary",className:"text-xs",children:"P"}):a==="cancelled"||a==="canceled"||a==="void"||a==="postponed"?e.jsx(B,{variant:"secondary",className:"text-xs capitalize",children:a==="canceled"?"cancelled":a}):a==="stale"?e.jsx(B,{variant:"secondary",className:"text-xs",children:"Stale"}):e.jsxs(B,{variant:"outline",className:"text-xs",children:[e.jsx($s,{className:"h-3 w-3 mr-1"})," Pending"]})}function ig(s){const a=s.filter(i=>i.status==="won"||i.status==="lost");if(!a.length)return{type:"W",count:0};const t=[...a].sort((i,l)=>l.game_date.localeCompare(i.game_date)),n=t[0].status==="won"?"W":"L";let r=0;for(const i of t)if((i.status==="won"?"W":"L")===n)r++;else break;return{type:n,count:r}}function gt(){return{wins:0,losses:0,pushes:0,total:0,winRate:0}}function ba(s,a){s.total++,a==="won"?s.wins++:a==="lost"?s.losses++:s.pushes++}function wa(s){const a=s.wins+s.losses;s.winRate=a>0?s.wins/a*100:0}function cg(){var ie;const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState(!1),[l,m]=v.useState(!1),[o,h]=v.useState(!1),[N,d]=v.useState(!1),[y,u]=v.useState(!1),{toast:x}=Ws(),[g,f]=v.useState(null),{data:_,isLoading:k,refetch:b}=ge({queryKey:["klutch-potd-picks"],queryFn:async()=>{const{data:Y,error:I}=await T.from("klutch_picks").select("id, game_date, pick, sport, pick_type, confidence_score, actual_result, status, home_team, away_team, generation_version, potd_rank, reasoning, trigger_type, trigger_data, edge_pct, original_line, original_odds, current_line, current_odds, picked_side, pick_direction, suggested_units, game_time, player_name, market_name, matchup, league").not("potd_rank","is",null).order("game_date",{ascending:!1}).order("potd_rank",{ascending:!0});if(I)throw I;return Y||[]},staleTime:60*1e3}),j=async()=>{try{const{data:Y,error:I}=await T.functions.invoke("lock-potd-picks");if(I)throw I;x({title:"POTD Lock",description:`Status: ${Y==null?void 0:Y.status} for ${Y==null?void 0:Y.date}`}),b()}catch(Y){x({title:"Error",description:Y.message,variant:"destructive"})}},c=v.useMemo(()=>{const Y=new Date;return new Date(Y.toLocaleString("en-US",{timeZone:"America/Chicago"})).toISOString().split("T")[0]},[]),{todayPicks:p,historicalPicks:w,rankStats:S,combinedStats:P,streak:C,sportBreakdown:O,versionBreakdown:$,betTypeBreakdown:z,versionSportMatrix:D,dailySummaries:A,dailyAggregate:F}=v.useMemo(()=>{const Y={todayPicks:[],historicalPicks:[],rankStats:{1:gt(),2:gt(),3:gt()},combinedStats:gt(),streak:{type:"W",count:0},sportBreakdown:{},versionBreakdown:{},betTypeBreakdown:{},versionSportMatrix:{},dailySummaries:[],dailyAggregate:{daysTracked:0,perfectDays:0,winningDays:0,losingDays:0,splitDays:0,totalWins:0,totalSettledPicks:0,avgWinsPerDay:0}};if(!(_!=null&&_.length))return Y;const I=_.filter(be=>be.game_date===c),ee=be=>(s==="all"||be.sport===s)&&(t==="all"||be.generation_version===t),le=_.filter(be=>["won","lost","push"].includes(be.status)&&ee(be)),ve={1:gt(),2:gt(),3:gt()},te=gt();for(const be of le){const Qe=ve[be.potd_rank];Qe&&(ba(Qe,be.status),ba(te,be.status))}for(const be of[1,2,3])wa(ve[be]);wa(te);const X=_.filter(be=>be.potd_rank===1),ae=ig(X),W=_.filter(be=>["won","lost","push"].includes(be.status)),re={};for(const be of W){re[be.sport]||(re[be.sport]={1:gt(),2:gt(),3:gt()});const Qe=re[be.sport][be.potd_rank];Qe&&ba(Qe,be.status)}
248for(const be of Object.keys(re))for(const Qe of[1,2,3])wa(re[be][Qe]);const ce={};for(const be of W)ce[be.generation_version]||(ce[be.generation_version]=gt()),ba(ce[be.generation_version],be.status);for(const be of Object.keys(ce))wa(ce[be]);const Pe={};for(const be of W){const Qe=be.pick_type||"unknown";Pe[Qe]||(Pe[Qe]=gt()),ba(Pe[Qe],be.status)}for(const be of Object.keys(Pe))wa(Pe[be]);const Fe={};for(const be of W)Fe[be.generation_version]||(Fe[be.generation_version]={}),Fe[be.generation_version][be.sport]||(Fe[be.generation_version][be.sport]=gt()),ba(Fe[be.generation_version][be.sport],be.status);for(const be of Object.keys(Fe))for(const Qe of Object.keys(Fe[be]))wa(Fe[be][Qe]);const Ae=_.filter(be=>ee(be)).sort((be,Qe)=>Qe.game_date.localeCompare(be.game_date)||be.potd_rank-Qe.potd_rank).slice(0,30),Ve=_.filter(ee),as=new Map;for(const be of Ve)as.has(be.game_date)||as.set(be.game_date,[]),as.get(be.game_date).push(be);const Oe=[];for(const[be,Qe]of as.entries()){const et=[void 0,void 0,void 0];for(const Os of Qe)Os.potd_rank>=1&&Os.potd_rank<=3&&(et[Os.potd_rank-1]=Os);let Gs=0,xe=0,Ce=0,Se=0;for(const Os of et){if(!Os){Se++;continue}Os.status==="won"?Gs++:Os.status==="lost"?xe++:Os.status==="push"?Ce++:Se++}const ye=Gs+xe+Ce,We=et.filter(Boolean).length,ps=We>0&&Se===0;let bs="pending";ps&&(Gs===We&&We===3?bs="perfect":Gs>=2?bs="winning":Gs===1?bs="split":bs="losing"),Oe.push({date:be,picks:et,wins:Gs,losses:xe,pushes:Ce,pending:Se,totalSettled:ye,totalPicks:We,fullySettled:ps,grade:bs})}Oe.sort((be,Qe)=>Qe.date.localeCompare(be.date));const Ie=Oe.filter(be=>be.fullySettled),ds={daysTracked:Ie.length,perfectDays:Ie.filter(be=>be.grade==="perfect").length,winningDays:Ie.filter(be=>be.grade==="winning"||be.grade==="perfect").length,losingDays:Ie.filter(be=>be.grade==="losing").length,splitDays:Ie.filter(be=>be.grade==="split").length,totalWins:Ie.reduce((be,Qe)=>be+Qe.wins,0),totalSettledPicks:Ie.reduce((be,Qe)=>be+Qe.totalPicks,0),avgWinsPerDay:Ie.length>0?Ie.reduce((be,Qe)=>be+Qe.wins,0)/Ie.length:0};return{todayPicks:I,historicalPicks:Ae,rankStats:ve,combinedStats:te,streak:ae,sportBreakdown:re,versionBreakdown:ce,betTypeBreakdown:Pe,versionSportMatrix:Fe,dailySummaries:Oe,dailyAggregate:ds}},[_,c,s,t]),q=v.useMemo(()=>_!=null&&_.length?[...new Set(_.map(Y=>Y.sport))].sort():[],[_]),E=v.useMemo(()=>_!=null&&_.length?[...new Set(_.map(Y=>Y.generation_version))].sort():[],[_]),L=[Js,Mt,As],H=["#1 Pick","#2 Pick","#3 Pick"],Z=["text-yellow-500","text-muted-foreground","text-orange-400"],se=v.useMemo(()=>{const Y=new Set;for(const I of Object.keys(D))for(const ee of Object.keys(D[I]))Y.add(ee);return[...Y].sort()},[D]);return e.jsxs(G,{children:[e.jsxs(je,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Js,{className:"h-5 w-5 text-yellow-500"}),e.jsx(fe,{className:"text-lg",children:"Pick of the Day Tracker"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-28",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Versions"}),E.map(Y=>e.jsx(V,{value:Y,children:Y},Y))]})]}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-28",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),q.map(Y=>e.jsx(V,{value:Y,children:Y.toUpperCase()},Y))]})]}),e.jsx(R,{size:"sm",variant:"outline",onClick:j,children:"Lock Today"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-game locked top 3 picks by confidence — tracks win rates to evaluate social media viability"})]}),e.jsx(J,{className:"space-y-4",children:k?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading picks data..."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-lg border p-3 space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx($s,{className:"h-4 w-4 text-primary"}),"Today's Picks (",c,")"]}),p.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:'No picks locked for today yet. Click "Lock Today" to trigger.'}):e.jsx("div",{className:"space-y-1.5",children:p.sort((Y,I)=>Y.potd_rank-I.potd_rank).map(Y=>{const I=L[Y.potd_rank-1]||As;return e.jsxs("div",{className:"flex items-center gap-2 text-sm p-2 rounded bg-muted/30 cursor-pointer hover:bg-muted/60 transition-colors",onClick:()=>f(Y),children:[e.jsx(I,{className:`h-4 w-4 ${Z[Y.potd_rank-1]}`}),e.jsxs(B,{variant:"outline",className:"text-xs",children:["#",Y.potd_rank]}),e.jsx("span",{className:"font-medium truncate flex-1",children:Y.pick}),e.jsx("span",{className:"text-xs text-muted-foreground uppercase",children:Y.sport}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Y.confidence_score,"%"]}),e.jsx(Tn,{status:Y.status})]},Y.id)})})]}),e.jsx(lg,{todayStr:c}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:[1,2,3].map(Y=>{const I=S[Y],ee=L[Y-1];return e.jsx(G,{className:"border",children:e.jsxs(J,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ee,{className:`h-4 w-4 ${Z[Y-1]}`}),e.jsx("span",{className:"text-sm font-semibold",children:H[Y-1]})]}),e.jsxs("div",{className:"text-2xl font-bold",children:[I.winRate.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[I.wins,"W - ",I.losses,"L - ",I.pushes,"P (",I.total," picks)"]})]})},Y)})}),e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Combined Top 3:"}),e.jsxs("span",{className:"text-sm font-bold",children:[P.winRate.toFixed(1),"%"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",P.wins,"W-",P.losses,"L-",P.pushes,"P, n=",P.total,")"]})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[e.jsx(Oa,{className:`h-4 w-4 ${C.type==="W"?"text-green-500":"text-destructive"}`}),e.jsxs("span",{className:"text-sm font-medium",children:["#1 Streak: ",C.count,C.type]})]})]}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-semibold",children:"Daily Performance (All 3 Picks)"}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[F.daysTracked," fully-settled day",F.daysTracked===1?"":"s"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded border p-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Avg Wins / Day"}),e.jsxs("div",{className:"text-lg font-bold",children:[F.avgWinsPerDay.toFixed(2)," ",e.jsx("span",{className:"text-xs text-muted-foreground font-normal",children:"/ 3"})]})]}),e.jsxs("div",{className:"rounded border p-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Perfect Days (3-0)"}),e.jsxs("div",{className:"text-lg font-bold text-green-500",children:[F.perfectDays,e.jsxs("span",{className:"text-xs text-muted-foreground font-normal ml-1",children:["(",F.daysTracked>0?(F.perfectDays/F.daysTracked*100).toFixed(0):0,"%)"]})]})]}),e.jsxs("div",{className:"rounded border p-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Winning Days (2W+)"}),e.jsxs("div",{className:"text-lg font-bold",children:[F.winningDays,e.jsxs("span",{className:"text-xs text-muted-foreground font-normal ml-1",children:["(",F.daysTracked>0?(F.winningDays/F.daysTracked*100).toFixed(0):0,"%)"]})]})]}),e.jsxs("div",{className:"rounded border p-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Losing Days (0W)"}),e.jsxs("div",{className:"text-lg font-bold text-destructive",children:[F.losingDays,e.jsxs("span",{className:"text-xs text-muted-foreground font-normal ml-1",children:["(",F.daysTracked>0?(F.losingDays/F.daysTracked*100).toFixed(0):0,"%)"]})]})]})]}),e.jsxs(vs,{open:y,onOpenChange:u,children:[e.jsxs(ys,{className:"flex items-center gap-2 text-xs font-medium w-full p-1.5 rounded hover:bg-muted/50",children:[e.jsx(Ns,{className:`h-3.5 w-3.5 transition-transform ${y?"rotate-180":""}`}),"Day-by-day breakdown (",A.length," days)"]}),e.jsx(_s,{className:"pt-2",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"text-xs",children:"Date"}),e.jsx(U,{className:"text-xs",children:"#1"}),e.jsx(U,{className:"text-xs",children:"#2"}),e.jsx(U,{className:"text-xs",children:"#3"}),e.jsx(U,{className:"text-xs",children:"Record"}),e.jsx(U,{className:"text-xs",children:"Grade"})]})}),e.jsx($e,{children:A.slice(0,30).map(Y=>{const I=Y.grade==="perfect"?e.jsx(B,{className:"text-xs bg-green-600 hover:bg-green-600",children:"Perfect"}):Y.grade==="winning"?e.jsx(B,{className:"text-xs bg-green-500/80 hover:bg-green-500/80",children:"Winning"}):Y.grade==="split"?e.jsx(B,{variant:"secondary",className:"text-xs",children:"Split"}):Y.grade==="losing"?e.jsx(B,{variant:"destructive",className:"text-xs",children:"Losing"}):e.jsx(B,{variant:"outline",className:"text-xs",children:"Pending"});return e.jsxs(he,{children:[e.jsx(M,{className:"text-xs font-mono",children:Y.date}),[0,1,2].map(ee=>{const le=Y.picks[ee];
248return le?e.jsx(M,{children:e.jsx(Tn,{status:le.status})},ee):e.jsx(M,{className:"text-xs text-muted-foreground",children:"—"},ee)}),e.jsxs(M,{className:"text-xs font-medium",children:[Y.wins,"-",Y.losses,Y.pushes>0?`-${Y.pushes}P`:"",Y.pending>0&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",Y.pending," pending)"]})]}),e.jsx(M,{children:I})]},Y.date)})})]})})]})]}),Object.keys(O).length>0&&e.jsxs(vs,{open:r,onOpenChange:i,children:[e.jsxs(ys,{className:"flex items-center gap-2 text-sm font-medium w-full p-2 rounded hover:bg-muted/50",children:[e.jsx(Ns,{className:`h-4 w-4 transition-transform ${r?"rotate-180":""}`}),"Breakdown by Sport"]}),e.jsx(_s,{className:"space-y-2 pt-2",children:Object.entries(O).sort().map(([Y,I])=>e.jsxs("div",{className:"rounded border p-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase",children:Y}),e.jsx("div",{className:"grid grid-cols-3 gap-2 mt-1",children:[1,2,3].map(ee=>{const le=I[ee];return!le||le.total===0?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["#",ee,": —"]},ee):e.jsxs("div",{className:"text-xs",children:[e.jsxs("span",{className:"font-medium",children:["#",ee,":"]})," ",le.winRate.toFixed(0),"% (",le.wins,"W-",le.losses,"L, n=",le.total,")"]},ee)})})]},Y))})]}),Object.keys($).length>0&&e.jsxs(vs,{open:l,onOpenChange:m,children:[e.jsxs(ys,{className:"flex items-center gap-2 text-sm font-medium w-full p-2 rounded hover:bg-muted/50",children:[e.jsx(Ns,{className:`h-4 w-4 transition-transform ${l?"rotate-180":""}`}),"Breakdown by Version"]}),e.jsx(_s,{className:"space-y-2 pt-2",children:Object.entries($).sort().map(([Y,I])=>e.jsxs("div",{className:"rounded border p-2 flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold",children:Y}),e.jsxs("span",{className:"text-xs",children:[I.winRate.toFixed(1),"% — ",I.wins,"W-",I.losses,"L-",I.pushes,"P (n=",I.total,")"]})]},Y))})]}),Object.keys(z).length>0&&e.jsxs(vs,{open:o,onOpenChange:h,children:[e.jsxs(ys,{className:"flex items-center gap-2 text-sm font-medium w-full p-2 rounded hover:bg-muted/50",children:[e.jsx(Ns,{className:`h-4 w-4 transition-transform ${o?"rotate-180":""}`}),"Breakdown by Bet Type"]}),e.jsx(_s,{className:"space-y-2 pt-2",children:Object.entries(z).sort().map(([Y,I])=>e.jsxs("div",{className:"rounded border p-2 flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold capitalize",children:Y}),e.jsxs("span",{className:"text-xs",children:[I.winRate.toFixed(1),"% — ",I.wins,"W-",I.losses,"L-",I.pushes,"P (n=",I.total,")"]})]},Y))})]}),Object.keys(D).length>0&&se.length>0&&e.jsxs(vs,{open:N,onOpenChange:d,children:[e.jsxs(ys,{className:"flex items-center gap-2 text-sm font-medium w-full p-2 rounded hover:bg-muted/50",children:[e.jsx(Ns,{className:`h-4 w-4 transition-transform ${N?"rotate-180":""}`}),"Version × Sport Matrix"]}),e.jsx(_s,{className:"pt-2",children:e.jsx("div",{className:"overflow-auto rounded border",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"text-xs",children:"Version"}),se.map(Y=>e.jsx(U,{className:"text-xs text-center uppercase",children:Y},Y))]})}),e.jsx($e,{children:Object.entries(D).sort().map(([Y,I])=>e.jsxs(he,{children:[e.jsx(M,{className:"text-xs font-medium",children:Y}),se.map(ee=>{const le=I[ee];return!le||le.total===0?e.jsx(M,{className:"text-xs text-center text-muted-foreground",children:"—"},ee):e.jsxs(M,{className:"text-xs text-center",children:[e.jsxs("span",{className:le.winRate>=55?"text-green-500 font-medium":le.winRate<45?"text-destructive font-medium":"",children:[le.winRate.toFixed(0),"%"]}),e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",le.wins,"-",le.losses,")"]})]},ee)})]},Y))})]})})})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded border",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-24",children:"Date"}),e.jsx(U,{className:"w-16",children:"Rank"}),e.jsx(U,{children:"Pick"}),e.jsx(U,{className:"w-20",children:"Sport"}),e.jsx(U,{className:"w-16",children:"Version"}),e.jsx(U,{className:"w-20",children:"Type"}),e.jsx(U,{className:"w-16 text-center",children:"Conf"}),e.jsx(U,{className:"w-20 text-center",children:"Result"})]})}),e.jsx($e,{children:w.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:8,className:"text-center text-muted-foreground",children:"No POTD picks foun
248d"})}):w.map(Y=>e.jsxs(he,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>f(Y),children:[e.jsx(M,{className:"text-xs",children:Y.game_date}),e.jsx(M,{children:e.jsxs(B,{variant:Y.potd_rank===1?"default":"secondary",className:"text-xs",children:["#",Y.potd_rank]})}),e.jsx(M,{className:"text-xs font-medium max-w-48 truncate",children:Y.pick}),e.jsx(M,{className:"text-xs uppercase",children:Y.sport}),e.jsx(M,{className:"text-xs",children:Y.generation_version}),e.jsx(M,{className:"text-xs capitalize",children:Y.pick_type}),e.jsxs(M,{className:"text-center text-xs",children:[Y.confidence_score,"%"]}),e.jsx(M,{className:"text-center",children:e.jsx(Tn,{status:Y.status})})]},Y.id))})]})}),e.jsx(Ue,{open:!!g,onOpenChange:Y=>!Y&&f(null),children:e.jsx(Be,{className:"max-w-lg max-h-[85vh] overflow-y-auto overflow-x-hidden",children:g&&e.jsxs(e.Fragment,{children:[e.jsxs(ze,{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap pr-8",children:[e.jsxs(B,{variant:g.potd_rank===1?"default":"secondary",children:["#",g.potd_rank," Pick"]}),e.jsx(B,{variant:g.status==="won"?"default":g.status==="lost"?"destructive":"outline",children:g.status}),e.jsx(B,{variant:"outline",className:"text-xs",children:g.generation_version})]}),e.jsx(Ke,{className:"text-base mt-1 break-words",children:g.pick})]}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"rounded-lg border p-3 space-y-1.5 overflow-hidden",children:[e.jsx("h4",{className:"text-xs font-semibold text-muted-foreground uppercase",children:"Game Info"}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1",children:[e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Matchup:"})," ",g.matchup||`${g.away_team} @ ${g.home_team}`]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sport:"})," ",(ie=g.sport)==null?void 0:ie.toUpperCase(),g.league?` — ${g.league}`:""]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Date:"})," ",g.game_date]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Time:"})," ",g.game_time||"—"]}),g.player_name&&e.jsxs("div",{className:"col-span-2 break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Player:"})," ",g.player_name]}),g.market_name&&e.jsxs("div",{className:"col-span-2 break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Market:"})," ",g.market_name]})]})]}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-1.5 overflow-hidden",children:[e.jsx("h4",{className:"text-xs font-semibold text-muted-foreground uppercase",children:"Betting Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1",children:[e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Type:"})," ",g.pick_type]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Direction:"})," ",g.pick_direction||"—"]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Side:"})," ",g.picked_side||"—"]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Confidence:"})," ",g.confidence_score,"%"]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Edge:"})," ",g.edge_pct!=null?`${g.edge_pct.toFixed(1)}%`:"—"]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Units:"})," ",g.suggested_units??"—"]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Orig Line/Odds:"})," ",g.original_line??"—"," / ",g.original_odds??"—"]}),e.jsxs("div",{className:"break-words",children:[e.jsx("span",{className:"text-muted-foreground",children:"Curr Line/Odds:"})," ",g.current_line??"—"," / ",g.current_odds??"—"]}
248)]})]}),g.actual_result&&e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("h4",{className:"text-xs font-semibold text-muted-foreground uppercase mb-1",children:"Score / Outcome Description"}),e.jsx("p",{children:g.actual_result}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["Win/Loss verdict: ",e.jsx("span",{className:"font-mono",children:g.status})]})]}),g.reasoning&&e.jsxs("div",{className:"rounded-lg border p-3 overflow-hidden",children:[e.jsx("h4",{className:"text-xs font-semibold text-muted-foreground uppercase mb-1",children:"AI Reasoning"}),e.jsx("p",{className:"text-xs whitespace-pre-wrap break-words max-h-40 overflow-y-auto",children:g.reasoning})]}),g.trigger_type&&e.jsxs("div",{className:"rounded-lg border p-3 overflow-hidden",children:[e.jsx("h4",{className:"text-xs font-semibold text-muted-foreground uppercase mb-1",children:"Trigger"}),e.jsx("p",{className:"text-xs break-all",children:g.trigger_type})]})]})]})})})]})})]})}const ei={module_moneyline:"moneyline",module_totals:"totals",module_spread:"spread",module_props:"props"};function og(){const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState(!1),{toast:l}=Ws(),m=async()=>{i(!0);try{let o=T.from("klutch_picks").select("*").in("status",["won","lost","push"]);s!=="all"&&(s in ei?o=o.eq("source_type","module").eq("engine_id",ei[s]):o=o.eq("generation_version",s)),t!=="all"&&(o=o.eq("sport",t));const{data:h,error:N}=await o.order("game_date",{ascending:!1});if(N)throw N;if(!h||h.length===0){l({title:"No data",description:"No settled picks found for the selected filters.",variant:"destructive"}),i(!1);return}const{data:d}=await T.from("klutch_gameline_learning").select("*").eq("is_active",!0),y=new Map;(d||[]).forEach(b=>{const j=`${b.sport}|${b.pick_type}|${b.movement_direction}|${b.sharp_score_bucket}`;y.set(j,b)});const{data:u}=await T.from("klutch_engine_health").select("*"),x=new Map;(u||[]).forEach(b=>{const j=`${b.engine_id}|${b.sport}|${b.window_days}`;x.set(j,b)});const{data:g}=await T.from("klutch_engine_signal_performance").select("*").eq("window_days",30),f=new Map;(g||[]).forEach(b=>{const j=`${b.engine_id}|${b.sport}`,c=f.get(j)||[];c.push(b),f.set(j,c)});const _=h.map(b=>{const j=b.trigger_data||{},c=j.movement_direction||j.movementDirection||"",p=j.sharp_score_bucket||j.sharpScoreBucket||"",w=`${b.sport}|${b.pick_type}|${c}|${p}`,S=y.get(w),P=b.source_type==="module",C=b.engine_id||(P?b.pick_type:"legacy_monolith"),O=x.get(`${C}|${b.sport}|7`),$=x.get(`${C}|${b.sport}|30`),z=x.get(`${C}|${b.sport}|90`),A=(f.get(`${C}|${b.sport}`)||[]).slice(0,5).map(F=>`${F.signal_key}:${F.win_rate??""}/${F.picks_with_signal}`).join("; ");return{source_type:b.source_type||"legacy",engine_id:C,engine_version:b.engine_version||"",generation_version:b.generation_version,tier:b.tier||"",game_date:b.game_date,commence_time:b.commence_time||"",sport:b.sport,pick_type:b.pick_type,matchup:b.matchup,home_team:b.home_team,away_team:b.away_team,master_game_id:b.master_game_id||"",player_name:b.player_name||"",pick:b.pick,pick_direction:b.pick_direction,picked_side:b.picked_side,confidence_score:b.confidence_score,edge_pct:b.edge_pct,suggested_units:b.suggested_units,original_odds:b.original_odds,original_line:b.original_line,current_odds:b.current_odds??"",current_line:b.current_line??"",reasoning:b.reasoning||"",trigger_type:b.trigger_type,trigger_sharp_score:j.sharp_score??j.sharpScore??"",trigger_movement_pct:j.movement_pct??j.movementPct??"",trigger_movement_direction:c,trigger_sharp_bucket:p,trigger_edge:j.edge??"",trigger_consensus_odds:j.consensus_odds??j.consensusOdds??"",status:b.status,score_or_outcome_description:b.actual_result,settled_at:b.settled_at,promoted_at:b.promoted_at||"",learning_adjustment:(S==null?void 0:S.learned_adjustment)??"",learning_win_rate:(S==null?void 0:S.win_rate)??"",learning_net_units:(S==null?void 0:S.net_units)??"",learning_sample_size:(S==null?void 0:S.sample_size)??"",learning_reasoning_factors:S!=null&&S.reasoning_factors?JSON.stringify(S.reasoning_factors):"",engine_health_7d_wr:(O==null?void 0:O.win_rate)??"",engine_health_7d_n:(O==null?void 0:O.sample_size)??"",engine_health_30d_wr:($==null?void 0:$.win_rate)??"",engine_health_30d_roi:($==null?void 0:$.roi)??"",engine_health_30d_n:($==null?void 0:$.sample_size)??"",engine_health_90d_wr:(z==null?void 0:z.win_rate)??"",engine_health_90d_roi:(z==null?void 0:z.roi)??"",engine_health_90d_n:(z==null?void 0:z.sample_size)??"",engine_top_signals_30d:A}}),k=`klutch_analysis_${s}_${t}_${new Date().toISOString().slice(0,10)}.csv`;cl(_,k),l({title:"Export complete",description:`${_.length} picks exported to ${k}`})}catch(o){l({title:"Export failed",description:o.message,variant:"destructive"})}finally{i(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{className:"text-lg",children:"KLUTCH Analysis Export"}),e.jsx(De,{children:"Export settled picks (legacy + modules) with reasoning, learning & engine-health data for external LLM analysis"})]}),e.jsx(J,{children:e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm font-medium",children:"Source"}),e.jsxs(oe,{value:s,onValueChange:o=>a(o),children:[e.jsx(de,{className:"w-[200px]",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All"}),e.jsx(V,{value:"v1",children:"Legacy v1"}),e.jsx(V,{value:"v1a",children:"v1a · Opus 4.8"}),e.jsx(V,{value:"v2",children:"Legacy v2"}),e.jsx(V,{value:"v2.5",children:"Legacy v2.5"}),e.jsx(V,{value:"v2.5a",children:"v2.5a · GPT-5.5"}),e.jsx(V,{value:"v3",children:"Legacy v3"}),e.jsx(V,{value:"v3a",children:"v3a · Gemini 3.5"}),e.jsx(V,{value:"module_moneyline",children:"Module: Moneyline"}),e.jsx(V,{value:"module_totals",children:"Module: Totals"}),e.jsx(V,{value:"module_spread",children:"Module: Spread"}),e.jsx(V,{value:"module_props",children:"Module: Props"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm font-medium",children:"Sport"}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),e.jsx(V,{value:"basketball",children:"Basketball"}),e.jsx(V,{value:"baseball",children:"Baseball"}),e.jsx(V,{value:"hockey",children:"Hockey"}),e.jsx(V,{value:"football",children:"Football"}),e.jsx(V,{value:"soccer",children:"Soccer"})]})]})]}),e.jsxs(R,{onClick:m,disabled:r,children:[r?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Gt,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})})]})}function Ln({title:s,description:a,children:t}){return e.jsxs(vs,{defaultOpen:!1,className:"border rounded-lg p-4",children:[e.jsxs(ys,{className:"flex items-center gap-2 w-full text-left group",children:[e.jsx(st,{className:"h-4 w-4 shrink-0 transition-transform duration-200 group-data-[state=open]:rotate-90"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:s}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a})]})]}),e.jsx(_s,{className:"mt-4 pt-4 border-t",children:e.jsx("div",{className:"grid gap-6",children:t})})]})}function dg(){const[s,a]=v.useState("pipeline"),[t,n]=v.useState(!1),[r,i]=v.useState(30);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(vs,{open:t,onOpenChange:n,children:[e.jsx(ys,{asChild:!0,children:e.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 rounded-lg border bg-card px-4 py-3 hover:bg-accent/40 transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-md bg-primary/10 flex items-center justify-center",children:e.jsx(it,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"KLUTCH Analyst Chat"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"AI-powered diagnostic chat — ask about performance, drift, overlays, proposals"})]})]}),e.jsx(Ns,{className:`h-5 w-5 text-muted-foreground transition-transform ${t?"rotate-180":""}`})]})}),e.jsx(_s,{className:"mt-2",children:e.jsx(G,{className:"p-2",children:e.jsx(oh,{})})})]}),e.jsxs(js,{value:s,onValueChange:a,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-1 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"pipeline",className:"text-xs gap-1.5",children:[e.jsx(Yi,{className:"h-3.5 w-3.5"}),"Pipeline"]}),e.jsxs(Ne,{value:"performance",className:"text-xs gap-1.5",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"Performance"]}),e.jsxs(Ne,{value:"learning",className:"text-xs gap-1.5",children:[e.jsx(it,{className:"h-3.5 w-3.5"}),"Learning"]}),e.jsxs(Ne,{value:"utilities",className:"text-xs gap-1.5",children:[e.jsx(ga,{className:"h-3.5 w-3.5"}),"Utilities"]})]}),e.jsx(we,{value:"pipeline",className:"mt-4",children:e.jsx(Oh,{})}),e.jsx(we,{value:"performance",className:"mt-4",children:e.jsxs(js,{defaultValue:"dashboard",className:"w-full",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(fs,{className:"flex flex-wrap gap-1 h-auto p-1 justify-start",children:[e.jsxs(Ne,{value:"dashboard",className:"text-xs gap-1.5",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"Performance Dashboard"]}),e.jsxs(Ne,{value:"engine-health",className:"text-xs gap-1.5",children:[e.jsx(iu,{className:"h-3.5 w-3.5"}),"Engine Health"]}),e.jsxs(Ne,{value:"clv",className:"text-xs gap-1.5",children:[e.jsx(_t,{className:"h-3.5 w-3.5"}),"CLV Analytics"]}),e.jsxs(Ne,{value:"v4-specialization",className:"text-xs gap-1.5",children:[e.jsx(Gn,{className:"h-3.5 w-3.5"}),"v4 Specialization"]}),e.jsxs(Ne,{value:"engine-lift",className:"text-xs gap-1.5",children:[e.jsx(xu,{className:"h-3.5 w-3.5"}),"Engine Lift Audit"]})]}),e.jsx("div",{className:"flex items-center gap-1 rounded-md border bg-card p-1",role:"group","aria-label":"Performance time window",children:dh.map(l
248=>e.jsx(R,{type:"button",size:"sm",variant:r===l.value?"default":"ghost",className:Le("h-7 px-2.5 text-xs",r===l.value&&"shadow"),onClick:()=>i(l.value),children:l.label},l.value))})]}),e.jsx(we,{value:"dashboard",className:"mt-4",children:e.jsx(mh,{windowDays:r})}),e.jsx(we,{value:"engine-health",className:"mt-4",children:e.jsx(eg,{windowDays:r})}),e.jsx(we,{value:"clv",className:"mt-4",children:e.jsx(yh,{windowDays:r})}),e.jsx(we,{value:"v4-specialization",className:"mt-4",children:e.jsx(Gh,{})}),e.jsx(we,{value:"engine-lift",className:"mt-4",children:e.jsx(Zh,{})})]})}),e.jsx(we,{value:"learning",className:"mt-4",children:e.jsx(Wp,{})}),e.jsx(we,{value:"utilities",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ln,{title:"Maintenance",description:"Settlement, cleanup, and manual KLUTCH operations",children:[e.jsx(sg,{}),e.jsx(tg,{}),e.jsx(ag,{})]}),e.jsx(Ln,{title:"Pick of the Day",description:"Daily top pick tracker and history",children:e.jsx(cg,{})}),e.jsx(Ln,{title:"Analysis Export",description:"Export pick data for LLM review and analysis",children:e.jsx(og,{})})]})})]})]})}function ug({userId:s}){var t;const a=po(s);return e.jsxs("section",{className:"space-y-3 rounded-lg border p-4",children:[e.jsx("h3",{className:"font-semibold",children:"Kapital access"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Paper remains super-admin only. Granting Live does not arm the user's trader."}),["kapital","live"].map(n=>{var r;return e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:!!((r=a.data)!=null&&r[n==="kapital"?"kapital_enabled":"live_enabled"]),disabled:a.isLoading||!!a.error||a.grants.isPending,onChange:i=>{var l,m;return a.grants.mutate({kapital:!!((l=a.data)!=null&&l.kapital_enabled),live:!!((m=a.data)!=null&&m.live_enabled),[n]:i.target.checked})}}),n==="kapital"?"Kapital access":"Live trader access"]},n)}),(a.error||a.grants.error)&&e.jsx("p",{role:"alert",children:(t=a.error||a.grants.error)==null?void 0:t.message})]})}function zn({userId:s,currentRole:a,userEmail:t}){const[n,r]=v.useState(a),[i,l]=v.useState(!1),[m,o]=v.useState(null),h=Me(),N=_e({mutationFn:async g=>{const{error:f}=await T.from("user_roles").update({role:g}).eq("user_id",s);if(f)throw f},onSuccess:()=>{h.invalidateQueries({queryKey:["users"]}),K.success("Role updated successfully"),l(!1),o(null)},onError:g=>{console.error("Error updating role:",g),K.error("Failed to update role"),r(a)}}),d=g=>{g!==a&&(o(g),l(!0))},y=()=>{m&&(r(m),N.mutate(m))},u=()=>{l(!1),o(null),r(a)},x=g=>{switch(g){case"super_admin":return"Super Admin";case"admin":return"Admin";case"user":return"User"}};return e.jsxs(e.Fragment,{children:[e.jsxs(oe,{value:n,onValueChange:d,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"user",children:"User"}),e.jsx(V,{value:"admin",children:"Admin"}),e.jsx(V,{value:"super_admin",children:"Super Admin"})]})]}),e.jsx(ws,{open:i,onOpenChange:l,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Confirm Role Change"}),e.jsxs(Ps,{children:["Are you sure you want to change ",t?`${t}'s`:"this user's"," role from"," ",e.jsx("strong",{children:x(a)})," to"," ",e.jsx("strong",{children:m?x(m):""}),"?",m==="super_admin"&&e.jsx("span",{className:"block mt-2 text-destructive",children:"Warning: Super Admins have full system access."})]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{onClick:u,children:"Cancel"}),e.jsx(Ls,{onClick:y,children:"Confirm"})]})]})})]})}function mg({models:s,open:a,onOpenChange:t}){const n=s.filter(i=>i.model_type==="betting"),r=s.filter(i=>i.model_type==="fantasy");return e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-5 w-5"}),"User Models (",s.length,")"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[n.length," Betting"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-4 w-4 text-blue-500"}),e.jsxs("span",{children:[r.length," Fantasy"]})]})]}),s.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No models created"}):e.jsx("div",{className:"space-y-2",children:s.map(i=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[i.model_type==="betting"?e.jsx(As,{className:"h-4 w-4 text-primary"}):e.jsx(it,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:i.model_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Created ",ke(new Date(i.created_at),"MMM dd, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",className:"uppercase text-xs",children:i.sport}),e.jsxs(B,{variant:i.model_type==="betting"?"default":"secondary",className:"text-xs",children:[i.model_type==="betting"?"🎰":"🏈"," ",i.model_type]}),i.is_active?e.jsx(Es,{className:"h-4 w-4 text-green-500"}):e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"})]})]},i.id))})]})]})})}function En({title:s,icon:a,stats:t,showPushes:n=!0,showProfitLoss:r=!0}
248){const i=t.wins+t.losses+(n?t.pushes:0),l=i>0?(t.wins/i*100).toFixed(1):null;return t.count===0?e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:s})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"No activity"})]}):e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:s})]}),e.jsxs(B,{variant:"outline",className:"text-xs",children:[t.count," total"]})]}),e.jsxs("div",{className:`grid ${n?"grid-cols-4":"grid-cols-3"} gap-2`,children:[e.jsxs("div",{className:"bg-green-500/10 border border-green-500/20 rounded-lg p-2 text-center",children:[e.jsx(Ds,{className:"h-3 w-3 text-green-500 mx-auto mb-1"}),e.jsx("p",{className:"text-sm font-bold text-green-500",children:t.wins}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Wins"})]}),e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2 text-center",children:[e.jsx(qt,{className:"h-3 w-3 text-red-500 mx-auto mb-1"}),e.jsx("p",{className:"text-sm font-bold text-red-500",children:t.losses}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Losses"})]}),n&&e.jsxs("div",{className:"bg-yellow-500/10 border border-yellow-500/20 rounded-lg p-2 text-center",children:[e.jsx(Da,{className:"h-3 w-3 text-yellow-500 mx-auto mb-1"}),e.jsx("p",{className:"text-sm font-bold text-yellow-500",children:t.pushes}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Pushes"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2 text-center",children:[e.jsx($s,{className:"h-3 w-3 text-muted-foreground mx-auto mb-1"}),e.jsx("p",{className:"text-sm font-bold",children:t.pending}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Pending"})]})]}),e.jsx("div",{className:"flex justify-between items-center text-sm",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Win Rate: "}),e.jsx("span",{className:"font-medium",children:l?`${l}%`:"N/A"})]}),r&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"P/L: "}),e.jsxs("span",{className:`font-medium ${t.profitLoss>=0?"text-green-500":"text-red-500"}`,children:[t.profitLoss>=0?"+":"","$",t.profitLoss.toFixed(2)]})]})]})}),Object.keys(t.bySport).length>0&&e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(t.bySport).map(([m,o])=>e.jsxs(B,{variant:"outline",className:"text-[10px] uppercase",children:[m,": ",o]},m))})]})}function xg({regularStats:s,dfsStats:a,trackedStats:t,placed:n,tracked:r,open:i,onOpenChange:l}){const m=s.count+a.count+t.count,o=s.profitLoss+a.profitLoss;return e.jsx(Ue,{open:i,onOpenChange:l,children:e.jsxs(Be,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx($n,{className:"h-5 w-5"}),"Betting Activity (",m," total)"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold",children:n}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"📤 Placed"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold",children:r}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"👁️ Tracked"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsxs("p",{className:`text-2xl font-bold ${o>=0?"text-green-500":"text-red-500"}`,children:[o>=0?"+":"","$",o.toFixed(0)]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"💰 Placed P/L"})]})]}),e.jsx(En,{title:"Betting Performance (Placed)",icon:Js,stats:s,showPushes:!0}),e.jsx(En,{title:"DFS Contest Performance",icon:tu,stats:a,showPushes:!1}),e.jsx(En,{title:"Tracked Recommendations",icon:us,stats:t,showPushes:!0,showProfitLoss:!1})]})]})})}function hg({stats:s,open:a,onOpenChange:t}){const n=s.wins+s.losses,r=n>0?(s.wins/n*100).toFixed(1):null;return e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-lg",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5"}),"DFS Lineups (",s.total," total)"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx(It,{className:"h-4 w-4 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-bold",children:s.saved}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx(us,{className:"h-4 w-4 mx-auto mb-1 text-blue-500"}),e.jsx("p",{className:"text-xl font-bold",children:s.tracked}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tracked"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx(Jr,{className:"h-4 w-4 mx-auto mb-1 text-primary"}),e.jsx("p",{className:"text-xl font-bold",children:s.placed}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Placed"})]})]}),n>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Performance (Tracked/Placed)"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{className:"bg-green-500/10 border border-green-500/20 rounded-lg p-2 text-center",children:[e.jsx(Ds,{className:"h-4 w-4 text-green-500 mx-auto mb-1"}),e.jsx("p",{className:"text-lg font-bold text-green-500",children:s.wins}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Wins"})]}),e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2 text-center",children:[e.jsx(qt,{className:"h-4 w-4 text-red-500 mx-auto mb-1"}),e.jsx("p",{className:"text-lg font-bold text-red-500",children:s.losses}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Losses"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2 text-center",children:[e.jsxs("p",{className:"text-lg font-bold",children:[r,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Win Rate"})]})]})]}),Object.keys(s.bySport).length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"By Sport"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Object.entries(s.bySport).map(([i,l])=>e.jsxs(B,{variant:"outline",className:"uppercase",children:[i,": ",l]},i))})]}),Object.keys(s.byPlatform).length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"By Platform"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Object.entries(s.byPlatform).map(([i,l])=>e.jsxs(B,{variant:"secondary",children:[i,": ",l]},i))})]})]})]})})}const pg={klutch:{label:"KLUTCH",icon:"🎯"},kollective:{label:"Kollective",icon:"📊"},kontests:{label:"Kontests",icon:"🏆"}
248,kash:{label:"KASH",icon:"💰"}};function gg({progress:s}){if(!s)return e.jsx("div",{className:"text-sm text-muted-foreground bg-muted/30 rounded-lg p-4 text-center",children:"No onboarding data — user hasn't started any tours"});const a=[{key:"klutch",field:"klubhub_klutch_tour_completed"},{key:"kollective",field:"klubhub_kollective_tour_completed"},{key:"kontests",field:"klubhub_kontests_tour_completed"},{key:"kash",field:"klubhub_kash_tour_completed"}],t=a.filter(i=>s[i.field]).length,n=a.length,r=t/n*100;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Tour Progress"}),e.jsxs("span",{className:"font-medium",children:[t,"/",n," Complete"]})]}),e.jsx(Ct,{value:r,className:"h-2"})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2",children:e.jsx(zt,{children:a.map(({key:i,field:l})=>{const m=s[l],o=pg[i];return e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsxs("div",{className:`flex flex-col items-center justify-center p-2 rounded-lg border transition-colors ${m?"bg-green-500/10 border-green-500/30 text-green-600 dark:text-green-400":"bg-muted/30 border-border text-muted-foreground"}`,children:[e.jsx("span",{className:"text-lg",children:o.icon}),m?e.jsx(Ks,{className:"h-3 w-3 mt-1"}):e.jsx(rt,{className:"h-3 w-3 mt-1 opacity-50"})]})}),e.jsx(zs,{children:e.jsxs("p",{children:[o.label,": ",m?"Completed":"Not Started"]})})]},i)})})}),t===n?e.jsx(B,{className:"bg-green-500/10 text-green-600 border-green-500/30",children:"✨ All Tours Completed"}):t===0?e.jsx(B,{variant:"outline",className:"text-muted-foreground",children:"No tours completed yet"}):null]})}const jg={too_expensive:"Too Expensive",not_winning:"Not Winning",not_using:"Not Using",hard_to_use:"Hard to Use",missing_features:"Missing Features",other:"Other"};function fg({user:s,open:a,onOpenChange:t}){var P,C,O,$,z,D,A,F,q,E,L,H,Z,se,ie,Y,I,ee,le,ve,te,X,ae,W,re,ce,Pe,Fe,Ae,Ve,as,Oe,Ie,ds,be,Qe,et,Gs,xe,Ce,Se,ye,We,ps,bs,Os,Ft,pt,Qs,At,Tt,Ja;const n=Me(),[r,i]=v.useState(!1),[l,m]=v.useState(!1),[o,h]=v.useState(!1),[N,d]=v.useState(((P=s==null?void 0:s.subscription)==null?void 0:P.cancel_outreach_status)||"pending");v.useEffect(()=>{var Hs;d(((Hs=s==null?void 0:s.subscription)==null?void 0:Hs.cancel_outreach_status)||"pending")},[(C=s==null?void 0:s.subscription)==null?void 0:C.id,(O=s==null?void 0:s.subscription)==null?void 0:O.cancel_outreach_status]);const y=async Hs=>{var Lt;if(!((Lt=s==null?void 0:s.subscription)!=null&&Lt.id))return;d(Hs);const{error:qs}=await T.from("user_subscriptions").update({cancel_outreach_status:Hs}).eq("id",s.subscription.id);qs?K.error("Failed to update outreach status"):(K.success("Outreach status updated"),n.invalidateQueries({queryKey:["users"]}))},{data:u}=ge({queryKey:["duplicate-ip-check",s==null?void 0:s.id,s==null?void 0:s.signup_ip_address,s==null?void 0:s.last_known_ip_address],queryFn:async()=>{if(!(s!=null&&s.signup_ip_address)&&!(s!=null&&s.last_known_ip_address))return{isDuplicate:!1,count:0};const Hs=[s.signup_ip_address,s.last_known_ip_address].filter(Boolean);let qs=T.from("user_profiles").select("id").is("deleted_at",null).neq("id",s.id);Hs.length===1?qs=qs.or(`signup_ip_address.eq.${Hs[0]},last_known_ip_address.eq.${Hs[0]}`):qs=qs.or(`signup_ip_address.eq.${Hs[0]},last_known_ip_address.eq.${Hs[0]},signup_ip_address.eq.${Hs[1]},last_known_ip_address.eq.${Hs[1]}`);const{data:Lt,error:Za}=await qs;if(Za)return console.warn("Could not check duplicate IPs:",Za),{isDuplicate:!1,count:0};const Xa=((Lt==null?void 0:Lt.length)||0)+1;return{isDuplicate:Xa>1,count:Xa}},enabled:a&&!!s});if(!s)return null;const x=Hs=>{switch(Hs){case"super_admin":return"destructive";case"admin":return"default";default:return"secondary"}},g=()=>{var qs;if(!s.subscription)return e.jsx(B,{variant:"outline",children:"Free"});const Hs={active:"default",cancelled:"secondary",expired:"destructive",trial:"outline",paused:"outline"};return e.jsxs(B,{variant:Hs[s.subscription.status]||"outline",children:[((qs=s.subscription.package)==null?void 0:qs.name)||"Unknown"," - ",s.subscription.status]})},f=Hs=>{if(!Hs)return"Never";try{return ha(new Date(Hs),"America/Chicago","MMM dd, yyyy h:mm a")+" CST"}catch{return"Unknown"}},_=(($=s.subscription)==null?void 0:$.cancel_reason)||((z=s.subscription)==null?void 0:z.cancel_feedback),k={count:0,wins:0,losses:0,pushes:0,pending:0,profitLoss:0,bySport:{}},b=((D=s.activity)==null?void 0:D.regularBetStats)||k,j=((A=s.activity)==null?void 0:A.dfsBetStats)||k,c=((F=s.activity)==null?void 0:F.trackedBetStats)||k,p=((q=s.activity)==null?void 0:q.betCount)||0,w=((E=s.activity)==null?void 0:E.trackedBetCount)||0,S={total:((L=s.activity)==null?void 0:L.lineupCount)||0,saved:((H=s.activity)==null?void 0:H.lineupSaved)||0,tracked:((Z=s.activity)==null?void 0:Z.lineupTracked)||0,placed:((se=s.activity)==null?void 0:se.lineupPlaced)||0,wins:((ie=s.activity)==null?void 0:ie.lineupWins)||0,losses:((Y=s.activity)==null?void 0:Y.lineupLosses)||0,bySport:((I=s.activity)==null?void 0:I.lineupsBySport)||{},byPlatform:((ee=s.activity)==null?void 0:ee.lineupsByPlatform)||{}};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"User Details"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(ua,{className:"h-20 w-20",children:[e.jsx(ma,{src:s.avatar_url||void 0}
248),e.jsx(xa,{children:((le=s.full_name)==null?void 0:le.charAt(0))||((ve=s.username)==null?void 0:ve.charAt(0))||((te=s.email)==null?void 0:te.charAt(0))||"U"})]}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("h3",{className:"text-lg font-semibold",children:s.full_name||s.username||"Unnamed User"}),s.email&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.email}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(B,{variant:x(s.role),children:s.role.replace("_"," ")}),g()]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4"}),"Demographics"]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Display Name"}),e.jsx("p",{className:"font-medium",children:s.display_name||"Not set"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Age"}),e.jsx("p",{className:"font-medium",children:s.current_age?`${s.current_age} years`:"Not set"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kd,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"State"}),e.jsx("p",{className:"font-medium",children:s.state_code||"Not set"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Experience"}),e.jsx("p",{className:"font-medium",children:s.experience_level||"Not set"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Preferred Sportsbook"}),e.jsx("p",{className:"font-medium",children:s.preferred_sportsbook||"Not set"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Last Login (CST)"}),e.jsx("p",{className:"font-medium",children:f(s.last_login_at||null)})]})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx(Ds,{className:"h-4 w-4"}),"Activity Summary"]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("button",{onClick:()=>i(!0),className:"bg-muted/50 hover:bg-muted/80 rounded-lg p-3 text-center transition-colors cursor-pointer group",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 mb-1",children:[e.jsx(it,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(st,{className:"h-3 w-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-2xl font-bold",children:((X=s.activity)==null?void 0:X.modelCount)??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Models Created"}),(((ae=s.activity)==null?void 0:ae.modelCount)??0)>0&&e.jsxs("p",{className:"text-xs text-primary mt-1",children:[((W=s.activity)==null?void 0:W.bettingModelCount)||0,"🎰 / ",((re=s.activity)==null?void 0:re.fantasyModelCount)||0,"🏈"]})]}),e.jsxs("button",{onClick:()=>m(!0),className:"bg-muted/50 hover:bg-muted/80 rounded-lg p-3 text-center transition-colors cursor-pointer group",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 mb-1",children:[e.jsx(As,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(st,{className:"h-3 w-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(((ce=s.activity)==null?void 0:ce.betCount)??0)+(((Pe=s.activity)==null?void 0:Pe.trackedBetCount)??0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Bets"}),e.jsxs("p",{className:"text-xs text-primary mt-1",children:[((Fe=s.activity)==null?void 0:Fe.betCount)||0,"📤 / ",((Ae=s.activity)==null?void 0:Ae.trackedBetCount)||0,"👁️"]})]}),e.jsxs("button",{onClick:()=>h(!0),className:"bg-muted/50 hover:bg-muted/80 rounded-lg p-3 text-center transition-colors cursor-pointer group",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 mb-1",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(st,{className:"h-3 w-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-2xl font-bold",children:((Ve=s.activity)==null?void 0:Ve.lineupCount)??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"DFS Lineups"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold",children:((as=s.activity)==null?void 0:as.marketplaceSubscriptions)??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Marketplace Subs"})]})]}),(((Oe=s.activity)==null?void 0:Oe.bettingWinRate)!==null&&((Ie=s.activity)==null?void 0:Ie.bettingWinRate)!==void 0||((ds=s.activity)==null?void 0:ds.dfsWinRate)!==null&&((be=s.activity)==null?void 0:be.dfsWinRate)!==void 0||((Qe=s.activity)==null?void 0:Qe.totalProfitLoss)!==null&&((et=s.activity)==null?void 0:et.totalProfitLoss)!==void 0&&s.activity.totalProfitLoss!==0)&&e.jsxs("div",{className:"bg-muted/30 rounded-lg p-3 flex flex-wrap gap-4 text-sm",children:[((Gs=s.activity)==null?void 0:Gs.bettingWinRate)!==null&&((xe=s.activity)==null?void 0:xe.bettingWinRate)!==void 0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-muted-foreground",children:"Betting Win Rate:"}),e.jsxs("span",{className:"font-bold",children:[s.activity.bettingWinRate.toFixed(1),"%"]})]}),((Ce=s.activity)==null?void 0:Ce.dfsWinRate)!==null&&((Se=s.activity)==null?void 0:Se.dfsWinRate)!==void 0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-muted-foreground",children:"DFS Win Rate:"}),e.jsxs("span",{className:"font-bold",children:[s.activity.dfsWinRate.toFixed(1),"%"]})]}),((ye=s.activity)==null?void 0:ye.totalProfitLoss)!==null&&((We=s.activity)==null?void 0:We.totalProfitLoss)!==void 0&&s.activity.totalProfitLoss!==0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($n,{className:"h-4 w-4"}),e.jsx("span",{className:"text-muted-foreground",children:"Total P/L:"}),e.jsxs("span",{className:`font-bold ${s.activity.totalProfitLoss>=0?"text-green-500":"text-red-500"}`,children:[s.activity.totalProfitLoss>=0?"+":"","$",s.activity.totalProfitLoss.toFixed(2)]})]})]}),((ps=s.activity)==null?void 0:ps.subscribedSports)&&s.activity.subscribedSports.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Sports Subscribed"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:s.activity.subscribedSports.map(Hs=>e.jsx(B,{variant:"outline",className:"uppercase",children:Hs},Hs))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[((bs=s.activity)==null?void 0:bs.lastBetAt)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last Bet"}),e.jsx("p",{className:"mt-1",children:ke(new Date(s.activity.lastBetAt),"MMM dd, yyyy h:mm a")})]}),((Os=s.activity)==null?void 0:Os.lastLineupAt)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last Lineup"}),e.jsx("p",{className:"mt-1",children:ke(new Date(s.activity.lastLineupAt),"MMM dd, yyyy h:mm a")})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx(ru,{className:"h-4 w-4"}),"Onboarding Progress"]}),e.jsx(gg,{progress:s.onboardingProgress})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium",children:"Account Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"User ID"}),e.jsx("p",{className:"font-mono text-xs mt-1",children:s.id})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Username"}),e.jsx("p",{className:"mt-1",children:s.username||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Joined"}
248),e.jsx("p",{className:"mt-1",children:s.created_at?ke(new Date(s.created_at),"MMM dd, yyyy"):"Unknown"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last Updated"}),e.jsx("p",{className:"mt-1",children:s.updated_at?ke(new Date(s.updated_at),"MMM dd, yyyy"):"Unknown"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Trial Status"}),e.jsx("div",{className:"mt-1",children:s.has_used_trial?e.jsx(B,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200",children:"Trial Used"}):e.jsx(B,{variant:"outline",className:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:"Eligible for Trial"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Signup IP Address"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("p",{className:"font-mono text-xs",children:s.signup_ip_address||"Not captured"}),s.signup_ip_address&&(u==null?void 0:u.isDuplicate)&&e.jsxs(B,{variant:"destructive",className:"text-[10px] px-1 py-0 h-4",children:[u.count," users share this IP"]})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last Known IP Address"}),e.jsx("p",{className:"mt-1 font-mono text-xs",children:s.last_known_ip_address||s.signup_ip_address||"Not captured"})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium",children:"Role Management"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Current Role:"}),e.jsx(ug,{userId:s.id}),e.jsx(zn,{userId:s.id,currentRole:s.role,userEmail:s.email})]})]}),s.subscription&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx($n,{className:"h-4 w-4"}),"Subscription Details"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Package"}),e.jsx("p",{className:"mt-1",children:((Ft=s.subscription.package)==null?void 0:Ft.name)||"Unknown"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Status"}),e.jsx("p",{className:"mt-1 capitalize",children:s.subscription.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Start Date"}),e.jsx("p",{className:"mt-1",children:ke(new Date(s.subscription.start_date),"MMM dd, yyyy")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"End Date"}),e.jsx("p",{className:"mt-1",children:ke(new Date(s.subscription.end_date),"MMM dd, yyyy")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Auto Renew"}),e.jsx("p",{className:"mt-1",children:s.subscription.auto_renew?"Yes":"No"})]}),s.subscription.paused_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Paused At"}),e.jsx("p",{className:"mt-1",children:ke(new Date(s.subscription.paused_at),"MMM dd, yyyy")})]})]})]})]}),_&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx(ls,{className:"h-4 w-4 text-yellow-500"}),"Cancellation History"]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3 text-sm",children:[((pt=s.subscription)==null?void 0:pt.cancel_reason)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Cancel Reason"}),e.jsx("p",{className:"mt-1 font-medium",children:jg[s.subscription.cancel_reason]||s.subscription.cancel_reason})]}),((Qs=s.subscription)==null?void 0:Qs.cancel_feedback)&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(St,{className:"h-3.5 w-3.5"}),"Feedback"]}),e.jsxs("p",{className:"mt-1 text-foreground bg-background/50 rounded p-2",children:['"',s.subscription.cancel_feedback,'"']})]}),((At=s.subscription)==null?void 0:At.cancel_requested_call)&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Cd,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Requested Video Call"})]}),((Tt=s.subscription)==null?void 0:Tt.paused_reason)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Paused Reason"}),e.jsx("p",{className:"mt-1",children:s.subscription.paused_reason==="sport_out_of_season"?"Sport out of season":s.subscription.paused_reason})]}),e.jsxs("div",{className:"pt-2 border-t border-border/50",children:[e.jsx("p",{className:"text-muted-foreground mb-2",children:"Outreach Status"}),e.jsxs(oe,{value:N,onValueChange:y,children:[e.jsx(de,{className:"w-full",children:e.jsx(ue,{placeholder:"Select status..."})}),e.jsxs(me,{children:[e.jsx(V,{value:"pending",children:"Pending"}),e.jsx(V,{value:"first_attempt",children:"First Attempt"}),e.jsx(V,{value:"second_attempt",children:"Second Attempt"}),e.jsx(V,{value:"responded",children:"Responded"}),e.jsx(V,{value:"closed",children:"Closed"})]})]})]})]})]})]})]})]})}),e.jsx(mg,{models:((Ja=s.activity)==null?void 0:Ja.models)||[],open:r,onOpenChange:i}),e.jsx(xg,{regularStats:b,dfsStats:j,trackedStats:c,placed:p,tracked:w,open:l,onOpenChange:m}),e.jsx(hg,{stats:S,open:o,onOpenChange:h})]})}function vg({user:s,open:a,onOpenChange:t}){const n=Me(),{data:r,isLoading:i}=go(),{data:l,isLoading:m}=jo((s==null?void 0:s.id)||null),[o,h]=v.useState("clear"),[N,d]=v.useState(""),[y,u]=v.useState(""),[x,g]=v.useState(""),[f,_]=v.useState(!0),[k,b]=v.useState(!1);v.useEffect(()=>{a&&l?(h(l.status),u(l.reason||""),g(l.admin_notes||""),l.template_id&&d(l.template_id)):a&&(h("clear"),u(""),g(""),d("")),_(!0)},[a,l]),v.useEffect(()=>{if(o==="clear"){d("");return}const C=r==null?void 0:r.find(O=>O.status===o&&O.is_default);C&&!N&&d(C.id)},[o,r]);const j=(r==null?void 0:r.filter(C=>C.status===o))||[],c=r==null?void 0:r.find(C=>C.id===N),p=C=>{switch(C){case"banned":return e.jsx(Hr,{className:"h-4 w-4 text-red-500"});case"flagged":return e.jsx(ls,{className:"h-4 w-4 text-orange-500"});case"monitored":return e.jsx(us,{className:"h-4 w-4 text-yellow-500"});case"clear":return e.jsx(Es,{className:"h-4 w-4 text-green-500"})}},w=C=>{switch(C){case"banned":return e.jsx(B,{className:"bg-red-500/20 text-red-400 border-red-500/50",children:"Banned"});case"flagged":return e.jsx(B,{className:"bg-orange-500/20 text-orange-400 border-orange-500/50",children:"Flagged"});case"monitored":return e.jsx(B,{className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/50",children:"Monitored"});case"clear":return e.jsx(B,{className:"bg-green-500/20 text-green-400 border-green-500/50",children:"Clear"})}},S=async()=>
248{if(s){b(!0);try{const{data:{session:C}}=await T.auth.getSession();if(!C){K.error("Not authenticated");return}const O=await T.functions.invoke("apply-account-moderation",{body:{userId:s.id,status:o,templateId:N||void 0,reason:y||void 0,adminNotes:x||void 0,sendEmail:f&&o!=="clear"}});if(O.error)throw new Error(O.error.message);const $=O.data;if($.success)K.success($.message),n.invalidateQueries({queryKey:["users"]}),n.invalidateQueries({queryKey:["user-moderation-status",s.id]}),t(!1);else throw new Error($.error||"Failed to apply moderation")}catch(C){console.error("Error applying moderation:",C),K.error(C instanceof Error?C.message:"Failed to apply moderation")}finally{b(!1)}}};if(!s)return null;const P=i||m;return e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"h-5 w-5"}),"Moderate Account"]}),e.jsxs(Vs,{children:["Apply moderation actions to ",s.full_name||s.email||"this user"]})]}),P?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[l&&l.status!=="clear"&&e.jsxs("div",{className:"p-4 rounded-lg border bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Current Status:"}),w(l.status)]}),l.reason&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Reason: ",l.reason]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"New Status"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:["clear","monitored","flagged","banned"].map(C=>e.jsxs(R,{variant:o===C?"default":"outline",className:o===C?C==="banned"?"bg-red-600 hover:bg-red-700":C==="flagged"?"bg-orange-600 hover:bg-orange-700":C==="monitored"?"bg-yellow-600 hover:bg-yellow-700":"bg-green-600 hover:bg-green-700":"",onClick:()=>h(C),children:[p(C),e.jsx("span",{className:"ml-2 capitalize",children:C})]},C))})]}),o!=="clear"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Template"}),e.jsxs(oe,{value:N,onValueChange:d,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select a template..."})}),e.jsx(me,{children:j.map(C=>e.jsxs(V,{value:C.id,children:[C.display_name," ",C.is_default&&"(Default)"]},C.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Reason (shown to user)"}),e.jsx(pe,{value:y,onChange:C=>u(C.target.value),placeholder:(c==null?void 0:c.display_name)||"Enter reason..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Admin Notes (internal only)"}),e.jsx(Xs,{value:x,onChange:C=>g(C.target.value),placeholder:"Internal notes about this action...",rows:3})]}),o!=="clear"&&c&&e.jsxs(js,{defaultValue:"banner",children:[e.jsxs(fs,{className:"grid w-full grid-cols-2",children:[e.jsx(Ne,{value:"banner",children:"Banner Preview"}),e.jsx(Ne,{value:"email",children:"Email Preview"})]}),e.jsx(we,{value:"banner",className:"mt-2",children:e.jsx("div",{className:`p-4 rounded-lg text-white ${o==="banned"?"bg-red-600":o==="flagged"?"bg-orange-600":"bg-yellow-600"}`,children:e.jsx("p",{className:"text-sm",children:c.banner_text})})}),e.jsx(we,{value:"email",className:"mt-2",children:e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"bg-muted px-4 py-2 border-b",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Subject: ",c.email_subject]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"From: [email protected]"})]}),e.jsx("div",{className:"p-4 bg-white text-black max-h-64 overflow-y-auto",dangerouslySetInnerHTML:{__html:c.email_html_content}})]})})]}),o!=="clear"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Q,{htmlFor:"send-email",children:"Send notification email"})]}),e.jsx(Ge,{id:"send-email",checked:f,onCheckedChange:_})]})]}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>t(!1),disabled:k,children:"Cancel"}),e.jsx(R,{onClick:S,disabled:k||P,className:o==="banned"?"bg-red-600 hover:bg-red-700":o==="flagged"?"bg-orange-600 hover:bg-orange-700":o==="monitored"?"bg-yellow-600 hover:bg-yellow-700":"",children:k?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Applying..."]}):`Apply ${o==="clear"?"Clear Status":o.charAt(0).toUpperCase()+o.slice(1)}`})]})]})})}const yg=[{value:"user_request",label:"User Requested Deletion"},{value:"fraud",label:"Fraud / Abuse"},{value:"spam",label:"Spam Account"},{value:"duplicate",label:"Duplicate Account"},{value:"test_account",label:"Test Account Cleanup"},{value:"other",label:"Other"}];function Ng({user:s,open:a,onOpenChange:t}){const[n,r]=v.useState(""),[i,l]=v.useState(""),m=Me(),o=_e({mutationFn:async()=>
248{if(!s)throw new Error("No user selected");const{data:u,error:x}=await T.functions.invoke("delete-user-account",{body:{userId:s.id,reason:i}});if(x)throw x;if(u!=null&&u.error)throw new Error(u.error);return u},onSuccess:()=>{K.success("Account deleted successfully"),m.invalidateQueries({queryKey:["users"]}),m.invalidateQueries({queryKey:["dashboard-stats"]}),h()},onError:u=>{K.error(`Failed to delete account: ${u.message}`)}}),h=()=>{r(""),l(""),t(!1)},N=(s==null?void 0:s.email)||(s==null?void 0:s.username)||"",d=n.toLowerCase()===N.toLowerCase(),y=d&&i;return e.jsx(ws,{open:a,onOpenChange:t,children:e.jsxs(Ss,{className:"max-w-md",children:[e.jsxs(ks,{children:[e.jsxs(Cs,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(ls,{className:"h-5 w-5"}),"Delete User Account"]}),e.jsxs(Ps,{className:"space-y-3",children:[e.jsxs("p",{children:["You are about to delete the account for"," ",e.jsx("strong",{className:"text-foreground",children:(s==null?void 0:s.full_name)||N}),"."]}),e.jsxs("div",{className:"bg-destructive/10 border border-destructive/30 rounded-md p-3 text-sm space-y-1",children:[e.jsx("p",{className:"font-medium text-destructive",children:"This action will:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-0.5",children:[e.jsx("li",{children:"Cancel any active Stripe subscription"}),e.jsx("li",{children:"Log the user out of all sessions"}),e.jsx("li",{children:"Mark the account as deleted"}),e.jsx("li",{children:"Exclude from LTV and churn metrics"})]})]})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"reason",children:"Deletion Reason"}),e.jsxs(oe,{value:i,onValueChange:l,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select a reason..."})}),e.jsx(me,{children:yg.map(u=>e.jsx(V,{value:u.value,children:u.label},u.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{htmlFor:"confirm-email",children:["Type ",e.jsx("strong",{className:"font-mono text-xs",children:N})," to confirm"]}),e.jsx(pe,{id:"confirm-email",value:n,onChange:u=>r(u.target.value),placeholder:"Enter email to confirm",className:n&&!d?"border-destructive":""})]})]}),e.jsxs(Fs,{children:[e.jsx(R,{variant:"outline",onClick:h,children:"Cancel"}),e.jsxs(R,{variant:"destructive",onClick:()=>o.mutate(),disabled:!y||o.isPending,children:[o.isPending&&e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Delete Account"]})]})]})})}function $r(s){const{status:a,packageName:t,cancelReason:n,pausedAt:r,isFeedbackTrial:i}=s,l=t||"Plan";if(i&&(a==="active"||a==="trial"))return e.jsxs(B,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/50",children:["Feedback Trial - ",l]});if(a==="paused"||r)return e.jsxs(B,{className:"bg-cyan-500/20 text-cyan-400 border-cyan-500/50",children:["Paused - ",l]});if(n==="replaced_by_extended_trial")return e.jsxs(B,{className:"bg-teal-500/20 text-teal-400 border-teal-500/50",children:["Extended - ",l]});if(n==="upgrading")return e.jsxs(B,{className:"bg-purple-500/20 text-purple-400 border-purple-500/50",children:["Upgrading from ",l]});if(n==="downgrading")return e.jsxs(B,{className:"bg-orange-500/20 text-orange-400 border-orange-500/50",children:["Downgrading from ",l]});if(n&&a!=="cancelled")return e.jsxs(B,{className:"bg-blue-500/20 text-blue-400 border-blue-500/50",children:["Cancelling - ",l]});switch(a){case"active":return e.jsx(B,{className:"bg-green-500/20 text-green-400 border-green-500/50",children:l});case"trial":return e.jsxs(B,{className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/50",children:["Trial - ",l]});case"past_due":return e.jsxs(B,{className:"bg-rose-500/20 text-rose-400 border-rose-500/50",children:["Payment Failed - ",l]});case"cancelled":return e.jsxs(B,{className:"bg-red-500/20 text-red-400 border-red-500/50",children:["Cancelled",t?` - ${t}`:""]});default:return e.jsx(B,{variant:"secondary",children:a})}}function si(){return e.jsx(B,{variant:"outline",children:"Free"})}function _g({open:s,onOpenChange:a}){const t=Me(),[n,r]=v.useState(new Set),[i,l]=v.useState(null),[m,o]=v.useState(""),[h,N]=v.useState(null),[d,y]=v.useState(""),{data:u,isLoading:x}=ge({queryKey:["email-lists"],queryFn:async()=>{const{data:w,error:S}=await T.from("email_lists").select("id, name, description, created_at").order("created_at",{ascending:!1});if(S)throw S;return await Promise.all((w||[]).map(async C=>{const{count:O}=await T.from("email_list_members").select("*",{count:"exact",head:!0}).eq("list_id",C.id);return{...C,member_count:O||0}}))},enabled:s}),g=async w=>{const{data:S,error:P}=await T.from("email_list_members").select("id, user_id, email, display_name").eq("list_id",w).order("added_at",{ascending:!1});if(P)throw P;return S||[]},f=_e({mutationFn:async({listId:w,name:S})=>{const{error:P}=await T.from("email_lists").update({name:S,updated_at:new Date().toISOString()}).eq("id",w);if(P)throw P},onSuccess:()=>{t.invalidateQueries({queryKey:["email-lists"]}),l(null),K.success("List renamed successfully")},onError:w=>{K.error("Failed to rename list: "+w.message)}}),_=_e({mutationFn:async w=>{const{error:S}=await T.from("email_lists").delete().eq("id",w);if(S)throw S},onSuccess:()=>{t.invalidateQueries({queryKey:["email-lists"]}),N(null),K.success("List deleted successfully")},onError:w=>{K.error("Failed to delete list: "+w.message)}}),k=_e({mutationFn:async({memberId:w,listId:S})=>{const{error:P}=await T.from("email_list_members").delete().eq("id",w);if(P)throw P;return S},onSuccess:w=>{t.invalidateQueries({queryKey:["email-lists"]}),t.invalidateQueries({queryKey:["email-list-members",w]}),K.success("Member removed from list")},onError:w=>{K.error("Failed to remove member: "+w.message)}}),b=w=>{const S=new Set(n);S.has(w)?S.delete(w):S.add(w),r(S)},j=w=>{l(w.id),o(w.name)},c=()=>{i&&m.trim()&&f.mutate({listId:i,name:m.trim()})},p=u==null?void 0:u.filter(w=>{var S;return w.name.toLowerCase().includes(d.toLowerCase())||((S=w.description)==null?void 0:S.toLowerCase().includes(d.toLowerCase()))});return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-5 w-5"}),"Manage Email Lists"]})}),e.jsxs("div",{className:"relative mb-4",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search lists...",value:d,onChange:w=>y(w.target.value),className:"pl-9"})]}),e.jsx(cs,{className:"h-[400px] pr-4",children:x?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx("p",{className:"text-muted-foreground",children:"Loading lists..."})}):(p==null?void 0:p.length)===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-center",children:[e.jsx(hs,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("p",{className:"text-muted-foreground",children:d?"No lists match your search":"No email lists created yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select users in the Users tab to create a list"})]}):e.jsx("div",{className:"space-y-3",children:p==null?void 0:p.map(w=>e.jsx(bg,{list:w,isExpanded:n.has(w.id),isEditing:i===w.id,editingName:m,onToggleExpand:()=>b(w.id),onStartEdit:()=>j(w),onCancelEdit:()=>l(null),onSaveEdit:c,onEditNameChange:o,onDelete:()=>N(w.id),onRemoveMember:S=>k.mutate({memberId:S,listId:w.id}),fetchMembers:()=>g(w.id)},w.id))})})]})}),e.jsx(ws,{open:!!h,onOpenChange:()=>N(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Email List?"}),e.jsx(Ps,{children:"This will permanently delete this email list and remove all its members. This action cannot be undone."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>h&&_.mutate(h),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete List"})]})]})})]})}function bg({list:s,isExpanded:a,isEditing:t,editingName:n,onToggleExpand:r,onStartEdit:i,onCancelEdit:l,onSaveEdit:m,onEditNameChange:o,onDelete:h,onRemoveMember:N,fetchMembers:d}){const[y,u]=v.useState([]),[x,g]=v.useState(!1),[f,_]=v.useState(""),k=async()=>
248{if(!a){g(!0);try{const j=await d();u(j)}catch{K.error("Failed to load members")}finally{g(!1)}}r()},b=y.filter(j=>{var c;return j.email.toLowerCase().includes(f.toLowerCase())||((c=j.display_name)==null?void 0:c.toLowerCase().includes(f.toLowerCase()))});return e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"p-3 bg-muted/30",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(vs,{open:a,children:e.jsx(ys,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:k,children:a?e.jsx(Ns,{className:"h-4 w-4"}):e.jsx(st,{className:"h-4 w-4"})})})}),t?e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(pe,{value:n,onChange:j=>o(j.target.value),className:"h-7 text-sm",autoFocus:!0,onKeyDown:j=>{j.key==="Enter"&&m(),j.key==="Escape"&&l()}}),e.jsx(R,{size:"sm",variant:"ghost",onClick:m,children:"Save"}),e.jsx(R,{size:"sm",variant:"ghost",onClick:l,children:"Cancel"})]}):e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"font-medium",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(B,{variant:"secondary",className:"text-xs",children:[s.member_count," member",s.member_count!==1?"s":""]}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:["Created ",ke(new Date(s.created_at),"MMM d, yyyy")]})]})]})]}),!t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:i,children:e.jsx(va,{className:"h-3.5 w-3.5"})}),e.jsx(R,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:h,children:e.jsx(os,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(vs,{open:a,children:e.jsx(_s,{children:e.jsx("div",{className:"p-3 border-t bg-background",children:x?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"Loading members..."}):y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No members in this list"}):e.jsxs(e.Fragment,{children:[y.length>5&&e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Rs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search members...",value:f,onChange:j=>_(j.target.value),className:"h-7 text-xs pl-7"})]}),e.jsx("div",{className:"max-h-40 overflow-auto space-y-1",children:b.map(j=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2 rounded hover:bg-muted/50 text-sm",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:j.display_name}),e.jsx("span",{children:j.email})]}),e.jsx(R,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>N(j.id),children:e.jsx(rt,{className:"h-3 w-3"})})]},j.id))})]})})})})]})}function Vc({open:s,onOpenChange:a,selectedUsers:t,onSuccess:n}){const r=Me(),[i,l]=v.useState(""),[m,o]=v.useState(""),h=_e({mutationFn:async()=>{const{data:{user:u}}=await T.auth.getUser(),{data:x,error:g}=await T.from("email_lists").insert({name:i.trim(),description:m.trim()||null,created_by:u==null?void 0:u.id}).select().single();if(g)throw g;const _=t.filter((b,j,c)=>j===c.findIndex(p=>p.id===b.id)).map(b=>({list_id:x.id,user_id:b.id,email:b.email,display_name:b.display_name})),{error:k}=await T.from("email_list_members").insert(_);if(k)throw k;return x},onSuccess:u=>{r.invalidateQueries({queryKey:["email-lists"]}),K.success(`Created "${u.name}" with ${t.length} members`),N(),a(!1),n==null||n()},onError:u=>{K.error("Failed to create list: "+u.message)}}),N=()=>{l(""),o("")},d=u=>{u||N(),a(u)},y=i.trim().length>0&&t.length>0;return e.jsx(Ue,{open:s,onOpenChange:d,children:e.jsxs(Be,{className:"max-w-md",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"h-5 w-5"}),"Create Email List"]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"list-name",children:"List Name *"}),e.jsx(pe,{id:"list-name",placeholder:"e.g., Trial Users - January",value:i,onChange:u=>l(u.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"list-description",children:"Description (optional)"}),e.jsx(Xs,{id:"list-description",placeholder:"e.g., Users who signed up for trial in January 2026",value:m,onChange:u=>o(u.target.value),className:"min-h-[80px]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{children:["Members (",t.length," user",t.length!==1?"s":"",")"]}),e.jsx(cs,{className:"h-32 border rounded-md p-2 bg-muted/30",children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[t.slice(0,20).map(u=>e.jsx(B,{variant:"secondary",className:"text-xs",children:u.display_name||u.email},u.id)),t.length>20&&e.jsxs(B,{variant:"outline",className:"text-xs",children:["+",t.length-20," more"]})]})})]})]}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsx(R,{onClick:()=>h.mutate(),disabled:!y||h.isPending,children:h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"}),"Create List"]})})]})]})})}function wg({open:s,onOpenChange:a,selectedUsers:t,onSuccess:n}){const r=Me(),[i,l]=v.useState(null),[m,o]=v.useState(!1),{data:h,isLoading:N}=ge({queryKey:["email-lists"],queryFn:async()=>{const{data:g,error:f}=await T.from("email_lists").select("id, name").order("name");if(f)throw f;return await Promise.all((g||[]).map(async k=>{const{count:b}=await T.from("email_list_members").select("*",{count:"exact",head:!0}).eq("list_id",k.id);return{...k,member_count:b||0}}))},enabled:s}),d=_e({mutationFn:async()=>
248{if(!i)throw new Error("No list selected");const{data:g}=await T.from("email_list_members").select("user_id").eq("list_id",i),f=new Set((g==null?void 0:g.map(b=>b.user_id))||[]),_=t.filter(b=>!f.has(b.id)).map(b=>({list_id:i,user_id:b.id,email:b.email,display_name:b.display_name}));if(_.length===0)throw new Error("All selected users are already in this list");const{error:k}=await T.from("email_list_members").insert(_);if(k)throw k;return{added:_.length,skipped:t.length-_.length}},onSuccess:({added:g,skipped:f})=>{r.invalidateQueries({queryKey:["email-lists"]});const _=f>0?`Added ${g} user${g!==1?"s":""} to list (${f} already existed)`:`Added ${g} user${g!==1?"s":""} to list`;K.success(_),y(),n==null||n()},onError:g=>{K.error(g.message)}}),y=()=>{l(null),a(!1)},u=()=>{o(!1),y(),n==null||n()},x=h==null?void 0:h.find(g=>g.id===i);return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-md",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"h-5 w-5"}),"Add to Email List"]})}),e.jsxs("div",{className:"py-4",children:[e.jsx("div",{className:"mb-4",children:e.jsxs(Q,{className:"text-sm text-muted-foreground",children:["Adding ",t.length," user",t.length!==1?"s":""]})}),N?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(h==null?void 0:h.length)===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(hs,{className:"h-8 w-8 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No email lists exist yet"}),e.jsxs(R,{onClick:()=>o(!0),children:[e.jsx(Zs,{className:"mr-2 h-4 w-4"}),"Create New List"]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Q,{className:"text-sm font-medium",children:"Select a list:"}),e.jsx(cs,{className:"h-48 mt-2 border rounded-md p-2",children:e.jsx(Ut,{value:i||"",onValueChange:l,children:h==null?void 0:h.map(g=>e.jsxs("div",{className:"flex items-center space-x-3 py-2 px-2 rounded hover:bg-muted/50 cursor-pointer",onClick:()=>l(g.id),children:[e.jsx(nt,{value:g.id,id:g.id}),e.jsx(Q,{htmlFor:g.id,className:"flex-1 cursor-pointer",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:g.name}),e.jsxs(B,{variant:"secondary",className:"text-xs",children:[g.member_count," member",g.member_count!==1?"s":""]})]})})]},g.id))})}),e.jsx(is,{className:"my-4"}),e.jsxs(R,{variant:"outline",className:"w-full",onClick:()=>o(!0),children:[e.jsx(Zs,{className:"mr-2 h-4 w-4"}),"Create New List Instead"]})]})]}),h&&h.length>0&&e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:y,children:"Cancel"}),e.jsx(R,{onClick:()=>d.mutate(),disabled:!i||d.isPending,children:d.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"}),"Add to ",(x==null?void 0:x.name)||"List"]})})]})]})}),e.jsx(Vc,{open:m,onOpenChange:o,selectedUsers:t,onSuccess:u})]})}const ti=s=>{switch(s){case"banned":return"bg-red-500/20 hover:bg-red-500/30";case"flagged":return"bg-orange-500/20 hover:bg-orange-500/30";case"monitored":return"bg-yellow-500/20 hover:bg-yellow-500/30";default:return""}};function Sg(){const[s,a]=v.useState(""),[t,n]=v.useState("all"),[r,i]=v.useState("all"),[l,m]=v.useState("all"),[o,h]=v.useState("all"),[N,d]=v.useState(null),[y,u]=v.useState(!1),[x,g]=v.useState(!1),[f,_]=v.useState(null),[k,b]=v.useState(!1),[j,c]=v.useState(null),[p,w]=v.useState(null),[S,P]=v.useState(new Set),[C,O]=v.useState(!1),[$,z]=v.useState(!1),[D,A]=v.useState(!1),F=W=>{P(re=>{const ce=new Set(re);return ce.has(W)?ce.delete(W):ce.add(W),ce})},{data:q,isLoading:E}=ge({queryKey:["users",t],queryFn:async()=>{let W=T.from("user_profiles").select("id, username, full_name, avatar_url, created_at, updated_at, state_code, current_age, date_of_birth, last_login_at, display_name, experience_level, preferred_sportsbook, has_used_trial, signup_ip_address, last_known_ip_address, ip_updated_at, wants_kompete_notification").is("deleted_at",null).order("created_at",{ascending:!1});const{data:re,error:ce}=await W;if(ce)throw ce;const{data:Pe,error:Fe}=await T.from("user_roles").select("*");if(Fe)throw Fe;let Ae=[];try{const{data:Se}=await T.from("user_subscriptions").select("*, package:subscription_packages!package_id(name)").order("created_at",{ascending:!1});Ae=Se||[]}catch(Se){console.warn("Could not fetch subscriptions:",Se)}let Ve=new Set;try{const{data:Se}=await T.from("feedback_call_bookings").select("reward_subscription_id").not("reward_subscription_id","is",null),{data:ye}=await T.from("feedback_submissions").select("reward_subscription_id").not("reward_subscription_id","is",null);Se==null||Se.forEach(We=>Ve.add(We.reward_subscription_id)),ye==null||ye.forEach(We=>Ve.add(We.reward_subscription_id))}catch(Se){console.warn("Could not fetch feedback reward subscriptions:",Se)}let as={};try{const{data:Se}=await T.from("user_subscription_sports").select("subscription_id, sport_code");if(Se){const ye={};Se.forEach(We=>{ye[We.subscription_id]||(ye[We.subscription_id]=[]),ye[We.subscription_id].push(We.sport_code)}),Ae.forEach(We=>
248{ye[We.id]&&(as[We.user_id]=ye[We.id])})}}catch(Se){console.warn("Could not fetch subscription sports:",Se)}let Oe={};try{const{data:Se}=await T.from("user_ai_models").select("id, user_id, model_name, model_type, sport, is_active, created_at");Se&&Se.forEach(ye=>{Oe[ye.user_id]||(Oe[ye.user_id]=[]),Oe[ye.user_id].push({id:ye.id,model_name:ye.model_name,model_type:ye.model_type,sport:ye.sport,is_active:ye.is_active,created_at:ye.created_at})})}catch(Se){console.warn("Could not fetch models:",Se)}const Ie=()=>({count:0,wins:0,losses:0,pushes:0,pending:0,profitLoss:0,bySport:{}});let ds={};try{const{data:Se}=await T.from("user_bets").select("user_id, created_at, result, sport, amount, potential_win, bet_type").order("created_at",{ascending:!1});Se&&Se.forEach(ye=>{ds[ye.user_id]||(ds[ye.user_id]={lastAt:ye.created_at,regular:Ie(),dfs:Ie()});const ps=ye.bet_type==="dfs"?ds[ye.user_id].dfs:ds[ye.user_id].regular;ps.count++,ye.result==="win"?(ps.wins++,ye.potential_win&&(ps.profitLoss+=Number(ye.potential_win))):ye.result==="loss"?(ps.losses++,ye.amount&&(ps.profitLoss-=Number(ye.amount))):ye.result==="push"?ps.pushes++:ps.pending++,ye.sport&&(ps.bySport[ye.sport]=(ps.bySport[ye.sport]||0)+1)})}catch(Se){console.warn("Could not fetch bet stats:",Se)}let be={};try{const{data:Se}=await T.from("saved_betting_recommendations").select("user_id, result, sport").eq("tracking_status","tracked");Se&&Se.forEach(ye=>{be[ye.user_id]||(be[ye.user_id]=Ie()),be[ye.user_id].count++,ye.result==="win"?be[ye.user_id].wins++:ye.result==="loss"?be[ye.user_id].losses++:ye.result==="push"?be[ye.user_id].pushes++:be[ye.user_id].pending++,ye.sport&&(be[ye.user_id].bySport[ye.sport]=(be[ye.user_id].bySport[ye.sport]||0)+1)})}catch(Se){console.warn("Could not fetch tracked bet stats:",Se)}let Qe={};try{const{data:Se}=await T.from("dfs_generated_lineups").select("user_id, created_at, tracking_status, sport, platform").order("created_at",{ascending:!1});Se&&Se.forEach(ye=>{Qe[ye.user_id]||(Qe[ye.user_id]={count:0,lastAt:ye.created_at,saved:0,tracked:0,placed:0,bySport:{},byPlatform:{}}),Qe[ye.user_id].count++,ye.tracking_status==="saved"?Qe[ye.user_id].saved++:ye.tracking_status==="tracked"?Qe[ye.user_id].tracked++:ye.tracking_status==="bet"&&Qe[ye.user_id].placed++;const We=ye.sport||"unknown";Qe[ye.user_id].bySport[We]=(Qe[ye.user_id].bySport[We]||0)+1;const ps=ye.platform||"unknown";Qe[ye.user_id].byPlatform[ps]=(Qe[ye.user_id].byPlatform[ps]||0)+1})}catch(Se){console.warn("Could not fetch lineup stats:",Se)}let et={};try{const{data:Se}=await T.from("model_subscriptions").select("subscriber_id").eq("status","active");Se&&Se.forEach(ye=>{et[ye.subscriber_id]=(et[ye.subscriber_id]||0)+1})}catch(Se){console.warn("Could not fetch marketplace counts:",Se)}let Gs={};try{const{data:Se}=await T.from("user_onboarding_progress").select("user_id, betting_tour_completed, dfs_tour_completed, model_learning_tour_completed, draft_marketplace_tour_completed, kash_tour_completed, kommunity_tour_completed, props_tour_completed");Se&&Se.forEach(ye=>{Gs[ye.user_id]=ye})}catch(Se){console.warn("Could not fetch onboarding progress:",Se)}let xe={};try{const{data:Se}=await T.from("account_moderation_status").select("user_id, status, reason");Se&&Se.forEach(ye=>{ye.status!=="clear"&&(xe[ye.user_id]={status:ye.status,reason:ye.reason})})}catch(Se){console.warn("Could not fetch moderation statuses:",Se)}const Ce=re.map(Se=>{const ye=Pe.find(qs=>qs.user_id===Se.id),We=["active","trial","paused","past_due"],bs=Ae.filter(qs=>qs.user_id===Se.id&&We.includes(qs.status)).sort((qs,Lt)=>{const Za=We.indexOf(qs.status),Xa=We.indexOf(Lt.status);return Za!==Xa?Za-Xa:new Date(Lt.created_at).getTime()-new Date(qs.created_at).getTime()})[0]||null,Os=Ae.filter(qs=>qs.user_id===Se.id&&qs.status==="cancelled").sort((qs,Lt)=>new Date(Lt.end_date).getTime()-new Date(qs.end_date).getTime())[0]||void 0,Ft=Oe[Se.id]||[],pt=ds[Se.id],Qs=Qe[Se.id],At=(pt==null?void 0:pt.regular)||{count:0,wins:0,losses:0,pushes:0,pending:0,profitLoss:0,bySport:{}},Tt=(pt==null?void 0:pt.dfs)||{count:0,wins:0,losses:0,pushes:0,pending:0,profitLoss:0,bySport:{}},Ja=be[Se.id]||{count:0,wins:0,losses:0,pushes:0,pending:0,profitLoss:0,bySport:{}},Hs={modelCount:Ft.length,bettingModelCount:Ft.filter(qs=>qs.model_type==="betting").length,fantasyModelCount:Ft.filter(qs=>qs.model_type==="fantasy").length,betCount:At.count+Tt.count,trackedBetCount:Ja.count,lineupCount:(Qs==null?void 0:Qs.count)||0,subscribedSports:as[Se.id]||[],marketplaceSubscriptions:et[Se.id]||0,lastBetAt:(pt==null?void 0:pt.lastAt)||null,lastLineupAt:(Qs==null?void 0:Qs.lastAt)||null,models:Ft,regularBetStats:At,dfsBetStats:Tt,trackedBetStats:Ja,betWins:At.wins+Tt.wins,betL
248osses:At.losses+Tt.losses,betPushes:At.pushes+Tt.pushes,betPending:At.pending+Tt.pending,betsBySport:{...At.bySport,...Tt.bySport},totalProfitLoss:At.profitLoss+Tt.profitLoss,lineupSaved:(Qs==null?void 0:Qs.saved)||0,lineupTracked:(Qs==null?void 0:Qs.tracked)||0,lineupPlaced:(Qs==null?void 0:Qs.placed)||0,lineupWins:0,lineupLosses:0,lineupsBySport:(Qs==null?void 0:Qs.bySport)||{},lineupsByPlatform:(Qs==null?void 0:Qs.byPlatform)||{}};return{...Se,role:(ye==null?void 0:ye.role)||"user",email:Se.username,subscription:bs?{...bs,isFeedbackTrial:Ve.has(bs.id)}:null,cancelledSubscription:Os,activity:Hs,onboardingProgress:Gs[Se.id]||null,moderationStatus:xe[Se.id]||null}});return t!=="all"?Ce.filter(Se=>Se.role===t):Ce}}),L=v.useMemo(()=>{if(!q)return new Map;const W=new Map;return q.forEach(re=>{[re.signup_ip_address,re.last_known_ip_address].filter(Boolean).forEach(Pe=>{const Fe=W.get(Pe)||[];Fe.includes(re.id)||(Fe.push(re.id),W.set(Pe,Fe))})}),W},[q]),H=W=>{var Fe,Ae;const re=W.signup_ip_address&&((Fe=L.get(W.signup_ip_address))==null?void 0:Fe.length)||0,ce=W.last_known_ip_address&&((Ae=L.get(W.last_known_ip_address))==null?void 0:Ae.length)||0,Pe=Math.max(re,ce);return{isDuplicate:Pe>1,count:Pe}},Z=q==null?void 0:q.filter(W=>{var Pe,Fe,Ae,Ve,as,Oe;const re=s.toLowerCase();if(!(((Pe=W.full_name)==null?void 0:Pe.toLowerCase().includes(re))||((Fe=W.username)==null?void 0:Fe.toLowerCase().includes(re))||((Ae=W.email)==null?void 0:Ae.toLowerCase().includes(re))))return!1;if(r!=="all"){const Ie=W.subscription;switch(r){case"active":if(!Ie||Ie.status!=="active"||Ie.cancel_reason)return!1;break;case"trial":if(!Ie||Ie.status!=="trial"||Ie.cancel_reason)return!1;break;case"paused":if(!Ie||Ie.status!=="paused")return!1;break;case"cancelling":if(!Ie||!Ie.cancel_reason||Ie.status==="cancelled"||Ie.status==="paused"||Ie.status==="past_due")return!1;break;case"cancelled":if(Ie||!W.cancelledSubscription)return!1;break;case"past_due":if(!Ie||Ie.status!=="past_due")return!1;break;case"free":if(Ie)return!1;break}}if(l!=="all"){const Ie=((Ve=W.subscription)==null?void 0:Ve.cancel_outreach_status)||"pending";if(!((as=W.subscription)!=null&&as.cancel_reason)||Ie!==l)return!1}if(o!=="all"){if(o==="none"){if(W.moderationStatus)return!1}else if(((Oe=W.moderationStatus)==null?void 0:Oe.status)!==o)return!1}return!0}),se=v.useMemo(()=>!Z||!p?Z:[...Z].sort((W,re)=>{var Pe,Fe,Ae,Ve;let ce=0;switch(p.column){case"user":const as=W.full_name||W.username||W.email||"",Oe=re.full_name||re.username||re.email||"";ce=as.localeCompare(Oe);break;case"role":ce=(W.role||"").localeCompare(re.role||"");break;case"subscription":const Ie=Gs=>{if(!Gs.subscription)return 0;const xe=Gs.subscription.status;return xe==="active"?5:xe==="trial"?4:xe==="paused"?3:xe==="past_due"?2:xe==="cancelled"?1:0};ce=Ie(W)-Ie(re);break;case"lastLogin":const ds=W.last_login_at?new Date(W.last_login_at).getTime():0,be=re.last_login_at?new Date(re.last_login_at).getTime():0;ce=ds-be;break;case"activity":const Qe=(((Pe=W.activity)==null?void 0:Pe.betCount)||0)+(((Fe=W.activity)==null?void 0:Fe.lineupCount)||0),et=(((Ae=re.activity)==null?void 0:Ae.betCount)||0)+(((Ve=re.activity)==null?void 0:Ve.lineupCount)||0);ce=Qe-et;break}return p.direction==="desc"?-ce:ce}),[Z,p]),ie=()=>{if(!se)return;const W=se.every(re=>S.has(re.id));P(W?new Set:new Set(se.map(re=>re.id)))},Y=se&&se.length>0&&se.every(W=>S.has(W.id)),I=S.size>0,ee=v.useMemo(()=>se?se.filter(W=>S.has(W.id)).map(W=>({id:W.id,email:W.email||W.username||"",display_name:W.display_name||W.full_name||null})):[],[se,S]),le=W=>{const re=(se==null?void 0:se.filter(ce=>S.has(ce.id)).map(ce=>ce.email||ce.username).filter(Boolean))||[];if(re.length===0){K.error("No emails to export");return}if(W==="clipboard")navigator.clipboard.writeText(re.join(", ")),K.success(`${re.length} emails copied to clipboard!`);else if(W==="newline")navigator.clipboard.writeText(re.join(`
249`)),K.success(`${re.length} emails copied as list!`);else if(W==="csv"){const ce=`Email
250`+re.join(`
251`),Pe=new Blob([ce],{type:"text/csv"}),Fe=URL.createObjectURL(Pe),Ae=document.createElement("a");Ae.href=Fe,Ae.download=`user-emails-${new Date().toISOString().split("T")[0]}.csv`,Ae.click(),URL.revokeObjectURL(Fe),K.success(`Downloaded ${re.length} emails as CSV!`)}},ve=W=>{(p==null?void 0:p.column)===W?p.direction==="asc"?w({column:W,direction:"desc"}):w(null):w({column:W,direction:"asc"})},te=({column:W,label:re})=>{const ce=(p==null?void 0:p.column)===W,Pe=ce?p.direction:null;return e.jsx(U,{className:"cursor-pointer hover:bg-muted/50 select-none transition-colors",onClick:()=>ve(W),children:e.jsxs("div",{className:"flex items-center gap-1",children:[re,ce?Pe==="asc"?e.jsx(Ua,{className:"h-4 w-4"}):e.jsx(Ns,{className:"h-4 w-4"}
251):e.jsx(dc,{className:"h-4 w-4 text-muted-foreground/50"})]})})},X=W=>{d(W),u(!0)},ae=W=>{if(!W)return"Never";try{return ha(new Date(W),"America/Chicago","MMM dd, yyyy h:mm a")+" CST"}catch{return"Unknown"}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:W=>a(W.target.value),className:"pl-9"})]}),e.jsxs(oe,{value:t,onValueChange:W=>n(W),children:[e.jsx(de,{className:"w-full sm:w-[150px]",children:e.jsx(ue,{placeholder:"Filter by role"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Roles"}),e.jsx(V,{value:"user",children:"User"}),e.jsx(V,{value:"admin",children:"Admin"}),e.jsx(V,{value:"super_admin",children:"Super Admin"})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs(oe,{value:r,onValueChange:W=>i(W),children:[e.jsx(de,{className:"w-full sm:w-[180px]",children:e.jsx(ue,{placeholder:"Subscription status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Subscriptions"}),e.jsx(V,{value:"active",children:"Active (Paid)"}),e.jsx(V,{value:"trial",children:"Trial"}),e.jsx(V,{value:"paused",children:"Paused"}),e.jsx(V,{value:"cancelling",children:"Cancelling"}),e.jsx(V,{value:"cancelled",children:"Cancelled"}),e.jsx(V,{value:"past_due",children:"Past Due"}),e.jsx(V,{value:"free",children:"Free"})]})]}),e.jsxs(oe,{value:l,onValueChange:W=>m(W),children:[e.jsx(de,{className:"w-full sm:w-[180px]",children:e.jsx(ue,{placeholder:"Outreach status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Outreach"}),e.jsx(V,{value:"pending",children:"Pending"}),e.jsx(V,{value:"first_attempt",children:"First Attempt"}),e.jsx(V,{value:"second_attempt",children:"Second Attempt"}),e.jsx(V,{value:"responded",children:"Responded"}),e.jsx(V,{value:"closed",children:"Closed"})]})]}),e.jsxs(oe,{value:o,onValueChange:W=>h(W),children:[e.jsx(de,{className:"w-full sm:w-[180px]",children:e.jsx(ue,{placeholder:"Moderation status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Moderation"}),e.jsx(V,{value:"none",children:"No Action"}),e.jsx(V,{value:"monitored",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-yellow-500"}),"Monitored"]})}),e.jsx(V,{value:"flagged",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-orange-500"}),"Flagged"]})}),e.jsx(V,{value:"banned",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"Banned"]})})]})]})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>O(!0),children:[e.jsx(hs,{className:"h-4 w-4 mr-2"}),"View Email Lists"]})}),I&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[e.jsxs("span",{className:"text-sm font-medium",children:[S.size," user",S.size!==1?"s":""," selected"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(R,{variant:"default",size:"sm",onClick:()=>z(!0),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Create Email List"]}),e.jsxs(R,{variant:"secondary",size:"sm",onClick:()=>A(!0),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Add to List"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>le("clipboard"),children:[e.jsx(vt,{className:"h-4 w-4 mr-2"}),"Copy Emails"]}
251),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>le("newline"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Copy as List"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>le("csv"),children:[e.jsx(Gt,{className:"h-4 w-4 mr-2"}),"Export CSV"]}),e.jsxs(R,{variant:"ghost",size:"sm",onClick:()=>P(new Set),children:[e.jsx(rt,{className:"h-4 w-4 mr-1"}),"Clear"]})]})]}),e.jsx("div",{className:"hidden md:block border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-[50px]",children:e.jsx(Ms,{checked:Y,onCheckedChange:ie,"aria-label":"Select all"})}),e.jsx(te,{column:"user",label:"User"}),e.jsx(te,{column:"role",label:"Role"}),e.jsx(te,{column:"subscription",label:"Subscription"}),e.jsx(te,{column:"lastLogin",label:"Last Login (CST)"}),e.jsx(te,{column:"activity",label:"Activity"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:E?Array.from({length:5}).map((W,re)=>e.jsxs(he,{children:[e.jsx(M,{children:e.jsx(gs,{className:"h-10 w-full"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-6 w-20"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-6 w-24"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-32"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-24"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-8 w-20 ml-auto"})})]},re)):se&&se.length>0?se.map(W=>{var re,ce,Pe,Fe,Ae,Ve,as,Oe,Ie,ds,be,Qe,et,Gs,xe,Ce,Se,ye;return e.jsxs(he,{className:ti((re=W.moderationStatus)==null?void 0:re.status),children:[e.jsx(M,{children:e.jsx(Ms,{checked:S.has(W.id),onCheckedChange:()=>F(W.id),"aria-label":`Select ${W.full_name||W.email}`})}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ua,{children:[e.jsx(ma,{src:W.avatar_url||void 0}),e.jsx(xa,{children:((ce=W.full_name)==null?void 0:ce.charAt(0))||((Pe=W.username)==null?void 0:Pe.charAt(0))||((Fe=W.email)==null?void 0:Fe.charAt(0))||"U"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"font-medium",children:W.full_name||W.username||"Unnamed User"}),e.jsx(Ia,{userId:W.id,size:"xs",showTooltip:!0}),W.wants_kompete_notification&&e.jsx("span",{title:"Wants Kompete notifications",children:e.jsx(Js,{className:"w-4 h-4 text-yellow-500"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W.email||"No email"}),(W.current_age||W.state_code)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:[W.current_age?`${W.current_age}yo`:null,W.state_code].filter(Boolean).join(" • ")}),W.signup_ip_address&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("p",{className:"text-xs text-muted-foreground font-mono",title:`Last: ${W.last_known_ip_address||"Same"}`,children:["IP: ",W.signup_ip_address]}),H(W).isDuplicate&&e.jsxs(B,{variant:"destructive",className:"text-[10px] px-1 py-0 h-4",children:[H(W).count," users"]})]})]})]})}),e.jsx(M,{children:e.jsx(zn,{userId:W.id,currentRole:W.role,userEmail:W.email})}),e.jsx(M,{children:e.jsx("div",{className:"flex gap-1 flex-wrap",children:W.subscription?$r({status:W.subscription.status,packageName:(Ae=W.subscription.package)==null?void 0:Ae.name,cancelReason:W.subscription.cancel_reason,pausedAt:W.subscription.paused_at,isFeedbackTrial:W.subscription.isFeedbackTrial}):e.jsxs(e.Fragment,{children:[W.cancelledSubscription&&$r({status:"cancelled",packageName:(Ve=W.cancelledSubscription.package)==null?void 0:Ve.name}),si()]})})}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx($s,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs",children:ae(W.last_login_at||null)})]})}),e.jsx(M,{children:e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[(((as=W.activity)==null?void 0:as.modelCount)??0)>0&&e.jsxs(B,{variant:"outline",className:"text-xs",children:[((Oe=W.activity)==null?void 0:Oe.bettingModelCount)||0,"🎰 ",((Ie=W.activity)==null?void 0:Ie.fantasyModelCount)||0,"🏈"]}),(((ds=W.activity)==null?void 0:ds.betCount)??0)+(((be=W.activity)==null?void 0:be.trackedBetCount)??0)>0&&e.jsxs(B,{variant:"outline",className:"text-xs",children:[((Qe=W.activity)==null?void 0:Qe.betCount)||0,"📤 ",((et=W.activity)==null?void 0:et.trackedBetCount)||0,"👁️"]}),(((Gs=W.activity)==null?void 0:Gs.lineupCount)??0)>0&&e.jsxs(B,{variant:"outline",className:"text-xs",children:[(xe=W.activity)==null?void 0:xe.lineupCount," lineups"]})]})}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>{_(W),g(!0)},title:W.moderationStatus?`${W.moderationStatus.status.charAt(0).toUpperCase()+W.moderationStatus.status.slice(1)}: ${W.moderationStatus.reason||"No reason"}
251`:"Moderate account",className:((Ce=W.moderationStatus)==null?void 0:Ce.status)==="banned"?"text-red-500 hover:text-red-600":((Se=W.moderationStatus)==null?void 0:Se.status)==="flagged"?"text-orange-500 hover:text-orange-600":((ye=W.moderationStatus)==null?void 0:ye.status)==="monitored"?"text-yellow-500 hover:text-yellow-600":"",children:e.jsx(Hr,{className:"h-4 w-4"})}),e.jsxs(R,{variant:"ghost",size:"sm",onClick:()=>X(W),children:[e.jsx(us,{className:"h-4 w-4 mr-2"}),"View"]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>{c(W),b(!0)},title:"Delete Account",className:"text-muted-foreground hover:text-destructive",children:e.jsx(os,{className:"h-4 w-4"})})]})})]},W.id)}):e.jsx(he,{children:e.jsx(M,{colSpan:7,className:"text-center text-muted-foreground py-8",children:"No users found"})})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:E?Array.from({length:3}).map((W,re)=>e.jsx(G,{children:e.jsxs(J,{className:"p-4 space-y-3",children:[e.jsx(gs,{className:"h-10 w-full"}),e.jsx(gs,{className:"h-4 w-3/4"}),e.jsx(gs,{className:"h-6 w-1/2"})]})},re)):Z&&Z.length>0?Z.map(W=>{var re,ce,Pe,Fe,Ae,Ve,as,Oe,Ie,ds,be,Qe,et,Gs,xe;return e.jsx(G,{className:ti((re=W.moderationStatus)==null?void 0:re.status),children:e.jsxs(J,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ms,{checked:S.has(W.id),onCheckedChange:()=>F(W.id),"aria-label":`Select ${W.full_name||W.email}`}),e.jsxs(ua,{children:[e.jsx(ma,{src:W.avatar_url||void 0}),e.jsx(xa,{children:((ce=W.full_name)==null?void 0:ce.charAt(0))||((Pe=W.username)==null?void 0:Pe.charAt(0))||((Fe=W.email)==null?void 0:Fe.charAt(0))||"U"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"font-medium truncate",children:W.full_name||W.username||"Unnamed User"}),e.jsx(Ia,{userId:W.id,size:"xs",showTooltip:!0})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:W.email||"No email"}),(W.current_age||W.state_code)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:[W.current_age?`${W.current_age}yo`:null,W.state_code].filter(Boolean).join(" • ")}),W.signup_ip_address&&e.jsxs("p",{className:"text-xs text-muted-foreground font-mono",title:`Last: ${W.last_known_ip_address||"Same"}`,children:["IP: ",W.signup_ip_address]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(zn,{userId:W.id,currentRole:W.role,userEmail:W.email}),W.subscription?$r({status:W.subscription.status,packageName:(Ae=W.subscription.package)==null?void 0:Ae.name,cancelReason:W.subscription.cancel_reason,pausedAt:W.subscription.paused_at,isFeedbackTrial:W.subscription.isFeedbackTrial}):si()]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx($s,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:ae(W.last_login_at||null)})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[(((Ve=W.activity)==null?void 0:Ve.modelCount)??0)>0&&e.jsxs(B,{variant:"outline",className:"text-xs",children:[((as=W.activity)==null?void 0:as.bettingModelCount)||0,"🎰 ",((Oe=W.activity)==null?void 0:Oe.fantasyModelCount)||0,"🏈"]}),(((Ie=W.activity)==null?void 0:Ie.betCount)??0)+(((ds=W.activity)==null?void 0:ds.trackedBetCount)??0)>0&&e.jsxs(B,{variant:"outline",className:"text-xs",children:[((be=W.activity)==null?void 0:be.betCount)||0,"📤 ",((Qe=W.activity)==null?void 0:Qe.trackedBetCount)||0,"👁️"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>{_(W),g(!0)},className:((et=W.moderationStatus)==null?void 0:et.status)==="banned"?"text-red-500":((Gs=W.moderationStatus)==null?void 0:Gs.status)==="flagged"?"text-orange-500":((xe=W.moderationStatus)==null?void 0:xe.status)==="monitored"?"text-yellow-500":"",children:e.jsx(Hr,{className:"h-4 w-4"})}),e.jsxs(R,{variant:"ghost",size:"sm",onClick:()=>X(W),children:[e.jsx(us,{className:"h-4 w-4 mr-2"}),"View"]}
251),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>{c(W),b(!0)},className:"text-muted-foreground hover:text-destructive",children:e.jsx(os,{className:"h-4 w-4"})})]})]})]})},W.id)}):e.jsx(G,{children:e.jsx(J,{className:"p-8 text-center text-muted-foreground",children:"No users found"})})}),e.jsx(fg,{user:N,open:y,onOpenChange:u}),e.jsx(vg,{user:f,open:x,onOpenChange:g}),e.jsx(Ng,{user:j,open:k,onOpenChange:b}),e.jsx(_g,{open:C,onOpenChange:O}),e.jsx(Vc,{open:$,onOpenChange:z,selectedUsers:ee,onSuccess:()=>P(new Set)}),e.jsx(wg,{open:D,onOpenChange:A,selectedUsers:ee,onSuccess:()=>P(new Set)})]})}const kg={award:Mt,target:As,flame:Oa,brain:it,trophy:Js,star:Wt,trending_up:Ds,users:hs},Cg=["Bronze","Silver","Gold","Platinum"];function Pg({name:s,icon:a,tierColors:t}){const n=kg[a.toLowerCase()]||Mt;return e.jsx("div",{className:"flex flex-wrap gap-4 justify-center",children:[1,2,3,4].map(r=>{const i=t[String(r)]||"#888888";return e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsxs("div",{className:"relative h-16 w-16 rounded-full flex items-center justify-center",style:{background:`linear-gradient(135deg, ${i} 0%, ${Fg(i,-20)} 100%)`,boxShadow:`0 4px 12px ${i}40`},children:[e.jsx(n,{className:"h-8 w-8 text-white"}),e.jsx("div",{className:"absolute -bottom-1 -right-1 h-6 w-6 rounded-full bg-background border-2 flex items-center justify-center text-xs font-bold",style:{borderColor:i,color:i},children:r})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:s||"Badge Name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Cg[r-1]})]})]},r)})})}function Fg(s,a){const t=parseInt(s.replace("#",""),16),n=Math.round(2.55*a),r=Math.max(0,Math.min(255,(t>>16)+n)),i=Math.max(0,Math.min(255,(t>>8&255)+n)),l=Math.max(0,Math.min(255,(t&255)+n));return`#${(16777216+r*65536+i*256+l).toString(16).slice(1)}`}const Ag=[{value:"betting",label:"Betting"},{value:"models",label:"Models"},{value:"streak",label:"Streak"},{value:"accuracy",label:"Accuracy"},{value:"roi",label:"ROI"},{value:"social",label:"Social"}],ai=[{value:"award",label:"Award",icon:Mt},{value:"target",label:"Target",icon:As},{value:"flame",label:"Flame",icon:Oa},{value:"brain",label:"Brain",icon:it},{value:"trophy",label:"Trophy",icon:Js},{value:"star",label:"Star",icon:Wt},{value:"trending_up",label:"Trending Up",icon:Ds},{value:"users",label:"Users",icon:hs}],Tg=[{value:"count",label:"Count"},{value:"streak",label:"Streak"},{value:"accuracy",label:"Accuracy (%)"},{value:"roi",label:"ROI (%)"}],Lg={1:"#CD7F32",2:"#C0C0C0",3:"#FFD700",4:"#E5E4E2"},Eg=["Bronze","Silver","Gold","Platinum"];function Dg({initialData:s,onSubmit:a,onCancel:t,isSubmitting:n}){const[r,i]=v.useState({id:(s==null?void 0:s.id)||"",name:(s==null?void 0:s.name)||"",description:(s==null?void 0:s.description)||"",category:(s==null?void 0:s.category)||"betting",icon:(s==null?void 0:s.icon)||"award",trigger_type:(s==null?void 0:s.trigger_type)||"count",trigger_field:(s==null?void 0:s.trigger_field)||"",points_reward:(s==null?void 0:s.points_reward)||10,tier_thresholds:(s==null?void 0:s.tier_thresholds)||{1:5,2:15,3:30,4:50},tier_colors:(s==null?void 0:s.tier_colors)||Lg,is_active:(s==null?void 0:s.is_active)??!0,display_order:(s==null?void 0:s.display_order)||0}),l=!!(s!=null&&s.id),m=(d,y)=>{i(u=>({...u,[d]:y}))},o=(d,y)=>{const u=parseInt(y)||0;i(x=>({...x,tier_thresholds:{...x.tier_thresholds,[d]:u}}))},h=(d,y)=>{i(u=>({...u,tier_colors:{...u.tier_colors,[d]:y}}))},N=d=>{d.preventDefault(),a(r)};return e.jsxs("form",{onSubmit:N,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Basic Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"id",children:"Badge ID"}
251),e.jsx(pe,{id:"id",value:r.id,onChange:d=>m("id",d.target.value.toLowerCase().replace(/\s+/g,"_")),placeholder:"e.g., hot_streak",disabled:l,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique identifier (snake_case)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"name",children:"Display Name"}),e.jsx(pe,{id:"name",value:r.name,onChange:d=>m("name",d.target.value),placeholder:"e.g., Hot Streak",required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"description",children:"Description"}),e.jsx(Xs,{id:"description",value:r.description,onChange:d=>m("description",d.target.value),placeholder:"Describe what this badge represents...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Category"}),e.jsxs(oe,{value:r.category,onValueChange:d=>m("category",d),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:Ag.map(d=>e.jsx(V,{value:d.value,children:d.label},d.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Icon"}),e.jsxs(oe,{value:r.icon,onValueChange:d=>m("icon",d),children:[e.jsx(de,{children:e.jsx(ue,{children:(()=>{const d=ai.find(y=>y.value===r.icon);if(d){const y=d.icon;return e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(y,{className:"h-4 w-4"}),d.label]})}return"Select an icon"})()})}),e.jsx(me,{children:ai.map(d=>{const y=d.icon;return e.jsx(V,{value:d.value,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(y,{className:"h-4 w-4"}),d.label]})},d.value)})})]})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Trigger Configuration"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Trigger Type"}),e.jsxs(oe,{value:r.trigger_type,onValueChange:d=>m("trigger_type",d),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:Tg.map(d=>e.jsx(V,{value:d.value,children:d.label},d.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"trigger_field",children:"Trigger Field"}),e.jsx(pe,{id:"trigger_field",value:r.trigger_field,onChange:d=>m("trigger_field",d.target.value),placeholder:"e.g., current_streak"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Database field to track"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"points_reward",children:"Points Per Tier"}),e.jsx(pe,{id:"points_reward",type:"number",min:0,value:r.points_reward,onChange:d=>m("points_reward",parseInt(d.target.value)||0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"display_order",children:"Display Order"}),e.jsx(pe,{id:"display_order",type:"number",min:0,value:r.display_order,onChange:d=>m("display_order",parseInt(d.target.value)||0)})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Tier Thresholds & Colors"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(d=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-10 w-10 rounded-full mx-auto mb-1",style:{backgroundColor:r.tier_colors[String(d)]}}),e.jsx("span",{className:"text-sm font-medium",children:Eg[d-1]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-xs",children:"Threshold"}),e.jsx(pe,{type:"number",min:0,value:r.tier_thresholds[String(d)]||0,onChange:y=>o(String(d),y.target.value),className:"text-center"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-xs",children:"Color"}),e.jsx(pe,{type:"color",value:r.tier_colors[String(d)]||"#888888",onChange:y=>h(String(d),y.target.value),className:"h-10 p-1 cursor-pointer"})]})]},d))})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Preview"}),e.jsx(Pg,{name:r.name,icon:r.icon,tierColors:r.tier_colors})]}),e.jsx(is,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Q,{children:"Active"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enable this badge for users to earn"})]}),e.jsx(Ge,{checked:r.is_active,onCheckedChange:d=>m("is_active",d)})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(R,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(R,{type:"submit",disabled:n,children:n?"Saving...":l?"Update Badge":"Create Badge"})]})]})}const Mg={award:Mt,target:As,flame:Oa,brain:it,trophy:Js,star:Wt,trending_up:Ds,users:hs};function Ig(){const s=Me(),[a,t]=v.useState(!1),[n,r]=v.useState(null),[i,l]=v.useState(null),[m,o]=v.useState(0),h=async c=>{const{count:p}=await T.from("user_badges").select("*",{count:"exact",head:!0}).eq("badge_id",c.id);o(p||0),l(c)},{data:N,isLoading:d}=ge({queryKey:["badge-definitions"],queryFn:async()=>{const{data:c,error:p}=await T.from("badge_definitions").select("*").order("display_order",{ascending:!0});if(p)throw p;return c}}),{data:y}=ge({queryKey:["badge-stats"],queryFn:async()=>{const{count:c}=await T.from("user_badges").select("*",{count:"exact",head:!0});return{totalEarned:c||0}}}),u=_e({mutationFn:async c=>{const{error:p}=await T.from("badge_definitions").insert({id:c.id,name:c.name,description:c.description,category:c.category,icon:c.icon,trigger_type:c.trigger_type,trigger_field:c.trigger_field,points_reward:c.points_reward,tier_thresholds:c.tier_thresholds,tier_colors:c.tier_colors,is_active:c.is_active,display_order:c.display_order});if(p)throw p},onSuccess:()=>{s.invalidateQueries({queryKey:["badge-definitions"]}),K.success("Badge created successfully"),t(!1)},onError:c=>{K.error(`Failed to create badge: ${c.message}`)}}),x=_e({mutationFn:async({id:c,data:p})=>{const{error:w}=await T.from("badge_definitions").update({name:p.name,description:p.description,category:p.category,icon:p.icon,trigger_type:p.trigger_type,trigger_field:p.trigger_field,points_reward:p.points_reward,tier_thresholds:p.tier_thresholds,tier_colors:p.tier_colors,is_active:p.is_active,display_order:p.display_order}).eq("id",c);if(w)throw w},onSuccess:()=>{s.invalidateQueries({queryKey:["badge-definitions"]}),K.success("Badge updated successfully"),t(!1),r(null)},onError:c=>{K.error(`Failed to update badge: ${c.message}`)}}),g=_e({mutationFn:async c=>{const{error:p}=await T.from("badge_definitions").delete().eq("id",c);if(p)throw p},onSuccess:()=>{s.invalidateQueries({queryKey:["badge-definitions"]}),K.success("Badge deleted successfully"),l(null)},onError:c=>{K.error(`Failed to delete badge: ${c.message}`)}}),f=c=>{r(c),t(!0)},_=c=>{n?x.mutate({id:n.id,data:c}):u.mutate(c)},k=()=>{t(!1),r(null)},b=c=>c?Mg[c.toLowerCase()]||Mt:Mt,j=(N==null?void 0:N.filter(c=>c.is_active))||[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(G,{children:[e.jsx(je,{className:"pb-2",children:e.jsx(fe,{className:"text-sm font-medium text-muted-foreground",children:"Total Achievements"})}),e.jsx(J,{children:e.jsx("div",{className:"text-2xl font-bold",children:(N==null?void 0:N.length)||0})})]}),e.jsxs(G,{children:[e.jsx(je,{className:"pb-2",children:e.jsx(fe,{className:"text-sm font-medium text-muted-foreground",children:"Active Achievements"})}),e.jsx(J,{children:e.jsx("div",{className:"text-2xl font-bold text-primary",children:j.length})})]}),e.jsxs(G,{children:[e.jsx(je,{className:"pb-2",children:e.jsx(fe,{className:"text-sm font-medium text-muted-foreground",children:"Total Earned"})}),e.jsx(J,{children:e.jsx("div",{className:"text-2xl font-bold",children:(y==null?void 0:y.totalEarned)||0})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(R,{onClick:()=>t(!0),className:"gap-2",children:[e.jsx(Zs,{className:"h-4 w-4"}),"Create Achievement"]})}),e.jsx(G,{children:e.jsx(J,{className:"p-0",children:d?e.jsx("div",{className:"space-y-3 p-4",children:[...Array(5)].map((c,p)=>e.jsx(gs,{className:"h-14 w-full"},p))}):N!=null&&N.length?e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-16",children:"Icon"}),e.jsx(U,{children:"Name"}),e.jsx(U,{children:"Category"}),e.jsx(U,{children:"Trigger"}),e.jsx(U,{className:"text-center",children:"Tiers"}),e.jsx(U,{className:"text-right",children:"Points"}),e.jsx(U,{className:"text-center",children:"Status"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:N.map(c=>{const p=b(c.icon),w=c.tier_thresholds?Object.keys(c.tier_thresholds).length:0;return e.jsxs(he,{children:[e.jsx(M,{children:e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(p,{className:"h-5 w-5 text-primary"})})}),e.jsx(M,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:c.name}),e.jsx("p",{className:"text-sm text-muted-foreground truncate max-w-[200px]",children:c.description})]})}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:"capitalize",children:c.category||"general"})}),e.jsx(M,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:c.trigger_type||"-"})}),e.jsx(M,{className:"text-center",children:e.jsx("div",{className:"flex items-center justify-center gap-1",children:w>0?Array.from({length:w}).map((S,P)=>{var O;const C=((O=c.tier_colors)==null?void 0:O[String(P+1)])||"#888";return e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:C}},P)}
251):e.jsx("span",{className:"text-muted-foreground",children:"-"})})}),e.jsx(M,{className:"text-right",children:c.points_reward||0}),e.jsx(M,{className:"text-center",children:e.jsx(B,{variant:c.is_active?"default":"secondary",children:c.is_active?"Active":"Inactive"})}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>f(c),children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>h(c),children:e.jsx(os,{className:"h-4 w-4"})})]})})]},c.id)})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Mt,{className:"h-12 w-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"No achievements defined yet."}),e.jsx("p",{className:"text-sm",children:"Create your first achievement to get started!"})]})})}),e.jsx(Ue,{open:a,onOpenChange:k,children:e.jsxs(Be,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:n?"Edit Achievement":"Create Achievement"})}),e.jsx(Dg,{initialData:n,onSubmit:_,onCancel:k,isSubmitting:u.isPending||x.isPending})]})}),e.jsx(ws,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Achievement"}),e.jsx(Ps,{asChild:!0,children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{children:['Are you sure you want to delete the "',i==null?void 0:i.name,'" achievement? This action cannot be undone.']}),m>0&&e.jsxs("p",{className:"font-medium text-destructive",children:["⚠️ This badge has been earned by ",m," user",m!==1?"s":"",". Deleting it will remove it from all users."]})]})})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>i&&g.mutate(i.id),children:"Delete"})]})]})})]})}const ri=[{value:"user",label:"User",icon:oa},{value:"target",label:"Target",icon:As},{value:"star",label:"Star",icon:Wt},{value:"crown",label:"Crown",icon:Gn},{value:"trophy",label:"Trophy",icon:Js},{value:"award",label:"Award",icon:Mt},{value:"shield",label:"Shield",icon:Sr},{value:"zap",label:"Zap",icon:ra},{value:"flame",label:"Flame",icon:Oa},{value:"diamond",label:"Diamond",icon:wd}],Rg={id:"",name:"",description:"",min_points:0,icon:"user",color:"#6B7280",gradient_from:"#6B7280",gradient_to:"#9CA3AF",display_order:1,is_active:!0};function qg({initialData:s,onSubmit:a,onCancel:t,isSubmitting:n,isEditing:r=!1}){const[i,l]=v.useState(s||Rg),m=(N,d)=>{l(y=>({...y,[N]:d}))},o=N=>{N.preventDefault(),a(i)},h={id:i.id,name:i.name||"Preview",description:i.description,min_points:i.min_points,icon:i.icon,color:i.color,gradient_from:i.gradient_from,gradient_to:i.gradient_to,display_order:i.display_order};return e.jsxs("form",{onSubmit:o,className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsx(Ia,{tier:h,size:"lg",showTooltip:!1}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-semibold",children:i.name||"Tier Name"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.min_points.toLocaleString(),"+ points"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"id",children:"Tier ID"}),e.jsx(pe,{id:"id",value:i.id,onChange:N=>m("id",N.target.value.toLowerCase().replace(/\s/g,"_")),placeholder:"rookie",disabled:r}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique identifier (cannot change after creation)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"name",children:"Display Name"}),e.jsx(pe,{id:"name",value:i.name,onChange:N=>m("name",N.target.value),placeholder:"Rookie"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"description",children:"Description"}),e.jsx(Xs,{id:"description",value:i.description,onChange:N=>m("description",N.target.value),placeholder:"What this tier represents...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"min_points",children:"Minimum Points"}),e.jsx(pe,{id:"min_points",type:"number",value:i.min_points,onChange:N=>m("min_points",parseInt(N.target.value)||0),min:0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"display_order",children:"Display Order"}),e.jsx(pe,{id:"display_order",type:"number",value:i.display_order,onChange:N=>m("display_order",parseInt(N.target.value)||1),min:1})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"icon",children:"Icon"}),e.jsxs(oe,{value:i.icon,onValueChange:N=>m("icon",N),children:[e.jsx(de,{children:e.jsx(ue,{children:(()=>{const N=ri.find(d=>d.value===i.icon);if(N){const d=N.icon;return e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(d,{className:"h-4 w-4"}),N.label]})}return"Select an icon"})()})}),e.jsx(me,{children:ri.map(N=>{const d=N.icon;return e.jsx(V,{value:N.value,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(d,{className:"h-4 w-4"}),N.label]})},N.value)})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"color",children:"Base Color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",id:"color",value:i.color,onChange:N=>m("color",N.target.value),className:"w-12 h-10 p-1 cursor-pointer"}),e.jsx(pe,{value:i.color,onChange:N=>m("color",N.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"gradient_from",children:"Gradient From"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",id:"gradient_from",value:i.gradient_from,onChange:N=>m("gradient_from",N.target.value),className:"w-12 h-10 p-1 cursor-pointer"}),e.jsx(pe,{value:i.gradient_from,onChange:N=>m("gradient_from",N.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"gradient_to",children:"Gradient To"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",id:"gradient_to",value:i.gradient_to,onChange:N=>m("gradient_to",N.target.value),className:"w-12 h-10 p-1 cursor-pointer"}),e.jsx(pe,{value:i.gradient_to,onChange:N=>m("gradient_to",N.target.value),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{htmlFor:"is_active",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this tier to users"})]}),e.jsx(Ge,{id:"is_active",checked:i.is_active,onCheckedChange:N=>m("is_active",N)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(R,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(R,{type:"submit",disabled:n||!i.id||!i.name,children:n?"Saving...":r?"Update Tier":"Create Tier"})]})]})}function $g(){const s=Me(),[a,t]=v.useState(!1),[n,r]=v.useState(null),[i,l]=v.useState(null),{data:m,isLoading:o}=ge({queryKey:["admin-user-tiers"],queryFn:async()=>{const{data:k,error:b}=await T.from("user_tiers").select("*").order("display_order",{ascending:!0});if(b)throw b;return k}}),{data:h}=ge({queryKey:["tier-user-stats"],queryFn:async()=>{const{data:k,error:b}=await T.from("user_points").select("lifetime_points");if(b)throw b;const j={};return m&&(m.forEach(c=>{j[c.id]=0}
251),k==null||k.forEach(c=>{const p=c.lifetime_points??0,S=[...m].sort((P,C)=>C.min_points-P.min_points).find(P=>p>=P.min_points);S&&(j[S.id]=(j[S.id]||0)+1)})),j},enabled:!!m}),N=_e({mutationFn:async k=>{const{error:b}=await T.from("user_tiers").insert({id:k.id,name:k.name,description:k.description,min_points:k.min_points,icon:k.icon,color:k.color,gradient_from:k.gradient_from,gradient_to:k.gradient_to,display_order:k.display_order,is_active:k.is_active});if(b)throw b},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-user-tiers"]}),s.invalidateQueries({queryKey:["user-tiers"]}),K.success("Tier created successfully"),t(!1)},onError:k=>{K.error(`Failed to create tier: ${k.message}`)}}),d=_e({mutationFn:async k=>{const{error:b}=await T.from("user_tiers").update({name:k.name,description:k.description,min_points:k.min_points,icon:k.icon,color:k.color,gradient_from:k.gradient_from,gradient_to:k.gradient_to,display_order:k.display_order,is_active:k.is_active}).eq("id",n==null?void 0:n.id);if(b)throw b},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-user-tiers"]}),s.invalidateQueries({queryKey:["user-tiers"]}),K.success("Tier updated successfully"),r(null),t(!1)},onError:k=>{K.error(`Failed to update tier: ${k.message}`)}}),y=_e({mutationFn:async k=>{const{error:b}=await T.from("user_tiers").delete().eq("id",k);if(b)throw b},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-user-tiers"]}),s.invalidateQueries({queryKey:["user-tiers"]}),K.success("Tier deleted successfully"),l(null)},onError:k=>{K.error(`Failed to delete tier: ${k.message}`)}}),u=_e({mutationFn:async({id:k,is_active:b})=>{const{error:j}=await T.from("user_tiers").update({is_active:b}).eq("id",k);if(j)throw j},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-user-tiers"]}),s.invalidateQueries({queryKey:["user-tiers"]})}}),x=k=>{r(k),t(!0)},g=()=>{t(!1),r(null)},f=k=>{n?d.mutate(k):N.mutate(k)},_=h?Object.values(h).reduce((k,b)=>k+b,0):0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4",children:[e.jsx(G,{children:e.jsxs(J,{className:"pt-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:(m==null?void 0:m.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Tiers"})]})}),e.jsx(G,{children:e.jsxs(J,{className:"pt-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:_}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Users with Points"})]})}),m==null?void 0:m.slice(0,4).map(k=>e.jsx(G,{children:e.jsx(J,{className:"pt-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{tier:k,size:"sm",showTooltip:!1}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold",children:(h==null?void 0:h[k.id])||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:k.name})]})]})})},k.id))]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Tier Definitions"}),e.jsxs(R,{onClick:()=>t(!0),className:"gap-2",children:[e.jsx(Zs,{className:"h-4 w-4"}),"Add Tier"]})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-[50px]",children:"Order"}),e.jsx(U,{children:"Preview"}),e.jsx(U,{children:"Name"}),e.jsx(U,{children:"ID"}),e.jsx(U,{children:"Min Points"}),e.jsx(U,{children:"Users"}),e.jsx(U,{children:"Active"}),e.jsx(U,{className:"w-[100px]",children:"Actions"})]})}),e.jsx($e,{children:o?e.jsx(he,{children:e.jsx(M,{colSpan:8,className:"text-center py-8",children:"Loading tiers..."})}):(m==null?void 0:m.length)===0?e.jsx(he,{children:e.jsx(M,{colSpan:8,className:"text-center py-8",children:"No tiers defined yet. Create your first tier!"})}):m==null?void 0:m.map(k=>e.jsxs(he,{children:[e.jsx(M,{children:k.display_order}),e.jsx(M,{children:e.jsx(Ia,{tier:k,size:"md",showTooltip:!1})}),e.jsx(M,{className:"font-medium",children:k.name}),e.jsx(M,{children:e.jsx(B,{variant:"outline",children:k.id})}
251),e.jsx(M,{children:k.min_points.toLocaleString()}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(hs,{className:"h-3 w-3 text-muted-foreground"}),(h==null?void 0:h[k.id])||0]})}),e.jsx(M,{children:e.jsx(Ge,{checked:k.is_active??!0,onCheckedChange:b=>u.mutate({id:k.id,is_active:b})})}),e.jsx(M,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>x(k),children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>l(k),children:e.jsx(os,{className:"h-4 w-4 text-destructive"})})]})})]},k.id))})]})}),e.jsx(Ue,{open:a,onOpenChange:g,children:e.jsxs(Be,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:n?"Edit Tier":"Create New Tier"})}),e.jsx(qg,{initialData:n?{id:n.id,name:n.name,description:n.description||"",min_points:n.min_points,icon:n.icon,color:n.color,gradient_from:n.gradient_from||n.color,gradient_to:n.gradient_to||n.color,display_order:n.display_order,is_active:n.is_active??!0}:void 0,onSubmit:f,onCancel:g,isSubmitting:N.isPending||d.isPending,isEditing:!!n})]})}),e.jsx(ws,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Tier"}),e.jsxs(Ps,{children:['Are you sure you want to delete the "',i==null?void 0:i.name,'" tier? Users currently at this tier will be reassigned to the next lower tier.']})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>i&&y.mutate(i.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}const Og=[{value:"subscription",label:"Subscription"},{value:"feature",label:"Feature"},{value:"merchandise",label:"Merchandise"},{value:"general",label:"General"}];function Ug({reward:s,onClose:a}){const t=Me(),{data:n=[]}=Sd(),[r,i]=v.useState({name:(s==null?void 0:s.name)||"",description:(s==null?void 0:s.description)||"",point_cost:(s==null?void 0:s.point_cost)||100,required_tier_id:(s==null?void 0:s.required_tier_id)||"none",category:(s==null?void 0:s.category)||"general",stock:(s==null?void 0:s.stock)??"",image_url:(s==null?void 0:s.image_url)||"",is_active:(s==null?void 0:s.is_active)??!0,display_order:(s==null?void 0:s.display_order)||0}),[l,m]=v.useState((s==null?void 0:s.stock)!==null),o=_e({mutationFn:async()=>{const N={name:r.name,description:r.description||null,point_cost:r.point_cost,required_tier_id:r.required_tier_id==="none"?null:r.required_tier_id,category:r.category,stock:l?Number(r.stock):null,image_url:r.image_url||null,is_active:r.is_active,display_order:r.display_order,updated_at:new Date().toISOString()};if(s){const{error:d}=await T.from("rewards").update(N).eq("id",s.id);if(d)throw d}else{const{error:d}=await T.from("rewards").insert(N);if(d)throw d}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-rewards"]}),K.success(s?"Reward updated":"Reward created"),a()},onError:()=>K.error("Failed to save reward")}),h=N=>{if(N.preventDefault(),!r.name||r.point_cost<1){K.error("Name and point cost are required");return}o.mutate()};return e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:r.name,onChange:N=>i({...r,name:N.target.value}),placeholder:"Free Week Premium"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"description",children:"Description"}),e.jsx(Xs,{id:"description",value:r.description,onChange:N=>i({...r,description:N.target.value}),placeholder:"What the user receives...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"point_cost",children:"Point Cost *"}),e.jsx(pe,{id:"point_cost",type:"number",min:1,value:r.point_cost,onChange:N=>i({...r,point_cost:Number(N.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"category",children:"Category"}),e.jsxs(oe,{value:r.category,onValueChange:N=>i({...r,category:N}),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:Og.map(N=>e.jsx(V,{value:N.value,children:N.label},N.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"required_tier",children:"Required Tier"}),e.jsxs(oe,{value:r.required_tier_id,onValueChange:N=>i({...r,required_tier_id:N}),children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"None (anyone can redeem)"})}),e.jsxs(me,{children:[e.jsx(V,{value:"none",children:"None"}),n.map(N=>
251e.jsxs(V,{value:N.id,children:[N.name," (",N.min_points.toLocaleString(),"+ pts)"]},N.id))]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Q,{children:"Limited Stock"}),e.jsx(Ge,{checked:l,onCheckedChange:m})]}),l&&e.jsx(pe,{type:"number",min:0,value:r.stock,onChange:N=>i({...r,stock:N.target.value}),placeholder:"Available quantity"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"image_url",children:"Image URL (optional)"}),e.jsx(pe,{id:"image_url",value:r.image_url,onChange:N=>i({...r,image_url:N.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Q,{children:"Active"}),e.jsx(Ge,{checked:r.is_active,onCheckedChange:N=>i({...r,is_active:N})})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(R,{type:"button",variant:"outline",onClick:a,children:"Cancel"}),e.jsx(R,{type:"submit",disabled:o.isPending,children:o.isPending?"Saving...":s?"Update":"Create"})]})]})}function Bg(){const s=Me(),{data:a=[],isLoading:t}=ge({queryKey:["admin-redemptions"],queryFn:async()=>{const{data:l,error:m}=await T.from("reward_redemptions").select("*").order("redeemed_at",{ascending:!1}).limit(100);if(m)throw m;const o=[...new Set(l.map(d=>
251d.user_id))],{data:h}=await T.from("user_profiles").select("id, username, display_name").in("id",o),N=new Map((h==null?void 0:h.map(d=>[d.id,d]))||[]);return l.map(d=>({...d,user_profile:N.get(d.user_id)||null}))}}),n=_e({mutationFn:async({id:l,status:m})=>{const o={status:m};m==="fulfilled"&&(o.fulfilled_at=new Date().toISOString());const{error:h}=await T.from("reward_redemptions").update(o).eq("id",l);if(h)throw h},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-redemptions"]}),s.invalidateQueries({queryKey:["admin-redemption-stats"]}),K.success("Redemption updated")},onError:()=>K.error("Failed to update redemption")}),r=l=>{switch(l){case"fulfilled":return e.jsx(B,{className:"bg-green-500",children:"Fulfilled"});case"cancelled":return e.jsx(B,{variant:"destructive",children:"Cancelled"});default:return e.jsx(B,{variant:"secondary",children:"Pending"})}},i=l=>{const m=l.user_profile;return m!=null&&m.display_name?m.display_name:m!=null&&m.username?m.username:l.user_id.slice(0,8)+"..."};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Recent Redemptions"})}),e.jsx(J,{children:t?e.jsx("p",{className:"text-muted-foreground",children:"Loading..."}):a.length===0?e.jsx("p",{className:"text-muted-foreground",children:"No redemptions yet."}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"User"}),e.jsx(U,{children:"Reward"}),e.jsx(U,{children:"Points"}),e.jsx(U,{children:"Date"}),e.jsx(U,{children:"Status"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:a.map(l=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:i(l)}),e.jsx(M,{children:l.reward_name}),e.jsx(M,{children:e.jsx(B,{variant:"outline",children:l.points_spent.toLocaleString()})}),e.jsx(M,{className:"text-muted-foreground",children:ke(new Date(l.redeemed_at),"MMM d, yyyy")}),e.jsx(M,{children:r(l.status)}),e.jsx(M,{className:"text-right",children:l.status==="pending"&&e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{size:"sm",variant:"ghost",className:"text-green-600",onClick:()=>n.mutate({id:l.id,status:"fulfilled"}),children:e.jsx(Es,{className:"h-4 w-4"})}),e.jsx(R,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>n.mutate({id:l.id,status:"cancelled"}),children:e.jsx(Is,{className:"h-4 w-4"})})]})})]},l.id))})]})})]})}function zg(){var j;const[s,a]=v.useState(!1),[t,n]=v.useState(null),[r,i]=v.useState(!1),[l,m]=v.useState(null),[o,h]=v.useState(0),N=Me(),{data:d=[],isLoading:y}=ge({queryKey:["admin-rewards"],queryFn:async()=>{const{data:c,error:p}=await T.from("rewards").select("*").order("display_order",{ascending:!0});if(p)throw p;return c}}),{data:u}=ge({queryKey:["admin-redemption-stats"],queryFn:async()=>{const{data:c,error:p}=await T.from("reward_redemptions").select("points_spent");if(p)throw p;return{totalRedemptions:c.length,totalPointsRedeemed:c.reduce((w,S)=>w+S.points_spent,0)}}}),x=_e({mutationFn:async({id:c,is_active:p})=>{const{error:w}=await T.from("rewards").update({is_active:p,updated_at:new Date().toISOString()}).eq("id",c);if(w)throw w},onSuccess:()=>{N.invalidateQueries({queryKey:["admin-rewards"]}),K.success("Reward updated")},onError:()=>K.error("Failed to update reward")}),g=_e({mutationFn:async c=>{const{error:p}=await T.from("rewards").delete().eq("id",c);if(p)throw p},onSuccess:()=>{N.invalidateQueries({queryKey:["admin-rewards"]}),K.success("Reward deleted"),m(null)},onError:()=>K.error("Failed to delete reward")}),f=c=>{n(c),a(!0)},_=()=>{a(!1),n(null)},k=async c=>{const{count:p}=await T.from("reward_redemptions").select("*",{count:"exact",head:!0}).eq("reward_id",c.id);h(p||0),m(c)},b=d.filter(c=>c.is_active).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(G,{children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ja,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:d.length}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Rewards"})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Td,{className:"h-5 w-5 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:b}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active"})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-5 w-5 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(u==null?void 0:u.totalRedemptions)||0}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Redemptions"})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ld,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:((j=u==null?void 0:u.totalPointsRedeemed)==null?void 0:j.toLocaleStr
251ing())||0}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Points Redeemed"})]})]})})})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(R,{onClick:()=>i(!r),variant:"outline",children:r?"Show Rewards":"View Redemptions"}),e.jsxs(R,{onClick:()=>a(!0),children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Create Reward"]})]}),r?e.jsx(Bg,{}):e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"All Rewards"})}),e.jsx(J,{children:y?e.jsx("p",{className:"text-muted-foreground",children:"Loading..."}):d.length===0?e.jsx("p",{className:"text-muted-foreground",children:"No rewards created yet."}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Name"}),e.jsx(U,{children:"Cost"}),e.jsx(U,{children:"Required Tier"}),e.jsx(U,{children:"Stock"}),e.jsx(U,{children:"Category"}),e.jsx(U,{children:"Active"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:d.map(c=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:c.name}),e.jsx(M,{children:e.jsxs(B,{variant:"secondary",children:[c.point_cost.toLocaleString()," pts"]})}),e.jsx(M,{children:c.required_tier_id?e.jsx(Ia,{tierId:c.required_tier_id,size:"xs",showTooltip:!1}):e.jsx("span",{className:"text-muted-foreground",children:"None"})}),e.jsx(M,{children:c.stock===null?e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"}):e.jsxs(B,{variant:c.stock>0?"outline":"destructive",children:[c.stock," left"]})}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:"capitalize",children:c.category})}),e.jsx(M,{children:e.jsx(Ge,{checked:c.is_active,onCheckedChange:p=>x.mutate({id:c.id,is_active:p})})}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>f(c),children:e.jsx(Bt,{className:"h-4 w-4"})}),e.jsx(R,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>k(c),children:e.jsx(os,{className:"h-4 w-4"})})]})})]},c.id))})]})})]}),e.jsx(Ue,{open:s,onOpenChange:_,children:e.jsxs(Be,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:t?"Edit Reward":"Create Reward"})}),e.jsx(Ug,{reward:t,onClose:_})]})}),e.jsx(ws,{open:!!l,onOpenChange:()=>m(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Reward"}),e.jsx(Ps,{asChild:!0,children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{children:['Are you sure you want to delete the "',l==null?void 0:l.name,'" reward? This action cannot be undone.']}),o>0&&e.jsxs("p",{className:"font-medium text-destructive",children:["⚠️ This reward has been redeemed ",o," time",o!==1?"s":"",". Deleting it will remove all redemption records."]})]})})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>l&&g.mutate(l.id),children:"Delete"})]})]})})]})}const Kg=[{value:"all",label:"All Pages"},{value:"/",label:"Home"},{value:"/pricing",label:"Pricing"},{value:"/blog",label:"Blog"},{value:"/kontests",label:"Kontests"},{value:"/kommunity",label:"Kommunity"},{value:"/klub",label:"KLUB Hub"},{value:"/draft",label:"Draft"},{value:"/kollective",label:"Kollective"},{value:"/kashai",label:"Kash AI"},{value:"/rewards",label:"Rewards"},{value:"/leaderboard",label:"Leaderboard"},{value:"/support",label:"Support"},{value:"/subscriptions",label:"My Subscriptions"},{value:"/profile",label:"Profile"},{value:"/bankroll",label:"Bankroll"}],Vg=[{value:"all",label:"Everyone (All visitors)"},{value:"guest",label:"Guests Only (Non-authenticated)"},{value:"users",label:"All Users (Authenticated only)"},{value:"subscribers",label:"Subscribers Only (Active subscription or Admin)"}],Hg={name:"",banner_text:"",background_color:"#22c55e",text_color:"#ffffff",click_url:"",target_audience:"all",visible_pages:["all"],is_active:!1,start_date:"",end_date:""};function Wg({initialData:s,onSubmit:a,onCancel:t,isLoading:n}){const[r,i]=v.useState({...Hg,...s,visible_pages:(s==null?void 0:s.visible_pages)||["all"],start_date:s!=null&&s.start_date?new Date(s.start_date).toISOString().slice(0,16):"",end_date:s!=null&&s.end_date?new Date(s.end_date).toISOString().slice(0,16):""}),l=(h,N)=>{i(d=>({...d,[h]:N}))},m=(h,N)=>{let d=[...r.visible_pages];h==="all"?d=N?["all"]:[]:(d=d.filter(y=>y!=="all"),N?d.push(h):d=d.filter(y=>
251y!==h),d.length===0&&(d=["all"])),l("visible_pages",d)},o=async h=>{h.preventDefault(),await a({...r,start_date:r.start_date||null,end_date:r.end_date||null})};return e.jsxs("form",{onSubmit:o,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Preview"}),e.jsxs("div",{className:"relative w-full py-2 px-4 text-center rounded-md",style:{backgroundColor:r.background_color,color:r.text_color},children:[e.jsx("p",{className:"text-sm font-medium pr-8",children:r.banner_text||"Your banner text will appear here..."}),e.jsx("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 p-1",style:{color:r.text_color},children:e.jsx(rt,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"name",children:"Internal Name *"}),e.jsx(pe,{id:"name",value:r.name,onChange:h=>l("name",h.target.value),placeholder:"e.g., Kontest Launch Promo",required:!0})]}),e.jsxs("div",{className:"space-y-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{id:"is_active",checked:r.is_active,onCheckedChange:h=>l("is_active",h)}),e.jsx(Q,{htmlFor:"is_active",children:"Immediately Active"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"For instant activation without scheduling"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"banner_text",children:"Banner Text *"}),e.jsx(Xs,{id:"banner_text",value:r.banner_text,onChange:h=>l("banner_text",h.target.value),placeholder:"🎉 New Kontest available! Click here to enter and win prizes!",rows:2,required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"background_color",children:"Backgroun
251d Color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"color",value:r.background_color,onChange:h=>l("background_color",h.target.value),className:"w-12 h-10 rounded border cursor-pointer"}),e.jsx(pe,{id:"background_color",value:r.background_color,onChange:h=>l("background_color",h.target.value),placeholder:"#22c55e"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"text_color",children:"Text Color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"color",value:r.text_color,onChange:h=>l("text_color",h.target.value),className:"w-12 h-10 rounded border cursor-pointer"}),e.jsx(pe,{id:"text_color",value:r.text_color,onChange:h=>l("text_color",h.target.value),placeholder:"#ffffff"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"click_url",children:"Click Navigation URL"}),e.jsx(pe,{id:"click_url",value:r.click_url,onChange:h=>l("click_url",h.target.value),placeholder:"/kontests"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Internal route path (e.g., /kontests, /pricing)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Target Audience"}),e.jsxs(oe,{value:r.target_audience,onValueChange:h=>l("target_audience",h),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{className:"bg-background border",children:Vg.map(h=>e.jsx(V,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Visible Pages"}),e.jsx("div",{className:"grid grid-cols-3 gap-2 p-3 border rounded-md bg-muted/30",children:Kg.map(h=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ms,{id:`page-${h.value}`,checked:r.visible_pages.includes(h.value),onCheckedChange:N=>m(h.value,!!N),disabled:h.value!=="all"&&r.visible_pages.includes("all")}),e.jsx(Q,{htmlFor:`page-${h.value}`,className:"text-sm cursor-pointer",children:h.label})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Scheduling"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Setting a Start Date will automatically show the banner when that time arrives, regardless of the Active toggle."}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"start_date",children:"Start Date"}),e.jsx(pe,{id:"start_date",type:"datetime-local",value:r.start_date,onChange:h=>l("start_date",h.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"end_date",children:"End Date"}),e.jsx(pe,{id:"end_date",type:"datetime-local",value:r.end_date,onChange:h=>l("end_date",h.target.value)})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(R,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(R,{type:"submit",disabled:n,children:n?"Saving...":s!=null&&s.name?"Update Banner":"Create Banner"})]})]})}function Gg(){const{banners:s,isLoading:a,createBanner:t,updateBanner:n,deleteBanner:r,toggleBanner:i}=fo(),[l,m]=v.useState(!1),[o,h]=v.useState(null),[N,d]=v.useState(!1),{toast:y}=Ws(),u=s.filter(p=>p.is_active),x=s.filter(p=>p.start_date||p.end_date),g=()=>{h(null),m(!0)},f=p=>{h(p),m(!0)},_=async p=>{d(!0);try{o?(await n(o.id,p),y({title:"Banner updated successfully"})):(await t(p),y({title:"Banner created successfully"})),m(!1),h(null)}catch(w){y({title:"Error saving banner",description:w.message,variant:"destructive"})}finally{d(!1)}},k=async p=>{if(confirm("Are you sure you want to delete this banner?"))try{await r(p),y({title:"Banner deleted successfully"})}catch(w){y({title:"Error deleting banner",description:w.message,variant:"destructive"})}},b=p=>({all:"Everyone",guest:"Guests",users:"Users",subscribers:"Subscribers"})[p]||p,j=p=>p.includes("all")?"All Pages":p.length>2?`${p.length} pages`:p.join(", "),c=p=>{const w=new Date,S=p.start_date?new Date(p.start_date):null,P=p.end_date?new Date(p.end_date):null;return P&&P<w?{label:"Expired",variant:"destructive"}:S&&S>w?{label:"Scheduled",variant:"secondary"}:p.is_active||S&&S<=w?{label:"Active",variant:"default"}:{label:"Inactive",variant:"outline"}};return a?e.jsx("div",{className:"text-center py-8",children:"Loading banners..."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(G,{children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_r,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:s.length}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Banners"})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(us,{className:"h-8 w-8 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:u.length}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active Banners"})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xt,{className:"h-8 w-8 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:x.length}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Scheduled"})]})]})})})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Promotional Banners"}),e.jsxs(R,{onClick:g,children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Create Banner"]})]}),s.length===0?e.jsx(G,{children:e.jsxs(J,{className:"py-12 text-center",children:[e.jsx(_r,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No promotional banners yet"}),e.jsx(R,{onClick:g,className:"mt-4",children:"Create Your First Banner"})]})}):e.jsx(G,{children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Name"}),e.jsx(U,{children:"Preview"}),e.jsx(U,{children:"Audience"}),e.jsx(U,{children:"Pages"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:s.map(p=>{const w=c(p);return e.jsxs(he,{children:[e.jsx(M,{children:e.jsx(B,{variant:w.variant,children:w.label})}),e.jsxs(M,{children:[e.jsx("div",{className:"font-medium",children:p.name}),p.click_url&&e.jsx("div",{className:"text-xs text-muted-foreground",children:p.click_url})]}),e.jsx(M,{children:e.jsx("div",{className:"text-xs px-2 py-1 rounded max-w-[200px] truncate",style:{backgroundColor:p.background_color,color:p.text_color},children:p.banner_text})}),e.jsx(M,{children:e.jsx(B,{variant:"outline",children:b(p.target_audience)})}),e.jsx(M,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:j(p.visible_pages)})}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>f(p),children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>k(p.id),className:"text-destructive hover:text-destructive",children:e.jsx(os,{className:"h-4 w-4"})})]})})]}
251,p.id)})})]})}),e.jsx(Ue,{open:l,onOpenChange:m,children:e.jsxs(Be,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:o?"Edit Banner":"Create New Banner"})}),e.jsx(Wg,{initialData:o||void 0,onSubmit:_,onCancel:()=>m(!1),isLoading:N})]})})]})}const tn="subscription-images";async function Qg(s,a){const t=s.name.split(".").pop(),r=`packages/${`${a}-${Date.now()}.${t}`}`,{error:i}=await T.storage.from(tn).upload(r,s,{cacheControl:"3600",upsert:!0});if(i)throw new Error(`Failed to upload image: ${i.message}`);const{data:l}=T.storage.from(tn).getPublicUrl(r);return l.publicUrl}async function Yg(s){const a=s.split(`${tn}/`);if(a.length!==2){console.warn("Could not parse image URL for deletion");return}const t=a[1],{error:n}=await T.storage.from(tn).remove([t]);n&&console.error("Failed to delete image:",n.message)}const Jg=el({name:ot().min(1,"Name is required"),price_monthly:Rr().min(0,"Monthly price must be positive"),price_annual:Rr().min(0,"Annual price must be positive"),image_url:ot().nullable(),features:Ed(ot()).min(1,"At least one feature is required"),is_active:hr(),is_popular:hr(),display_order:Rr().min(0),stripe_price_id_monthly:ot().optional(),stripe_price_id_annual:ot().optional(),package_type:Gr(["insider","single","triple","full"]),tier_name:Gr(["founding","early_edge","core","advanced","pro","elite"]).nullable(),trial_enabled:hr()});function Zg({open:s,onOpenChange:a,package_:t,onSuccess:n}){const[r,i]=v.useState((t==null?void 0:t.features)||[""]),[l,m]=v.useState(!1),[o,h]=v.useState((t==null?void 0:t.image_url)||null),[N,d]=v.useState(!1),y=v.useRef(null),{register:u,handleSubmit:x,formState:{errors:g},setValue:f,reset:_,watch:k}=Wa({resolver:Ga(Jg),defaultValues:{name:(t==null?void 0:t.name)||"",price_monthly:(t==null?void 0:t.price_monthly)||0,price_annual:(t==null?void 0:t.price_annual)||0,image_url:(t==null?void 0:t.image_url)||null,features:(t==null?void 0:t.features)||[""],is_active:(t==null?void 0:t.is_active)??!0,is_popular:(t==null?void 0:t.is_popular)??!1,display_order:(t==null?void 0:t.display_order)||0,stripe_price_id_monthly:(t==null?void 0:t.stripe_price_id_monthly)||"",stripe_price_id_annual:(t==null?void 0:t.stripe_price_id_annual)||"",package_type:(t==null?void 0:t.package_type)||"single",tier_name:(t==null?void 0:t.tier_name)||null,trial_enabled:(t==null?void 0:t.trial_enabled)??!0}}),b=k("package_type"),j=k("trial_enabled"),c=k("is_popular");v.useEffect(()=>{if(s){const D=(t==null?void 0:t.features)||[""];i(D),h((t==null?void 0:t.image_url)||null),_({name:(t==null?void 0:t.name)||"",price_monthly:(t==null?void 0:t.price_monthly)||0,price_annual:(t==null?void 0:t.price_annual)||0,image_url:(t==null?void 0:t.image_url)||null,features:D,is_active:(t==null?void 0:t.is_active)??!0,is_popular:(t==null?void 0:t.is_popular)??!1,display_order:(t==null?void 0:t.display_order)||0,stripe_price_id_monthly:(t==null?void 0:t.stripe_price_id_monthly)||"",stripe_price_id_annual:(t==null?void 0:t.stripe_price_id_annual)||"",package_type:(t==null?void 0:t.package_type)||"single",tier_name:(t==null?void 0:t.tier_name)||null,trial_enabled:(t==null?void 0:t.trial_enabled)??!0})}},[s,t,_]);const p=()=>{const D=[...r,""];i(D),f("features",D)},w=D=>{const A=r.filter((F,q)=>q!==D);i(A),f("features",A)},S=(D,A)=>{const F=[...r];F[D]=A,i(F),f("features",F)},P=async D=>{var F;const A=(F=D.target.files)==null?void 0:F[0];if(A){if(!A.type.startsWith("image/")){K.error("Please upload an image file");return}if(A.size>5*1024*1024){K.error("Image must be less than 5MB");return}d(!0);try{const q=(t==null?void 0:t.id)||crypto.randomUUID(),E=await Qg(A,q);h(E),f("image_url",E),K.success("Image uploaded successfully")}catch(q){K.error(q.message||"Failed to upload image")}finally{d(!1)}}},C=async()=>{if(o)try{await Yg(o)}catch(D){console.error("Failed to delete old image:",D)}h(null),f("image_url",null),y.current&&(y.current.value="")},O=!!(t!=null&&t.id),$=t&&!t.id,z=async D=>{m(!0);try{const A=D.features.filter(q=>q.trim()!=="");D.is_popular&&await T.from("subscription_packages").update({is_popular:!1}).neq("id",(t==null?void 0:t.id)||"");const F={name:D.name,price_monthly:D.price_monthly,price_annual:D.price_annual,price:D.price_monthly,billing_period:"monthly",image_url:o,features:A,is_active:D.is_active,is_popular:D.is_popular,display_order:D.display_order,stripe_price_id_monthly:D.stripe_price_id_monthly||null,stripe_price_id_annual:D.stripe_price_id_annual||null,package_type:D.package_type,tier_name:D.tier_name,trial_enabled:D.trial_enabled};if(O&&(t!=null&&t.id)){const{error:q}=await T.from("subscription_packages").update({...F,updated_at:new Date().toISOString()}).eq("id",t.id);if(q)throw q;K.success("Package updated successfully")}else{const{error:q}=await T.from("subscription_packages").insert(F);if(q)throw q;K.success($?"Package duplicated successfully":"Package created successfully")}n(),a(!1)}catch(A){K.error(A.message||"Failed to save package")}finally{m(!1)}};return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:O?"Edit Package":$?"Duplicate Package":"Create Package"})}),e.jsxs("form",{onSubmit:x(z),className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"name",children:"Package Name"}),e.jsx(pe,{id:"name",...u("name"),placeholder:"e.g., Pro, Elite, Premium"}),g.name&&e.jsx("p",{className:"text-sm text-destructive",children:g.name.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Package Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[o?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:o,alt:"Package",className:"w-24 h-24 object-cover rounded-lg border border-border"}),e.jsx(R,{type:"button",size:"icon",variant:"destructive",className:"absolute -top-2 -right-2 h-6 w-6",onClick:C,children:e.jsx(rt,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"w-24 h-24 rounded-lg border border-dashed border-border flex items-center justify-center bg-muted/50",children:e.jsx(Ot,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{ref:y,type:"file",accept:"image/*",onChange:P,className:"hidden"}),e.jsxs(R,{type:"button",variant:"outline",onClick:()=>{var D;return(D=y.current)==null?void 0:D.click()},disabled:N,children:[e.jsx(fa,{className:"h-4 w-4 mr-2"}),N?"Uploading...":"Upload Image"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Recommended: 400x400px, max 5MB"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"price_monthly",children:"Monthly Price ($)"}),e.jsx(pe,{id:"price_monthly",type:"number",step:"0.01",...u("price_monthly",{valueAsNumber:!0}),placeholder:"9.99"}),g.price_monthly&&e.jsx("p",{className:"text-sm text-destructive",children:g.price_monthly.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"price_annual",children:"Annual Price ($)"}),e.jsx(pe,{id:"price_annual",type:"number",step:"0.01",...u("price_annual",{valueAsNumber:!0}),placeholder:"99.99"}),g.price_annual&&e.jsx("p",{className:"text-sm text-destructive",children:g.price_annual.message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"display_order",children:"Display Order"}),e.jsx(pe,{id:"display_order",type:"number",...u("display_order",{valueAsNumber:!0}),placeholder:"0"}),g.display_order&&e.jsx("p",{className:"text-sm text-destructive",children:g.display_order.message})]}),e.jsxs("div",{className:"space-y-4 border-t pt-4",children:[e.jsx(Q,{className:"text-base font-semibold",children:"Package Configuration"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"package_type",children:"Package Type"}),e.jsxs("select",{id:"package_type",...u("package_type"),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm r
251ing-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("option",{value:"insider",children:"Insider (Entry Level)"}),e.jsx("option",{value:"single",children:"Single Sport"}),e.jsx("option",{value:"triple",children:"Triple Sport"}),e.jsx("option",{value:"full",children:"Full Access"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b==="insider"&&"No sport selection, limited features",b==="single"&&"User selects 1 sport",b==="triple"&&"User selects 3 sports",b==="full"&&"Access to all sports"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"tier_name",children:"Tier Assignment"}),e.jsxs("select",{id:"tier_name",value:k("tier_name")||"",onChange:D=>f("tier_name",D.target.value||null),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("option",{value:"",children:"No tier"}),e.jsx("option",{value:"founding",children:"Founding"}),e.jsx("option",{value:"early_edge",children:"Early Edge"}),e.jsx("option",{value:"core",children:"Core"}),e.jsx("option",{value:"advanced",children:"Advanced"}),e.jsx("option",{value:"pro",children:"Pro"}),e.jsx("option",{value:"elite",children:"Elite"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assign to a tier for auto-progression pricing"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Trial Period"}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-input bg-background px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:j?"7-day trial enabled":"No trial period"}),e.jsx(Ge,{checked:j,onCheckedChange:D=>f("trial_enabled",D)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Insider packages typically have no trial"})]})]})]}),e.jsxs("div",{className:"space-y-4 border-t pt-4",children:[e.jsx(Q,{className:"text-base font-semibold",children:"Stripe Integration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Find Price IDs in your Stripe Dashboard → Products → [Product] → Pricing"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"stripe_price_id_monthly",children:"Monthly Price ID"}),e.jsx(pe,{id:"stripe_price_id_monthly",...u("stripe_price_id_monthly"),placeholder:"price_xxxxxxxxxx"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"stripe_price_id_annual",children:"Annual Price ID"}),e.jsx(pe,{id:"stripe_price_id_annual",...u("stripe_price_id_annual"),placeholder:"price_xxxxxxxxxx"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Q,{children:"Features"}),e.jsxs(R,{type:"button",size:"sm",variant:"outline",onClick:p,children:[e.jsx(Zs,{className:"h-4 w-4 mr-1"}),"Add Feature"]})]}),r.map((D,A)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:D,onChange:F=>S(A,F.target.value),placeholder:"Enter feature description"}),e.jsx(R,{type:"button",size:"icon",variant:"ghost",onClick:()=>w(A),disabled:r.length===1,children:e.jsx(rt,{className:"h-4 w-4"})})]},A)),g.features&&e.jsx("p",{className:"text-sm text-destructive",children:g.features.message})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{htmlFor:"is_popular",children:"Most Popular"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlights this package on the pricing page"})]}),e.jsx(Ge,{id:"is_popular",checked:c,onCheckedChange:D=>f("is_popular",D)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Q,{htmlFor:"is_active",children:"Active"}),e.jsx(Ge,{id:"is_active",defaultChecked:(t==null?void 0:t.is_active)??!0,onCheckedChange:D=>f("is_active",D)})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(R,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(R,{type:"submit",disabled:l||N,children:l?"Saving...":O?"Update Package":"Create Package"})]})]})]})})}function Xg(){const[s,a]=v.useState([]),[t,n]=v.useState(!0),[r,i]=v.useState(null),[l,m]=v.useState(!1),[o,h]=v.useState(!1),[N,d]=v.useState(null),[y,u]=v.useState(!1),x=async()=>{n(!0);try{let S=T.from("subscription_packages").select("*").order("display_order",{ascending:!0});
251y||(S=S.is("archived_at",null));const{data:P,error:C}=await S;if(C)throw C;a(P||[])}catch(S){K.error("Failed to load packages"),console.error(S)}finally{n(!1)}};v.useEffect(()=>{x()},[y]);const g=async(S,P)=>{try{const{error:C}=await T.from("subscription_packages").update({is_active:!P}).eq("id",S);if(C)throw C;K.success(`Package ${P?"deactivated":"activated"}`),x()}catch{K.error("Failed to update package status")}},f=async()=>{if(N)try{const{error:S}=await T.from("subscription_packages").update({archived_at:new Date().toISOString(),is_active:!1}).eq("id",N);if(S)throw S;K.success("Package archived successfully"),x()}catch{K.error("Failed to archive package")}finally{h(!1),d(null)}},_=async S=>{try{const{error:P}=await T.from("subscription_packages").update({archived_at:null}).eq("id",S);if(P)throw P;K.success("Package restored from archive"),x()}catch{K.error("Failed to restore package")}},k=S=>{d(S),h(!0)},b=S=>{i(S),m(!0)},j=()=>{i(null),m(!0)},c=S=>{const P={...S,id:"",name:`${S.name} (Copy)`,display_order:S.display_order+1,archived_at:null};i(P),m(!0)},p=S=>{const P=S.price_monthly>0?`$${S.price_monthly.toFixed(2)}/mo`:"-",C=S.price_annual>0?`$${S.price_annual.toFixed(2)}/yr`:"-";return{monthly:P,annual:C}},w=S=>{const P=!!S.stripe_price_id_monthly,C=!!S.stripe_price_id_annual;return P&&C?"complete":P||C?"partial":"missing"};return t?e.jsx("div",{className:"text-center py-8",children:"Loading packages..."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Subscription Packages"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>u(!y),children:[y?e.jsx(Ht,{className:"h-4 w-4 mr-2"}):e.jsx(us,{className:"h-4 w-4 mr-2"}),y?"Hide Archived":"Show Archived"]}),e.jsxs(R,{onClick:j,className:"w-full sm:w-auto",children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Create Package"]})]})]}),e.jsx("div",{className:"hidden md:block border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-16",children:"Image"}),e.jsx(U,{children:"Package Name"}),e.jsx(U,{children:"Monthly"}),e.jsx(U,{children:"Annual"}),e.jsx(U,{children:"Features"}),e.jsx(U,{children:"Tier"}),e.jsx(U,{children:"Stripe"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Active"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:s.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:10,className:"text-center text-muted-foreground py-8",children:"No packages found. Create your first package to get started."})}):s.map(S=>{const P=p(S),C=w(S),O=!!S.archived_at;return e.jsxs(he,{className:O?"opacity-60":"",children:[e.jsx(M,{children:S.image_url?e.jsx("img",{src:S.image_url,alt:S.name,className:"w-12 h-12 object-cover rounded-md"}):e.jsx("div",{className:"w-12 h-12 rounded-md bg-muted flex items-center justify-center",children:e.jsx(Ot,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(M,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[S.name,S.is_popular&&e.jsx(Wt,{className:"h-4 w-4 text-yellow-500 fill-yellow-500"}),O&&e.jsxs(B,{variant:"outline",className:"text-muted-foreground",children:[e.jsx(Nt,{className:"h-3 w-3 mr-1"}),"Archived"]})]})}),e.jsx(M,{className:"text-primary font-semibold",children:P.monthly}),e.jsx(M,{className:"text-primary font-semibold",children:P.annual}),e.jsx(M,{children:e.jsx("div",{className:"max-w-xs",children:e.jsxs("span",{className:"text-sm text-muted-foreground",children:[S.features.length," feature",S.features.length!==1?"s":""]})})}),e.jsx(M,{children:S.tier_name?e.jsx(B,{variant:"outline",className:"capitalize",children:S.tier_name.replace("_"," ")}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(M,{children:e.jsx(zt,{children:e.jsxs(Us,{children:[e.jsx(Bs,{children:C==="complete"?e.jsx(ta,{className:"h-4 w-4 text-green-500"}):C==="partial"?e.jsx(ta,{className:"h-4 w-4 text-yellow-500"}):e.jsx(xs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs(zs,{children:[C==="complete"&&"Stripe configured (monthly & annual)",C==="partial"&&"Stripe partially configured",C==="missing"&&"
251Stripe Price IDs not configured"]})]})})}),e.jsx(M,{children:e.jsx(B,{variant:S.is_active?"default":"secondary",children:S.is_active?"Active":"Inactive"})}),e.jsx(M,{children:e.jsx(Ge,{checked:S.is_active,onCheckedChange:()=>g(S.id,S.is_active),disabled:O})}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>b(S),title:"Edit package",children:e.jsx(Bt,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>c(S),title:"Duplicate package",children:e.jsx(vt,{className:"h-4 w-4"})}),O?e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>_(S.id),title:"Restore package",children:e.jsx(Nt,{className:"h-4 w-4 text-primary"})}):e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>k(S.id),title:"Archive package",children:e.jsx(Nt,{className:"h-4 w-4"})})]})})]},S.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:s.length===0?e.jsx(G,{children:e.jsx(J,{className:"p-8 text-center text-muted-foreground",children:"No packages found. Create your first package to get started."})}):s.map(S=>{const P=p(S),C=w(S),O=!!S.archived_at;return e.jsx(G,{className:O?"opacity-60":"",children:e.jsxs(J,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[S.image_url?e.jsx("img",{src:S.image_url,alt:S.name,className:"w-12 h-12 object-cover rounded-md"}):e.jsx("div",{className:"w-12 h-12 rounded-md bg-muted flex items-center justify-center",children:e.jsx(Ot,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium truncate flex items-center gap-2",children:[S.name,S.is_popular&&e.jsx(Wt,{className:"h-4 w-4 text-yellow-500 fill-yellow-500"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[S.features.length," feature",S.features.length!==1?"s":""]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-primary font-semibold",children:P.monthly}),e.jsx("span",{className:"text-muted-foreground",children:"|"}),e.jsx("span",{className:"text-primary font-semibold",children:P.annual})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(B,{variant:S.is_active?"default":"secondary",children:S.is_active?"Active":"Inactive"}),O&&e.jsxs(B,{variant:"outline",className:"text-muted-foreground",children:[e.jsx(Nt,{className:"h-3 w-3 mr-1"}),"Archived"]}),C==="complete"?e.jsxs(B,{variant:"outline",className:"text-green-500",children:[e.jsx(ta,{className:"h-3 w-3 mr-1"}),"Stripe ✓"]}):C==="partial"?e.jsxs(B,{variant:"outline",className:"text-yellow-500",children:[e.jsx(ta,{className:"h-3 w-3 mr-1"}),"Partial"]}):e.jsxs(B,{variant:"outline",className:"text-muted-foreground",children:[e.jsx(xs,{className:"h-3 w-3 mr-1"}),"No Stripe"]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active:"}),e.jsx(Ge,{checked:S.is_active,onCheckedChange:()=>g(S.id,S.is_active),disabled:O})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>b(S),children:e.jsx(Bt,{className:"h-4 w-4"})}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>c(S),children:e.jsx(vt,{className:"h-4 w-4"})}),O?e.jsx(R,{variant:"outline",size:"sm",onClick:()=>_(S.id),children:e.jsx(Nt,{className:"h-4 w-4 text-primary"})}):e.jsx(R,{variant:"outline",size:"sm",onClick:()=>k(S.id),children:e.jsx(Nt,{className:"h-4 w-4"})})]})]})]})},S.id)})})]}),e.jsx(Zg,{open:l,onOpenChange:m,package_:r,onSuccess:x}),e.jsx(ws,{open:o,onOpenChange:h,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Archive Package"}),e.jsx(Ps,{children:"This will deactivate and archive the package. It will be hidden from the default view but subscription history will be preserved. You can restore it later."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:f,children:"Archive"})]})]})})]})}const ej=s=>
251({auto_renew_mismatch:{label:"Auto-Renew Mismatch",detail:"Database auto_renew setting differs from Stripe cancel_at_period_end"},status_mismatch:{label:"Status Mismatch",detail:"Subscription status in database differs from Stripe"},cancel_at_period_end_mismatch:{label:"Cancel Status Mismatch",detail:"Cancellation setting differs between database and Stripe"},pause_mismatch:{label:"Pause Mismatch",detail:"Pause status in database differs from Stripe"},not_found_in_stripe:{label:"Missing in Stripe",detail:"Subscription exists in database but not found in Stripe"}})[s]||{label:s.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase()),detail:s},sj=s=>{navigator.clipboard.writeText(s),Ee({title:"Copied",description:s})};function tj({open:s,onOpenChange:a}){const[t,n]=v.useState(null),r=Me(),{data:i,isLoading:l,refetch:m,isRefetching:o}=ge({queryKey:["subscription-discrepancies"],queryFn:async()=>{const x=await T.functions.invoke("verify-all-subscriptions");if(x.error)throw x.error;return x.data},enabled:s,staleTime:0}),h=_e({mutationFn:async({subscriptionId:x,stripeSubscriptionId:g,resolveWith:f})=>{const _=await T.functions.invoke("resolve-subscription-discrepancy",{body:{subscriptionId:x,stripeSubscriptionId:g,resolveWith:f}});if(_.error)throw _.error;return _.data},onSuccess:x=>{Ee({title:"Discrepancy Resolved",description:x.message}),m(),r.invalidateQueries({queryKey:["subscribers"]}
251)},onError:x=>{Ee({title:"Resolution Failed",description:x.message||"Failed to resolve discrepancy",variant:"destructive"})},onSettled:()=>{n(null)}}),N=_e({mutationFn:async x=>{const g=[];for(const f of x)try{const _=await T.functions.invoke("resolve-subscription-discrepancy",{body:{subscriptionId:f.subscriptionId,stripeSubscriptionId:f.stripeSubscriptionId,resolveWith:"stripe"}});g.push({id:f.subscriptionId,success:!_.error,error:_.error})}catch(_){g.push({id:f.subscriptionId,success:!1,error:_.message})}return g},onSuccess:x=>{const g=x.filter(_=>_.success).length,f=x.filter(_=>!_.success).length;Ee({title:"Bulk Resolution Complete",description:`${g} resolved, ${f} failed`}),m(),r.invalidateQueries({queryKey:["subscribers"]})},onError:x=>{Ee({title:"Bulk Resolution Failed",description:x.message||"Failed to resolve discrepancies",variant:"destructive"})}}),d=x=>{const g={active:"bg-green-500/20 text-green-400 border-green-500/50",trial:"bg-blue-500/20 text-blue-400 border-blue-500/50",trialing:"bg-blue-500/20 text-blue-400 border-blue-500/50",paused:"bg-yellow-500/20 text-yellow-400 border-yellow-500/50",past_due:"bg-orange-500/20 text-orange-400 border-orange-500/50",cancelled:"bg-red-500/20 text-red-400 border-red-500/50",canceled:"bg-red-500/20 text-red-400 border-red-500/50",NOT_FOUND:"bg-gray-500/20 text-gray-400 border-gray-500/50"};return e.jsx(B,{variant:"outline",className:`${g[x]||"bg-muted text-muted-foreground"} text-xs`,children:x})},y=(i==null?void 0:i.discrepancies)||[],u=x=>x.userName&&x.userName!=="Unknown"&&x.userName.trim()!==""?x.userName:null;return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-6xl max-h-[90vh]",children:[e.jsxs(ze,{children:[e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"Subscription Verification Results"]}),e.jsx(Vs,{children:"Compare subscription statuses between your database and Stripe"})]}),l?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx(gs,{className:"h-8 w-full"}),e.jsx(gs,{className:"h-32 w-full"})]}):i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-2xl font-bold",children:i.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Checked"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:`text-2xl font-bold ${y.length>0?"text-yellow-500":"text-green-500"}`,children:y.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Discrepancies"})]}),i.errors>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-red-500",children:i.errors}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Errors"})]})]}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>m(),disabled:o,children:o?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"})})]}),y.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Es,{className:"h-12 w-12 text-green-500 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"All Subscriptions In Sync"}),e.jsx("p",{className:"text-muted-foreground",children:"No discrepancies found between database and Stripe"})]}):e.jsxs(zt,{children:[e.jsx(cs,{className:"h-[400px] border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-[180px]",children:"User"}),e.jsx(U,{className:"w-[160px]",children:"Package"}),e.jsx(U,{className:"w-[80px]",children:"DB"}),e.jsx(U,{className:"w-[80px]",children:"Stripe"}),e.jsx(U,{className:"w-[140px]",children:"Issue"}),e.jsx(U,{className:"w-[130px]",children:"Stripe Sub ID"}),e.jsx(U,{className:"text-right w-[160px]",children:"Actions"})]})}),e.jsx($e,{children:y.map(x=>{var _;const g=ej(x.discrepancyType),f=u(x);return e.jsxs(he,{children:[e.jsx(M,{className:"py-3",children:e.jsxs("div",{className:"min-w-0",children:[f&&e.jsx("p",{className:"font-medium text-sm truncate",children:f}),e.jsx("p",{className:`text-xs ${f?"text-muted-foreground":"font-medium text-foreground"} truncate`,children:x.userEmail})]})}),e.jsx(M,{className:"py-3",children:e.jsx("span",{className:"text-sm line-clamp-2",children:x.packageName})}),e.jsx(M,{className:"py-3",children:d(x.dbStatus)}),e.jsx(M,{className:"py-3",children:d(x.stripeStatus)}),e.jsx(M,{className:"py-3",children:e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1.5 cursor-help",children:[e.jsx(ls,{className:"h-3.5 w-3.5 text-yellow-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs font-medium",children:g.label}),e.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(zs,{side:"top",className:"max-w-[280px]",children:[e.jsx("p",{className:"text-xs",children:g.detail}),e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:["DB Auto-Renew: ",x.dbAutoRenew?"Yes":"No"]}
251),e.jsxs("p",{children:["Stripe Cancel at Period End: ",(_=x.stripeDetails)!=null&&_.cancelAtPeriodEnd?"Yes":"No"]})]})]})]})}),e.jsx(M,{className:"py-3",children:x.stripeSubscriptionId&&x.stripeSubscriptionId!=="NOT_FOUND"?e.jsxs("button",{onClick:()=>sj(x.stripeSubscriptionId),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors font-mono",children:[e.jsx("span",{className:"truncate max-w-[90px]",children:x.stripeSubscriptionId.replace("sub_","")}),e.jsx(vt,{className:"h-3 w-3 flex-shrink-0"})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(M,{className:"text-right py-3",children:e.jsxs("div",{className:"flex justify-end gap-1.5",children:[e.jsx(R,{variant:"outline",size:"sm",className:"h-7 text-xs px-2",onClick:()=>{n(x.subscriptionId+"_stripe"),h.mutate({subscriptionId:x.subscriptionId,stripeSubscriptionId:x.stripeSubscriptionId,resolveWith:"stripe"})},disabled:t===x.subscriptionId+"_stripe"||x.stripeStatus==="NOT_FOUND",title:"Update database to match Stripe",children:t===x.subscriptionId+"_stripe"?e.jsx(ne,{className:"h-3 w-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ta,{className:"h-3 w-3 mr-1"}),"Stripe"]})}),e.jsx(R,{variant:"outline",size:"sm",className:"h-7 text-xs px-2",onClick:()=>{n(x.subscriptionId+"_db"),h.mutate({subscriptionId:x.subscriptionId,stripeSubscriptionId:x.stripeSubscriptionId,resolveWith:"database"})},disabled:t===x.subscriptionId+"_db"||x.stripeStatus==="NOT_FOUND",title:"Update Stripe to match database",children:t===x.subscriptionId+"_db"?e.jsx(ne,{className:"h-3 w-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-3 w-3 mr-1"}),"DB"]})})]})})]},x.subscriptionId)})})]})}),e.jsxs(lt,{className:"gap-2 sm:gap-0",children:[e.jsxs(R,{variant:"outline",onClick:()=>N.mutate(y),disabled:N.isPending,children:[N.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Accept All Stripe"]}),e.jsx(R,{variant:"ghost",onClick:()=>a(!1),children:"Close"})]})]})]}):null]})})}function aj(){var N,d;const[s,a]=v.useState(!1),[t,n]=v.useState(null),r=Me(),{data:i,isLoading:l}=ge({queryKey:["triple-sport-trials"],queryFn:async()=>{const{data:y,error:u}=await T.from("user_subscriptions").select(`
252          id,
253          user_id,
254          status,
255          stripe_subscription_id,
256          user_profile:user_profiles!user_subscriptions_user_id_fkey(full_name, username),
257          subscription_packages!package_id(name, price)
258        `).eq("status","trial").eq("package_id","d9ae54be-9f85-4603-8d6f-86025f85beb7");if(u)throw u;return y??[]}}),m=_e({mutationFn:async()=>{const{data:y,error:u}=await T.functions.invoke("migrate-trial-subscriptions",{body:{dryRun:!0}});if(u)throw u;return y},onSuccess:y=>{n(y),a(!0)},onError:y=>{Ee({title:"Dry Run Failed",description:y.message,variant:"destructive"})}}),o=_e({mutationFn:async()=>{const{data:y,error:u}=await T.functions.invoke("migrate-trial-subscriptions",{body:{dryRun:!1}});if(u)throw u;return y},onSuccess:y=>{var u;a(!1),n(null),r.invalidateQueries({queryKey:["triple-sport-trials"]}),r.invalidateQueries({queryKey:["subscribers"]}
258),Ee({title:"Migration Complete",description:`Successfully migrated ${y.migratedCount} subscription(s)${((u=y.errors)==null?void 0:u.length)>0?`, ${y.errors.length} failed`:""}`})},onError:y=>{Ee({title:"Migration Failed",description:y.message,variant:"destructive"})}}),h=(i==null?void 0:i.length)??0;return l?e.jsx(G,{className:"border-amber-500/50 bg-amber-500/5",children:e.jsx(J,{className:"py-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Checking for Triple Sport trials..."})]})})}):h===0?null:e.jsxs(e.Fragment,{children:[e.jsxs(ss,{variant:"default",className:"border-amber-500/50 bg-amber-500/10",children:[e.jsx(ls,{className:"h-4 w-4 text-amber-500"}),e.jsx(pa,{className:"text-amber-600",children:"Trial Migration Required"}),e.jsx(ts,{className:"mt-2",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:h})," user",h!==1?"s":""," on Triple Sport trials need migration to Full Access at the new lower pricing ($49.99/mo)."]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>m.mutate(),disabled:m.isPending,children:[m.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rt,{className:"h-4 w-4 mr-2"}),"Preview Migration"]})})]})})]}),e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-2xl",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Migration Preview"}),e.jsx(Vs,{children:"The following subscriptions will be migrated from Triple Sport to Full Access."})]}),t&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsx(G,{className:"flex-1",children:e.jsxs(J,{className:"pt-4",children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:t.migratedCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Will be migrated"})]})}),(((N=t.errors)==null?void 0:N.length)??0)>0&&e.jsx(G,{className:"flex-1",children:e.jsxs(J,{className:"pt-4",children:[e.jsx("div",{className:"text-2xl font-bold text-red-600",children:t.errors.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Errors found"})]})})]}),e.jsx("div",{className:"border rounded-lg max-h-64 overflow-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"User"}),e.jsx(U,{children:"Current"}),e.jsx(U,{}),e.jsx(U,{children:"New"}),e.jsx(U,{children:"Status"})]})}),e.jsx($e,{children:(i??[]).map(y=>{var x,g,f;const u=(x=t.results)==null?void 0:x.find(_=>_.subscriptionId===y.id);return e.jsxs(he,{children:[e.jsx(M,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:((g=y.user_profile)==null?void 0:g.full_name)||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((f=y.user_profile)==null?void 0:f.username)||"No email"})]})}),e.jsx(M,{children:e.jsx(B,{variant:"secondary",children:"Triple Sport"})}),e.jsx(M,{children:e.jsx(aa,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(M,{children:e.jsx(B,{variant:"default",children:"Full Access"})}),e.jsx(M,{children:u!=null&&u.success?e.jsx(Es,{className:"h-4 w-4 text-green-600"}):u!=null&&u.error?e.jsx("span",{className:"text-xs text-red-600",children:u.error}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Pending"})})]},y.id)})})]})}),(((d=t.errors)==null?void 0:d.length)??0)>0&&e.jsxs(ss,{variant:"destructive",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsx(pa,{children:"Some migrations may fail"}),e.jsx(ts,{children:t.errors.map((y,u)=>e.jsxs("div",{className:"text-xs",children:["Subscription ",y.subscriptionId,": ",y.error]},u))})]})]}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(R,{onClick:()=>o.mutate(),disabled:o.isPending,children:[o.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Execute Migration"]})]})]})})]})}function rj(){const[s,a]=v.useState(""),[t,n]=v.useState("all"),[r,i]=v.useState(null),[l,m]=v.useState(null),[o,h]=v.useState(!1),[N,d]=v.useState(new Set),y=O=>{d($=>{const z=new Set($);return z.has(O)?z.delete(O):z.add(O),z})}
258,u=Me(),x=_e({mutationFn:async O=>{const $=await T.functions.invoke("sync-paused-subscriptions",{body:{subscriptionId:O}});if($.error)throw $.error;return $.data},onSuccess:O=>{Ee({title:"Synced to Stripe",description:O.message||"Subscription pause synced successfully"}),u.invalidateQueries({queryKey:["subscribers"]})},onError:O=>{Ee({title:"Sync Failed",description:O.message||"Failed to sync to Stripe",variant:"destructive"})},onSettled:()=>{m(null)}}),g=_e({mutationFn:async()=>{const O=await T.functions.invoke("sync-paused-subscriptions");if(O.error)throw O.error;return O.data},onSuccess:O=>{Ee({title:"Bulk Sync Complete",description:`Synced ${O.synced} subscriptions${O.failed>0?`, ${O.failed} failed`:""}`}),u.invalidateQueries({queryKey:["subscribers"]})},onError:O=>{Ee({title:"Bulk Sync Failed",description:O.message||"Failed to sync subscriptions",variant:"destructive"})}}),f=_e({mutationFn:async O=>{const $=await T.functions.invoke("sync-cancelling-subscriptions",{body:{subscriptionId:O}});if($.error)throw $.error;return $.data},onSuccess:O=>{Ee({title:"Verified with Stripe",description:O.message||"Subscription status verified"}),u.invalidateQueries({queryKey:["subscribers"]}
258)},onError:O=>{Ee({title:"Verification Failed",description:O.message||"Failed to verify with Stripe",variant:"destructive"})},onSettled:()=>{m(null)}}),_=_e({mutationFn:async()=>{const O=await T.functions.invoke("sync-cancelling-subscriptions");if(O.error)throw O.error;return O.data},onSuccess:O=>{Ee({title:"Cancelling Subscriptions Verified",description:O.message}),u.invalidateQueries({queryKey:["subscribers"]})},onError:O=>{Ee({title:"Verification Failed",description:O.message||"Failed to verify subscriptions",variant:"destructive"})}}),{data:k,isLoading:b}=ge({queryKey:["subscribers",t],queryFn:async()=>{let O=T.from("user_subscriptions").select(`
259          id,
260          user_id,
261          status,
262          stripe_customer_id,
263          stripe_subscription_id,
264          start_date,
265          end_date,
266          trial_end_date,
267          auto_renew,
268          created_at,
269          cancel_reason,
270          paused_at,
271          paused_reason,
272          user_profile:user_profiles!user_subscriptions_user_id_fkey(id, full_name, username, avatar_url),
273          subscription_packages!package_id(name, price)
274        `).order("created_at",{ascending:!1});t!=="all"&&(O=O.eq("status",t));const{data:$,error:z}=await O;if(z)throw z;return $}}),c=v.useMemo(()=>{if(!k)return[];const O=["past_due","active","trial","paused","cancelled"],$=k.reduce((z,D)=>{const A=D.user_id;return z[A]||(z[A]=[]),z[A].push(D),z},{});return Object.entries($).map(([z,D])=>{const A=[...D].sort((F,q)=>{const E=O.indexOf(F.status),L=O.indexOf(q.status),H=E===-1?999:E,Z=L===-1?999:L;return H!==Z?H-Z:new Date(q.created_at||0).getTime()-new Date(F.created_at||0).getTime()});return{userId:z,userProfile:A[0].user_profile,currentSubscription:A[0],allSubscriptions:A,subscriptionCount:D.length}})},[k]).filter(O=>{var A,F,q,E;const $=s.toLowerCase(),z=((A=O.userProfile)==null?void 0:A.full_name)||((F=O.userProfile)==null?void 0:F.username)||"",D=((q=O.userProfile)==null?void 0:q.username)||"";return z.toLowerCase().includes($)||D.toLowerCase().includes($)||((E=O.currentSubscription.stripe_customer_id)==null?void 0:E.toLowerCase().includes($))}),p=(O,$)=>{navigator.clipboard.writeText(O),i($),Ee({title:"Copied to clipboard"}),setTimeout(()=>i(null),2e3)},w=O=>{var $;return $r({status:O.status,packageName:($=O.subscription_packages)==null?void 0:$.name,cancelReason:O.cancel_reason,pausedAt:O.paused_at})},S=(k==null?void 0:k.filter(O=>O.paused_at&&O.status!=="paused"&&O.stripe_subscription_id).length)||0,P=(k==null?void 0:k.filter(O=>O.cancel_reason&&O.cancel_reason!=="upgrading"&&O.cancel_reason!=="downgrading"&&O.status!=="cancelled"&&O.status!=="paused"&&O.stripe_subscription_id).length)||0,C=O=>O.cancel_reason&&O.cancel_reason!=="upgrading"&&O.cancel_reason!=="downgrading"&&O.cancel_reason!=="payment_failed"&&O.status!=="cancelled"&&O.status!=="paused"&&O.status!=="past_due"&&O.stripe_subscription_id;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(aj,{}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or Stripe ID...",value:s,onChange:O=>a(O.target.value),className:"pl-9"})]}),e.jsxs(oe,{value:t,onValueChange:O=>n(O),children:[e.jsx(de,{className:"w-full sm:w-[180px]",children:e.jsx(ue,{placeholder:"Filter by status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Statuses"}),e.jsx(V,{value:"active",children:"Active"}),e.jsx(V,{value:"trial",children:"Trial"}),e.jsx(V,{value:"cancelled",children:"Cancelled"}),e.jsx(V,{value:"past_due",children:"Past Due"})]})]}),e.jsxs(R,{variant:"outline",onClick:()=>h(!0),children:[e.jsx(Zn,{className:"h-4 w-4 mr-2"}),"Verify All Subscriptions"]}),S>0&&e.jsxs(R,{variant:"outline",onClick:()=>g.mutate(),disabled:g.isPending,children:[g.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(He,{className:"h-4 w-4 mr-2"}),"Sync Paused (",S,")"]}),P>0&&e.jsxs(R,{variant:"outline",onClick:()=>_.mutate(),disabled:_.isPending,children:[_.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(He,{className:"h-4 w-4 mr-2"}),"Verify Cancelling (",P,")"]})]}),e.jsx(tj,{open:o,onOpenChange:h}),e.jsx("div",{className:"hidden md:block border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-8"}),e.jsx(U,{children:"User"}),e.jsx(U,{children:"Package"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Started"}),e.jsx(U,{children:"Trial End"}),e.jsx(U,{children:"End Date"}),e.jsx(U,{children:"Auto-Renew"}),e.jsx(U,{children:"Stripe Customer"}),e.jsx(U,{children:"Stripe Subscription"}),e.jsx(U,{children:"Actions"})]})}),e.jsx($e,{children:b?Array.from({length:5}).map((O,$)=>e.jsxs(he,{children:[e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-4"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-10 w-full"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-24"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-6 w-20"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-24"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-24"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-24"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-12"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-32"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-32"})}),e.jsx(M,{children:e.jsx(gs,{className:"h-4 w-16"})})]},$)):c&&c.length>0?c.map(O=>{var A,F,q,E,L,H,Z,se,ie;const $=O.currentSubscription,z=N.has(O.userId),D=O.subscriptionCount>1;return e.jsxs(e.Fragment,{children:[e.jsxs(he,{className:D?"cursor-pointer hover:bg-muted/50":"",onClick:D?()=>y(O.userId):void 0,children:[e.jsx(M,{className:"w-8",children:D?z?e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(st,{className:"h-4 w-4 text-muted-foreground"}):null}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ua,{className:"h-8 w-8",children:[e.jsx(ma,{src:((A=O.userProfile)==null?void 0:A.avatar_url)||void 0}
274),e.jsx(xa,{className:"text-xs",children:((q=(F=O.userProfile)==null?void 0:F.full_name)==null?void 0:q.charAt(0))||((L=(E=O.userProfile)==null?void 0:E.username)==null?void 0:L.charAt(0))||"U"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:((H=O.userProfile)==null?void 0:H.full_name)||"Unnamed User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Z=O.userProfile)==null?void 0:Z.username)||"No email"}),D&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Pt,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[O.subscriptionCount," subscriptions"]})]})]})]})}),e.jsx(M,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:((se=$.subscription_packages)==null?void 0:se.name)||"Unknown"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["$",((ie=$.subscription_packages)==null?void 0:ie.price)||0,"/month"]})]})}),e.jsx(M,{children:w($)}),e.jsx(M,{className:"text-sm text-muted-foreground",children:$.created_at?ke(new Date($.created_at),"MMM d, yyyy"):"-"}),e.jsx(M,{className:"text-sm text-muted-foreground",children:$.trial_end_date?ke(new Date($.trial_end_date),"MMM d, yyyy"):"-"}),e.jsx(M,{className:"text-sm text-muted-foreground",children:$.end_date?ke(new Date($.end_date),"MMM d, yyyy"):"-"}),e.jsx(M,{children:e.jsx(B,{variant:$.auto_renew&&$.status!=="cancelled"?"default":"secondary",children:$.auto_renew&&$.status!=="cancelled"?"Yes":"No"})}),e.jsx(M,{onClick:Y=>Y.stopPropagation(),children:$.stripe_customer_id?e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs font-mono",onClick:()=>p($.stripe_customer_id,`cust-${$.id}`),children:[$.stripe_customer_id.slice(0,14),"...",r===`cust-${$.id}`?e.jsx(Ks,{className:"h-3 w-3 ml-1 text-green-500"}):e.jsx(vt,{className:"h-3 w-3 ml-1"})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(M,{onClick:Y=>Y.stopPropagation(),children:$.stripe_subscription_id?e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs font-mono",onClick:()=>p($.stripe_subscription_id,`sub-${$.id}`),children:[$.stripe_subscription_id.slice(0,14),"...",r===`sub-${$.id}`?e.jsx(Ks,{className:"h-3 w-3 ml-1 text-green-500"}):e.jsx(vt,{className:"h-3 w-3 ml-1"})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(M,{onClick:Y=>Y.stopPropagation(),children:$.paused_at&&$.status!=="paused"&&$.stripe_subscription_id?e.jsx(R,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{m($.id),x.mutate($.id)},disabled:l===$.id,children:l===$.id?e.jsx(ne,{className:"h-3 w-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-3 w-3 mr-1"}),"Sync Pause"]})}):C($)?e.jsx(R,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{m($.id),f.mutate($.id)},disabled:l===$.id,children:l===$.id?e.jsx(ne,{className:"h-3 w-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-3 w-3 mr-1"}),"Verify"]})}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})})]},O.userId),z&&O.allSubscriptions.map((Y,I)=>{var ee,le;return e.jsxs(he,{className:"bg-muted/30",children:[e.jsx(M,{}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-2 pl-4",children:[e.jsx("span",{className:"text-muted-foreground",children:"└"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I===0?"(Current)":`Record ${O.subscriptionCount-I}`})]})}),e.jsx(M,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:((ee=Y.subscription_packages)==null?void 0:ee.name)||"Unknown"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["$",((le=Y.subscription_packages)==null?void 0:le.price)||0,"/month"]})]})}),e.jsx(M,{children:w(Y)}),e.jsx(M,{className:"text-sm text-muted-foreground",children:Y.created_at?ke(new Date(Y.created_at),"MMM d, yyyy"):"-"}),e.jsx(M,{className:"text-sm text-muted-foreground",children:Y.trial_end_date?ke(new Date(Y.trial_end_date),"MMM d, yyyy"):"-"}),e.jsx(M,{className:"text-sm text-muted-foreground",children:Y.end_date?ke(new Date(Y.end_date),"MMM d, yyyy"):"-"}),e.jsx(M,{children:e.jsx(B,{variant:Y.auto_renew&&Y.status!=="c
274ancelled"?"default":"secondary",children:Y.auto_renew&&Y.status!=="cancelled"?"Yes":"No"})}),e.jsx(M,{children:Y.stripe_customer_id?e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs font-mono",onClick:ve=>{ve.stopPropagation(),p(Y.stripe_customer_id,`cust-${Y.id}`)},children:[Y.stripe_customer_id.slice(0,14),"...",r===`cust-${Y.id}`?e.jsx(Ks,{className:"h-3 w-3 ml-1 text-green-500"}):e.jsx(vt,{className:"h-3 w-3 ml-1"})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(M,{children:Y.stripe_subscription_id?e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs font-mono",onClick:ve=>{ve.stopPropagation(),p(Y.stripe_subscription_id,`sub-${Y.id}`)},children:[Y.stripe_subscription_id.slice(0,14),"...",r===`sub-${Y.id}`?e.jsx(Ks,{className:"h-3 w-3 ml-1 text-green-500"}):e.jsx(vt,{className:"h-3 w-3 ml-1"})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(M,{children:Y.cancel_reason&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Y.cancel_reason})})]},`${O.userId}-${Y.id}`)})]})}):e.jsx(he,{children:e.jsx(M,{colSpan:11,className:"text-center text-muted-foreground py-8",children:"No subscribers found"})})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:b?Array.from({length:3}).map((O,$)=>e.jsx(G,{children:e.jsxs(J,{className:"p-4 space-y-3",children:[e.jsx(gs,{className:"h-10 w-full"}),e.jsx(gs,{className:"h-4 w-3/4"}),e.jsx(gs,{className:"h-6 w-1/2"})]})},$)):c&&c.length>0?c.map(O=>{var z,D,A,F,q,E,L,H,Z;const $=O.currentSubscription;return e.jsx(G,{children:e.jsxs(J,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ua,{className:"h-10 w-10",children:[e.jsx(ma,{src:((z=O.userProfile)==null?void 0:z.avatar_url)||void 0}),e.jsx(xa,{children:((A=(D=O.userProfile)==null?void 0:D.full_name)==null?void 0:A.charAt(0))||((q=(F=O.userProfile)==null?void 0:F.username)==null?void 0:q.charAt(0))||"U"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium truncate",children:((E=O.userProfile)==null?void 0:E.full_name)||"Unnamed User"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((L=O.userProfile)==null?void 0:L.username)||"No email"}),O.subscriptionCount>1&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(Pt,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[O.subscriptionCount," subscriptions"]})]})]})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs("span",{className:"text-sm font-medium",children:[((H=$.subscription_packages)==null?void 0:H.name)||"Unknown"," - $",((Z=$.subscription_packages)==null?void 0:Z.price)||0,"/mo"]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[w($),e.jsxs(B,{variant:$.auto_renew?"default":"secondary",children:["Renew: ",$.auto_renew?"Yes":"No"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm text-muted-foreground",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-xs",children:"Started"}),$.created_at?ke(new Date($.created_at),"MMM d, yyyy"):"-"]}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-xs",children:"Ends"}),$.end_date?ke(new Date($.end_date),"MMM d, yyyy"):"-"]}),$.trial_end_date&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"block text-xs",children:"Trial End"}),ke(new Date($.trial_end_date),"MMM d, yyyy")]})]}),$.stripe_customer_id&&e.jsx("div",{className:"pt-2 border-t",children:e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs font-mono w-full justify-between",onClick:()=>p($.stripe_customer_id,$.id),children:[e.jsx("span",{className:"truncate",children:$.stripe_customer_id}),r===$.id?e.jsx(Ks,{className:"h-3 w-3 ml-1 text-green-500 flex-shrink-0"}):e.jsx(vt,{className:"h-3 w-3 ml-1 flex-shrink-0"})]})}),$.paused_at&&$.status!=="paused"&&$.stripe_subscription_id&&e.jsx("div",{className:"pt-2 border-t",children:e.jsxs(R,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{m($.id),x.mutate($.id)},disabled:l===$.id,children:[l===$.id?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(He,{className:"h-4 w-4 mr-2"}),"Sync Pause to Stripe"]})}),C($)&&e.jsx("div",{className:"pt-2 border-t",children:e.jsxs(R,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{m($.id),f.mutate($.id)},disabled:l===$.id,children:[l===$.id?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(He,{className:"h-4 w-4 mr-2"}),"Verify Cancellation Status"]})})]})},O.userId)}):e.jsx(G,{children:e.jsx(J,{className:"p-8 text-center text-muted-foreground",children:"No subscribers found"})})})]})}const nj={waiting:"bg-yellow-500/10 text-yellow-500 border-yellow-500/30",invited:"bg-blue-500/10 text-blue-500 border-blue-500/30",subscribed:"bg-green-500/10 text-green-500 border-green-500/30",expired:"bg-muted text-muted-foreground border-border"};function lj(){const[s,a]=v.useState(""),[t,n]=v.useState("all"),{data:r,isLoading:i}=ge({queryKey:["admin-waitlist",t,s],queryFn:async()=>{let m=T.from("waitlist").select("*").order("joined_at",{ascending:!0});t!=="all"&&(m=m.eq("status",t)),s&&(m=m.or(`email.ilike.%${s}%,full_name.ilike.%${s}%`));const{data:o,error:h}=await m;if(h)throw h;return o??[]}}
274),l={waiting:(r==null?void 0:r.filter(m=>m.status==="waiting").length)??0,invited:(r==null?void 0:r.filter(m=>m.status==="invited").length)??0,subscribed:(r==null?void 0:r.filter(m=>m.status==="subscribed").length)??0,expired:(r==null?void 0:r.filter(m=>m.status==="expired").length)??0};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-3",children:[e.jsx(hs,{className:"h-5 w-5 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:l.waiting}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Waiting"})]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-3",children:[e.jsx(dt,{className:"h-5 w-5 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:l.invited}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Invited"})]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-3",children:[e.jsx(On,{className:"h-5 w-5 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:l.subscribed}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Subscribed"})]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-3",children:[e.jsx(ud,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:l.expired}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Expired"})]})]})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:m=>a(m.target.value),className:"pl-9"})]}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-[160px]",children:e.jsx(ue,{placeholder:"Filter status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Statuses"}),e.jsx(V,{value:"waiting",children:"Waiting"}),e.jsx(V,{value:"invited",children:"Invited"}),e.jsx(V,{value:"subscribed",children:"Subscribed"}),e.jsx(V,{value:"expired",children:"Expired"})]})]})]}),e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Name"}),e.jsx(U,{children:"Email"}),e.jsx(U,{children:"Joined"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Invites Sent"}),e.jsx(U,{children:"Last Invited"})]})}),e.jsx($e,{children:i?e.jsx(he,{children:e.jsx(M,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):r!=null&&r.length?r.map(m=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:m.full_name||"—"}),e.jsx(M,{children:m.email}),e.jsx(M,{className:"text-sm text-muted-foreground",children:new Date(m.joined_at).toLocaleDateString()}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:nj[m.status]||"",children:m.status})}),e.jsx(M,{children:m.invite_count}),e.jsx(M,{className:"text-sm text-muted-foreground",children:m.last_invited_at?new Date(m.last_invited_at).toLocaleString():"—"})]},m.id)):e.jsx(he,{children:e.jsx(M,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No waitlist entries found"})})})]})})]})}function ij(){return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{children:"Subscription Management"}),e.jsx(De,{children:"Manage subscription packages and view all subscribers"})]}),e.jsx(J,{children:e.jsxs(js,{defaultValue:"subscribers",className:"space-y-4",children:[e.jsxs(fs,{children:[e.jsx(Ne,{value:"subscribers",children:"Subscribers"}),e.jsx(Ne,{value:"packages",children:"Packages"}),e.jsx(Ne,{value:"waitlist",children:"Waitlist"})]}),e.jsx(we,{value:"subscribers",children:e.jsx(rj,{})}),e.jsx(we,{value:"packages",children:e.jsx(Xg,{})}),e.jsx(we,{value:"waitlist",children:e.jsx(lj,{})})]})})]})}function cj(){return e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"User Management"})}),e.jsx(J,{children:e.jsxs(js,{defaultValue:"users",className:"w-full",children:[e.jsxs(fs,{className:"mb-4 flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"users",className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4"}),"Users"]}),e.jsxs(Ne,{value:"subscriptions",className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-4 w-4"}),"Subscriptions"]}),e.jsxs(Ne,{value:"banners",className:"flex items-center gap-2",children:[e.jsx(_r,{className:"h-4 w-4"}),"Banners"]}),e.jsxs(Ne,{value:"tiers",className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"h-4 w-4"}),"Tiers"]}),e.jsxs(Ne,{value:"achievements",className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"h-4 w-4"}),"Achievements"]}),e.jsxs(Ne,{value:"rewards",className:"flex items-center gap-2",children:[e.jsx(ja,{className:"h-4 w-4"}),"Rewards"]})]}),e.jsx(we,{value:"users",children:e.jsx(Sg,{})}),e.jsx(we,{value:"subscriptions",children:e.jsx(ij,{})}),e.jsx(we,{value:"banners",children:e.jsx(Gg,{})}),e.jsx(we,{value:"tiers",children:e.jsx($g,{})}),e.jsx(we,{value:"achievements",children:e.jsx(Ig,{})}),e.jsx(we,{value:"rewards",children:e.jsx(zg,{})})]})})]})}const oj=[{value:1,label:"Single Entry"},{value:3,label:"3 Max"},{value:20,label:"20 Max"},{value:-1,label:"Unlimited"},{value:0,label:"Custom"}],Hc=[{value:"moneyline",label:"Moneyline"},{value:"spread",label:"Spreads"},{value:"totals",label:"Totals (Over/Under)"},{value:"props",label:"Player Props"}],Wc=[{value:"cash",label:"Cash"},{value:"entry_credits",label:"Entry Credits"},{value:"tier_points",label:"Tier Points"}],Xt={moneyline_favorite:1,moneyline_dog:1.5,spread:1.2,totals:1.3,props:1.5},ea={60:1.5,75:2,90:3,100:5},dj=Te.object({title:Te.string().min(1,"Title is required").max(100,"Title must be less than 100 characters"),description:Te.string().max(500,"Description must be less than 500 characters").optional().default(""),sport:Te.string().min(1,"Sport is required"),entry_fee:Te.number().min(0,"Entry fee must be positive"),prize_pool:Te.number().min(0,"Prize pool must be positive"),start_date:Te.date(),end_date:Te.date(),max_entries:Te.number().min(1,"Max entries must be at least 1").nullable(),status:Te.enum(["draft","active","pending_approval","completed","cancelled"]),rules:Te.array(Te.string()).optional().default([]),kontest_type:Te.enum(["scoring","survivor","man_vs_machine"]).default("scoring"),ai_opponent_id:Te.string().nullable().optional(),scoring_rules:Te.record(Te.any()).nullable().optional(),slate_id:Te.string().nullable().optional(),is_subscriber_only:Te.boolean().default(!1),min_picks:Te.number().min(1).default(3),max_picks:Te.number().min(1).default(10),pick_deadline:Te.date().nullable().optional(),prize_type:Te.enum(["cash","entry_credits","tier_points"]).default("
274cash"),payout_structure:Te.object({places_type:Te.enum(["top_n","percentage"]),places_value:Te.number().min(1),total_allocation:Te.number().min(0),first_place_percentage:Te.number().min(5).max(50).default(15),payouts:Te.array(Te.object({place:Te.number(),percentage:Te.number(),amount:Te.number()}))}).optional(),date_type:Te.enum(["single","multiday"]).default("single"),pick_types:Te.array(Te.string()).default(["moneyline","spread","totals"]),bet_type_multipliers:Te.object({moneyline_favorite:Te.number().optional(),moneyline_dog:Te.number().optional(),spread:Te.number().optional(),totals:Te.number().optional(),props:Te.number().optional()}).optional(),win_percentage_multipliers:Te.object({60:Te.number().optional(),75:Te.number().optional(),90:Te.number().optional(),100:Te.number().optional()}).optional(),total_ai_picks:Te.number().min(1).default(10),allow_all_true_false:Te.boolean().default(!1),max_entries_per_user:Te.number().min(1).nullable().default(1),prop_markets:Te.array(Te.string()).nullable().default(null)}).refine(s=>{const a=new Date(s.start_date.getFullYear(),s.start_date.getMonth(),s.start_date.getDate()),t=new Date(s.end_date.getFullYear(),s.end_date.getMonth(),s.end_date.getDate());return s.date_type==="single"?t>=a:t>a},{message:"End date must be after start date for multi-day contests",path:["end_date"]}),gr={scoring:{label:"Scoring",description:"Points-based competition with weighted scoring by odds",icon:"Target"},survivor:{label:"Survivor",description:"Double-elimination bracket tournament",icon:"Users"},man_vs_machine:{label:"Man vs Machine",description:"Compete against KLUTCH AI picks by selecting fades",icon:"Cpu"}},uj=[{value:"90-91",label:"90-91% Confidence"},{value:"92-94",label:"92-94% Confidence"},{value:"95-99",label:"95-99% Confidence"},{value:"100",label:"100% Confidence (Locks)"},{value:"all",label:"All KLUTCH Picks"}],mj={scoring:As,survivor:hs,man_vs_machine:Ha};function xj({kontests:s,onEdit:a,onDelete:t,onCreate:n,onViewDetails:r}){const[i,l]=v.useState("all"),[m,o]=v.useState("all"),[h,N]=v.useState("all"),[d,y]=v.useState(null),u=s.filter(c=>!(i!=="all"&&c.status!==i||m!=="all"&&c.sport!==m||h!=="all"&&c.kontest_type!==h)),x=Array.from(new Set(s.map(c=>c.sport))),g=c=>{switch(c){case"draft":return"secondary";case"active":return"default";case"pending_approval":return"warning";case"completed":return"outline";case"cancelled":return"destructive";default:return"secondary"}},f=c=>c==="pending_approval"?"Pending Approval":c,_=(c,p)=>!p||!c?0:c/p*100,k=c=>{var p;return c?((p=gr[c])==null?void 0:p.label)||c:"Scoring"},b=(c,p)=>{if(!c)return"-";switch(p){case"entry_credits":return`${c.toLocaleString()} credits`;case"tier_points":return`${c.toLocaleString()} pts`;default:return`$${c.toFixed(2)}`}},j=({type:c})=>{const p=mj[c||"scoring"]||As;return e.jsx(p,{className:"h-4 w-4"})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 w-full sm:w-auto",children:[e.jsxs(oe,{value:h,onValueChange:N,children:[e.jsx(de,{className:"w-full sm:w-[180px]",children:e.jsx(ue,{placeholder:"Filter by type"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Types"}),e.jsx(V,{value:"scoring",children:"Scoring"}),e.jsx(V,{value:"survivor",children:"Survivor"}),e.jsx(V,{value:"man_vs_machine",children:"Man vs Machine"})]})]}),e.jsxs(oe,{value:i,onValueChange:l,children:[e.jsx(de,{className:"w-full sm:w-[180px]",children:e.jsx(ue,{placeholder:"Filter by status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Statuses"}),e.jsx(V,{value:"draft",children:"Draft"}),e.jsx(V,{value:"active",children:"Active"}),e.jsx(V,{value:"pending_approval",children:"Pending Approval"}),e.jsx(V,{value:"completed",children:"Completed"}),e.jsx(V,{value:"cancelled",children:"Cancelled"})]})]}),e.jsxs(oe,{value:m,onValueChange:o,children:[e.jsx(de,{className:"w-full sm:w-[180px]",children:e.jsx(ue,{placeholder:"Filter by sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),x.map(c=>e.jsx(V,{value:c,children:c},c))]})]})]}),e.jsxs(R,{onClick:n,className:"w-full sm:w-auto",children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Create Kontest"]})]}),e.jsx("div",{className:"hidden md:block border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Title"}),e.jsx(U,{children:"Type"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Entry Fee"}),e.jsx(U,{children:"Prize Type"}),e.jsx(U,{children:"Prize Pool"}),e.jsx(U,{children:"Dates"}),e.jsx(U,{children:"Entries"}),e.jsx(U,{children:"Status"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:u.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:9,className:"text-center text-muted-foreground",children:"No kontests found"})}):u.map(c=>{var p;return e.jsxs(he,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(c),children:[e.jsx(M,{className:"font-medium",children:c.title}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(j,{type:c.kontest_type}),e.jsx("span",{className:"text-xs",children:k(c.kontest_type)})]})}),e.jsx(M,{children:c.sport}),e.jsxs(M,{children:["$",((p=c.entry_fee)==null?void 0:p.toFixed(2))||"0.00"]}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:"text-xs capitalize",children:(c.prize_type||"cash").replace("_"," ")})}),e.jsx(M,{children:b(c.prize_pool,c.prize_type)}),e.jsxs(M,{className:"text-sm",children:[e.jsx("div",{children:ke(new Date(c.start_date),"MMM d, yyyy")}),e.jsx("div",{className:"text-muted-foreground",children:ke(new Date(c.end_date),"MMM d, yyyy")})]}),e.jsx(M,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm",children:[c.current_entries||0," / ",c.max_entries||"∞"]}),c.max_entries&&e.jsx(Ct,{value:_(c.current_entries,c.max_entries),className:"h-2"})]})}),e.jsx(M,{children:e.jsx(B,{variant:g(c.status),children:f(c.status)})}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{variant:"ghost",size:"icon",onClick:w=>{w.stopPropagation(),a(c)},children:e.jsx(Bt,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"icon",onClick:w=>{w.stopPropagation(),y(c.id)},children:e.jsx(os,{className:"h-4 w-4"})})]})})]},c.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:u.length===0?e.jsx(G,{children:e.jsx(J,{className:"p-8 text-center text-muted-foreground",children:"No kontests found"})}):u.map(c=>{var p;return e.jsx(G,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(c),children:e.jsxs(J,{className:"p-4 space-y-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium truncate",children:c.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:c.sport}),e.jsx(B,{variant:g(c.status),children:f(c.status)}),e.jsx(B,{variant:"outline",className:"text-xs capitalize",children:(c.prize_type||"cash").replace("_"," ")})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Entry:"})," ",e.jsxs("span",{className:"font-medium",children:["$",((p=c.entry_fee)==null?void 0:p.toFixed(2))||"0.00"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Prize:"})," ",e.jsx("span",{className:"font-medium",children:b(c.prize_pool,c.prize_type)})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ke(new Date(c.start_date),"MMM d")," → ",ke(new Date(c.end_date),"MMM d, yyyy")]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm",children:["Entries: ",c.current_entries||0," / ",c.max_entries||"∞"]}),c.max_entries&&e.jsx(Ct,{value:_(c.current_entries,c.max_entries),className:"h-2"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:w=>{w.stopPropagation(),a(c)},children:[e.jsx(Bt,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:w=>{w.stopPropagation(),y(c.id)},children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})},c.id)})}),e.jsx(ws,{open:!!d,onOpenChange:()=>y(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Kontest"}),e.jsx(Ps,{children:"Are you sure you want to delete this kontest? This action cannot be undone."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>{d&&t(d),y(null)},children:"Delete"})]})]})})]})}function hj({date:s,onSelect:a,timezone:t="America/Chicago",disabled:n=!1}){const r=c=>{if(!c)return{hours:6,minutes:0,period:"PM"};const p=c.getHours(),w=p>=12?"PM":"AM";return{hours:p===0?12:p>12?p-12:p,minutes:c.getMinutes(),period:w}},i=r(s),[l,m]=v.useState(i.hours),[o,h]=v.useState(i.minutes),[N,d]=v.useState(i.period),[y,u]=v.useState(!1);v.useEffect(()=>{if(s){const c=r(s);m(c.hours),h(c.minutes),d(c.period)}},[s]);const x=(c,p)=>p==="AM"?c===12?0:c:c===12?12:c+12,g=(c,p,w,S)=>{if(!c){a(void 0);return}const P=new Date(c);P.setHours(x(p,S),w,0,0),a(P)},f=c=>{g(c,l,o,N)},_=c=>{const p=parseInt(c);m(p),s&&g(s,p,o,N)},k=c=>{const p=parseInt(c);h(p),s&&g(s,l,p,N)},b=c=>{d(c),s&&g(s,l,o,c)},j=()=>
274{if(!s)return"Pick a date and time";try{return ha(s,t,"MMM d, yyyy 'at' h:mm a")+" CT"}catch{return ke(s,"MMM d, yyyy 'at' h:mm a")+" CT"}};return e.jsxs(Ba,{open:y,onOpenChange:u,children:[e.jsx(za,{asChild:!0,children:e.jsxs(R,{variant:"outline",disabled:n,className:Le("w-full justify-start text-left font-normal",!s&&"text-muted-foreground"),children:[e.jsx(xt,{className:"mr-2 h-4 w-4"}),j()]})}),e.jsxs(Ka,{className:"w-auto p-0",align:"start",children:[e.jsx(Va,{mode:"single",selected:s,onSelect:f,initialFocus:!0,className:Le("p-3 pointer-events-auto")}),e.jsxs("div",{className:"p-3 border-t flex items-center gap-2 bg-background",children:[e.jsx($s,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(oe,{value:l.toString(),onValueChange:_,children:[e.jsx(de,{className:"w-[70px]",children:e.jsx(ue,{})}),e.jsx(me,{children:[12,1,2,3,4,5,6,7,8,9,10,11].map(c=>e.jsx(V,{value:c.toString(),children:c},c))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(oe,{value:o.toString(),onValueChange:k,children:[e.jsx(de,{className:"w-[70px]",children:e.jsx(ue,{})}),e.jsx(me,{children:[0,15,30,45].map(c=>e.jsx(V,{value:c.toString(),children:c.toString().padStart(2,"0")},c))})]}),e.jsxs(oe,{value:N,onValueChange:b,children:[e.jsx(de,{className:"w-[70px]",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"AM",children:"AM"}),e.jsx(V,{value:"PM",children:"PM"})]})]}),e.jsx("span",{className:"text-sm text-muted-foreground ml-2 font-medium",children:"CT"})]})]})]})}const pj=[15,12,10,8,7,6,5,5,4,4,3,3,3,3,3,3,3,3,2,2],ni=pj.map(s=>s/15);function ol(s,a,t=15){const n=[];let r=0;for(let m=0;m<a;m++){let o;m<ni.length?o=Math.round(t*ni[m]*10)/10:o=Math.round(t*(2/15)*10)/10,o=Math.max(1,o),n.push({place:m+1,percentage:o,amount:Math.round(s*o/100*100)/100}),r+=o}const i=Math.max(0,100-r),l=Math.round(s*i/100*100)/100;return{payouts:n,remainingPercentage:i,remainingAmount:l}}function gj({prizeType:s,placesType:a,placesValue:t,totalAllocation:n,maxEntries:r,firstPlacePercentage:i,onPlacesTypeChange:l,onPlacesValueChange:m,onTotalAllocationChange:o,onFirstPlacePercentageChange:h}){const N=a==="percentage"?Math.max(1,Math.ceil(t/100*r)):t,{payouts:d,remainingPercentage:y,remainingAmount:u}=ol(n,N,i),x=()=>{switch(s){case"cash":return e.jsx(La,{className:"h-4 w-4"});case"entry_credits":return e.jsx(ja,{className:"h-4 w-4"});case"tier_points":return e.jsx(Wt,{className:"h-4 w-4"})}},g=f=>s==="cash"?`$${f.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`:`${f.toLocaleString(void 0,{maximumFractionDigits:0})} ${s==="entry_credits"?"credits":"pts"}`;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Places Paid"}),e.jsxs(Ut,{value:a,onValueChange:f=>l(f),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"top_n",id:"top_n"}),e.jsxs(Q,{htmlFor:"top_n",className:"cursor-pointer flex items-center gap-1",children:[e.jsx(Js,{className:"h-4 w-4"}),"Top N Places"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"percentage",id:"percentage"}),e.jsxs(Q,{htmlFor:"percentage",className:"cursor-pointer flex items-center gap-1",children:[e.jsx(Jn,{className:"h-4 w-4"}),"% of Entries"]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:a==="top_n"?"Number of Places":"Percentage of Entries"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",min:1,max:a==="percentage"?100:1e3,value:t,onChange:f=>m(parseInt(f.target.value)||1),className:"w-24"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:a==="top_n"?"places":"%"})]}),a==="percentage"&&r>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["= ",N," places (based on ",r," max entries)"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[x(),"Total ",s==="cash"?"Prize Pool":s==="entry_credits"?"Credits Pool":"Points Pool"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:s==="cash"?"$"
274:""}),e.jsx(pe,{type:"number",min:0,step:s==="cash"?.01:1,value:n,onChange:f=>o(parseFloat(f.target.value)||0),className:"w-32"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"1st Place Percentage"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",min:5,max:50,step:1,value:i,onChange:f=>h(parseInt(f.target.value)||15),className:"w-24"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"%"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Higher % = more top-heavy prize distribution (5-50%)"})]}),n>0&&t>0&&e.jsxs(G,{children:[e.jsx(je,{className:"pb-2",children:e.jsxs(fe,{className:"text-sm flex items-center gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Payout Structure Preview"]})}),e.jsxs(J,{children:[e.jsx("div",{className:"max-h-64 overflow-y-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-20",children:"Place"}),e.jsx(U,{className:"text-right",children:"%"}),e.jsx(U,{className:"text-right",children:"Amount"})]})}),e.jsxs($e,{children:[d.slice(0,20).map(f=>e.jsxs(he,{children:[e.jsxs(M,{className:"font-medium",children:[f.place===1?"🥇":f.place===2?"🥈":f.place===3?"🥉":""," ",f.place]}),e.jsxs(M,{className:"text-right",children:[f.percentage,"%"]}),e.jsx(M,{className:"text-right font-medium",children:g(f.amount)})]},f.place)),d.length>20&&e.jsx(he,{children:e.jsxs(M,{colSpan:3,className:"text-center text-muted-foreground",children:["... and ",d.length-20," more places"]})}),y>0&&e.jsxs(he,{className:"bg-muted/50 border-t-2",children:[e.jsx(M,{className:"font-medium text-muted-foreground",children:"📦 Remaining Pool"}),e.jsxs(M,{className:"text-right text-muted-foreground",children:[y,"%"]}),e.jsx(M,{className:"text-right font-medium text-muted-foreground",children:g(u)})]})]})]})}),e.jsx("div",{className:"mt-2 pt-2 border-t text-sm text-muted-foreground",children:e.jsxs("p",{children:[e.jsx("strong",{children:"Tie-Breaking:"})," Tied users share combined prizes for their positions equally."]})})]})]})]})}const li={moneyline_favorite:{label:"Moneyline (Favorite)",icon:As,description:"Base multiplier for ML favorites"},moneyline_dog:{label:"Moneyline (Underdog)",icon:Ds,description:"Higher risk, higher reward"},spread:{label:"Spreads",icon:da,description:"Point spread bets"},totals:{label:"Totals (O/U)",icon:Qn,description:"Over/under bets"},props:{label:"Player Props",icon:ra,description:"Individual player props"}},ii={60:{label:"60%+ Correct",tier:"Bronze",color:"text-amber-600"},75:{label:"75%+ Correct",tier:"Silver",color:"text-slate-400"},90:{label:"90%+ Correct",tier:"Gold",color:"text-yellow-500"},100:{label:"100% Perfect",tier:"Diamond",color:"text-cyan-400"}};function jj({betTypeMultipliers:s,winPercentageMultipliers:a,allowAllTrueFalse:t,onBetTypeMultipliersChange:n,onWinPercentageMultipliersChange:r,onAllowAllTrueFalseChange:i}){const l=(d,y)=>{n({...s,[d]:y})},m=(d,y)=>{r({...a,[d]:y})},o=()=>{n(Xt),r(ea)},N=(()=>{const d=[{type:"spread",correct:!0},{type:"spread",correct:!0},{type:"spread",correct:!0},{type:"moneyline_favorite",correct:!0},{type:"moneyline_favorite",correct:!0},{type:"moneyline_favorite",correct:!0},{type:"totals",correct:!0},{type:"totals",correct:!0},{type:"props",correct:!1},{type:"props",correct:!1}];let y=0,u=0;d.forEach(f=>{if(f.correct){u++;const _=s[f.type]||1;y+=1*_}});const x=u/d.length*100;let g=1;return x>=100?g=a[100]||5:x>=90?g=a[90]||3:x>=75?g=a[75]||2:x>=60&&(g=a[60]||1.5),{baseScore:y.toFixed(1),winPct:x,finalMultiplier:g,finalScore:(y*g).toFixed(1)}})();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(Qn,{className:"h-4 w-4"}),"Bet Type Multipliers"]}),e.jsx(De,{children:"Each correct pick gets 1 base point × bet type multiplier"})]}),e.jsx(J,{children:e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Object.keys(li).map(d=>{const{label:y,icon:u,description:x}
274=li[d];return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Q,{className:"flex items-center gap-2 text-sm",children:[e.jsx(u,{className:"h-3 w-3"}),y]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",step:.1,min:.1,max:10,value:s[d]??Xt[d],onChange:g=>l(d,parseFloat(g.target.value)||1),className:"w-20"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"×"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x})]},d)})})})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(Jn,{className:"h-4 w-4"}),"Win Percentage Multipliers"]}),e.jsx(De,{children:"Applied to total score based on overall win percentage"})]}),e.jsx(J,{children:e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:Object.keys(ii).map(d=>{const{label:y,tier:u,color:x}=ii[d];return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Q,{className:"flex items-center gap-2 text-sm",children:[e.jsx(Js,{className:`h-3 w-3 ${x}`}),y]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",step:.1,min:1,max:20,value:a[d]??ea[d],onChange:g=>m(d,parseFloat(g.target.value)||1),className:"w-20"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"×"})]}),e.jsxs("p",{className:`text-xs font-medium ${x}`,children:[u," Tier"]})]},d)})})})]}),e.jsxs(G,{className:"bg-muted/30",children:[e.jsx(je,{className:"pb-2",children:e.jsx(fe,{className:"text-sm",children:"Example Calculation"})}),e.jsxs(J,{className:"text-sm",children:[e.jsx("p",{className:"text-muted-foreground mb-2",children:"User gets 8/10 picks correct (80%)"}),e.jsxs("ul",{className:"space-y-1 mb-2",children:[e.jsxs("li",{children:["• 3 spreads × ",s.spread||1.2," = ",(3*(s.spread||1.2)).toFixed(1)]}),e.jsxs("li",{children:["• 3 ML favorites × ",s.moneyline_favorite||1," = ",(3*(s.moneyline_favorite||1)).toFixed(1)]}),e.jsxs("li",{children:["• 2 totals × ",s.totals||1.3," = ",(2*(s.totals||1.3)).toFixed(1)]})]}),e.jsxs("p",{className:"font-medium",children:["Base Score: ",N.baseScore," × ",N.finalMultiplier,"× (75%+ tier) = ",e.jsxs("span",{className:"text-primary font-bold",children:[N.finalScore," points"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Q,{className:"text-base",children:'Allow "All True" / "All False"'}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Users can select all picks as True or all as False with one button"})]}),e.jsx(Ge,{checked:t,onCheckedChange:i})]}),e.jsx("button",{type:"button",onClick:o,className:"text-sm text-muted-foreground hover:text-foreground underline",children:"Reset to default values"})]})}const ci={basketball:[{value:"Points",label:"Points",category:"scoring"},{value:"3PT Made",label:"3PT Made",category:"scoring"},{value:"Assists",label:"Assists",category:"playmaking"},{value:"Rebounds",label:"Rebounds",category:"rebounding"},{value:"Blocks",label:"Blocks",category:"defense"},{value:"Steals",label:"Steals",category:"defense"},{value:"PTS+REB+AST",label:"PTS+REB+AST",category:"combo"},{value:"PTS+REB",label:"PTS+REB",category:"combo"},{value:"PTS+AST",label:"PTS+AST",category:"combo"},{value:"REB+AST",label:"REB+AST",category:"combo"},{value:"Fantasy Score",label:"Fantasy Score",category:"combo"}],football:[{value:"Passing Yards",label:"Passing Yards",category:"passing"},{value:"Passing TDs",label:"Passing TDs",category:"passing"},{value:"Completions",label:"Completions",category:"passing"},{value:"Pass Attempts",label:"Pass Attempts",category:"passing"},{value:"Interceptions",label:"Interceptions",category:"passing"},{value:"Rushing Yards",label:"Rushing Yards",category:"rushing"},{value:"Rush Attempts",label:"Rush Attempts",category:"rushing"},{value:"Rushing TDs",label:"Rushing TDs",category:"rushing"},{value:"Receiving Yards",label:"Receiving Yards",category:"receiving"},{value:"Receptions",label:"Receptions",category:"receiving"},{value:"Receiving TDs",label:"Receiving TDs",category:"receiving"},{value:"Tackles + Assists",label:"Tackles + Assists",category:"defense"},{value:"Sacks",label:"Sacks",category:"defense"},{value:"Fantasy Score",label:"Fantasy Score",category:"other"},{value:"Longest Rush",label:"Longest Rush",category:"other"},{value:"Longest Reception",label:"Longest Reception",category:"other"}],hockey:[{value:"Points",label:"Points",category:"scoring"},{value:"Goals",label:"Goals",category:"scoring"},{value:"Power Play Points",label:"Power Play Points",category:"scoring"},{value:"Assists",label:"Assists",category:"playmaking"},{value:"Blocked Shots",label:"Blocked Shots",category:"defense"},{value:"Hits",label:"Hits",category:"defense"},{value:"Shots on Goal",label:"Shots on Goal",category:"other"},{value:"Goalie Saves",label:"Goalie Saves",category:"other"},{value:"Goalie Goals Against",label:"Goalie Goals Against",category:"other"}],baseball:[{value:"Hits",label:"Hits",category:"scoring"},{value:"Home Runs",label:"Home Runs",category:"scoring"},{value:"RBIs",label:"RBIs",category:"scoring"},{value:"Runs",label:"Runs",category:"scoring"},{value:"Total Bases",label:"Total Bases",category:"scoring"}
274,{value:"Strikeouts",label:"Strikeouts",category:"other"},{value:"Hits Allowed",label:"Hits Allowed",category:"other"},{value:"Earned Runs",label:"Earned Runs",category:"other"},{value:"Outs Recorded",label:"Outs Recorded",category:"other"}],mma:[{value:"Significant Strikes",label:"Significant Strikes",category:"scoring"},{value:"Takedowns",label:"Takedowns",category:"other"},{value:"Method of Victory",label:"Method of Victory",category:"other"},{value:"Round Betting",label:"Round Betting",category:"other"}],soccer:[{value:"Goals",label:"Goals",category:"scoring"},{value:"Assists",label:"Assists",category:"playmaking"},{value:"Shots",label:"Shots",category:"scoring"},{value:"Shots on Target",label:"Shots on Target",category:"scoring"},{value:"Tackles",label:"Tackles",category:"defense"},{value:"Saves",label:"Saves",category:"defense"}],golf:[{value:"Tournament Winner",label:"Tournament Winner",category:"scoring"},{value:"Top 5 Finish",label:"Top 5 Finish",category:"scoring"},{value:"Top 10 Finish",label:"Top 10 Finish",category:"scoring"},{value:"Top 20 Finish",label:"Top 20 Finish",category:"scoring"},{value:"Make Cut",label:"Make Cut",category:"other"},{value:"Round Score",label:"Round Score",category:"other"}],tennis:[{value:"Match Winner",label:"Match Winner",category:"scoring"},{value:"Set Winner",label:"Set Winner",category:"scoring"},{value:"Games Won",label:"Games Won",category:"scoring"},{value:"Aces",label:"Aces",category:"other"},{value:"Double Faults",label:"Double Faults",category:"other"}]};function fj({selectedMarkets:s,onChange:a,sport:t}){const[n,r]=v.useState(s!==null&&s.length>0),i=s===null?"all":"specific",m=(()=>{const y=t.toLowerCase();if(y==="all"||y===""){const u=[],x=new Set;return Object.values(ci).forEach(g=>{g.forEach(f=>{x.has(f.value)||(x.add(f.value),u.push(f))})}),u}return ci[y]||[]})(),o=m.reduce((y,u)=>(y[u.category]||(y[u.category]=[]),y[u.category].push(u),y),{}),h=y=>{if(y==="all")a(null),r(!1);else{const u=m.slice(0,3).map(x=>x.value);a(u),r(!0)}},N=y=>{s!==null&&(s.includes(y)?s.length>1&&a(s.filter(u=>u!==y)):a([...s,y]))},d={scoring:"Scoring",playmaking:"Playmaking",rebounding:"Rebounding",defense:"Defense",combo:"Combo Stats",passing:"Passing",rushing:"Rushing",receiving:"Receiving",other:"Other"};return m.length===0?e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg text-sm text-muted-foreground",children:["No prop markets available for ",t||"this sport"]}):e.jsxs("div",{className:"space-y-3 p-3 bg-muted/30 rounded-lg border border-border/50",children:[e.jsx(Q,{className:"text-sm font-medium",children:"Prop Markets Configuration"}),e.jsxs(Ut,{value:i,onValueChange:h,className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"all",id:"prop-all"}),e.jsxs("label",{htmlFor:"prop-all",className:"text-sm cursor-pointer",children:["All Prop Markets ",e.jsx("span",{className:"text-muted-foreground",children:"(default)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"specific",id:"prop-specific"}),e.jsx("label",{htmlFor:"prop-specific",className:"text-sm cursor-pointer",children:"Select Specific Markets"})]})]}),i==="specific"&&e.jsxs(vs,{open:n,onOpenChange:r,children:[e.jsxs(ys,{className:"flex items-center gap-2 text-sm text-primary hover:underline w-full justify-between p-2 bg-background rounded border",children:[e.jsxs("span",{children:[(s==null?void 0:s.length)||0," market",((s==null?void 0:s.length)||0)!==1?"s":""," selected"]}),n?e.jsx(Ua,{className:"h-4 w-4"}):e.jsx(Ns,{className:"h-4 w-4"})]}),e.jsx(_s,{className:"mt-2 space-y-3",children:Object.entries(o).map(([y,u])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:d[y]||y}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:u.map(x=>{const g=(s==null?void 0:s.includes(x.value))||!1;return e.jsxs("div",{className:`flex items-center space-x-2 rounded-md border p-2 cursor-pointer transition-colors text-sm ${g?"border-primary bg-primary/5":"border-border hover:border-primary/50"}`,onClick:()=>
274N(x.value),children:[e.jsx("div",{className:`h-4 w-4 shrink-0 rounded-sm border flex items-center justify-center transition-colors ${g?"bg-primary border-primary text-primary-foreground":"border-primary"}`,children:g&&e.jsx(Ks,{className:"h-3 w-3"})}),e.jsx("span",{className:"truncate",children:x.label})]},x.value)})})]},y))})]})]})}const vj={moneyline:As,spread:da,totals:Ds,props:oa};function yj({selectedTypes:s,onChange:a,sport:t,propMarkets:n,onPropMarketsChange:r}){const i=l=>{if(s.includes(l)){if(s.length>1){const m=s.filter(o=>o!==l);a(m),l==="props"&&r(null)}}else a([...s,l])};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Q,{children:"Pick Types Included"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select which bet types will be included in this contest"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Hc.map(({value:l,label:m})=>{const o=vj[l],h=s.includes(l);return e.jsxs("div",{className:`flex items-center space-x-3 rounded-lg border p-3 cursor-pointer transition-colors ${h?"border-primary bg-primary/5":"border-border hover:border-primary/50"}`,onClick:()=>i(l),children:[e.jsx("div",{className:`h-4 w-4 shrink-0 rounded-sm border flex items-center justify-center transition-colors ${h?"bg-primary border-primary text-primary-foreground":"border-primary"}`,children:h&&e.jsx(Ks,{className:"h-3 w-3"})}),e.jsxs("span",{className:"flex items-center gap-2 flex-1",children:[o&&e.jsx(o,{className:"h-4 w-4"}),m]})]},l)})}),s.includes("props")&&e.jsx(fj,{selectedMarkets:n,onChange:r,sport:t})]})}function Nj({entryFee:s,maxEntriesPerUser:a,pickDeadline:t,totalPicks:n,pickTypes:r,allowAllTrueFalse:i,betTypeMultipliers:l,winPercentageMultipliers:m,prizeType:o,totalAllocation:h,placesValue:N,placesType:d,maxEntries:y,kontestType:u,propMarkets:x,firstPlacePercentage:g}){var $;const f=s===0?"FREE":`$${s.toFixed(2)}`,_=a===null?"Unlimited":a===1?"Single Entry":`${a} Max`,k=t?ha(t,"America/Chicago","MMM d, yyyy 'at' h:mm a 'CT'"):"Not set",b=r.map(z=>{var D;return((D=Hc.find(A=>A.value===z))==null?void 0:D.label)||z}).join(", "),j=(($=Wc.find(z=>z.value===o))==null?void 0:$.label)||o,c={moneyline_favorite:"Moneyline (Favorite)",moneyline_dog:"Moneyline (Underdog)",spread:"Spreads",totals:"Totals (O/U)",props:"Player Props"},p={60:"60%+ Correct",75:"75%+ Correct",90:"90%+ Correct",100:"100% Perfect"},w=d==="percentage"?Math.max(1,Math.ceil(N/100*y)):N,{payouts:S}=ol(h,w,g),P=z=>o==="cash"?`$${z.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`:`${Math.round(z).toLocaleString()} ${o==="entry_credits"?"credits":"pts"}`,C=z=>z===1?"🥇":z===2?"🥈":z===3?"🥉":"",O=z=>{const D=["th","st","nd","rd"],A=z%100;return z+(D[(A-20)%10]||D[A]||D[0])};return e.jsxs(G,{children:[e.jsxs(je,{className:"pb-3",children:[e.jsxs(fe,{className:"text-sm flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Contest Rules Preview"]}),e.jsx(De,{children:"These rules are auto-generated from your contest settings"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm mb-2 text-foreground",children:"Entry Requirements"}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("li",{children:["• Entry Fee: ",e.jsx("span",{className:"text-foreground font-medium",children:f})]}),e.jsxs("li",{children:["• Max Entries Per User: ",e.jsx("span",{className:"text-foreground font-medium",children:_})]}),e.jsxs("li",{children:["• Entry Deadline: ",e.jsx("span",{className:"text-foreground font-medium",children:k})]})]})]}),e.jsx(is,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm mb-2 text-foreground",children:"Pick Requirements"}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("li",{children:["• Total Picks: ",e.jsx("span",{className:"text-foreground font-medium",children:n})]}),e.jsxs("li",{children:["• Pick Types: ",e.jsx("span",{className:"text-foreground font-medium",children:b||"None selected"})]}),i&&e.jsxs("li",{children:["• Quick Selection: ",e.jsx("span",{className:"text-foreground font-medium",children:"All True/All False enabled"})]}),r.includes("props")&&e.jsxs("li",{children:["• Prop Markets: ",e.jsx("span",{className:"text-foreground font-medium",children:x===null||x.length===0?"All Markets":`${x.length} selected (${x.slice(0,3).join(", ")}${x.length>3?"...":""})`})]})]})]}),(u==="scoring"||u==="man_vs_machine")&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm mb-2 text-foreground",children:"Scoring Multipliers"}),e.jsx("ul",{className:"text-sm text-muted-foreground space-y-1",children:Object.entries(l).map(([z,D])=>D&&e.jsxs("li",{children:["• ",c[z]||z,": ",e.jsxs("span",{className:"text-foreground font-medium",children:[D,"x"]})]},z))})]})]}),(u==="scoring"||u==="man_vs_machine")&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm mb-2 text-foreground",children:"Win Percentage Bonu
274ses"}),e.jsx("ul",{className:"text-sm text-muted-foreground space-y-1",children:Object.entries(m).map(([z,D])=>D&&e.jsxs("li",{children:["• ",p[z]||`${z}%`,": ",e.jsxs("span",{className:"text-foreground font-medium",children:[D,"x"]})]},z))})]})]}),e.jsx(is,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm mb-2 text-foreground",children:"Payouts"}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("li",{children:["• Prize Type: ",e.jsx("span",{className:"text-foreground font-medium",children:j})]}),e.jsxs("li",{children:["• Total Pool: ",e.jsx("span",{className:"text-foreground font-medium",children:o==="cash"?`$${h.toLocaleString()}`:`${h.toLocaleString()} ${o==="entry_credits"?"credits":"points"}`})]}),e.jsxs("li",{children:["• Rewarded Places: ",e.jsx("span",{className:"text-foreground font-medium",children:d==="percentage"?`Top ${N}% of entries (${w} places)`:`Top ${N}`})]})]}),h>0&&S.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx("span",{className:"text-sm text-foreground font-medium",children:"Prize Distribution:"}),e.jsx("div",{className:"mt-1 max-h-48 overflow-y-auto",children:e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-0.5 pl-4",children:[S.slice(0,10).map(z=>e.jsxs("li",{children:[C(z.place)," ",O(z.place),": ",e.jsx("span",{className:"text-foreground font-medium",children:P(z.amount)})," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",z.percentage,"%)"]})]},z.place)),S.length>10&&e.jsxs("li",{className:"text-muted-foreground italic",children:["...and ",S.length-10," more places"]})]})})]})]})]})]})}const _j={scoring:As,survivor:hs,man_vs_machine:Ha};function bj({open:s,onClose:a,onSubmit:t,kontest:n}){const[r,i]=v.useState(!1),[l,m]=v.useState("basic"),[o,h]=v.useState("cash"),[N,d]=v.useState("top_n"),[y,u]=v.useState(10),[x,g]=v.useState(15),[f,_]=v.useState(1e3),[k,b]=v.useState("single"),[j,c]=v.useState(Xt),[p,w]=v.useState(ea),[S,P]=v.useState(!1),[C,O]=v.useState(["moneyline","spread","totals"]),[$,z]=v.useState(null),[D,A]=v.useState(1),[F,q]=v.useState(5),E=Wa({resolver:Ga(dj),defaultValues:{title:"",description:"",sport:"MLB",entry_fee:0,prize_pool:0,start_date:new Date,end_date:new Date(Date.now()+7*24*60*60*1e3),max_entries:100,status:"draft",rules:[""],kontest_type:"scoring",ai_opponent_id:null,is_subscriber_only:!1,min_picks:3,max_picks:5,pick_deadline:null,prize_type:"cash",date_type:"single",pick_types:["moneyline","spread","totals"],bet_type_multipliers:Xt,win_percentage_multipliers:ea,total_ai_picks:10,allow_all_true_false:!1,max_entries_per_user:1,prop_markets:null}}),L=E.watch("kontest_type"),H=E.watch("max_entries"),Z=v.useMemo(()=>H??100,[H]);v.useEffect(()=>{var I;if(s){if(n){const ee=n.payout_structure,le=n.bet_type_multipliers,ve=n.win_percentage_multipliers;E.reset({title:n.title,description:n.description||"",sport:n.sport,entry_fee:n.entry_fee||0,prize_pool:n.prize_pool||0,start_date:new Date(n.start_date),end_date:new Date(n.end_date),max_entries:n.max_entries,status:n.status,rules:((I=n.rules)==null?void 0:I.list)||[""],kontest_type:n.kontest_type||"scoring",ai_opponent_id:n.ai_opponent_id||null,is_subscriber_only:n.is_subscriber_only||!1,min_picks:n.min_picks||3,max_picks:n.max_picks||5,pick_deadline:n.pick_deadline?new Date(n.pick_deadline):null,prize_type:n.prize_type||"cash",date_type:n.date_type||"single",pick_types:n.pick_types||["moneyline","spread","totals"],bet_type_multipliers:le||Xt,win_percentage_multipliers:ve||ea,total_ai_picks:n.total_ai_picks||10,allow_all_true_false:n.allow_all_true_false||!1,max_entries_per_user:n.max_entries_per_user??1,prop_markets:n.prop_markets||null});const te=n.max_entries_per_user;te===null?A(-1):[1,3,20].includes(te)?A(te):(A(0),q(te)),h(n.prize_type||"cash"),d((ee==null?void 0:ee.places_type)||"top_n"),u((ee==null?void 0:ee.places_value)||10),_((ee==null?void 0:ee.total_allocation)||n.prize_pool||1e3),g((ee==null?void 0:ee.first_place_percentage)||15),b(n.date_type||"single"),c(le||Xt),w(ve||ea),P(n.allow_all_true_false||!1),O(n.pick_types||["moneyline","spread","totals"]),z(n.prop_markets||null)}
274else E.reset({title:"",description:"",sport:"MLB",entry_fee:0,prize_pool:0,start_date:new Date,end_date:new Date(Date.now()+7*24*60*60*1e3),max_entries:100,status:"draft",rules:[""],kontest_type:"scoring",ai_opponent_id:null,is_subscriber_only:!1,min_picks:3,max_picks:5,pick_deadline:null,prize_type:"cash",date_type:"single",pick_types:["moneyline","spread","totals"],bet_type_multipliers:Xt,win_percentage_multipliers:ea,total_ai_picks:10,allow_all_true_false:!1,max_entries_per_user:1,prop_markets:null}),A(1),q(5),h("cash"),d("top_n"),u(10),_(1e3),g(15),b("single"),c(Xt),w(ea),P(!1),z(null),O(["moneyline","spread","totals"]);m("basic")}},[n,s]);const se=I=>{console.error("Form validation errors:",I);const ee={title:"basic",description:"basic",sport:"basic",status:"basic",max_entries:"basic",max_entries_per_user:"basic",entry_fee:"prizes",prize_pool:"prizes",start_date:"structure",end_date:"structure",pick_deadline:"structure",min_picks:"structure",max_picks:"structure"},le=Object.keys(I)[0];le&&ee[le]&&m(ee[le]);const ve=Object.entries(I).slice(0,3).map(([te,X])=>`${te}: ${X==null?void 0:X.message}`).join(", ");K.error(`Please fix the following errors: ${ve}`)},ie=async I=>{i(!0);try{const ee=E.getValues("max_entries")||100,le=N==="percentage"?Math.max(1,Math.ceil(y/100*ee)):y,ve={places_type:N,places_value:y,total_allocation:f,first_place_percentage:x,payouts:ol(f,le,x).payouts},te=Y({entryFee:I.entry_fee,maxEntriesPerUser:D===-1?null:D===0?F:D,pickDeadline:I.pick_deadline,totalPicks:I.total_ai_picks,pickTypes:C,prizeType:o,totalAllocation:f,placesValue:y});await t({...I,rules:te,prize_type:o,payout_structure:ve,date_type:k,pick_types:C,bet_type_multipliers:j,win_percentage_multipliers:p,allow_all_true_false:S,max_entries_per_user:D===-1?null:D===0?F:D,prop_markets:C.includes("props")?$:null}),a()}catch(ee){console.error("Error submitting kontest:",ee)}finally{i(!1)}},Y=I=>{const ee=[];if(ee.push(I.entryFee===0?"Entry is FREE":`Entry fee: $${I.entryFee.toFixed(2)}`),ee.push(I.maxEntriesPerUser===null?"Unlimited entries per user":I.maxEntriesPerUser===1?"Single entry per user":`Maximum ${I.maxEntriesPerUser} entries per user`),ee.push(`Make predictions on ${I.totalPicks} AI picks`),I.pickTypes.length>0){const ve=I.pickTypes.map(te=>te==="moneyline"?"Moneyline":te==="spread"?"Spreads":te==="totals"?"Totals":te==="props"?"Props":te);ee.push(`Pick types include: ${ve.join(", ")}`)}const le=I.prizeType==="cash"?`$${I.totalAllocation.toLocaleString()}`:I.prizeType==="entry_credits"?`${I.totalAllocation.toLocaleString()} Entry Credits`:`${I.totalAllocation.toLocaleString()} Tier Points`;return ee.push(`Prize pool: ${le}`),ee.push(`Top ${I.placesValue} finishers win prizes`),ee};return s?e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:n?"Edit Kontest":"Create New Kontest"}),e.jsx(Vs,{children:n?"Update kontest details":"Create a new kontest for users to enter"})]}),e.jsx(Cr,{...E,children:e.jsxs("form",{onSubmit:E.handleSubmit(ie,se),className:"space-y-4",children:[e.jsx(Ye,{control:E.control,name:"kontest_type",render:({field:I})=>{var ee;return e.jsxs(Je,{children:[e.jsx(Ze,{children:"Contest Type"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Object.keys(gr).map(le=>{const ve=_j[le],te=gr[le];return e.jsxs("button",{type:"button",onClick:()=>I.onChange(le),className:Le("flex flex-col items-center p-3 rounded-lg border-2 transition-all",I.value===le?"border-primary bg-primary/10":"border-border hover:border-primary/50"),children:[e.jsx(ve,{className:"h-6 w-6 mb-1"}),e.jsx("span",{className:"text-xs font-medium",children:te.label})]},le)})}),e.jsx(er,{children:(ee=gr[I.value])==null?void 0:ee.description}),e.jsx(Xe,{})]})}}),e.jsxs(js,{value:l,onValueChange:m,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"basic",className:"flex items-center gap-1 text-xs",children:[e.jsx(kt,{className:"h-3 w-3"}),"Basic"]}),e.jsxs(Ne,{value:"prizes",className:"flex items-center gap-1 text-xs",children:[e.jsx(Js,{className:"h-3 w-3"}),"Prizes"]}),e.jsxs(Ne,{value:"structure",className:"flex items-center gap-1 text-xs",children:[e.jsx(xt,{className:"h-3 w-3"}),"Structure"]}),e.jsxs(Ne,{value:"scoring",className:"flex items-center gap-1 text-xs",children:[e.jsx(Qn,{className:"h-3 w-3"}),"Scoring"]}),e.jsxs(Ne,{value:"summary",className:"flex items-center gap-1 text-xs",children:[e.jsx(kt,{className:"h-3 w-3"}),"Summary"]})]}
274),e.jsxs(we,{value:"basic",className:"space-y-4 mt-4",children:[e.jsx(Ye,{control:E.control,name:"title",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Title"}),e.jsx(es,{children:e.jsx(pe,{placeholder:"Spring Baseball Championship",...I})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:E.control,name:"description",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Description"}),e.jsx(es,{children:e.jsx(Xs,{placeholder:"Enter kontest description...",rows:3,...I})}),e.jsx(Xe,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ye,{control:E.control,name:"sport",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Sport"}),e.jsxs(oe,{onValueChange:I.onChange,value:I.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select sport"})})}),e.jsx(me,{children:Dd.map(ee=>e.jsx(V,{value:ee,children:ee},ee))})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:E.control,name:"status",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Status"}),e.jsxs(oe,{onValueChange:I.onChange,value:I.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select status"})})}),e.jsxs(me,{children:[e.jsx(V,{value:"draft",children:"Draft"}),e.jsx(V,{value:"active",children:"Active"}),e.jsx(V,{value:"completed",children:"Completed"}),e.jsx(V,{value:"cancelled",children:"Cancelled"})]})]}),e.jsx(Xe,{})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ye,{control:E.control,name:"entry_fee",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Entry Fee ($)"}),e.jsx(es,{children:e.jsx(pe,{type:"number",step:"0.01",...I,onChange:ee=>I.onChange(parseFloat(ee.target.value)||0)})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:E.control,name:"max_entries",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Max Entries"}),e.jsx(es,{children:e.jsx(pe,{type:"number",...I,value:I.value||"",onChange:ee=>I.onChange(parseInt(ee.target.value)||null)})}),e.jsx(Xe,{})]})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Q,{className:"text-sm font-medium",children:"Max Entries Per User"}),e.jsx(Ut,{value:D.toString(),onValueChange:I=>A(parseInt(I)),className:"grid grid-cols-3 gap-2",children:oj.map(I=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:I.value.toString(),id:`entry-limit-${I.value}`}),e.jsx(Q,{htmlFor:`entry-limit-${I.value}`,className:"text-sm cursor-pointer",children:I.label})]},I.value))}),D===0&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(pe,{type:"number",min:1,value:F,onChange:I=>q(parseInt(I.target.value)||1),className:"w-24"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"entries per user"})]})]}),e.jsx(Ye,{control:E.control,name:"is_subscriber_only",render:({field:I})=>e.jsxs(Je,{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ze,{className:"text-base",children:"Subscribers Only"}),e.jsx(er,{children:"Restrict this contest to paid subscribers"})]}),e.jsx(es,{children:e.jsx(Ge,{checked:I.value,onCheckedChange:I.onChange})})]})})]}),e.jsx(we,{value:"prizes",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Prize Type"}),e.jsxs(oe,{value:o,onValueChange:I=>h(I),children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select prize type"})}),e.jsx(me,{children:Wc.map(I=>e.jsx(V,{value:I.value,children:I.label},I.value))})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o==="cash"&&"Real money payouts to winners",o==="entry_credits"&&"Credits for future contest entries",o==="tier_points"&&"Points toward tier advancement"]})]}),e.jsx(gj,{prizeType:o,placesType:N,placesValue:y,totalAllocation:f,maxEntries:Z,firstPlacePercentage:x,onPlacesTypeChange:d,onPlacesValueChange:u,onTotalAllocationChange:_,onFirstPlacePercentageChange:g})]})}),e.jsxs(we,{value:"structure",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Date Type"}),e.jsxs(Ut,{value:k,onValueChange:I=>{const ee=I;b(ee),E.setValue("date_type",ee)},className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"single",id:"single"}),e.jsx(Q,{htmlFor:"single",className:"cursor-pointer",children:"Single Day"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"multiday",i
274d:"multiday"}),e.jsx(Q,{htmlFor:"multiday",className:"cursor-pointer",children:"Multi-Day"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ye,{control:E.control,name:"start_date",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Start Date"}),e.jsx(es,{children:e.jsx(yr,{date:I.value,onSelect:I.onChange})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:E.control,name:"end_date",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"End Date"}),e.jsx(es,{children:e.jsx(yr,{date:I.value,onSelect:I.onChange})}),e.jsx(Xe,{})]})})]}),e.jsx(Ye,{control:E.control,name:"pick_deadline",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Entry Deadline"}),e.jsx(es,{children:e.jsx(hj,{date:I.value||void 0,onSelect:I.onChange,timezone:"America/Chicago"})}),e.jsx(er,{children:"All entries must be submitted by this date/time (Central Time)"}),e.jsx(Xe,{})]})}),L==="man_vs_machine"&&e.jsxs("div",{className:"space-y-4 p-4 rounded-lg border bg-muted/30",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Man vs Machine Settings"]}),e.jsx(Ye,{control:E.control,name:"ai_opponent_id",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"AI Confidence Band"}),e.jsxs(oe,{onValueChange:I.onChange,value:I.value||"all",children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select confidence band"})})}),e.jsx(me,{children:uj.map(ee=>e.jsx(V,{value:ee.value,children:ee.label},ee.value))})]}),e.jsx(er,{children:"Which KLUTCH picks to include in this contest"}),e.jsx(Xe,{})]})}),e.jsx(yj,{selectedTypes:C,onChange:O,sport:E.watch("sport"),propMarkets:$,onPropMarketsChange:z}),e.jsx(Ye,{control:E.control,name:"total_ai_picks",render:({field:I})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Total AI Picks"}),e.jsx(es,{children:e.jsx(pe,{type:"number",min:1,max:50,...I,onChange:ee=>I.onChange(parseInt(ee.target.value)||10)})}),e.jsx(er,{children:"Number of AI picks users must predict (True/False)"}),e.jsx(Xe,{})]})})]})]}),e.jsx(we,{value:"scoring",className:"space-y-4 mt-4",children:e.jsx(jj,{betTypeMultipliers:j,winPercentageMultipliers:p,allowAllTrueFalse:S,onBetTypeMultipliersChange:c,onWinPercentageMultipliersChange:w,onAllowAllTrueFalseChange:P})}),e.jsx(we,{value:"summary",className:"space-y-4 mt-4",children:e.jsx(Nj,{entryFee:E.watch("entry_fee"),maxEntriesPerUser:D===-1?null:D===0?F:D,pickDeadline:E.watch("pick_deadline"),totalPicks:E.watch("total_ai_picks"),pickTypes:C,allowAllTrueFalse:S,betTypeMultipliers:j,winPercentageMultipliers:p,prizeType:o,totalAllocation:f,placesValue:y,placesType:N,maxEntries:Z,kontestType:L,propMarkets:$,firstPlacePercentage:x})})]}),e.jsxs(lt,{children:[e.jsx(R,{type:"button",variant:"outline",onClick:a,children:"Cancel"}),e.jsx(R,{type:"submit",disabled:r,children:r?"Saving...":n?"Update Kontest":"Create Kontest"})]})]})})]})}):null}const oi=s=>{const a=s.current_line;if(a!=null&&a!==0)return a;const t=s.trigger_data,n=t==null?void 0:t.sportsbook_breakdown;if(n&&Array.isArray(n)&&n.length>0){const r=n.find(i=>i.current_line>0);return r?r.current_line:n[0].current_line}return null},wj=s=>{const a={moneyline:"moneyline",spread:"spread",totals:"total",props:"prop"};return s.map(t=>a[t]||t)};function Sj(s,a,t,n,r,i,l){return ge({queryKey:["kontest-ai-picks",s,a,t,r,i,l],queryFn:async()=>{const m=l||10,{data:o,error:h}=await T.from("kontest_approved_picks").select(`
275          *,
276          klutch_pick:klutch_picks(*)
277        `).eq("kontest_id",s).order("display_order",{ascending:!0});if(h)throw h;const N=(o||[]).map(c=>({...c.klutch_pick,approved_at:c.approved_at,display_order:c.display_order,current_line:oi(c.klutch_pick)})),d=N.length;if(d>=m)return{approvedCount:d,totalRequired:m,approvedPicks:N,availablePicks:[],isFullyApproved:!0};const u=(o||[]).map(c=>c.klutch_pick_id),x=c=>{const p=c.match(/^(\d{4}-\d{2}-\d{2})/);return p?p[1]:c},g=x(t),f=x(n);let _=T.from("klutch_picks").select("*").gte("game_date",g).lte("game_date",f);if(a.toLowerCase()!=="all"&&(_=_.ilike("sport",a)),u.length>0&&(_=_.not("id","in",`(${u.join(",")})`)),r&&r.length>0){const c=wj(r);_=_.in("pick_type",c)}if(i&&typeof i=="object"){const c=i.ai_confidence_band;if(c&&c!=="all"&&typeof c=="string"){const[p]=c.split("-").map(Number);isNaN(p)||(_=_.gte("confidence_score",p))}}const{data:k,error:b}=await _.order("confidence_score",{ascending:!1});if(b)throw b;const j=(k||[]).map(c=>({...c,current_line:oi(c)}));return{approvedCount:d,totalRequired:m,approvedPicks:N,availablePicks:j,isFullyApproved:!1}},enabled:!!s&&!!a})}function kj(){const s=Me();return _e({mutationFn:async({kontestId:a,pickIds:t})=>{const{data:{user:n}}=await T.auth.getUser();if(!n)throw new Error("Not authenticated");const r=t.map((m,o)=>({kontest_id:a,klutch_pick_id:m,approved_by:n.id,display_order:o+1})),{error:i}=await T.from("kontest_approved_picks").insert(r);if(i)throw i;const{error:l}=await T.from("kontests").update({picks_approved_at:new Date().toISOString(),picks_approved_by:n.id}).eq("id",a);if(l)throw l;return{success:!0}},onSuccess:(a,t)=>{s.invalidateQueries({queryKey:["kontest-ai-picks",t.kontestId]}),s.invalidateQueries({queryKey:["kontests"]}),K.success("AI picks approved successfully")},onError:a=>{K.error(`Failed to approve picks: ${a.message}`)}})}function Cj(s){return ge({queryKey:["kontest-user-entries",s],queryFn:async()=>{var y;const{data:a,error:t}=await T.from("kontests").select("payout_structure").eq("id",s).single();if(t)throw t;const n=((y=a==null?void 0:a.payout_structure)==null?void 0:y.payouts)||[],r={};
277n.forEach(u=>{r[u.place]=u.amount});const{data:i,error:l}=await T.from("kontest_entries").select(`
278          id,
279          user_id,
280          kontest_id,
281          status,
282          score,
283          created_at,
284          user:user_profiles(display_name)
285        `).eq("kontest_id",s);if(l)throw l;const{data:m,error:o}=await T.from("kontest_leaderboard").select("user_id, prize_awarded_at, username").eq("kontest_id",s);if(o)throw o;const h={};(m||[]).forEach(u=>{h[u.user_id]={prize_awarded_at:u.prize_awarded_at,username:u.username}});const N={};(i||[]).forEach(u=>{var f;const x=u.user_id,g=u.score??0;N[x]||(N[x]={entry_count:0,best_score:g,display_name:((f=u.user)==null?void 0:f.display_name)||"Unknown User"}),N[x].entry_count+=1,g>N[x].best_score&&(N[x].best_score=g)});const d=Object.keys(N).map(u=>{const x=N[u],g=h[u];return{user_id:u,kontest_id:s,score:x.best_score,rank:void 0,prize_amount:void 0,prize_awarded_at:g==null?void 0:g.prize_awarded_at,entry_count:x.entry_count,display_name:x.display_name||(g==null?void 0:g.username)||"Unknown User",username:(g==null?void 0:g.username)||void 0}});return d.sort((u,x)=>x.score-u.score),d.forEach((u,x)=>{if(x===0)u.rank=1;else{const g=d[x-1];u.score===g.score?u.rank=g.rank:u.rank=x+1}u.prize_amount=r[u.rank]||void 0}),d},enabled:!!s})}function Pj(){const s=Me();return _e({mutationFn:async a=>{const{data:{user:t}}=await T.auth.getUser();if(!t)throw new Error("Not authenticated");const{data:n,error:r}=await T.rpc("award_kontest_prizes",{p_kontest_id:a,p_admin_id:t.id});if(r)throw r;return n},onSuccess:(a,t)=>{s.invalidateQueries({queryKey:["kontest-user-entries",t]}),s.invalidateQueries({queryKey:["kontests"]});const n=a;n.success?K.success(`Awarded prizes to ${n.awarded_count} users (${n.prize_type})`):K.error("Failed to award prizes")},onError:a=>{K.error(`Failed to award prizes: ${a.message}`)}})}function Fj(){const s=Me();return _e({mutationFn:async({kontestId:a,userId:t})=>{const{data:{user:n}}=await T.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:r,error:i}=await T.rpc("award_kontest_prize_single",{p_kontest_id:a,p_user_id:t,p_admin_id:n.id});if(i)throw i;return r},onSuccess:(a,t)=>{s.invalidateQueries({queryKey:["kontest-user-entries",t.kontestId]});const n=a;n.success&&K.success(`Awarded ${n.prize_type==="cash"?"$":""}${n.prize_amount}${n.prize_type==="entry_credits"?" credits":n.prize_type==="tier_points"?" pts":""} to rank #${n.rank}`)},onError:a=>{K.error(`Failed to award prize: ${a.message}`)}})}function Aj(){const s=Me();return _e({mutationFn:async({kontestId:a,pickId:t})=>{const{error:n}=await T.from("kontest_approved_picks").delete().eq("kontest_id",a).eq("klutch_pick_id",t);if(n)throw n;return{success:!0}},onSuccess:(a,t)=>{s.invalidateQueries({queryKey:["kontest-ai-picks",t.kontestId]}),K.success("Pick removed from approved list")},onError:a=>{K.error(`Failed to unapprove pick: ${a.message}`)}})}function Tj(){const s=Me();return _e({mutationFn:async a=>{const{data:{user:t}}=await T.auth.getUser();if(!t)throw new Error("Not authenticated");const{error:n}=await T.from("kontests").update({picks_locked_at:new Date().toISOString()}).eq("id",a);if(n)throw n;const{error:r}=await T.from("kontest_entries").update({status:"pending_picks"}).eq("kontest_id",a).eq("status","reserved");r&&console.error("Failed to update entry statuses:",r);const{data:i}=await T.from("kontests").select("title").eq("id",a).single(),{data:l}=await T.from("kontest_entries").select("user_id").eq("kontest_id",a);let m=0;if(l&&l.length>0){const o=[...new Set(l.map(N=>N.user_id))];m=o.length;const h=o.map(N=>({user_id:N,notification_type:"kontest_picks_ready",title:"Kontest Picks Are Ready!",message:`The AI picks for "${i==null?void 0:i.title}" are now available. Make your selections!`,action_url:`/kontests/lobby?open=${a}`,metadata:{kontest_id:a}}));await T.from("user_notifications").insert(h)}return{success:!0,notified:m}},onSuccess:(a,t)=>{s.invalidateQueries({queryKey:["kontest",t]}),s.invalidateQueries({queryKey:["kontests"]}),s.invalidateQueries({queryKey:["kontest-ai-picks",t]}),K.success(`Kontest locked! ${a.notified} user(s) notified.`)},onError:a=>{K.error(`Failed to lock kontest: ${a.message}`)}})}function Lj(){const s=Me();return _e({mutationFn:async a=>{const{error:t}=await T.from("kontests").update({picks_locked_at:null}).eq("id",a);if(t)throw t;return{success:!0}},onSuccess:(a,t)=>{s.invalidateQueries({queryKey:["kontest",t]}),s.invalidateQueries({queryKey:["kontests"]}),s.invalidateQueries({queryKey:["kontest-ai-picks",t]}),K.success("Kontest unlocked - you can now modify picks")},onError:a=>{K.error(`Failed to unlock: ${a.message}`)}})}function jr(s,a){if(!s)return"-";
285switch(a){case"entry_credits":return`${s.toLocaleString()} credits`;case"tier_points":return`${s.toLocaleString()} pts`;default:return`$${s.toFixed(2)}`}}function Ej({kontest:s}){const[a,t]=v.useState(new Set),[n,r]=v.useState(!1),[i,l]=v.useState(!1),{data:m,isLoading:o,isFetching:h,refetch:N}=Sj(s.id,s.sport,s.start_date,s.end_date,s.pick_types,s.scoring_rules,s.total_ai_picks),d=kj(),y=Aj(),u=Tj(),x=Lj(),g=(m==null?void 0:m.approvedPicks)||[],f=(m==null?void 0:m.availablePicks)||[],_=(m==null?void 0:m.approvedCount)||0,k=(m==null?void 0:m.totalRequired)||s.total_ai_picks||10,b=(m==null?void 0:m.isFullyApproved)||!1,j=!!s.picks_locked_at,c=new Date,p=s.pick_deadline?new Date(s.pick_deadline):new Date(s.end_date),w=c<p,S=!j&&w,P=A=>{const F=new Set(a);F.has(A)?F.delete(A):F.add(A),t(F)},C=()=>{a.size===f.length?t(new Set):t(new Set(f.map(A=>A.id)))},O=()=>{a.size!==0&&d.mutate({kontestId:s.id,pickIds:Array.from(a)},{onSuccess:()=>{r(!1),t(new Set)}})},$=A=>{y.mutate({kontestId:s.id,pickId:A})},z=A=>{A?l(!0):x.mutate(s.id)},D=A=>!A||A==="pending"?e.jsxs(B,{variant:"outline",children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),"Pending"]}):A==="won"?e.jsxs(B,{variant:"default",className:"bg-green-600",children:[e.jsx(Js,{className:"h-3 w-3 mr-1"}),"Won"]}):e.jsx(B,{variant:"destructive",children:"Lost"});return o?e.jsx(G,{children:e.jsx(J,{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(G,{children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(fe,{className:"text-lg",children:"AI Picks"}),b?e.jsxs(B,{variant:"default",className:"bg-green-600",children:[e.jsx(Ks,{className:"h-3 w-3 mr-1"}),"Complete ",_,"/",k]}):_>0?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"text-blue-600 border-blue-600",children:[_,"/",k," Approved"]}),f.length>0&&e.jsxs(B,{variant:"outline",className:"text-yellow-600 border-yellow-600",children:[e.jsx(xs,{className:"h-3 w-3 mr-1"}),f.length," more available"]})]}):f.length>0?e.jsxs(B,{variant:"outline",className:"text-yellow-600 border-yellow-600",children:[e.jsx(xs,{className:"h-3 w-3 mr-1"}),"0/",k," (",f.length," available)"]}):e.jsx(B,{variant:"secondary",children:"No picks available"}),_>0&&w&&e.jsxs("div",{className:"flex items-center gap-2 ml-2 pl-2 border-l border-border",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[j?e.jsx(mt,{className:"h-4 w-4 text-green-600"}):e.jsx(qr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:j?"Locked":"Unlocked"})]}),e.jsx(Ge,{checked:j,onCheckedChange:z,disabled:u.isPending||x.isPending})]})]}),S&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>N(),disabled:h,children:[e.jsx(He,{className:`h-4 w-4 mr-2 ${h?"animate-spin":""}`}),h?"Refreshing...":"Refresh"]}),f.length>0&&e.jsxs(R,{size:"sm",onClick:()=>r(!0),disabled:a.size===0||d.isPending,children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Approve Selected (",a.size,")"]})]})]})}),e.jsx(J,{className:"space-y-6",children:g.length===0&&f.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground space-y-2",children:[e.jsx("p",{children:"No AI picks available for this kontest yet."}),e.jsxs("p",{className:"text-xs",children:["Looking for ",s.sport," picks from"," ",ke(new Date(s.start_date),"MMM d")," to"," ",ke(new Date(s.end_date),"MMM d, yyyy")]})]}):e.jsxs(e.Fragment,{children:[g.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(Ks,{className:"h-4 w-4 text-green-600"}),"Approved Picks (",g.length,")",j&&e.jsxs(B,{variant:"outline",className:"text-green-600 border-green-600 ml-2",children:[e.jsx(mt,{className:"h-3 w-3 mr-1"}),"Locked"]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-12",children:"#"}),e.jsx(U,{children:"Pick"}),e.jsx(U,{children:"Matchup"}),e.jsx(U,{children:"Confidence"}),e.jsx(U,{children:"Result"}),S&&e.jsx(U,{className:"w-16",children:"Actions"})]})}),e.jsx($e,{children:g.map((A,F)=>{var q;return e.jsxs(he,{className:"bg-green-50/50 dark:bg-green-950/20",children:[e.jsx(M,{className:"font-medium text-muted-foreground",children:F+1}),e.jsxs(M,{children:[e.jsx("div",{className:"font-medium",children:A.pick}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1 flex-wrap",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:A.pick_type}),A.pick_type==="spread"&&A.current_line!==null&&A.current_line!==void 0&&e.jsxs(B,{variant:"secondary",className:"text-xs font-mono",children:[A.current_line>0?"+":"",A.current_line]}),A.pick_type==="moneyline"&&A.original_odds!==null&&A.original_odds!==void 0&&e.jsxs(B,{variant:A.original_odds<0?"default":"secondary",className:A.original_odds<0?"bg-blue-600 text-xs":"bg-orange-500 text-white text-xs",children:[A.original_odds<0?"FAV":"DOG"," (",A.original_odds>0?"+":"",A.original_odds,")"]})]}),A.trigger_type&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 italic",children:["Trigger: ",A.trigger_type.replace(/_/g," ")
285]})]}),e.jsxs(M,{children:[e.jsx("div",{className:"text-sm",children:A.matchup||(A.home_team&&A.away_team?`${A.away_team} @ ${A.home_team}`:((q=A.game_id)==null?void 0:q.substring(0,20))||"N/A")}),A.game_date&&e.jsx("div",{className:"text-xs text-muted-foreground",children:ke(new Date(A.game_date+"T12:00:00"),"MMM d, yyyy")})]}),e.jsx(M,{children:e.jsxs(B,{variant:A.confidence_score>=90?"default":A.confidence_score>=75?"secondary":"outline",className:A.confidence_score>=90?"bg-green-600":"",children:[A.confidence_score,"%"]})}),e.jsx(M,{children:D(A.status)}),S&&e.jsx(M,{children:e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>$(A.id),disabled:y.isPending,className:"h-8 w-8",children:e.jsx(rt,{className:"h-4 w-4 text-destructive"})})})]},A.id)})})]})})]}),!b&&f.length>0&&S&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(xs,{className:"h-4 w-4 text-yellow-600"}),"Available for Approval (",f.length,")"]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-12",children:e.jsx(Ms,{checked:a.size===f.length&&f.length>0,onCheckedChange:C})}),e.jsx(U,{className:"w-12",children:"#"}),e.jsx(U,{children:"Pick"}),e.jsx(U,{children:"Matchup"}),e.jsx(U,{children:"Confidence"}),e.jsx(U,{children:"Result"})]})}),e.jsx($e,{children:f.map((A,F)=>{var q;return e.jsxs(he,{children:[e.jsx(M,{children:e.jsx(Ms,{checked:a.has(A.id),onCheckedChange:()=>P(A.id)})}),e.jsx(M,{className:"font-medium text-muted-foreground",children:_+F+1}),e.jsxs(M,{children:[e.jsx("div",{className:"font-medium",children:A.pick}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1 flex-wrap",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:A.pick_type}),A.pick_type==="spread"&&A.current_line!==null&&A.current_line!==void 0&&e.jsxs(B,{variant:"secondary",className:"text-xs font-mono",children:[A.current_line>0?"+":"",A.current_line]}),A.pick_type==="moneyline"&&A.original_odds!==null&&A.original_odds!==void 0&&e.jsxs(B,{variant:A.original_odds<0?"default":"secondary",className:A.original_odds<0?"bg-blue-600 text-xs":"bg-orange-500 text-white text-xs",children:[A.original_odds<0?"FAV":"DOG"," (",A.original_odds>0?"+":"",A.original_odds,")"]})]}),A.trigger_type&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 italic",children:["Trigger: ",A.trigger_type.replace(/_/g," ")]})]}),e.jsxs(M,{children:[e.jsx("div",{className:"text-sm",children:A.matchup||(A.home_team&&A.away_team?`${A.away_team} @ ${A.home_team}`:((q=A.game_id)==null?void 0:q.substring(0,20))||"N/A")}),A.game_date&&e.jsx("div",{className:"text-xs text-muted-foreground",children:ke(new Date(A.game_date+"T12:00:00"),"MMM d, yyyy")})]}),e.jsx(M,{children:e.jsxs(B,{variant:A.confidence_score>=90?"default":A.confidence_score>=75?"secondary":"outline",className:A.confidence_score>=90?"bg-green-600":"",children:[A.confidence_score,"%"]})}),e.jsx(M,{children:D(A.status)})]},A.id)})})]})})]})]})}),e.jsx(ws,{open:n,onOpenChange:r,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Approve AI Picks"}),e.jsxs(Ps,{children:["You are about to approve ",a.size," pick(s) for this kontest. These picks will be added to the official KLUTCH picks that users will compete against."]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:O,disabled:d.isPending,children:d.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Approving..."]}):"Approve Picks"})]})]})}),e.jsx(ws,{open:i,onOpenChange:l,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Lock Kontest Picks?"}),e.jsx(Ps,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{children:"This will:"}),e.jsxs("ul",{className:"list-disc ml-4 space-y-1 text-sm",children:[e.jsxs("li",{children:["Finalize the ",_," approved AI pick(s)"]}),e.jsx("li",{children:"Make picks visible to all entered users"}),e.jsx("li",{children:"Notify all entrants that picks are ready"})]}),e.jsx("p",{className:"font-medium text-foreground",children:"You can unlock later if needed before the deadline."})]})})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>{u.mutate(s.id),l(!1)},disabled:u.isPending,className:"bg-green-600 hover:bg-green-700",children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Locking..."]}):e.jsxs(e.Fragment,{children:[e.jsx(mt,{className:"h-4 w-4 mr-2"}),"Lock & Notify Users"]})})]})]})})]})}const Dj={1:"🥇",2:"🥈",3:"🥉"};function Mj({kontest:s}){const[a,t]=v.useState(!1),[n,r]=v.useState(null),{data:i,isLoading:l}=Cj(s.id),m=Pj(),o=Fj(),h=s.prize_type||"cash",N=(i==null?void 0:i.reduce((b,j)=>b+j.entry_count,0))||0,d=(i==null?void 0:i.filter(b=>(b.prize_amount||0)>0))||[],y=d.filter(b=>!b.prize_awarded_at),u=d.filter(b=>b.prize_awarded_at),x=v.useMemo(()=>{const b=s.payout_structure;return((b==null?void 0:b.payouts)||[]).reduce((c,p)=>c+(p.amount||0),0)},[s.payout_structure]),g=!!s.picks_locked_at,f=g&&y.length>0,_=b=>{o.mutate({kontestId:s.id,userId:b},{onSuccess:()=>r(null)})},k=()=>{m.mutate(s.id,{onSuccess:()=>t(!1)})};return l?e.jsx(G,{children:e.jsx(J,{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(G,{children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(fe,{className:"text-lg",children:"User Entries"}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:["Total Entries: ",e.jsx("strong",{className:"text-foreground",children:N})]}),e.jsxs("span",{children:["Users: ",e.jsx("strong",{className:"text-foreground",children:(i==null?void 0:i.length)||0})]}),e.jsxs("span",{children:["Prize Pool: ",e.jsx("strong",{className:"text-foreground",children:jr(x,h)})]})]})]}),!g&&y.length>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(mt,{className:"h-4 w-4"}),e.jsx("span",{children:"Picks not locked yet"})]}),f&&e.jsxs(R,{onClick:()=>t(!0),disabled:m.isPending,children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Award All Prizes (",y.length,")"]})]})}),e.jsxs(J,{children:[!i||i.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No entries for this kontest yet."}):e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-16",children:"Rank"}),e.jsx(U,{children:"User"}),e.jsx(U,{className:"text-center",children:"Entries"}),e.jsx(U,{className:"text-center",children:"Score"}),e.jsx(U,{className:"text-right",children:"Prize"}),e.jsx(U,{className:"text-right w-32",children:"Actions"})]})}),e.jsx($e,{children:i.map(b=>{const j=(b.prize_amount||0)>0,c=!!b.prize_awarded_at,p=Dj[b.rank||0];return e.jsxs(he,{children:[e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[p&&e.jsx("span",{className:"text-lg",children:p}),e.jsxs("span",{className:"font-medium",children:["#",b.rank]})]})}),e.jsx(M,{children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"font-medium",children:b.display_name})})}),e.jsx(M,{className:"text-center",children:b.entry_count}),e.jsx(M,{className:"text-center font-medium",children:b.score.toLocaleStr
285ing()}),e.jsx(M,{className:"text-right",children:j?e.jsx("span",{className:"font-medium text-green-600",children:jr(b.prize_amount,h)}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(M,{className:"text-right",children:j&&(c?e.jsxs(B,{variant:"outline",className:"text-green-600 border-green-600",children:[e.jsx(Es,{className:"h-3 w-3 mr-1"}),"Awarded"]}):g?e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>r(b.user_id),disabled:o.isPending,children:[e.jsx(ja,{className:"h-3 w-3 mr-1"}),"Award"]}):e.jsx(B,{variant:"outline",className:"text-muted-foreground",children:"Pending"}))})]},b.user_id)})})]})}),u.length>0&&e.jsxs("div",{className:"mt-4 text-sm text-muted-foreground",children:[e.jsx(Es,{className:"h-4 w-4 inline mr-1 text-green-600"}),u.length," of ",d.length," prizes already awarded"]})]}),e.jsx(ws,{open:a,onOpenChange:t,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Award All Prizes"}),e.jsxs(Ps,{children:["You are about to award prizes to ",y.length," users (",h==="cash"?"cash":h==="entry_credits"?"entry credits":"tier points","). This will update their wallets/points immediately."]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:k,disabled:m.isPending,children:m.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Awarding..."]}):"Award All"})]})]})}),e.jsx(ws,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Award Prize"}),e.jsx(Ps,{children:"Award prize to this user? This action cannot be undone."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>n&&_(n),disabled:o.isPending,children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Awarding..."]}):"Award Prize"})]})]})})]})}const Ij={scoring:As,survivor:hs,man_vs_machine:Ha};function Rj({kontest:s,open:a,onClose:t}){var x,g;const[n,r]=v.useState(!1),[i,l]=v.useState(!1),m=Me();if(!s)return null;const o=Ij[s.kontest_type||"scoring"]||As,h=((x=gr[s.kontest_type||"scoring"])==null?void 0:x.label)||"Scoring",N=s.prize_type||"cash",d=f=>{switch(f){case"draft":return"secondary";case"active":return"default";case"pending_approval":return"warning";case"completed":return"outline";case"cancelled":return"destructive";default:return"secondary"}},y=f=>f==="pending_approval"?"Pending Approval":f,u=async()=>{l(!0);try{const{data:{user:f}}=await T.auth.getUser();if(!f)throw new Error("Not authenticated");const{data:_,error:k}=await T.rpc("award_kontest_prizes",{p_kontest_id:s.id,p_admin_id:f.id});if(k)throw k;const b=_;b.success?(K.success(`Awarded ${b.awarded_count} prizes (${jr(b.total_awarded,b.prize_type)})`),m.invalidateQueries({queryKey:["kontests"]}),m.invalidateQueries({queryKey:["kontest-entries"]}),t()):K.error("Failed to award prizes")}catch(f){console.error("Error awarding prizes:",f),K.error("Failed to award prizes")}finally{l(!1),r(!1)}};return e.jsxs(Ue,{open:a,onOpenChange:t,children:[e.jsxs(Be,{className:"max-w-4xl max-h-[90vh] p-0",children:[e.jsx(ze,{className:"p-6 pb-4",children:e.jsx("div",{className:"flex items-start justify-between",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ke,{className:"text-2xl font-bold",children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(B,{variant:d(s.status),children:y(s.status)}),e.jsx(B,{variant:"outline",children:s.sport}),e.jsxs(B,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(o,{className:"h-3 w-3"}),h]})]})]})})}),e.jsx(is,{}),e.jsx(cs,{className:"max-h-[calc(90vh-140px)]",children:e.jsxs("div",{className:"p-6 space-y-6",children:[s.status==="pending_approval"&&e.jsx(G,{className:"border-amber-500/50 bg-amber-500/10",children:e.jsx(J,{className:"py-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Es,{className:"h-6 w-6 text-amber-500 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-amber-100",children:"All Picks Settled - Ready for Approval"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Review the leaderboard and award prizes to winners"})]})]}),e.jsxs(R,{onClick:()=>r(!0),className:"bg-amber-500 hover:bg-amber-600 text-black font-medium",children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Approve & Award All Prizes"]})]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(xt,{className:"h-4 w-4"}),"Dates"]}),e.jsxs("div",{className:"text-sm font-medium",children:[ke(new Date(s.start_date),"MMM d")," - ",ke(new Date(s.end_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(La,{className:"h-4 w-4"}),"Entry Fee"]}),e.jsxs("div",{className:"text-sm font-medium",children:["$",((g=s.entry_fee)==null?void 0:g.toFixed(2))||"0.00"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Js,{className:"h-4 w-4"}),"Prize Pool"]}),e.jsx("div",{className:"text-sm font-medium",children:jr(s.prize_pool,N)}),e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:N.replace("_"," ")})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(hs,{className:"h-4 w-4"}),"Entries"]}),e.jsxs("div",{className:"text-sm font-medium",children:[s.current_entries||0," / ",s.max_entries||"∞"]}),s.max_entries_per_user&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Max ",s.max_entries_per_user," per user"]})]})]}),s.kontest_type==="man_vs_machine"&&e.jsx(Ej,{kontest:s}),e.jsx(Mj,{kontest:s})]})})]}),e.jsx(ws,{open:n,onOpenChange:r,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Approve & Award All Prizes"}),e.jsxs(Ps,{className:"space-y-2",children:[e.jsx("p",{children:"This will distribute prizes to all winners based on their final rankings:"}),e.jsxs("ul",{className:"list-disc list-inside text-sm space-y-1 mt-2",children:[e.jsxs("li",{children:["Prize pool: ",jr(s.prize_pool,N)]}),e.jsxs("li",{children:["Prize type: ",e.jsx("span",{className:"capitalize",children:N.replace("_"," ")})]}),e.jsx("li",{children:"Winners will be notified of their prizes"}),e.jsx("li",{children:'Kontest status will change to "Completed"'})]}
285),e.jsx("p",{className:"text-amber-400 font-medium mt-3",children:"This action cannot be undone."})]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{disabled:i,children:"Cancel"}),e.jsx(Ls,{onClick:u,disabled:i,className:"bg-amber-500 hover:bg-amber-600 text-black",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Awarding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Confirm & Award"]})})]})]})})]})}function qj(){const s=Me(),[a,t]=v.useState(!1),[n,r]=v.useState(null),[i,l]=v.useState(!1),[m,o]=v.useState(null),{data:h,isLoading:N}=ge({queryKey:["kontests"],queryFn:async()=>{const{data:p,error:w}=await T.from("kontests").select("*").order("created_at",{ascending:!1});if(w)throw w;return p}}),d=(h==null?void 0:h.filter(p=>p.status==="active").length)||0,y=(h==null?void 0:h.length)||0,u=(h==null?void 0:h.reduce((p,w)=>p+(w.current_entries||0),0))||0,x=_e({mutationFn:async p=>{var P,C;const{data:w,error:S}=await T.from("kontests").insert([{title:p.title,description:p.description,sport:p.sport,entry_fee:p.entry_fee,prize_pool:((P=p.payout_structure)==null?void 0:P.total_allocation)||p.prize_pool,start_date:p.start_date.toISOString(),end_date:p.end_date.toISOString(),max_entries:p.max_entries,max_entries_per_user:p.max_entries_per_user,status:p.status,rules:{list:p.rules},current_entries:0,kontest_type:p.kontest_type,ai_opponent_id:p.ai_opponent_id,is_subscriber_only:p.is_subscriber_only,min_picks:p.min_picks,max_picks:p.max_picks,pick_deadline:((C=p.pick_deadline)==null?void 0:C.toISOString())||null,prize_type:p.prize_type,payout_structure:p.payout_structure,date_type:p.date_type,pick_types:p.pick_types,bet_type_multipliers:p.bet_type_multipliers,win_percentage_multipliers:p.win_percentage_multipliers,total_ai_picks:p.total_ai_picks,allow_all_true_false:p.allow_all_true_false,scoring_rules:{bet_type_multipliers:p.bet_type_multipliers,win_percentage_multipliers:p.win_percentage_multipliers},prop_markets:p.prop_markets}]).select().single();if(S)throw S;return w},onSuccess:()=>{s.invalidateQueries({queryKey:["kontests"]}),K.success("Kontest created successfully")},onError:p=>{K.error(`Failed to create kontest: ${p.message}`)}}),g=_e({mutationFn:async({id:p,data:w})=>{var P,C;const{error:S}=await T.from("kontests").update({title:w.title,description:w.description,sport:w.sport,entry_fee:w.entry_fee,prize_pool:((P=w.payout_structure)==null?void 0:P.total_allocation)||w.prize_pool,start_date:w.start_date.toISOString(),end_date:w.end_date.toISOString(),max_entries:w.max_entries,max_entries_per_user:w.max_entries_per_user,status:w.status,rules:{list:w.rules},kontest_type:w.kontest_type,ai_opponent_id:w.ai_opponent_id,is_subscriber_only:w.is_subscriber_only,min_picks:w.min_picks,max_picks:w.max_picks,pick_deadline:((C=w.pick_deadline)==null?void 0:C.toISOString())||null,prize_type:w.prize_type,payout_structure:w.payout_structure,date_type:w.date_type,pick_types:w.pick_types,bet_type_multipliers:w.bet_type_multipliers,win_percentage_multipliers:w.win_percentage_multipliers,total_ai_picks:w.total_ai_picks,allow_all_true_false:w.allow_all_true_false,scoring_rules:{bet_type_multipliers:w.bet_type_multipliers,win_percentage_multipliers:w.win_percentage_multipliers},prop_markets:w.prop_markets}).eq("id",p);if(S)throw S},onSuccess:()=>{s.invalidateQueries({queryKey:["kontests"]}),K.success("Kontest updated successfully")},onError:p=>{K.error(`Failed to update kontest: ${p.message}`)}}),f=_e({mutationFn:async p=>{const{error:w}=await T.from("kontests").delete().eq("id",p);if(w)throw w},onSuccess:()=>{s.invalidateQueries({queryKey:["kontests"]}),K.success("Kontest deleted successfully")},onError:p=>{K.error(`Failed to delete kontest: ${p.message}`)}}),_=()=>{r(null),t(!0)},k=p=>{r(p),t(!0)},b=async p=>{await f.mutateAsync(p)},j=async p=>{n?await g.mutateAsync({id:n.id,data:p}):await x.mutateAsync(p)},c=p=>{o(p),l(!0)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(fe,{className:"text-sm font-medium",children:"Active Kontests"}),e.jsx(_t,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(J,{children:e.jsx("div",{className:"text-2xl font-bold",children:d})})]}),e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(fe,{className:"text-sm font-medium",children:"Total Kontests"}),e.jsx(Js,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(J,{children:e.jsx("div",{className:"text-2xl font-bold",children:y})})]}),e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(fe,{className:"text-sm font-medium",children:"Total Entries"}),e.jsx(hs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(J,{children:e.jsx("div",{className:"text-2xl font-bold",children:u})})]})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{children:"Kontest Management"}),e.jsx(De,{children:"Create and manage platform kontests"})]}),e.jsxs(J,{children:[N?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(xj,{kontests:h||[],onCreate:_,onEdit:k,onDelete:b,onViewDetails:c}),e.jsx(bj,{open:a,onClose:()=>t(!1),onSubmit:j,kontest:n}),e.jsx(Rj,{kontest:m,open:i,onClose:()=>l(!1)})]})]})]})}const $j=["General Discussion","MLB Talk","NFL Talk","NBA Talk","NHL Talk","Betting Strategies","DFS Picks & Analysis","Success Stories","Questions & Help","Off-Topic"],Oj=[{value:"draft",label:"Draft"},{value:"published",label:"Published"},{value:"archived",label:"Archived"}];function di({posts:s,onViewDetails:a,onTogglePin:t,onToggleLock:n,onChangeStatus:r,onChangeCategory:i,onDelete:l,onBulkArchive:m,onBulkDelete:o,onBulkPin:h,onBulkUnpin:N,onBulkLock:d,onBulkUnlock:y}
285){const[u,x]=v.useState(""),[g,f]=v.useState("all"),[_,k]=v.useState("all"),[b,j]=v.useState(new Set),c=s.filter(P=>{const C=P.title.toLowerCase().includes(u.toLowerCase())||P.content.toLowerCase().includes(u.toLowerCase()),O=g==="all"||P.status===g,$=_==="all"||P.category===_;return C&&O&&$}),p=()=>{b.size===c.length?j(new Set):j(new Set(c.map(P=>P.id)))},w=P=>{const C=new Set(b);C.has(P)?C.delete(P):C.add(P),j(C)},S=P=>{switch(P){case"published":return"bg-green-500/10 text-green-500";case"draft":return"bg-gray-500/10 text-gray-500";case"archived":return"bg-orange-500/10 text-orange-500";default:return"bg-gray-500/10 text-gray-500"}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsx(pe,{placeholder:"Search posts...",value:u,onChange:P=>x(P.target.value),className:"w-full sm:max-w-xs"}),e.jsxs(oe,{value:g,onValueChange:f,children:[e.jsx(de,{className:"w-full sm:w-[180px]",children:e.jsx(ue,{placeholder:"Filter by status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Statuses"}),Oj.map(P=>e.jsx(V,{value:P.value,children:P.label},P.value))]})]}),e.jsxs(oe,{value:_,onValueChange:k,children:[e.jsx(de,{className:"w-full sm:w-[200px]",children:e.jsx(ue,{placeholder:"Filter by category"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Categories"}),$j.map(P=>e.jsx(V,{value:P,children:P},P))]})]})]}),b.size>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 p-4 bg-muted rounded-lg",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[b.size," selected"]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>h(Array.from(b)),children:[e.jsx(Zt,{className:"h-4 w-4 mr-2"}),"Pin"]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>N(Array.from(b)),children:[e.jsx(Zt,{className:"h-4 w-4 mr-2 opacity-50"}),"Unpin"]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>d(Array.from(b)),children:[e.jsx(mt,{className:"h-4 w-4 mr-2"}),"Lock"]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>y(Array.from(b)),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"}),"Unlock"]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>m(Array.from(b)),children:[e.jsx(Nt,{className:"h-4 w-4 mr-2"}),"Archive"]}),e.jsxs(R,{size:"sm",variant:"destructive",onClick:()=>o(Array.from(b)),children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]})]}),e.jsx("div",{className:"hidden md:block border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-12",children:e.jsx(Ms,{checked:b.size===c.length&&c.length>0,onCheckedChange:p})}),e.jsx(U,{children:"Author"}),e.jsx(U,{children:"Title"}),e.jsx(U,{children:"Category"}),e.jsx(U,{children:"Status"}),e.jsx(U,{className:"text-center",children:"Engagement"}),e.jsx(U,{children:"Created"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:c.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:8,className:"text-center text-muted-foreground",children:"No posts found"})}):c.map(P=>{var C;return e.jsxs(he,{children:[e.jsx(M,{children:e.jsx(Ms,{checked:b.has(P.id),onCheckedChange:()=>w(P.id)})}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[P.user_profiles.avatar_url?e.jsx("img",{src:P.user_profiles.avatar_url,alt:P.user_profiles.username,className:"h-8 w-8 rounded-full"}):e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center",children:(C=P.user_profiles.username[0])==null?void 0:C.toUpperCase()}),e.jsx("span",{className:"text-sm",children:P.user_profiles.username})]})}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[P.is_pinned&&e.jsx(Zt,{className:"h-4 w-4 text-primary"}),P.is_locked&&e.jsx(mt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:P.title})]})}),e.jsx(M,{children:e.jsx(B,{variant:"outline",children:P.category})}),e.jsx(M,{children:e.jsx(B,{className:S(P.status),children:P.status})}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-3 justify-center text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(us,{className:"h-4 w-4"}),P.views_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4"}),P.likes_count]})]})}),e.jsx(M,{className:"text-sm text-muted-foreground",children:ke(new Date(P.created_at),"MMM d, yyyy")}),e.jsx(M,{className:"text-right",children:e.jsxs(zr,{children:[e.jsx(Kr,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",children:e.jsx(Yr,{className:"h-4 w-4"})})}),e.jsxs(Vr,{align:"end",children:[e.jsxs(ht,{onClick:()=>a(P),children:[e.jsx(us,{className:"h-4 w-4 mr-2"}),"View Details"]}
285),e.jsxs(ht,{onClick:()=>t(P.id,P.is_pinned),children:[e.jsx(Zt,{className:"h-4 w-4 mr-2"}),P.is_pinned?"Unpin":"Pin"," Post"]}),e.jsxs(ht,{onClick:()=>n(P.id,P.is_locked),children:[P.is_locked?e.jsx(qr,{className:"h-4 w-4 mr-2"}):e.jsx(mt,{className:"h-4 w-4 mr-2"}),P.is_locked?"Unlock":"Lock"," Post"]}),e.jsx(xl,{}),e.jsxs(ht,{onClick:()=>r(P.id,P.status==="published"?"archived":"published"),children:[e.jsx(Nt,{className:"h-4 w-4 mr-2"}),P.status==="published"?"Archive":"Publish"]}),e.jsxs(ht,{onClick:()=>l(P.id),className:"text-destructive",children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},P.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:c.length===0?e.jsx(G,{children:e.jsx(J,{className:"p-8 text-center text-muted-foreground",children:"No posts found"})}):c.map(P=>{var C;return e.jsx(G,{children:e.jsxs(J,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ms,{checked:b.has(P.id),onCheckedChange:()=>w(P.id),className:"mt-1"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[P.is_pinned&&e.jsx(Zt,{className:"h-4 w-4 text-primary"}),P.is_locked&&e.jsx(mt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium truncate",children:P.title})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[P.user_profiles.avatar_url?e.jsx("img",{src:P.user_profiles.avatar_url,alt:P.user_profiles.username,className:"h-5 w-5 rounded-full"}):e.jsx("div",{className:"h-5 w-5 rounded-full bg-primary/10 flex items-center justify-center text-xs",children:(C=P.user_profiles.username[0])==null?void 0:C.toUpperCase()}),e.jsx("span",{className:"text-sm text-muted-foreground",children:P.user_profiles.username})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(B,{variant:"outline",children:P.category}),e.jsx(B,{className:S(P.status),children:P.status})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(us,{className:"h-4 w-4"}),P.views_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4"}),P.likes_count]})]}),e.jsx("span",{children:ke(new Date(P.created_at),"MMM d, yyyy")})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(zr,{children:[e.jsx(Kr,{asChild:!0,children:e.jsxs(R,{variant:"outline",size:"sm",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Actions"]})}),e.jsxs(Vr,{align:"end",children:[e.jsxs(ht,{onClick:()=>a(P),children:[e.jsx(us,{className:"h-4 w-4 mr-2"}),"View Details"]}),e.jsxs(ht,{onClick:()=>t(P.id,P.is_pinned),children:[e.jsx(Zt,{className:"h-4 w-4 mr-2"}),P.is_pinned?"Unpin":"Pin"," Post"]}),e.jsxs(ht,{onClick:()=>n(P.id,P.is_locked),children:[P.is_locked?e.jsx(qr,{className:"h-4 w-4 mr-2"}):e.jsx(mt,{className:"h-4 w-4 mr-2"}),P.is_locked?"Unlock":"Lock"," Post"]}),e.jsx(xl,{}),e.jsxs(ht,{onClick:()=>r(P.id,P.status==="published"?"archived":"published"),children:[e.jsx(Nt,{className:"h-4 w-4 mr-2"}),P.status==="published"?"Archive":"Publish"]}),e.jsxs(ht,{onClick:()=>l(P.id),className:"text-destructive",children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]})},P.id)})})]})}const Uj=["nfl","nba","mlb","nhl","soccer","mma","tennis","golf","racing"],Bj=["message-square","trophy","help-circle","coffee","target","layers","football","dribbble","circle","snowflake","circle-dot","swords","flag","car"],zj=el({name:ot().min(1,"Name is required"),slug:ot().min(1,"Slug is required"),parent_id:ot().nullable(),sport_code:ot().nullable(),category_type:Gr(["general","sport","strategy"]),is_active:hr(),requires_subscription:hr(),display_order:Rr(),icon:ot().nullable()});function Kj({open:s,onOpenChange:a,category:t,allCategories:n}){const r=Me(),i=!!t,l=Wa({resolver:Ga(zj),defaultValues:{name:"",slug:"",parent_id:null,
285sport_code:null,category_type:"general",is_active:!0,requires_subscription:!1,display_order:0,icon:null}});v.useEffect(()=>{t?l.reset({name:t.name,slug:t.slug,parent_id:t.parent_id,sport_code:t.sport_code,category_type:t.category_type,is_active:t.is_active,requires_subscription:t.requires_subscription??!1,display_order:t.display_order,icon:t.icon}):l.reset({name:"",slug:"",parent_id:null,sport_code:null,category_type:"general",is_active:!0,requires_subscription:!1,display_order:n.length*10,icon:null})},[t,n.length,l]);const m=l.watch("name");v.useEffect(()=>{if(!i&&m){const d=m.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"");l.setValue("slug",d)}},[m,i,l]);const o=_e({mutationFn:async d=>{if(i){const{error:y}=await T.from("kommunity_categories").update({name:d.name,slug:d.slug,parent_id:d.parent_id||null,sport_code:d.sport_code||null,category_type:d.category_type,is_active:d.is_active,requires_subscription:d.requires_subscription,display_order:d.display_order,icon:d.icon||null}).eq("id",t.id);if(y)throw y}else{const{error:y}=await T.from("kommunity_categories").insert({name:d.name,slug:d.slug,parent_id:d.parent_id||null,sport_code:d.sport_code||null,category_type:d.category_type,is_active:d.is_active,requires_subscription:d.requires_subscription,display_order:d.display_order,icon:d.icon||null});if(y)throw y}},onSuccess:()=>{K.success(i?"Category updated":"Category created"),r.invalidateQueries({queryKey:["kommunity-categories"]}),a(!1)},onError:d=>{K.error(d.message||"Failed to save category")}}),h=d=>{o.mutate(d)},N=n.filter(d=>!d.parent_id&&d.id!==(t==null?void 0:t.id));return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:i?"Edit Category":"Add Category"})}),e.jsx(Cr,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(h),className:"space-y-4",children:[e.jsx(Ye,{control:l.control,name:"name",render:({field:d})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Name"}),e.jsx(es,{children:e.jsx(pe,{placeholder:"Category name",...d})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"slug",render:({field:d})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Slug"}),e.jsx(es,{children:e.jsx(pe,{placeholder:"category-slug",...d})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"category_type",render:({field:d})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Type"}),e.jsxs(oe,{onValueChange:d.onChange,value:d.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{})})}),e.jsxs(me,{children:[e.jsx(V,{value:"general",children:"General (accessible to all)"}),e.jsx(V,{value:"sport",children:"Sport (requires subscription)"}),e.jsx(V,{value:"strategy",children:"Strategy (sub-category)"})]})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"parent_id",render:({field:d})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Parent Category (Optional)"}),e.jsxs(oe,{onValueChange:y=>d.onChange(y==="none"?null:y),value:d.value||"none",children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select parent..."})})}),e.jsxs(me,{children:[e.jsx(V,{value:"none",children:"None (Root Category)"}),N.map(y=>e.jsx(V,{value:y.id,children:y.name},y.id))]})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"sport_code",render:({field:d})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Sport Code (for subscription lock)"}),e.jsxs(oe,{onValueChange:y=>d.onChange(y==="none"?null:y),value:d.value||"none",children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select sport..."})})}),e.jsxs(me,{children:[e.jsx(V,{value:"none",children:"None (No subscription required)"}),Uj.map(y=>e.jsx(V,{value:y,children:y.toUpperCase()},y))]})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"icon",render:({field:d})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Icon"}),e.jsxs(oe,{onValueChange:y=>d.onChange(y==="none"?null:y),value:d.value||"none",children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select icon..."})})}),e.jsxs(me,{children:[e.jsx(V,{value:"none",children:"None"}),Bj.map(y=>e.jsx(V,{value:y,children:y},y))]})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"display_order",render:({field:d})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Display Order"}),e.jsx(es,{children:e.jsx(pe,{type:"number",...d,onChange:y=>
285d.onChange(parseInt(y.target.value)||0)})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"is_active",render:({field:d})=>e.jsxs(Je,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(Ze,{children:"Active"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Show this category to users"})]}),e.jsx(es,{children:e.jsx(Ge,{checked:d.value,onCheckedChange:d.onChange})})]})}),e.jsx(Ye,{control:l.control,name:"requires_subscription",render:({field:d})=>e.jsxs(Je,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(Ze,{children:"Requires Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Only paid subscribers can access this category"})]}),e.jsx(es,{children:e.jsx(Ge,{checked:d.value,onCheckedChange:d.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(R,{type:"submit",disabled:o.isPending,children:o.isPending?"Saving...":i?"Update":"Create"})]})]})})]})})}function Vj({posts:s}){const a=Me(),{data:t=[],isLoading:n}=od(),{data:r}=dd(),[i,l]=v.useState(!1),[m,o]=v.useState(null),[h,N]=v.useState(null),[d,y]=v.useState(new Set),x=(j=>{const c=new Map,p=[];return j.forEach(w=>{c.set(w.id,{...w,children:[]})}),j.forEach(w=>{const S=c.get(w.id);w.parent_id&&c.has(w.parent_id)?c.get(w.parent_id).children.push(S):w.parent_id||p.push(S)}),p})(t),g=_e({mutationFn:async({id:j,is_active:c})=>{const{error:p}=await T.from("kommunity_categories").update({is_active:c}).eq("id",j);if(p)throw p;await T.from("kommunity_categories").update({is_active:c}).eq("parent_id",j)},onSuccess:()=>{a.invalidateQueries({queryKey:["kommunity-categories"]}),a.invalidateQueries({queryKey:["kommunity-categories-all"]}),a.invalidateQueries({queryKey:["kommunity-category-counts"]}),K.success("Category updated")},onError:()=>{K.error("Failed to update category")}}),f=_e({mutationFn:async j=>{const{error:c}=await T.from("kommunity_categories").delete().eq("id",j);if(c)throw c},onSuccess:()=>{a.invalidateQueries({queryKey:["kommunity-categories"]}),a.invalidateQueries({queryKey:["kommunity-categories-all"]}),a.invalidateQueries({queryKey:["kommunity-category-counts"]}),K.success("Category deleted"),N(null)},onError:j=>{K.error(j.message||"Failed to delete category")}}),_=j=>{var c;return((c=r==null?void 0:r.counts)==null?void 0:c[j])||0},k=j=>{y(c=>{const p=new Set(c);return p.has(j)?p.delete(j):p.add(j),p})},b=(j,c=0)=>{const p=j.children.length>0,w=d.has(j.id),S=_(j.id),P=S===0&&j.children.length===0;return e.jsxs("div",{children:[e.jsxs("div",{className:Le("flex items-center justify-between p-3 border rounded-lg hover:bg-accent/50 transition-colors",c>0&&"ml-6 border-l-2 border-l-primary/30",!j.is_active&&"opacity-50"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[p?e.jsx("button",{onClick:()=>k(j.id),className:"p-1 hover:bg-accent rounded",children:w?e.jsx(uc,{className:"h-4 w-4 text-primary"}):e.jsx(su,{className:"h-4 w-4 text-muted-foreground"})}):e.jsx("div",{className:"w-6"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:j.name}),j.sport_code&&e.jsxs(B,{variant:"outline",className:"text-xs",children:[e.jsx(mt,{className:"h-3 w-3 mr-1"}),j.sport_code.toUpperCase()]}),e.jsx(B,{variant:"secondary",className:"text-xs",children:j.category_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/",j.slug," • ",S," posts"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{checked:j.is_active,onCheckedChange:C=>g.mutate({id:j.id,is_active:C})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>{o(j),l(!0)},children:e.jsx(Bt,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",disabled:!P,onClick:()=>N(j),className:"text-destructive hover:text-destructive",children:e.jsx(os,{className:"h-4 w-4"})})]})]}),p&&w&&e.jsx("div",{className:"mt-2 space-y-2",children:j.children.map(C=>
285b(C,c+1))})]},j.id)};return n?e.jsx("div",{className:"text-center py-8",children:"Loading categories..."}):e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between",children:[e.jsx(fe,{children:"Manage Categories"}),e.jsxs(R,{onClick:()=>{o(null),l(!0)},children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories with a sport code require users to have a subscription to that sport. Sub-categories inherit their parent's access restrictions."}),e.jsx("div",{className:"space-y-2",children:x.map(j=>b(j))}),x.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No categories found. Add one to get started."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Note: Categories with posts or children cannot be deleted. Remove posts/children first."})]}),e.jsx(Kj,{open:i,onOpenChange:l,category:m,allCategories:t}),e.jsx(ws,{open:!!h,onOpenChange:()=>N(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Category"}),e.jsxs(Ps,{children:['Are you sure you want to delete "',h==null?void 0:h.name,'"? This action cannot be undone.']})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>h&&f.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function Hj({posts:s}){const a=s.filter(m=>m.status==="published").length,t=s.filter(m=>m.status==="draft").length,n=s.filter(m=>m.status==="archived").length,r=s.reduce((m,o)=>m+(o.views_count||0),0),i=s.reduce((m,o)=>m+(o.likes_count||0),0),l=[{title:"Total Posts",value:s.length,icon:St,description:`${a} published, ${t} drafts`},{title:"Total Views",value:r.toLocaleString(),icon:us,description:"Across all posts"},{title:"Total Likes",value:i.toLocaleString(),icon:Nr,description:"Community engagement"},{title:"Archived Posts",value:n,icon:Nt,description:"Hidden from users"}];return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:l.map(m=>e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(fe,{className:"text-sm font-medium",children:m.title}),e.jsx(m.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(J,{children:[e.jsx("div",{className:"text-2xl font-bold",children:m.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m.description})]})]},m.title))})}function Wj({post:s,open:a,onOpenChange:t,onTogglePin:n,onToggleLock:r,onChangeStatus:i,onDelete:l}){var m;return s?e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2",children:[s.is_pinned&&e.jsx(Zt,{className:"h-5 w-5 text-primary"}),s.is_locked&&e.jsx(mt,{className:"h-5 w-5 text-muted-foreground"}),s.title]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s.user_profiles.avatar_url?e.jsx("img",{src:s.user_profiles.avatar_url,alt:s.user_profiles.username,className:"h-10 w-10 rounded-full"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center",children:(m=s.user_profiles.username[0])==null?void 0:m.toUpperCase()}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.user_profiles.username}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ke(new Date(s.created_at),"MMM d, yyyy 'at' h:mm a")})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{children:s.category}),e.jsx(B,{className:s.status==="published"?"bg-green-500/10 text-green-500":s.status==="draft"?"bg-gray-500/10 text-gray-500":"bg-orange-500/10 text-orange-500",children:s.status})]})]}),e.jsx(is,{}),e.jsx(Md,{content:s.content}),s.tags&&s.tags.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Tags:"}),s.tags.map(o=>e.jsx(B,{variant:"outline",children:o},o))]}),e.jsxs("div",{className:"flex items-center gap-6 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(us,{className:"h-4 w-4"}),s.views_count," views"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Nr,{className:"h-4 w-4"}),s.likes_count," likes"]}
285)]}),e.jsx(is,{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>{n(s.id,s.is_pinned),t(!1)},children:[e.jsx(Zt,{className:"h-4 w-4 mr-2"}),s.is_pinned?"Unpin":"Pin"," Post"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>{r(s.id,s.is_locked),t(!1)},children:[s.is_locked?e.jsx(mt,{className:"h-4 w-4 mr-2"}):e.jsx(mt,{className:"h-4 w-4 mr-2"}),s.is_locked?"Unlock":"Lock"," Post"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>{i(s.id,s.status==="published"?"archived":"published"),t(!1)},children:[e.jsx(Nt,{className:"h-4 w-4 mr-2"}),s.status==="published"?"Archive":"Publish"]}),e.jsxs(R,{variant:"destructive",size:"sm",onClick:()=>{l(s.id),t(!1)},children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})}):null}function Gj(){const{toast:s}=Ws(),a=Me(),[t,n]=v.useState(null),[r,i]=v.useState(null),[l,m]=v.useState([]),{data:o=[],isLoading:h}=ge({queryKey:["community-posts"],queryFn:async()=>{const{data:j,error:c}=await T.from("community_posts").select(`
286          *,
287          user_profiles!author_id (
288            username,
289            avatar_url,
290            display_name
291          )
292        `).order("is_pinned",{ascending:!1}).order("created_at",{ascending:!1});if(c)throw c;return j}}),N=_e({mutationFn:async({postId:j,isPinned:c})=>{const{error:p}=await T.from("community_posts").update({is_pinned:!c}).eq("id",j);if(p)throw p},onSuccess:()=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:"Post pin status updated"})},onError:()=>{s({title:"Error",description:"Failed to update pin status",variant:"destructive"})}}),d=_e({mutationFn:async({postId:j,isLocked:c})=>{const{error:p}=await T.from("community_posts").update({is_locked:!c}).eq("id",j);if(p)throw p},onSuccess:()=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:"Post lock status updated"})},onError:()=>{s({title:"Error",description:"Failed to update lock status",variant:"destructive"})}}),y=_e({mutationFn:async({postId:j,status:c})=>{const{error:p}=await T.from("community_posts").update({status:c}).eq("id",j);if(p)throw p},onSuccess:()=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:"Post status updated"})},onError:()=>{s({title:"Error",description:"Failed to update post status",variant:"destructive"})}}),u=_e({mutationFn:async j=>{const{error:c}=await T.from("community_posts").delete().eq("id",j);if(c)throw c},onSuccess:()=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:"Post deleted"}),i(null)},onError:()=>{s({title:"Error",description:"Failed to delete post",variant:"destructive"})}}),x=_e({mutationFn:async j=>{const{error:c}=await T.from("community_posts").update({status:"archived"}).in("id",j);if(c)throw c},onSuccess:(j,c)=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:`${c.length} posts archived`})},onError:()=>{s({title:"Error",description:"Failed to archive posts",variant:"destructive"})}}),g=_e({mutationFn:async j=>{const{error:c}=await T.from("community_posts").delete().in("id",j);if(c)throw c},onSuccess:(j,c)=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:`${c.length} posts deleted`}),m([])},onError:()=>{s({title:"Error",description:"Failed to delete posts",variant:"destructive"})}}),f=_e({mutationFn:async j=>{const{error:c}=await T.from("community_posts").update({is_pinned:!0}).in("id",j);if(c)throw c},onSuccess:(j,c)=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:`${c.length} posts pinned`})},onError:()=>{s({title:"Error",description:"Failed to pin posts",variant:"destructive"})}}),_=_e({mutationFn:async j=>{const{error:c}=await T.from("community_posts").update({is_pinned:!1}
292).in("id",j);if(c)throw c},onSuccess:(j,c)=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:`${c.length} posts unpinned`})},onError:()=>{s({title:"Error",description:"Failed to unpin posts",variant:"destructive"})}}),k=_e({mutationFn:async j=>{const{error:c}=await T.from("community_posts").update({is_locked:!0}).in("id",j);if(c)throw c},onSuccess:(j,c)=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:`${c.length} posts locked`})},onError:()=>{s({title:"Error",description:"Failed to lock posts",variant:"destructive"})}}),b=_e({mutationFn:async j=>{const{error:c}=await T.from("community_posts").update({is_locked:!1}).in("id",j);if(c)throw c},onSuccess:(j,c)=>{a.invalidateQueries({queryKey:["community"]}),a.invalidateQueries({queryKey:["community-posts"]}),s({title:"Success",description:`${c.length} posts unlocked`})},onError:()=>{s({title:"Error",description:"Failed to unlock posts",variant:"destructive"})}});return h?e.jsx(G,{children:e.jsx(J,{className:"p-6",children:e.jsx("p",{className:"text-center text-muted-foreground",children:"Loading posts..."})})}):e.jsxs(e.Fragment,{children:[e.jsxs(js,{defaultValue:"moderation",className:"space-y-6",children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsx(Ne,{value:"moderation",children:"Moderation"}),e.jsx(Ne,{value:"posts",children:"All Posts"}),e.jsx(Ne,{value:"categories",children:"Categories"})]}),e.jsxs(we,{value:"moderation",className:"space-y-6",children:[e.jsx(Hj,{posts:o}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Recent Posts"})}),e.jsx(J,{children:e.jsx(di,{posts:o.slice(0,10),onViewDetails:n,onTogglePin:(j,c)=>N.mutate({postId:j,isPinned:c}),onToggleLock:(j,c)=>d.mutate({postId:j,isLocked:c}),onChangeStatus:(j,c)=>y.mutate({postId:j,status:c}),onChangeCategory:(j,c)=>console.log("Change category",j,c),onDelete:i,onBulkArchive:j=>x.mutate(j),onBulkDelete:m,onBulkPin:j=>f.mutate(j),onBulkUnpin:j=>_.mutate(j),onBulkLock:j=>k.mutate(j),onBulkUnlock:j=>b.mutate(j)})})]})]}),e.jsx(we,{value:"posts",children:e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"All Community Posts"})}),e.jsx(J,{children:e.jsx(di,{posts:o,onViewDetails:n,onTogglePin:(j,c)=>N.mutate({postId:j,isPinned:c}),onToggleLock:(j,c)=>d.mutate({postId:j,isLocked:c}),onChangeStatus:(j,c)=>y.mutate({postId:j,status:c}),onChangeCategory:(j,c)=>console.log("Change category",j,c),onDelete:i,onBulkArchive:j=>x.mutate(j),onBulkDelete:m,onBulkPin:j=>f.mutate(j),onBulkUnpin:j=>_.mutate(j),onBulkLock:j=>k.mutate(j),onBulkUnlock:j=>b.mutate(j)})})]})}),e.jsx(we,{value:"categories",children:e.jsx(Vj,{posts:o})})]}),e.jsx(Wj,{post:t,open:!!t,onOpenChange:j=>!j&&n(null),onTogglePin:(j,c)=>N.mutate({postId:j,isPinned:c}),onToggleLock:(j,c)=>d.mutate({postId:j,isLocked:c}),onChangeStatus:(j,c)=>y.mutate({postId:j,status:c}),onDelete:i}),e.jsx(ws,{open:!!r,onOpenChange:j=>!j&&i(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Post"}),e.jsx(Ps,{children:"Are you sure you want to delete this post? This action cannot be undone."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>r&&u.mutate(r),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(ws,{open:l.length>0,onOpenChange:j=>!j&&m([]),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Multiple Posts"}),e.jsxs(Ps,{children:["Are you sure you want to delete ",l.length," posts? This action cannot be undone."]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>g.mutate(l),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete All"})]})]})})]})}const Qj=Te.object({title:Te.string().min(1,"Title is required").max(200,"Title must be less than 200 characters"),content:Te.string().min(100,"Content must be at least 100 characters"),excerpt:Te.string().min(1,"Excerpt is required").max(300,"Excerpt must be less than 300 characters"),featured_image_url:Te.string().url("Must be a valid URL").or(Te.literal("")).nullable().optional(),sport_tags:Te.array(Te.string()).min(1,"At least one sport tag is required"),blog_section:Te.enum(["KOACH","KAP","TEAM"],{required_error:"Blog section is required"}),is_featured:Te.boolean().default(!1),status:Te.enum(["draft","published","archived"]),publish_date:Te.date().nullable(),slug:Te.string().min(1,"Slug is required").regex(/^[a-z0-9-]+$/,"Slug must contain only lowercase letters, numbers, and hyphens"),meta_title:Te.string().max(60,"Meta title should be less than 60 characters").optional(),meta_description:Te.string().max(160,"Meta description should be less than 160 characters").optional(),keywords:Te.string().optional()}).refine(s=>s.status!=="published"||s.publish_date!==null,{message:"Publish date is required when status is published",path:["publish_date"]}),Gc=["Baseball","Football","Basketball","Hockey","Soccer","MMA","Golf","Tennis","Racing","General"];function Yj({posts:s,onEdit:a,onDelete:t,onDuplicate:n,onToggleFeatured:r,sectionFilter:i,onSectionFilterChange:l}){const[m,o]=v.useState(""),[h,N]=v.useState("all"),[d,y]=v.useState("all"),[u,x]=v.useState(null),g=s.filter(_=>{const k=_.title.toLowerCase().includes(m.toLowerCase()),b=h==="all"||_.status===h,j=d==="all"||_.sport_tags.includes(d);return k&&b&&j&&!0}),f=_=>{switch(_){case"published":return"default";case"draft":return"secondary";case"archived":return"outline";default:return"secondary"}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsx(pe,{placeholder:"Search posts...",value:m,onChange:_=>o(_.target.value),className:"max-w-xs"}),e.jsxs(oe,{value:h,onValueChange:N,children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{placeholder:"Filter by status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Statuses"}),e.jsx(V,{value:"draft",children:"Draft"}),e.jsx(V,{value:"published",children:"Published"}),e.jsx(V,{value:"archived",children:"Archived"})]})]}),e.jsxs(oe,{value:d,onValueChange:y,children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{placeholder:"Filter by sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),Gc.map(_=>e.jsx(V,{value:_,children:_},_))]})]}),e.jsxs(oe,{value:i,onValueChange:l,children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{placeholder:"Filter by section"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sections"}),e.jsx(V,{value:"KOACH",children:"KOACH"}),e.jsx(V,{value:"KAP",children:"KAP"}),e.jsx(V,{value:"TEAM",children:"TEAM"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Title"}),e.jsx(U,{children:"Section"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Sport Tags"}),e.jsx(U,{children:"Publish Date"}),e.jsx(U,{children:"Views"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:g.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:6,className:"text-center text-muted-foreground",children:"No blog posts found"})}):g.map(_=>e.jsxs(he,{children:[e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[_.is_featured&&e.jsx(Wt,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"}),e.jsx("span",{className:"font-medium",children:_.title})]})}),e.jsx(M,{children:e.jsx(B,{variant:_.blog_section==="KOACH"?"default":"secondary",children:_.blog_section})}),e.jsx(M,{children:e.jsx(B,{variant:f(_.status),children:_.status})}),e.jsx(M,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[_.sport_tags.slice(0,2).map(k=>e.jsx(B,{variant:"outline",className:"text-xs",children:k},k)),_.sport_tags.length>2&&e.jsxs(B,{variant:"outline",className:"text-xs",children:["+",_.sport_tags.length-2]})]})}),e.jsx(M,{children:_.publish_date?ke(new Date(_.publish_date),"MMM d, yyyy"):"-"}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(us,{className:"h-4 w-4"}),_.views_count]})}),e.jsx(M,{className:"text-right",children:e.jsxs(zr,{children:[e.jsx(Kr,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"icon",children:e.jsx(Yr,{className:"h-4 w-4"})})}),e.jsxs(Vr,{align:"end",children:[e.jsxs(ht,{onClick:()=>a(_),children:[e.jsx(Bt,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ht,{onClick:()=>n(_),children:[e.jsx(vt,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(ht,{onClick:()=>r(_.id,!_.is_featured),children:[e.jsx(Wt,{className:"h-4 w-4 mr-2"}),_.is_featured?"Unfeature":"Feature"]}),e.jsxs(ht,{onClick:()=>x(_.id),className:"text-destructive",children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},_.id))})]})}),e.jsx(ws,{open:!!u,onOpenChange:()=>x(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Blog Post"}),e.jsx(Ps,{children:"Are you sure you want to delete this blog post? This action cannot be undone."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:()=>{u&&(t(u),x(null))},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}async function Jj(s,a){var m;const t=((m=s.name.split(".").pop())==null?void 0:m.toLowerCase())||"jpg",r=`featured/${`${a}-${Date.now()}.${t}`}`,{error:i}=await T.storage.from("blog-images").upload(r,s,{cacheControl:"3600",upsert:!1});if(i)throw new Error(`Failed to upload image: ${i.message}`);const{data:l}=T.storage.from("blog-images").getPublicUrl(r);return{url:l.publicUrl,path:r}}async function Zj(s){try{const t=new URL(s).pathname.match(/blog-images\/(.+)$/);if(!t)return!1;const n=t[1],{error:r}=await T.storage.from("blog-images").remove([n]);return r?(console.error("Failed to delete image:",r),!1):!0}catch(a){return console.error("Error deleting image:",a),!1}}function Xj({value:s,onChange:a,slug:t}){const[n,r]=v.useState(!1),i=v.useCallback(async N=>{const d=N[0];if(d){if(d.size>5*1024*1024){K.error("Image must be less than 5MB");return}r(!0);try{const y=await Jj(d,t||"blog-post");a(y.url),K.success("Image uploaded successfully")}catch(y){K.error(y instanceof Error?y.message:"Failed to upload image")}finally{r(!1)}}},[t,a]),{getRootProps:l,getInputProps:m,isDragActive:o}=sl({onDrop:i,accept:{"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/webp":[".webp"]},maxFiles:1,disabled:n}),h=async()=>{s&&(await Zj(s),a(null),K.success("Image removed"))};return s?e.jsxs("div",{className:"relative group",children:[e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:s,alt:"Featured image preview",className:"w-full h-48 object-cover"})}),e.jsx(R,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity",onClick:h,children:e.jsx(rt,{className:"h-4 w-4"})})]}):e.jsxs("div",{...l(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${o?"border-primary bg-primary/5":"border-muted-foreground
292/25 hover:border-primary/50"} ${n?"pointer-events-none opacity-50":""}`,children:[e.jsx("input",{...m()}),e.jsx("div",{className:"flex flex-col items-center gap-2",children:n?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-10 w-10 text-muted-foreground animate-spin"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}):e.jsxs(e.Fragment,{children:[o?e.jsx(fa,{className:"h-10 w-10 text-primary"}):e.jsx(Ot,{className:"h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o?"Drop the image here":"Drag & drop an image, or click to select"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PNG, JPG, WEBP up to 5MB"})]})})]})}function ui(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}function ef({post:s,onSubmit:a,onCancel:t}){const[n,r]=v.useState(!!s),[i,l]=v.useState((s==null?void 0:s.sport_tags)||[]),m=Wa({resolver:Ga(Qj),defaultValues:{title:(s==null?void 0:s.title)||"",content:(s==null?void 0:s.content)||"",excerpt:(s==null?void 0:s.excerpt)||"",featured_image_url:(s==null?void 0:s.featured_image_url)||"",sport_tags:(s==null?void 0:s.sport_tags)||[],blog_section:(s==null?void 0:s.blog_section)||"KOACH",is_featured:(s==null?void 0:s.is_featured)||!1,status:(s==null?void 0:s.status)||"draft",publish_date:s!=null&&s.publish_date?new Date(s.publish_date):null,slug:(s==null?void 0:s.slug)||"",meta_title:(s==null?void 0:s.meta_title)||((s==null?void 0:s.title)||"").slice(0,60),meta_description:(s==null?void 0:s.meta_description)||((s==null?void 0:s.excerpt)||"").slice(0,160),keywords:(s==null?void 0:s.keywords)||""}}),o=Xi({extensions:[ec,sc,tc.configure({openOnClick:!1})],content:(s==null?void 0:s.content)||"",editorProps:{attributes:{class:"prose prose-sm prose-invert max-w-none focus:outline-none min-h-[300px] p-4 text-foreground [&_p]:text-foreground [&_h1]:text-foreground [&_h2]:text-foreground [&_h3]:text-foreground [&_li]:text-foreground [&_blockquote]:text-foreground"}},onUpdate:({editor:u})=>{m.setValue("content",u.getHTML())}});v.useEffect(()=>{const u=m.watch((x,{name:g})=>{g==="title"&&!n&&x.title&&m.setValue("slug",ui(x.title)),g==="title"&&x.title&&m.setValue("meta_title",x.title.slice(0,60)),g==="excerpt"&&x.excerpt&&m.setValue("meta_description",x.excerpt.slice(0,160))});return()=>u.unsubscribe()},[m,n]),v.useEffect(()=>{s!=null&&s.sport_tags&&(l(s.sport_tags),m.setValue("sport_tags",s.sport_tags))},[s==null?void 0:s.sport_tags,m]);const h=async u=>{const{data:x}=await T.from("blog_posts").select("id").eq("slug",u.slug).neq("id",(s==null?void 0:s.id)||"").maybeSingle();if(x){m.setError("slug",{message:"This slug is already in use"});return}a(u)},N=({onClick:u,active:x,children:g})=>e.jsx(R,{type:"button",variant:x?"secondary":"ghost",size:"icon",onClick:u,className:"h-8 w-8",children:g}),d=()=>{const u=prompt("Enter URL:");u&&o&&o.chain().focus().setLink({href:u}).run()},y=()=>{const u=prompt("Enter image URL:");u&&o&&o.chain().focus().setImage({src:u}).run()};return e.jsx(Cr,{...m,children:e.jsxs("form",{onSubmit:m.handleSubmit(h,u=>{const x=Object.keys(u);Ee({title:"Validation Error",description:`Please fix errors in: ${x.join(", ")}`,variant:"destructive"});const g=document.querySelector('[aria-invalid="true"]');g&&g.scrollIntoView({behavior:"smooth",block:"center"})}),className:"space-y-6",children:[e.jsx(Ye,{control:m.control,name:"title",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Title"}),e.jsx(es,{children:e.jsx(pe,{...u,placeholder:"Enter blog post title"})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"slug",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"URL Slug"}),e.jsx(es,{children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{...u,placeholder:"url-friendly-slug",onChange:x=>{r(!0),u.onChange(x)}}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>{r(!1),m.setValue("slug",ui(m.getValues("title")))},children:"Auto"})]})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"content",render:()=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Content"}),e.jsxs("div",{className:"border rounded-md",role:"textbox","aria-label":"Blog content editor",children:[e.jsxs("div",{className:"border-b p-2 flex flex-wrap gap-1 bg-muted/50",children:[e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleBold().run(),active:o==null?void 0:o.isActive("bold"),children:e.jsx(ac,{className:"h-4 w-4"})}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleItalic().run(),active:o==null?void 0:o.isActive("italic"),children:e.jsx(rc,{className:"h-4 w-4"})}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleStrike().run(),active:o==null?void 0:o.isActive("strike"),children:e.jsx(ju,{className:"h-4 w-4"})}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleCode().run(),active:o==null?void 0:o.isActive("code"),children:e.jsx(Zd,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-8 bg-border"}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleHeading({level:2}).run(),active:o==null?void 0:o.isActive("heading",{level:2}),children:e.jsx(Pd,{className:"h-4 w-4"})}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleHeading({level:3}).run(),active:o==null?void 0:o.isActive("heading",{level:3}),children:e.jsx(nu,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-8 bg-border"}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleBulletList().run(),active:o==null?void 0:o.isActive("bulletList"),children:e.jsx(nn,{className:"h-4 w-4"})}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleOrderedList().run(),active:o==null?void 0:o.isActive("orderedList"),children:e.jsx(nc,{className:"h-4 w-4"})}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().toggleBlockquote().run(),active:o==null?void 0:o.isActive("blockquote"),children:e.jsx(mu,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-8 bg-border"}),e.jsx(N,{onClick:d,children:e.jsx(Xn,{className:"h-4 w-4"})}),e.jsx(N,{onClick:y,children:e.jsx(Ot,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-8 bg-border"}),e.jsx(N,{onClick:()=>
292o==null?void 0:o.chain().focus().undo().run(),children:e.jsx(pc,{className:"h-4 w-4"})}),e.jsx(N,{onClick:()=>o==null?void 0:o.chain().focus().redo().run(),children:e.jsx(xc,{className:"h-4 w-4"})})]}),e.jsx(lc,{editor:o})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"excerpt",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Excerpt"}),e.jsx(es,{children:e.jsx(Xs,{...u,placeholder:"Brief summary for previews (max 300 characters)",rows:3})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"featured_image_url",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Featured Image"}),e.jsx(es,{children:e.jsx(Xj,{value:u.value||null,onChange:u.onChange,slug:m.watch("slug")||"blog-post"})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"sport_tags",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Sport Tags"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Gc.map(x=>{var g;return e.jsx(B,{variant:(g=u.value)!=null&&g.includes(x)?"default":"outline",className:"cursor-pointer",onClick:()=>{var _;const f=(_=u.value)!=null&&_.includes(x)?u.value.filter(k=>k!==x):[...u.value||[],x];u.onChange(f),l(f)},children:x},x)})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"blog_section",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Blog Section"}),e.jsxs(oe,{onValueChange:u.onChange,value:u.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select section"})})}),e.jsxs(me,{children:[e.jsx(V,{value:"KOACH",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold",children:"KOACH"}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"Pregame Insights & Predictions"})]})}),e.jsx(V,{value:"KAP",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold",children:"KAP"}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"Post-Game Analysis"})]})}),e.jsx(V,{value:"TEAM",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold",children:"TEAM"}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"Team Articles & Announcements"})]})})]})]}),e.jsx(Xe,{})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(Ye,{control:m.control,name:"status",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Status"}),e.jsxs(oe,{onValueChange:u.onChange,value:u.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{})})}),e.jsxs(me,{children:[e.jsx(V,{value:"draft",children:"Draft"}),e.jsx(V,{value:"published",children:"Published"}),e.jsx(V,{value:"archived",children:"Archived"})]})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"publish_date",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Publish Date"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(yr,{date:u.value||void 0,onSelect:u.onChange}),e.jsx(R,{type:"button",variant:"outline",onClick:()=>u.onChange(new Date),children:"Now"})]}),e.jsx(Xe,{})]})})]}),e.jsx(Ye,{control:m.control,name:"is_featured",render:({field:u})=>e.jsxs(Je,{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ze,{className:"text-base",children:"Featured Post"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display this post prominently on the blog homepage"})]}),e.jsx(es,{children:e.jsx(Ge,{checked:u.value,onCheckedChange:u.onChange})})]})}),e.jsxs(vs,{children:[e.jsx(ys,{asChild:!0,children:e.jsx(R,{type:"button",variant:"outline",className:"w-full",children:"SEO Metadata (Optional)"})}),e.jsxs(_s,{className:"space-y-4 mt-4",children:[e.jsx(Ye,{control:m.control,name:"meta_title",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Meta Title"}),e.jsx(es,{children:e.jsx(pe,{...u,placeholder:"SEO title (max 60 characters)"})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"meta_description",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Meta Description"}),e.jsx(es,{children:e.jsx(Xs,{...u,placeholder:"SEO description (max 160 characters)",rows:2})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:m.control,name:"keywords",render:({field:u})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Keywords"}),e.jsx(es,{children:e.jsx(pe,{...u,placeholder:"keyword1, keyword2, keyword3"})}),e.jsx(Xe,{})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(R,{type:"submit",children:s?"Update Post":"Create Post"})]})]})})}function sf(){const[s,a]=v.useState(!1),[t,n]=v.useState(),[r,i]=v.useState(!1),[l,m]=v.useState("all"),o=Me(),{data:h=[],isLoading:N}=ge({queryKey:["blog-posts",l],queryFn:async()=>{let j=T.from("blog_posts").select("*");l!=="all"&&(j=j.eq("blog_section",l));const{data:c,error:p}=await j.order("created_at",{ascending:!1});if(p)throw p;return c}}),d=_e({mutationFn:async j=>{var S;const{data:{user:c}}=await T.auth.getUser();if(!c)throw new Error("Not authenticated");const{data:p,error:w}=await T.from("blog_posts").insert([{title:j.title,slug:j.slug,content:j.content,excerpt:j.excerpt,featured_image_url:j.featured_image_url||null,sport_tags:j.sport_tags,blog_section:j.blog_section,is_featured:j.is_featured,status:j.status,publish_date:((S=j.publish_date)==null?void 0:S.toISOString())||null,author_id:c.id,meta_title:j.meta_title||j.title.slice(0,60),meta_description:j.meta_description||j.excerpt.slice(0,160),keywords:j.keywords||null}]).select().single();if(w)throw w;return p},onSuccess:()=>{o.invalidateQueries({queryKey:["blog-posts"]}),Ee({title:"Success",description:"Blog post created successfully"}),a(!1),n(void 0)},onError:j=>{Ee({title:"Error",description:j.message,variant:"destructive"})}}),y=_e({mutationFn:async({id:j,data:c})=>{var w;const{error:p}=await T.from("blog_posts").update({title:c.title,slug:c.slug,content:c.content,excerpt:c.excerpt,featured_image_url:c.featured_image_url||null,sport_tags:c.sport_tags,blog_section:c.blog_section,is_featured:c.is_featured,status:c.status,publish_date:((w=c.publish_date)==null?void 0:w.toISOString())||null,updated_at:new Date().toISOString(),meta_title:c.meta_title||c.title.slice(0,60),meta_description:c.meta_description||c.excerpt.slice(0,160),keywords:c.keywords||null}).eq("id",j);if(p)throw p},onSuccess:()=>{o.invalidateQueries({queryKey:["blog-posts"]}),Ee({title:"Success",description:"Blog post updated successfully"}),a(!1),n(void 0)},onError:j=>{Ee({title:"Error",description:j.message,variant:"destructive"})}}),u=_e({mutationFn:async j=>{const{error:c}=await T.from("blog_posts").delete().eq("id",j);if(c)throw c},onSuccess:()=>{o.invalidateQueries({queryKey:["blog-posts"]}),Ee({title:"Success",description:"Blog post deleted successfully"})},onError:j=>{Ee({title:"Error",description:j.message,variant:"destructive"})}}),x=_e({mutationFn:async({id:j,isFeatured:c})=>{const{error:p}=await T.from("blog_posts").update({is_featured:c}).eq("id",j);if(p)throw p},onSuccess:()=>{o.invalidateQueries({queryKey:["blog-posts"]}),Ee({title:"Success",description:"Featured status updated"})}}),g=j=>{t?y.mutate({id:t.id,data:j}):d.mutate(j)},f=j=>{n(j),a(!0)},_=async j=>{const{data:{user:c}}=await T.auth.getUser();if(!c)return;const{error:p}=await T.from("blog_posts").insert([{title:`${j.title} (Copy)`,slug:`${j.slug}-copy-${Date.now()}`,content:j.content,excerpt:j.excerpt,featured_image_url:j.featured_image_url,sport_tags:j.sport_tags,blog_section:j.blog_section,is_featured:!1,status:"draft",publish_date:null,author_id:c.id,meta_title:j.meta_title,meta_description:j.meta_description,keywords:j.keywords}]);p?Ee({title:"Error",description:p.message,variant:"destructive"}):(o.invalidateQueries({queryKey:["blog-posts"]}),Ee({title:"Success",description:"Blog post duplicated successfully"}))},k=()=>{n(void 0),a(!0)},b=async()=>{i(!0);try{const{data:j,error:c}=await T.functions.invoke("backfill-koach-blogs",{body:{}});if(c)throw c;o.invalidateQueries({queryKey:["blog-posts"]}),Ee({title:"KOACH Blogs Generated",description:`Processed ${j.summary.total} matchups: ${j.summary.succeeded} succeeded, ${j.summary.failed} failed`})}catch(j){console.error("Backfill error:",j),Ee({title:"Error",description:j instanceof Error?j.message:"Failed to generate KOACH blogs",variant:"destructive"})}finally{i(!1)}};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{children:"Koach & Kap Blog Management"}),e.jsx(De,{children:"Create and manage blog posts with rich content"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",onClick:b,disabled:r,children:[e.jsx(He,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Generating...":"Generate KOACH Blogs"]}),e.jsxs(R,{onClick:k,children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Create Post"]})]})]})}),e.jsx(J,{children:N?e.jsx("p",{className:"text-center text-muted-foreground",children:"Loading posts..."}):e.jsx(Yj,{posts:h,onEdit:f,onDelete:j=>u.mutate(j),onDuplicate:_,onToggleFeatured:(j,c)=>x.mutate({id:j,isFeatured:c}),sectionFilter:l,onSectionFilterChange:m})}),e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:t?"Edit Blog Post":"Create New Blog Post"})}),e.jsx(ef,{post:t,onSubmit:g,onCancel:()=>{a(!1),n(void 0)}})]})})]})}function tf({job:s,onDismiss:a}
292){if(!s)return null;const t=s.total_items>0?Math.round(s.processed_items/s.total_items*100):0,n=s.status==="running",r=s.status==="completed",i=s.status==="failed",l=n?e.jsx(ne,{className:"h-5 w-5 animate-spin text-primary"}):r?e.jsx(Es,{className:"h-5 w-5 text-green-500"}):i?e.jsx(Is,{className:"h-5 w-5 text-destructive"}):e.jsx($s,{className:"h-5 w-5 text-muted-foreground"}),m=n?"Running":r?"Completed":i?"Failed":s.status;return e.jsxs(G,{className:"border-primary/20 bg-primary/5",children:[e.jsx(je,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(fe,{className:"text-lg flex items-center gap-2",children:[l,e.jsx("span",{children:"Blog Generation Job"}),e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",m,")"]})]}),!n&&e.jsx(R,{variant:"ghost",size:"icon",onClick:a,children:e.jsx(rt,{className:"h-4 w-4"})})]})}),e.jsxs(J,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Progress: ",s.processed_items,"/",s.total_items]}),e.jsxs("span",{children:[t,"%"]})]}),e.jsx(Ct,{value:t,className:"h-2"})]}),e.jsxs("div",{className:"flex gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Es,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[s.success_count," success"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($s,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("span",{children:[s.skipped_count," skipped"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Is,{className:"h-4 w-4 text-destructive"}),e.jsxs("span",{children:[s.error_count," errors"]})]})]}),s.current_item&&n&&e.jsxs("div",{className:"text-sm text-muted-foreground truncate",children:["Current: ",s.current_item]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Started ",Dt(new Date(s.created_at),{addSuffix:!0}),r&&` • Completed ${Dt(new Date(s.updated_at),{addSuffix:!0})}`]})]})]})}const af={basketball_nba:"bg-orange-500/20 text-orange-400",americanfootball_nfl:"bg-green-500/20 text-green-400",baseball_mlb:"bg-red-500/20 text-red-400",icehockey_nhl:"bg-blue-500/20 text-blue-400",soccer_epl:"bg-purple-500/20 text-purple-400",soccer_usa_mls:"bg-purple-500/20 text-purple-400"},rf={basketball_nba:"NBA",americanfootball_nfl:"NFL",baseball_mlb:"MLB",icehockey_nhl:"NHL",soccer_epl:"EPL",soccer_usa_mls:"MLS"};function nf({games:s,selectedGameIds:a,onToggleSelect:t,onToggleSelectAll:n,onGenerateSingle:r,generatingGameId:i,isLoading:l}){if(l)return e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Loading games..."})]});if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[e.jsx(kt,{className:"h-12 w-12 mb-2 opacity-50"}),e.jsx("p",{children:"All games have KOACH blogs!"})]});const m=s.length>0&&s.every(h=>a.has(h.game_id)),o=s.some(h=>a.has(h.game_id))&&!m;return e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-12",children:e.jsx(Ms,{checked:m,ref:h=>{h&&(h.indeterminate=o)},onCheckedChange:n})}),e.jsx(U,{children:"Game"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Date"}),e.jsx(U,{className:"w-24",children:"Action"})]})}),e.jsx($e,{children:s.map(h=>e.jsxs(he,{children:[e.jsx(M,{children:e.jsx(Ms,{checked:a.has(h.game_id),onCheckedChange:()=>t(h.game_id)})}),e.jsxs(M,{className:"font-medium",children:[h.away_team," @ ",h.home_team]}),e.jsx(M,{children:e.jsx(B,{className:af[h.sport]||"bg-gray-500/20 text-gray-400",children:rf[h.sport]||h.sport})}),e.jsx(M,{children:ke(new Date(h.game_date),"MMM d, yyyy")}),e.jsx(M,{children:e.jsx(R,{variant:"outline",size:"sm",onClick:()=>r(h),disabled:i===h.game_id,children:i===h.game_id?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):"Generate"})})]},h.game_id))})]})})}const lf=[{value:"all",label:"All Sports"},{value:"nba",label:"NBA"},{value:"nfl",label:"NFL"},{value:"mlb",label:"MLB"},{value:"nhl",label:"NHL"},{value:"soccer",label:"Soccer"}];function cf(){const s=Me(),[a,t]=v.useState("all"),[n,r]=v.useState(new Date),[i,l]=v.useState(new Set),[m,o]=v.useState(null),[h,N]=v.useState(null),[d,y]=v.useState(null),{data:u=[],isLoading:x,refetch:g}=ge({queryKey:["games-without-koach-blogs",a,n.toISOString().split("T")[0]],queryFn:async()=>{const P=n.toISOString().split("T")[0],C=Oi(n,1).toISOString().split("T")[0],O={nba:["basketball_nba"],nfl:["americanfootball_nfl"],mlb:["baseball_mlb"],nhl:["icehockey_nhl"],soccer:["soccer_epl","soccer_usa_mls","soccer_uefa_champs_league"]};let $=T.from("game_matchup_views").select("game_id, sport, home_team, away_team, game_date").gte("game_date",P).lte("game_date",C);if(a!=="all"){const E=O[a]||[a];$=$.in("sport",E)}const{data:z,error:D}=await $;if(D)throw D;
292if(!z||z.length===0)return[];const A=z.map(E=>E.game_id),{data:F}=await T.from("blog_posts").select("game_id").in("game_id",A).eq("blog_section","KOACH"),q=new Set((F||[]).map(E=>E.game_id));return z.filter(E=>!q.has(E.game_id))}}),f=v.useCallback(async P=>{try{const{data:C,error:O}=await T.functions.invoke("schedule-koach-blogs",{body:{jobId:P}});if(O){console.error("Error polling job:",O);return}o(C),(C.status==="completed"||C.status==="failed")&&(h&&(clearInterval(h),N(null)),g(),s.invalidateQueries({queryKey:["blog-posts"]}),C.status==="completed"?K.success(`Generated ${C.success_count} blogs (${C.skipped_count} skipped, ${C.error_count} errors)`):K.error("Job failed: "+(C.error_message||"Unknown error")))}catch(C){console.error("Poll error:",C)}},[h,g,s]);v.useEffect(()=>{if(m&&m.status==="running"&&!h){const P=window.setInterval(()=>{f(m.id)},2e3);N(P)}return()=>{h&&clearInterval(h)}},[m==null?void 0:m.id,m==null?void 0:m.status]);const _=_e({mutationFn:async P=>{const{data:C,error:O}=await T.functions.invoke("schedule-koach-blogs",{body:P});if(O)throw O;return C},onSuccess:P=>{P.jobId?(o({id:P.jobId,status:"running",total_items:P.totalGames,processed_items:0,success_count:0,error_count:0,skipped_count:0,current_item:"Starting...",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}),K.info(`Starting blog generation for ${P.totalGames} games`)):K.info(P.message||"No games to process")},onError:P=>{K.error("Failed to start blog generation: "+P.message)}}),k=async P=>{y(P.game_id);try{const{error:C}=await T.functions.invoke("koach-ai-blog-writer",{body:{game_id:P.game_id,sport:P.sport,home_team:P.home_team,away_team:P.away_team,game_date:P.game_date}});if(C)throw C;K.success(`Generated blog for ${P.away_team} @ ${P.home_team}`),g()}catch(C){K.error("Failed to generate blog: "+C.message)}finally{y(null)}},b=()=>{_.mutate({sport:a!=="all"?a:void 0,date:n.toISOString().split("T")[0]})},j=()=>
292{if(i.size===0){K.warning("No games selected");return}_.mutate({game_ids:Array.from(i),date:n.toISOString().split("T")[0]})},c=P=>{l(C=>{const O=new Set(C);return O.has(P)?O.delete(P):O.add(P),O})},p=()=>{i.size===u.length?l(new Set):l(new Set(u.map(P=>P.game_id)))},w=()=>{o(null)},S=_.isPending||(m==null?void 0:m.status)==="running";return e.jsxs("div",{className:"space-y-6",children:[e.jsx(tf,{job:m,onDismiss:w}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{children:"KOACH Blog Management"}),e.jsx(De,{children:"Generate AI-powered pre-game analysis blogs for upcoming games"})]}),e.jsx(J,{className:"space-y-4",children:e.jsxs("div",{className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Sport"}),e.jsxs(oe,{value:a,onValueChange:t,children:[e.jsx(de,{className:"w-[160px]",children:e.jsx(ue,{placeholder:"Select sport"})}),e.jsx(me,{children:lf.map(P=>e.jsx(V,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Date"}),e.jsxs(Ba,{children:[e.jsx(za,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:Le("w-[200px] justify-start text-left font-normal",!n&&"text-muted-foreground"),children:[e.jsx(xt,{className:"mr-2 h-4 w-4"}),n?ke(n,"PPP"):"Pick a date"]})}),e.jsx(Ka,{className:"w-auto p-0",align:"start",children:e.jsx(Va,{mode:"single",selected:n,onSelect:P=>P&&r(P),initialFocus:!0})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{onClick:b,disabled:S||u.length===0,children:[S?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rt,{className:"h-4 w-4 mr-2"}),"Generate All (",u.length,")"]}),i.size>0&&e.jsxs(R,{variant:"secondary",onClick:j,disabled:S,children:["Generate Selected (",i.size,")"]}),e.jsx(R,{variant:"outline",onClick:()=>g(),disabled:x,children:e.jsx(He,{className:Le("h-4 w-4",x&&"animate-spin")})})]})]})})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{children:"Games Without KOACH Blogs"}),e.jsxs(De,{children:[u.length," games need blog generation for ",ke(n,"MMM d, yyyy")]})]}),e.jsx(J,{children:e.jsx(nf,{games:u,selectedGameIds:i,onToggleSelect:c,onToggleSelectAll:p,onGenerateSingle:k,generatingGameId:d,isLoading:x})})]})]})}function of(){const[s,a]=v.useState("posts");return e.jsxs(js,{value:s,onValueChange:a,className:"w-full",children:[e.jsxs(fs,{className:"mb-4 flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"posts",className:"flex items-center gap-2",children:[e.jsx(ic,{className:"h-4 w-4"}),"Blog Posts"]}),e.jsxs(Ne,{value:"koach",className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-4 w-4"}),"KOACH Generator"]})]}),e.jsx(we,{value:"posts",children:e.jsx(sf,{})}),e.jsx(we,{value:"koach",children:e.jsx(cf,{})})]})}const df=Te.object({contest_name:Te.string().min(1,"Contest name is required"),sport:Te.string().min(1,"Sport is required"),league:Te.string().optional(),platform:Te.string().min(1,"Platform is required"),slate_date:Te.date(),contest_type:Te.enum(["Classic","Showdown"]),contest_subtype:Te.string().optional(),home_team:Te.string().optional(),away_team:Te.string().optional(),game_id:Te.string().optional(),status:Te.enum(["draft","active","completed","cancelled"])}),Qc={Classic:[{value:"main",label:"Main"},{value:"all-day",label:"All Day"},{value:"early",label:"Early"},{value:"afternoon",label:"Afternoon"},{value:"late",label:"Late"},{value:"night",label:"Night"},{value:"primetime",label:"Primetime"},{value:"after-hours",label:"After Hours"},{value:"express",label:"Express"},{value:"express-2",label:"Express 2"},{value:"turbo",label:"Turbo"},{value:"turbo-2",label:"Turbo 2"},{value:"multi-day",label:"Multi-Day"}],Showdown:[]},uf=["DraftKings","FanDuel","Yahoo","Underdog"];function mf({open:s,onClose:a,onSubmit:t,contest:n}){const[r,i]=v.useState(!1),[l,m]=v.useState("Classic"),o=Wa({resolver:Ga(df),defaultValues:{contest_name:"",sport:"",league:"",platform:"DraftKings",slate_date:new Date,contest_type:"Classic",contest_subtype:"",home_team:"",away_team:"",game_id:"",status:"draft"}}),{data:h=[]}=ge({queryKey:["available-sports"],queryFn:async()=>{const{data:x,error:g}=await T.from("sport_statuses").select("sport_code, sport_name").order("sport_code");return g?[]:x.map(f=>({value:f.sport_code,label:f.sport_name}))},enabled:s}),N=o.watch("sport"),{data:d=[]}=ge({queryKey:["sport-leagues",N],queryFn:async()=>{const{data:x,error:g}=await T.from("sport_statuses").select("leagues_config").eq("sport_code",N).single();return g||!(x!=null&&x.leagues_config)?[]:x.leagues_config.filter(f=>f.is_enabled&&!f.is_grouped).map(f=>({value:f.league_id,label:f.league_name}))},enabled:s&&!!N}),{data:y=[]}=ge({queryKey:["available-games",o.watch("sport"),o.watch("slate_date")],queryFn:async()=>{const x=o.getValues("sport"),g=o.getValues("slate_date");if(!g)return[];const f=ke(g,"yyyy-MM-dd"),_=vo(x),{data:k,error:b}=await T.from("master_games").select("id, odds_api_game_id, home_team, away_team, game_date").eq("odds_api_sport_key",_).gte("game_date",`${f}T00:00:00`).lt("game_date",`${f}T23:59:59`).neq("game_status","completed").order("game_date");return b?(console.error("Error fetching games:",b),[]):(k||[]).map(j=>({game_id:j.odds_api_game_id||j.id,home_team:j.home_team,away_team:j.away_team,commence_time:j.game_date}))},enabled:l==="Showdown"&&s});v.useEffect(()=>{n?(o.reset({contest_name:n.contest_name,sport:n.sport,league:n.league||"",platform:n.platform,slate_date:an(jt(n.slate_date),"UTC"),contest_type:n.contest_type||"Classic",contest_subtype:n.contest_subtype||"",home_team:n.home_team||"",away_team:n.away_team||"",game_id:n.game_id||"",status:n.status}),m(n.contest_type||"Classic")):(o.reset({contest_name:"",sport:"",league:"",platform:"DraftKings",slate_date:new Date,contest_type:"Classic",contest_subtype:"",home_team:"",away_team:"",game_id:"",status:"draft"}),m("Classic"))}
292,[n,s,o]);const u=async x=>{i(!0);try{let g=null;x.contest_type==="Showdown"&&(g={salary_cap:5e4,captain_multiplier:1.5,min_players_per_team:1,total_roster_spots:6,positions:{CPT:1,FLEX:5},contest_type:"showdown"}),await t({...x,lineup_rules:g}),a()}catch(g){console.error("Error submitting DFS contest:",g)}finally{i(!1)}};return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:n?"Edit DFS Contest":"Create New DFS Contest"}),e.jsx(Vs,{children:n?"Update contest details":"Create a new DFS contest for data imports"})]}),e.jsx(Cr,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(u),className:"space-y-4",children:[e.jsx(Ye,{control:o.control,name:"contest_name",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Contest Name"}),e.jsx(es,{children:e.jsx(pe,{placeholder:"MLB Main Slate",...x})}),e.jsx(Xe,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(Ye,{control:o.control,name:"sport",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Sport"}),e.jsxs(oe,{onValueChange:g=>{x.onChange(g),o.setValue("league","")},value:x.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select sport"})})}),e.jsx(me,{children:h.length===0?e.jsx("div",{className:"px-2 py-4 text-center text-sm text-muted-foreground",children:"Loading sports..."}):h.map(g=>e.jsx(V,{value:g.value,children:g.label},g.value))})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:o.control,name:"league",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"League"}),e.jsxs(oe,{onValueChange:x.onChange,value:x.value||"",children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select league"})})}),e.jsx(me,{children:d.length===0?e.jsx("div",{className:"px-2 py-4 text-center text-sm text-muted-foreground",children:"No leagues available"}):d.map(g=>e.jsx(V,{value:g.value,children:g.label},g.value))})]}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:o.control,name:"platform",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Platform"}),e.jsxs(oe,{onValueChange:x.onChange,value:x.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select platform"})})}),e.jsx(me,{children:uf.map(g=>e.jsx(V,{value:g,children:g},g))})]}),e.jsx(Xe,{})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ye,{control:o.control,name:"slate_date",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Slate Date"}),e.jsx(es,{children:e.jsx(yr,{date:x.value,onSelect:x.onChange})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:o.control,name:"status",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Status"}),e.jsxs(oe,{onValueChange:x.onChange,value:x.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select status"})})}),e.jsxs(me,{children:[e.jsx(V,{value:"draft",children:"Draft"}),e.jsx(V,{value:"active",children:"Active"}),e.jsx(V,{value:"completed",children:"Completed"}),e.jsx(V,{value:"cancelled",children:"Cancelled"})]})]}),e.jsx(Xe,{})]})})]}),e.jsx(Ye,{control:o.control,name:"contest_type",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Contest Type"}),e.jsxs(oe,{onValueChange:g=>{x.onChange(g),m(g)},value:x.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select type"})})}),e.jsxs(me,{children:[e.jsx(V,{value:"Classic",children:"Classic"}),e.jsx(V,{value:"Showdown",children:"Showdown"})]})]}),e.jsx(Xe,{})]})}),l==="Classic"&&e.jsx(Ye,{control:o.control,name:"contest_subtype",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Subtype"}),e.jsxs(oe,{onValueChange:x.onChange,value:x.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select subtype"})})}),e.jsx(me,{children:Qc.Classic.map(g=>e.jsx(V,{value:g.value,children:g.label},g.value))})]}),e.jsx(Xe,{})]})}),l==="Showdown"&&e.jsx(Ye,{control:o.control,name:"game_id",render:({field:x})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Select Game"}),e.jsxs(oe,{onValueChange:g=>{x.onChange(g);const f=y==null?void 0:y.find(_=>_.game_id===g);f&&(o.setValue("home_team",f.home_team),o.setValue("away_team",f.away_team))},value:x.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select a game"})})}),e.jsx(me,{children:y.length===0?e.jsx("div",{className:"px-2 py-6 text-center text-sm text-muted-foreground",children:"No games found for this date"}):y.map(g=>e.jsxs(V,{value:g.game_id,children:[g.away_team," @ ",g.home_team]},g.game_id))})]}),e.jsx(Xe,{})]})}),e.jsxs(lt,{children:[e.jsx(R,{type:"button",variant:"outline",onClick:a,children:"Cancel"}),e.jsx(R,{type:"submit",disabled:r,children:r?"Saving...":n?"Update":"Create"})]})]})})]})})}const Dn=["A","B","C","D","F"];function xf({contest:s,onClose:a,onReprocessed:t}){const[n,r]=v.useState(!1),[i,l]=v.useState(""),[m,o]=v.useState("all"),[h,N]=v.useState("all"),[d,y]=v.useState("all"),[u,x]=v.useState("grade"),[g,f]=v.useState(!0),[_,k]=v.useState(null),[b,j]=v.useState(!1),c=Me(),{data:p,isLoading:w,refetch:S}
292=ge({queryKey:["contest-player-pool",s.id],queryFn:async()=>{const{data:F,error:q}=await T.from("dfs_contest_player_pool").select("*").eq("contest_id",s.id);if(q)throw q;return F}}),P=v.useMemo(()=>p?[...new Set(p.map(q=>q.position))].sort():[],[p]),C=v.useMemo(()=>p?p.filter(F=>F.is_injured).length:0,[p]),O=v.useMemo(()=>{if(!p)return[];let F=[...p];if(g||(F=F.filter(q=>!q.is_injured)),i){const q=i.toLowerCase();F=F.filter(E=>E.player_name.toLowerCase().includes(q)||E.team.toLowerCase().includes(q))}return m!=="all"&&(F=F.filter(q=>q.ai_grade===m)),h!=="all"&&(F=F.filter(q=>q.position===h)),d!=="all"&&(F=F.filter(q=>{switch(d){case"must_play":return q.is_must_play===!0;case"gpp":return q.is_gpp_play===!0;case"fade":return q.is_fade===!0;case"chalk":return q.is_chalk===!0;default:return!0}})),F.sort((q,E)=>{if(u==="grade"){const L=Dn.indexOf(q.ai_grade||"F"),H=Dn.indexOf(E.ai_grade||"F");return L!==H?L-H:(E.consensus_projection||0)-(q.consensus_projection||0)}return u==="projection"?(E.consensus_projection||0)-(q.consensus_projection||0):u==="hybrid"?(E.hybrid_projection||0)-(q.hybrid_projection||0):u==="salary"?E.salary-q.salary:u==="value"?(E.value_score||0)-(q.value_score||0):u==="cpt_value"?(E.captain_value_score||0)-(q.captain_value_score||0):u==="injury"?q.is_injured&&!E.is_injured?-1:!q.is_injured&&E.is_injured?1:(E.consensus_projection||0)-(q.consensus_projection||0):0}),F},[p,i,m,h,d,u,g]),$=v.useMemo(()=>{if(!p)return{};const F={};return p.forEach(q=>{const E=q.ai_grade||"Ungraded";F[E]=(F[E]||0)+1}),F},[p]),z=async()=>{r(!0);try{const{error:F}
292=await T.functions.invoke("process-contest-player-pool",{body:{contest_id:s.id}});if(F)throw F;K.success("Player pool reprocessed successfully"),S(),t(),c.invalidateQueries({queryKey:["contest-data-stats"]})}catch(F){console.error("Failed to reprocess player pool:",F),K.error("Failed to reprocess player pool")}finally{r(!1)}},D=()=>{if(!p||p.length===0){K.error("No players to export");return}const F=["Player Name","Team","Position","Roster Position","Salary","Opponent","Projection","Floor","Ceiling","Value Score","Ownership %","AI Grade","AI Confidence","Must Play","Fade","GPP Play","Injured","Injury Status","Beat Proj Rate","Consistency Score","Recent Trend","Pattern Status","Pattern Diff","Pattern Insight","Tags","AI Reasoning"],q=p.map(se=>[se.player_name,se.team,se.position,se.roster_position,se.salary,se.opponent||"",se.consensus_projection||"",se.consensus_floor||"",se.consensus_ceiling||"",se.value_score||"",se.ownership_projection||"",se.ai_grade||"",se.ai_confidence||"",se.is_must_play?"Yes":"No",se.is_fade?"Yes":"No",se.is_gpp_play?"Yes":"No",se.is_injured?"Yes":"No",se.injury_status||"",se.profile_beat_proj_rate||"",se.profile_consistency_score||"",se.profile_recent_trend||"",se.player_pattern_status||"",se.player_pattern_diff||"",se.player_pattern_insight||"",(se.tags||[]).join("; "),se.ai_reasoning||""]),E=[F.join(","),...q.map(se=>se.map(ie=>typeof ie=="string"&&(ie.includes(",")||ie.includes('"')||ie.includes(`
293`))?`"${ie.replace(/"/g,'""')}"`:ie).join(","))].join(`
294`),L=new Blob([E],{type:"text/csv;charset=utf-8;"}),H=URL.createObjectURL(L),Z=document.createElement("a");Z.href=H,Z.download=`${s.contest_name.replace(/[^a-z0-9]/gi,"_")}_player_pool.csv`,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(H),K.success("Player pool exported to CSV")},A=()=>{S()};return e.jsx(Ue,{open:!0,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-5xl h-[85vh] flex flex-col p-0",children:[e.jsxs(ze,{className:"p-4 pb-2 border-b border-border",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Ke,{className:"text-lg",children:s.contest_name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-muted-foreground flex-wrap",children:[e.jsx("span",{children:s.sport.toUpperCase()}),e.jsx("span",{children:"•"}),e.jsx("span",{children:s.platform}),e.jsx("span",{children:"•"}),e.jsx("span",{children:ha(jt(s.slate_date),"UTC","MMM d, yyyy")}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[(p==null?void 0:p.length)||0," players"]}),C>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-red-400 flex items-center gap-1",children:[e.jsx(Yi,{className:"h-3 w-3"}),C," injured"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:D,disabled:!p||p.length===0,children:[e.jsx(Gt,{className:"h-4 w-4 mr-1"}),"Export"]}),e.jsxs(R,{variant:"default",size:"sm",onClick:z,disabled:n,children:[e.jsx(He,{className:`h-4 w-4 mr-1 ${n?"animate-spin":""}`}),n?"Processing...":"Reprocess"]})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs(R,{variant:"outline",size:"sm",className:"sm:hidden w-full flex items-center justify-between mb-2",onClick:()=>j(!b),children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Id,{className:"h-4 w-4"}),"Filters"]}),b?e.jsx(Ua,{className:"h-4 w-4"}):e.jsx(Ns,{className:"h-4 w-4"})]}),e.jsxs("div",{className:`${b?"block":"hidden"} sm:block space-y-3`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Dn.map(F=>e.jsxs(B,{variant:"outline",className:`cursor-pointer ${m===F?"ring-2 ring-primary":""}`,onClick:()=>o(m===F?"all":F),children:[F,": ",$[F]||0]},F)),m!=="all"&&e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>o("all"),className:"h-6 px-2",children:e.jsx(rt,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-xs",children:[e.jsx(Rs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search players...",value:i,onChange:F=>l(F.target.value),className:"pl-8 h-8"})]}),e.jsxs(oe,{value:h,onValueChange:N,children:[e.jsx(de,{className:"w-[120px] h-8",children:e.jsx(ue,{placeholder:"Position"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Positions"}),P.map(F=>e.jsx(V,{value:F,children:F},F))]})]}),e.jsxs(oe,{value:d,onValueChange:y,children:[e.jsx(de,{className:"w-[130px] h-8",children:e.jsx(ue,{placeholder:"Badge"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Badges"}),e.jsx(V,{value:"must_play",children:"🔥 Must-Play"}),e.jsx(V,{value:"gpp",children:"🎯 GPP"}),e.jsx(V,{value:"fade",children:"⚠️ Fade"}),e.jsx(V,{value:"chalk",children:"📊 Chalk"})]})]}),e.jsxs(oe,{value:u,onValueChange:x,children:[e.jsx(de,{className:"w-[120px] h-8",children:e.jsx(ue,{placeholder:"Sort by"})}),e.jsxs(me,{children:[e.jsx(V,{value:"grade",children:"Grade"}),e.jsx(V,{value:"projection",children:"Projection"}),e.jsx(V,{value:"hybrid",children:"Hybrid"}),e.jsx(V,{value:"salary",children:"Salary"}),e.jsx(V,{value:"value",children:"Value"}),e.jsx(V,{value:"cpt_value",children:"CPT Value"}),e.jsx(V,{value:"injury",children:"Injury Status"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx(Ge,{id:"show-injured",checked:g,onCheckedChange:f}),e.jsx(Q,{htmlFor:"show-injured",className:"text-sm cursor-pointer",children:"Show Injured"})]})]})]})]})]}),e.jsx(cs,{className:"flex-1 p-4",children:w?e.jsx("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Loading player pool..."}):O.length===0?e.jsx("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:(p==null?void 0:p.length)===0?"No players in pool":"No players match filters"}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:O.map(F=>e.jsx(md,{player:F,sport:s.sport,onInjuryUpdate:A,onClick:()=>k(F)},F.id))})}),e.jsx(xd,{open:!!_,onOpenChange:F=>!F&&k(null),player:_,sport:s.sport,league:s.league||void 0,onInjuryUpdate:A,readOnly:!1})]})})}function hf({contests:s,dataStats:a,onEdit:t,onDelete:n,selectedIds:r=new Set,onToggleSelect:i,onToggleSelectAll:l}){const[m,o]=v.useState(null),[h,N]=v.useState(null),[d,y]=v.useState(null),u=Me(),x=s.length>0&&s.every(c=>r.has(c.id)),g=s.some(c=>r.has(c.id))&&!x,f=()=>{m&&(n(m),o(null))},_=async c=>{N(c);try{const{error:p}
294=await T.functions.invoke("process-contest-player-pool",{body:{contest_id:c}});if(p)throw p;K.success("Player pool generated successfully"),u.invalidateQueries({queryKey:["contest-data-stats"]})}catch(p){console.error("Failed to generate player pool:",p),K.error("Failed to generate player pool")}finally{N(null)}},k=c=>({stokastic:"Stokastic",linestart:"LineStar",sabersim:"SaberSim",rotowire:"RotoWire"})[c.toLowerCase()]||c,b=c=>{switch(c){case"active":return"default";case"completed":return"secondary";case"cancelled":return"destructive";default:return"outline"}},j=c=>{if(!(a!=null&&a[c.id]))return e.jsx("span",{className:"text-xs text-muted-foreground",children:"-"});const p=a[c.id];return e.jsx(zt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:e.jsxs(B,{variant:p.projectionCount>0?"default":"outline",className:"gap-1",children:["📊 ",p.projectionCount]})}),e.jsxs(zs,{children:[e.jsx("p",{className:"font-semibold",children:"Projection Sources:"}),p.projectionCount>0?e.jsx("ul",{className:"text-xs",children:p.projectionSources.map(w=>e.jsxs("li",{children:["• ",k(w)]},w))}):e.jsx("p",{className:"text-xs",children:"No projections imported"})]})]}),e.jsxs(Us,{children:[e.jsx(Bs,{asChild:!0,children:p.playerPoolCount>0?e.jsxs(B,{variant:"default",className:"gap-1 cursor-pointer hover:bg-primary/80 transition-colors",onClick:()=>y(c),children:[e.jsx(us,{className:"h-3 w-3"}),p.playerPoolCount]}):p.projectionCount>0?e.jsx(R,{variant:"outline",size:"sm",onClick:()=>_(c.id),disabled:h===c.id,className:"h-6 text-xs px-2",children:h===c.id?e.jsx(e.Fragment,{children:"⏳ Processing..."}):e.jsxs(e.Fragment,{children:[e.jsx(Rt,{className:"h-3 w-3 mr-1"}),"Generate"]})}):e.jsx(B,{variant:"outline",className:"gap-1 text-muted-foreground",children:"- No Pool"})}),e.jsxs(zs,{children:[e.jsx("p",{className:"text-xs font-semibold",children:"Player Pool:"}),e.jsx("p",{className:"text-xs",children:p.playerPoolCount>0?`${p.playerPoolCount} players processed with AI analysis`:p.projectionCount>0?"Click to generate player pool from projections":"Import projections first"})]})]}),c.status==="completed"&&e.jsxs(Us,{children:[e.jsx(Bs,{children:p.hasResults?e.jsx(rs,{className:"h-4 w-4 text-blue-600"}):e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(zs,{children:e.jsx("p",{className:"text-xs",children:p.hasResults?"Results uploaded":"No results"})})]})]})})};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden md:block",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-12",children:e.jsx(Ms,{checked:x,ref:c=>{c&&(c.indeterminate=g)},onCheckedChange:c=>l==null?void 0:l(!!c),"aria-label":"Select all"})}),e.jsx(U,{children:"Contest Name"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Platform"}),e.jsx(U,{children:"Type"}),e.jsx(U,{children:"Subtype"}),e.jsx(U,{children:"Slate Date"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Data Status"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:s.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:10,className:"text-center text-muted-foreground py-8",children:"No DFS contests found. Create one to get started."})}):s.map(c=>e.jsxs(he,{className:r.has(c.id)?"bg-primary/5":"",children:[e.jsx(M,{children:e.jsx(Ms,{checked:r.has(c.id),onCheckedChange:()=>i==null?void 0:i(c.id),"aria-label":`Select ${c.contest_name}`})}),e.jsx(M,{className:"font-medium",children:c.contest_name}),e.jsx(M,{className:"uppercase",children:c.sport}),e.jsx(M,{children:c.platform}),e.jsx(M,{children:c.contest_type||"N/A"}),e.jsx(M,{children:c.contest_type==="Showdown"&&c.home_team&&c.away_team?`${c.away_team} @ ${c.home_team}`:c.contest_subtype||"N/A"}),e.jsx(M,{children:ha(jt(c.slate_date),"UTC","MMM d, yyyy")}),e.jsx(M,{children:e.jsx(B,{variant:b(c.status),children:c.status})}),e.jsx(M,{children:j(c)}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>t(c),children:e.jsx(Bt,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(os,{className:"h-4 w-4"})})]})})]},c.id))})]})}),e.jsx("div",{className:"md:hidden space-y-3",children:s.length===0?e.jsx(G,{children:e.jsx(J,{className:"p-8 text-center text-muted-foreground",children:"No DFS contests found. Create one to get started."})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/50 rounded-lg",children:[e.jsx(Ms,{checked:x,ref:c=>{c&&(c.indeterminate=g)},onCheckedChange:c=>l==null?void 0:l(!!c),"aria-label":"Select all"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Select all visible"})]}),s.map(c=>e.jsx(G,{className:r.has(c.id)?"border-primary/50 bg-primary/5":"",children:e.jsx(J,{className:"p-4 space-y-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ms,{checked:r.has(c.id),onCheckedChange:()=>i==null?void 0:i(c.id),"aria-label":`Select ${c.contest_name}`,className:"mt-1"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium truncate",children:c.contest_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[c.sport.toUpperCase()," • ",c.platform," • ",c.contest_type||"N/A"]})]}),e.jsx(B,{variant:b(c.status),children:c.status})]}),c.contest_type==="Showdown"&&c.home_team&&c.away_team&&e.jsxs("p",{className:"text-sm font-medium mt
294-2",children:[c.away_team," @ ",c.home_team]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-2",children:["Date: ",ha(jt(c.slate_date),"UTC","MMM d, yyyy")]}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Data:"}),j(c)]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 mt-2 border-t",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>t(c),children:[e.jsx(Bt,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>o(c.id),children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})},c.id))]})}),e.jsx(ws,{open:!!m,onOpenChange:()=>o(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Are you sure?"}),e.jsx(Ps,{children:"This will permanently delete this DFS contest and all associated projections and salaries. This action cannot be undone."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:f,children:"Delete"})]})]})}),d&&e.jsx(xf,{contest:d,onClose:()=>y(null),onReprocessed:()=>u.invalidateQueries({queryKey:["contest-data-stats"]})})]})}const pf=["All","DraftKings","FanDuel","Yahoo","Underdog"],gf=["All","Classic","Showdown"],jf=["All","Main","Early","Afternoon","Late","Night","Primetime","After Hours","Express","Turbo","Multi-Day"],ff=["All","Draft","Active","Completed","Cancelled"],vf=["All","With Results","Without Results"];function yf({sport:s,league:a,platform:t,type:n,subtype:r,date:i,status:l,results:m,onSportChange:o,onLeagueChange:h,onPlatformChange:N,onTypeChange:d,onSubtypeChange:y,onDateChange:u,onStatusChange:x,onResultsChange:g,onReset:f,totalCount:_,filteredCount:k,availableSports:b,availableLeagues:j}){const c=n==="All"||n==="Showdown",p=s!=="All"||a!=="All"||t!=="All"||n!=="All"||r!=="All"||i!==void 0||l!=="All"||m!=="All";return e.jsx(G,{className:"p-4 mb-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Sport"}),e.jsxs(oe,{value:s,onValueChange:o,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"All",children:"All"}),b.map(w=>e.jsx(V,{value:w.sport_name,children:w.sport_name},w.sport_code))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"League"}),e.jsxs(oe,{value:a,onValueChange:h,disabled:s==="All"||j.length===0,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"All",children:"All"}),j.map(w=>e.jsx(V,{value:w.id,children:w.name},w.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Platform"}),e.jsxs(oe,{value:t,onValueChange:N,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:pf.map(w=>e.jsx(V,{value:w,children:w},w))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Type"}),e.jsxs(oe,{value:n,onValueChange:d,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:gf.map(w=>e.jsx(V,{value:w,children:w},w))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Subtype"}),e.jsxs(oe,{value:r,onValueChange:y,disabled:c,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:jf.map(w=>e.jsx(V,{value:w,children:w},w))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Date"}),e.jsx(yr,{date:i,onSelect:u})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Status"}),e.jsxs(oe,{value:l,onValueChange:x,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:ff.map(w=>e.jsx(V,{value:w,children:w},w))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Has Results"}),e.jsxs(oe,{value:m,onValueChange:g,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:vf.map(w=>e.jsx(V,{value:w,children:w}
294,w))})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:f,disabled:!p,children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Reset Filters"]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:p?e.jsxs(e.Fragment,{children:["Showing ",k," of ",_," contests"]}):e.jsxs(e.Fragment,{children:[_," contests"]})})]})]})})}function Nf(){return ge({queryKey:["contest-data-stats"],queryFn:async()=>{const s={},{data:a,error:t}=await T.rpc("get_contest_data_stats").limit(5e3);if(t)throw t;return a&&a.length>0&&a.forEach(n=>{s[n.contest_id]={projectionSources:n.projection_sources||[],projectionCount:n.source_count||0,hasResults:n.has_results||!1,playerPoolCount:n.player_pool_count||0}}),s},staleTime:3e4})}function _f(){const[s,a]=v.useState(!1),[t,n]=v.useState(null),[r,i]=v.useState(null),[l,m]=v.useState(new Set),o=v.useRef(null),h=Me(),[N,d]=v.useState("All"),[y,u]=v.useState("All"),[x,g]=v.useState("All"),[f,_]=v.useState("All"),[k,b]=v.useState("All"),[j,c]=v.useState(void 0),[p,w]=v.useState("All"),[S,P]=v.useState("All"),{data:C=[]}=ge({queryKey:["active-sports-for-filters"],queryFn:async()=>{const{data:re,error:ce}=await T.from("sport_statuses").select("sport_name, sport_code, leagues_config").eq("is_active",!0).order("sport_name");if(ce)throw ce;return re||[]}}),O=v.useMemo(()=>{if(N==="All")return[];const re=C.find(ce=>ce.sport_name===N);return re!=null&&re.leagues_config?(re.leagues_config||[]).filter(ce=>ce.is_enabled&&!ce.is_grouped).map(ce=>({id:ce.league_id,name:ce.league_name})):[]},[N,C]),{data:$=[],isLoading:z}=ge({queryKey:["dfs-contests"],queryFn:async()=>{const{data:re,error:ce}=await T.from("dfs_contests").select("*").order("slate_date",{ascending:!1});if(ce)throw ce;return re}}),{data:D,isLoading:A}=Nf();v.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const F=v.useCallback(async re=>{try{const{data:ce,error:Pe}=await T.functions.invoke("process-all-contest-pools",{body:{jobId:re}});if(Pe){console.error("Error polling job status:",Pe),i(Ae=>Ae?{...Ae,status:"failed",errorMessage:Pe.message}:null);return}const Fe={jobId:re,status:ce.status,total:ce.total_items||0,processed:ce.processed_items||0,current:ce.current_item||"",successCount:ce.success_count||0,errorCount:ce.error_count||0,skippedCount:ce.skipped_count||0,results:ce.results,errorMessage:ce.error_message};if(i(Fe),ce.status==="running"||ce.status==="pending")o.current=setTimeout(()=>F(re),2e3);else if(ce.status==="completed"){const Ae=Fe.successCount;Fe.errorCount>0?K.warning(`Processed ${Ae} contests with ${Fe.errorCount} errors`):K.success(`Successfully processed ${Ae} player pools`),h.invalidateQueries({queryKey:["contest-data-stats"]})}else ce.status==="failed"&&K.error(`Processing failed: ${ce.error_message||"Unknown error"}`)}catch(ce){console.error("Error polling job status:",ce),i(Pe=>Pe?{...Pe,status:"failed",errorMessage:"Polling error"}:null)}},[h]),q=v.useMemo(()=>$.filter(re=>{var ce,Pe,Fe,Ae,Ve,as,Oe;if(N!=="All"){const Ie=C.find(ds=>ds.sport_name===N);if(Ie){const ds=(ce=Ie.sport_code)==null?void 0:ce.toLowerCase(),be=(Pe=re.sport)==null?void 0:Pe.toLowerCase();if(!(be===ds||N==="Football"&&["nfl","ncaaf","football"].includes(be||"")||N==="Basketball"&&["nba","ncaab","basketball"].includes(be||"")||N==="Hockey"&&["nhl","hockey"].includes(be||"")||N==="Baseball"&&["mlb","baseball"].includes(be||"")||N==="Soccer"&&["soccer","mls","epl"].includes(be||"")||N==="Golf"&&["golf","pga"].includes(be||"")||N==="MMA"&&["mma","ufc"].includes(be||"")||N==="Racing"&&["racing","nascar","f1"].includes(be||"")))return!1}}if(y!=="All"&&((Fe=re.sport)==null?void 0:Fe.toLowerCase())!==y.toLowerCase()||x!=="All"&&((Ae=re.platform)==null?void 0:Ae.toLowerCase())!==x.toLowerCase()||f!=="All"&&((Ve=re.contest_type)==null?void 0:Ve.toLowerCase())!==f.toLowerCase()||k!=="All"&&((as=re.contest_subtype)==null?void 0:as.toLowerCase())!==k.toLowerCase())return!1;if(j){const Ie=re.slate_date,ds=ke(j,"yyyy-MM-dd");if(Ie!==ds)return!1}if(p!=="All"&&((Oe=re.status)==null?void 0:Oe.toLowerCase())!==p.toLowerCase())return!1;if(S!=="All"){if(!D)return!1;const Ie=D[re.id],ds=(Ie==null?void 0:Ie.hasResults)??!1;
294if(S==="With Results"&&!ds||S==="Without Results"&&ds)return!1}return!0}),[$,N,y,x,f,k,j,p,S,D,C]),E=()=>{d("All"),u("All"),g("All"),_("All"),b("All"),c(void 0),w("All"),P("All")},L=_e({mutationFn:async re=>{const{data:{user:ce}}=await T.auth.getUser(),Pe={contest_id:`${re.platform.toLowerCase()}-${re.sport}-${ke(re.slate_date,"yyyyMMdd")}-${re.contest_type.toLowerCase()}`,contest_name:re.contest_name,sport:re.sport,league:re.league||null,platform:re.platform,slate_date:ke(re.slate_date,"yyyy-MM-dd"),contest_type:re.contest_type,contest_subtype:re.contest_subtype||null,home_team:re.home_team||null,away_team:re.away_team||null,game_id:re.game_id||null,status:re.status,created_by:ce==null?void 0:ce.id},{error:Fe}=await T.from("dfs_contests").insert(Pe);if(Fe)throw Fe},onSuccess:()=>{h.invalidateQueries({queryKey:["dfs-contests"]}),K.success("DFS contest created successfully"),a(!1)},onError:re=>{console.error("Error creating contest:",re),K.error("Failed to create contest")}}),H=_e({mutationFn:async({id:re,data:ce})=>{const{error:Pe}=await T.from("dfs_contests").update({contest_name:ce.contest_name,sport:ce.sport,league:ce.league||null,platform:ce.platform,slate_date:ke(ce.slate_date,"yyyy-MM-dd"),contest_type:ce.contest_type,contest_subtype:ce.contest_subtype||null,home_team:ce.home_team||null,away_team:ce.away_team||null,game_id:ce.game_id||null,status:ce.status}).eq("id",re);if(Pe)throw Pe},onSuccess:()=>{h.invalidateQueries({queryKey:["dfs-contests"]}),K.success("DFS contest updated successfully"),a(!1),n(null)},onError:re=>{console.error("Error updating contest:",re),K.error("Failed to update contest")}}),Z=_e({mutationFn:async re=>{const{error:ce}=await T.from("dfs_contests").delete().eq("id",re);if(ce)throw ce},onSuccess:()=>{h.invalidateQueries({queryKey:["dfs-contests"]}),K.success("DFS contest deleted successfully")},onError:re=>{console.error("Error deleting contest:",re),K.error("Failed to delete contest")}}),se=async re=>{t?await H.mutateAsync({id:t.id,data:re}):await L.mutateAsync(re)},ie=re=>{n(re),a(!0)},Y=re=>{Z.mutate(re)},I=()=>{a(!1),n(null)},ee=re=>{m(ce=>{const Pe=new Set(ce);return Pe.has(re)?Pe.delete(re):Pe.add(re),Pe})},le=re=>{m(re?new Set(q.map(ce=>ce.id)):new Set)},ve=()=>{m(new Set)},te=async()=>{o.current&&clearTimeout(o.current);try{const re=l.size>0?Array.from(l):void 0,{data:ce,error:Pe}=await T.functions.invoke("process-all-contest-pools",{body:{contestIds:re}});if(Pe)throw Pe;if(ce!=null&&ce.jobId)i({jobId:ce.jobId,status:"pending",total:0,processed:0,current:"Starting...",successCount:0,errorCount:0,skippedCount:0}),F(ce.jobId),K.info("Processing started - tracking progress..."),m(new Set);else throw new Error("No job ID returned")}catch(re){console.error("Failed to start processing:",re),K.error("Failed to start processing player pools"),i(null)}},X=()=>{o.current&&clearTimeout(o.current),i(null)},ae=(r==null?void 0:r.status)==="running"||(r==null?void 0:r.status)==="pending",W=r&&r.total>0?r.processed/r.total*100:0;return e.jsxs("div",{className:"space-y-6",children:[r&&e.jsx(G,{className:Le("border-2",r.status==="running"||r.status==="pending"?"border-primary/50 bg-primary/5":r.status==="completed"?"border-green-500/50 bg-green-500/5":"border-destructive/50 bg-destructive/5"),children:e.jsx(J,{className:"pt-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0",children:ae?e.jsx(ne,{className:"h-6 w-6 animate-spin text-primary"}):r.status==="completed"?e.jsx(rs,{className:"h-6 w-6 text-green-500"}):e.jsx(Is,{className:"h-6 w-6 text-destructive"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-sm font-semibold",children:ae?"Processing Player Pools...":r.status==="completed"?"Processing Complete":"Processing Failed"}),!ae&&e.jsx(R,{variant:"ghost",size:"sm",onClick:X,children:"Dismiss"})]}),ae&&r.current&&e.jsxs("p",{className:"text-sm text-muted-foreground truncate mb-2",children:["Current: ",r.current]}),r.total>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ct,{value:W,className:"h-2 mb-2"}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[r.processed," / ",r.total," contests"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(rs,{className:"h-3 w-3 text-green-500"}),r.successCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Is,{className:"h-3 w-3 text-destructive"}),r.errorCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pu,{className:"h-3 w-3 text-muted-foreground"}),r.skippedCount]})]})]})]}),r.errorMessage&&e.jsxs("p",{className:"text-sm text-destructive mt-2",children:["Error: ",r.errorMessage]})]})]})})}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{children:"DFS Contest Management"}),e.jsx(De,{children:"Create and manage DFS contests for data imports"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{variant:"outline",onClick:te,disabled:ae,children:[e.jsx(He,{className:Le("h-4 w-4 mr-2",ae&&"animate-spin")}),l.size>0?`Process Selected (${l.size})`:"Process All Pools"]}),e.jsxs(R,{onClick:()=>a(!0),children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Create Contest"]})]})]})}),e.jsxs(J,{children:[e.jsx(yf,{sport:N,league:y,platform:x,type:f,subtype:k,date:j,status:p,results:S,onSportChange:re=>{d(re),u("All")},onLeagueChange:u,onPlatformChange:g,onTypeChange:re=>{_(re),(re==="Showdown"||re==="All")&&b("All")},onSubtypeChange:b,onDateChange:c,onStatusChange:w,onResultsChange:P,onReset:E,totalCount:$.length,filteredCount:q.length,availableSports:C,availableLeagues:O}),l.size>0&&e.jsxs("div",{className:"flex items-center justify-between p-3 mb-4 rounded-lg bg-primary/10 border border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[l.size," contest",l.size!==1?"s":""," selected"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"ghost",size:"sm",onClick:ve,children:[e.jsx(rt,{className:"h-4 w-4 mr-1"}),"Clear Selection"]}),e.jsxs(R,{size:"sm",onClick:te,disabled:ae,children:[e.jsx(He,{className:Le("h-4 w-4 mr-1",ae&&"animate-spin")}),"Process Selected"]})]})]}),z||A?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading contests..."}):e.jsx(hf,{contests:q,dataStats:D,onEdit:ie,onDelete:Y,selectedIds:l,onToggleSelect:ee,onToggleSelectAll:le})]})]}),e.jsx(mf,{open:s,onClose:I,onSubmit:se,contest:t})]})}const Er=s=>{const a=s.toLowerCase();return a==="nfl"||a==="ncaaf"?"FOOTBALL":a==="nba"||a==="ncaab"?"BASKETBALL":a==="nhl"?"HOCKEY":a==="mlb"?"BASEBALL":s.toUpperCase()};function bf(){const s=an(new Date,"America/Chicago"),a=ke(s,"yyyy-MM-dd");return ge({queryKey:["import-dashboard-stats",a],queryFn:async()=>{const{data:t,error:n}=await T.rpc("get_contests_needing_results",{p_before_date:a});if(n)throw n;const r={};
294(t||[]).forEach(x=>{const g=Er(x.sport||"unknown");r[g]=(r[g]||0)+1});const{data:i,error:l}=await T.from("dfs_contests").select("id, sport").eq("slate_date",a).eq("status","draft");if(l)throw l;const m={};(i||[]).forEach(x=>{const g=Er(x.sport||"unknown");m[g]=(m[g]||0)+1});const{data:o,error:h}=await T.from("dfs_contests").select("id, sport").eq("slate_date",a).eq("status","active");if(h)throw h;const N={};(o||[]).forEach(x=>{const g=Er(x.sport||"unknown");N[g]=(N[g]||0)+1});const{data:d,error:y}=await T.from("player_props").select("sport").eq("game_date",a);if(y)throw y;const u={};return(d||[]).forEach(x=>{const g=Er(x.sport||"unknown");u[g]=(u[g]||0)+1}),{results:{total:t.length,bySport:r},create:{total:(i==null?void 0:i.length)||0,bySport:m},update:{total:(o==null?void 0:o.length)||0,bySport:N},props:{total:(d==null?void 0:d.length)||0,bySport:u}}},staleTime:3e4})}function ln({steps:s,currentStep:a,className:t}){return e.jsx("nav",{"aria-label":"Progress",className:Le("w-full",t),children:e.jsx("ol",{className:"flex items-center justify-between",children:s.map((n,r)=>e.jsxs("li",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:Le("flex items-center justify-center w-8 h-8 rounded-full text-sm font-medium transition-colors",r<a?"bg-primary text-primary-foreground":r===a?"bg-primary text-primary-foreground ring-2 ring-primary ring-offset-2":"bg-muted text-muted-foreground"),children:r<a?e.jsx(Ks,{className:"h-4 w-4"}):r+1}),e.jsxs("div",{className:"mt-2 text-center",children:[e.jsx("p",{className:Le("text-xs font-medium",r<=a?"text-foreground":"text-muted-foreground"),children:n.label}),n.description&&e.jsx("p",{className:"text-xs text-muted-foreground hidden sm:block",children:n.description})]})]}),r<s.length-1&&e.jsx("div",{className:Le("absolute top-4 left-1/2 w-full h-0.5 -translate-y-1/2",r<a?"bg-primary":"bg-muted")})]},n.label))})})}const cn=[{value:"mlb",label:"MLB"},{value:"nfl",label:"NFL"},{value:"nba",label:"NBA"},{value:"nhl",label:"NHL"},{value:"mma",label:"MMA"},{value:"soccer",label:"Soccer"}],Aa=[{value:"projections",label:"DFS Projections",table:"dfs_projections"},{value:"salaries",label:"DFS Salaries",table:"dfs_projections"},{value:"contests",label:"DFS Contests",table:"dfs_contests"},{value:"game_schedules",label:"Game Schedules",table:"game_schedules"},{value:"betting_odds",label:"Betting Odds",table:"betting_odds"},{value:"dfs_results",label:"DFS Historical Results",table:"dfs_historical_results"},{value:"betting_results",label:"Betting Historical Results",table:"betting_historical_results"},{value:"injuries",label:"Injury Report",table:"dfs_injuries"},{value:"player_props",label:"Player Props",table:"player_props"}],mi=[{value:"stokastic",label:"Stokastic"},{value:"linestart",label:"LineStar App"},{value:"sabersim",label:"SaberSim"},{value:"rotowire",label:"RotoWire"},{value:"fantasypros",label:"FantasyPros"},{value:"other",label:"Other"}],Yc=[{value:"DraftKings",label:"DraftKings"},{value:"FanDuel",label:"FanDuel"},{value:"Yahoo",label:"Yahoo"},{value:"Underdog",label:"Underdog"}],wf=[{value:"insert",label:"Insert Only (Skip Duplicates)",description:"Skip records that already exist"},{value:"upsert",label:"Upsert (Update Existing)",description:"Update existing records from same source"},{value:"replace",label:"Replace (Delete & Insert)",description:"Delete all existing data and insert new"},{value:"add_source",label:"Add New Source (Keep Existing)",description:"Add projections from new source without affecting existing data"},{value:"merge_salaries",label:"Merge Salaries (Update)",description:"Update salary for existing projection records by matching player name + roster position"}],xi={required:["Name","Team","Position","Salary","Projected"],optional:["BatOrder","BatThrow","Opponent","GameInfo"],types:{Salary:"number",Projected:"number",BatOrder:"number"}},hi={required:["Player Name","Projection"],optional:["Player Name and Id","Player Name and Captain Id","Ownership","Captain Ownership","Max Exposure"],types:{Projection:"number",Ownership:"number","Captain Ownership":"number","Max Exposure":"number"}},pi={required:["Name","Position","Team","Salary","Projected"],optional:["Opp
294onent","GameInfo","Ownership"],types:{Salary:"number",Projected:"number",Ownership:"number"}},Sf={required:["Name","Team","Position","Salary","Projected"],optional:["Opponent","Avg Simulated ROI","Ceiling","Floor"],types:{Salary:"number",Projected:"number"}},kf={required:["Name","Salary","Roster Position"],optional:["Position","TeamAbbrev","ID","Name + ID","Game Info","AvgPointsPerGame"],types:{Salary:"number"}},Cf={required:["Name","Salary","Position"],optional:["Team","TeamAbbrev","ID","Game Info"],types:{Salary:"number"}},Pf={required:["Name","Salary"],optional:["Team","Position","ID","BatOrder"],types:{Salary:"number"}},gi={required:["Name","Team","Position","Salary","Projected"],optional:["Opponent","GameInfo","Ownership","Ceiling","Floor"],types:{Salary:"number",Projected:"number",Ownership:"number",Ceiling:"number",Floor:"number"}},Ff={required:["Name","Salary"],optional:["Team","Position","ID","Roster Position"],types:{Salary:"number"}},ji={required:["Name","Team","Position","Salary","Projected"],optional:["Opponent","GameInfo","Ownership","Ceiling","Floor"],types:{Salary:"number",Projected:"number",Ownership:"number",Ceiling:"number",Floor:"number"}},Af={required:["Name","Salary"],optional:["Team","Position","ID","Roster Position"],types:{Salary:"number"}},Jc={Player:"Player",Player_1:"Player",Player_2:"Player",Team:"Team",Team_1:"Team",Team_2:"Team",Opponent:"Opponent",Opponent_1:"Opponent",Opponent_2:"Opponent",Opp:"Opponent",Position:"Position",Position_1:"Position",Position_2:"Position",Pos:"Position",Pos_1:"Position",Pos_2:"Position","Market Name":"MarketName","Market Name_1":"MarketName","Market Name_2":"MarketName",market_name:"MarketName",Line:"ConsensusLine",Line_1:"ConsensusLine",Date:"GameDate",Date_1:"GameDate",Date_2:"GameDate","Game Date":"GameDate",game_date:"GameDate","At Home":"IsHome","At Home_1":"IsHome","Hit Rate: Last 5":"HitRateLast5","Hit Rate: Last 10":"HitRateLast10","Hit Rate: Last 20":"HitRateLast20","Hit Rate: Last 30":"HitRateLast30","Hit Rate: Season":"HitRateSeason","Hit Rate: Previous Season":"HitRatePrevSeason","Hit Rate: Vs Opponent":"HitRateVsOpponent","Weighted Hit Rate":"WeightedHitRate","Hit Rate: Last 5 Outcomes":"HitRateOutcomes5","Hit Rate: Last 10 Outcomes":"HitRateOutcomes10","Hit Rate: Last 20 Outcomes":"HitRateOutcomes20","Hit Rate: Last 30 Outcomes":"HitRateOutcomes30",L5:"HitRateLast5",L10:"HitRateLast10",L20:"HitRateLast20",L30:"HitRateLast30","Last 5":"HitRateLast5","Last 10":"HitRateLast10","Last 20":"HitRateLast20","Last 30":"HitRateLast30",Season:"HitRateSeason","Vs Opp":"HitRateVsOpponent","vs Opp":"HitRateVsOpponent",VsOpponent:"HitRateVsOpponent","vs Opponent":"HitRateVsOpponent",Lean:"Lean",Lean_1:"Lean","Fa Lean":"Lean","Fa Lean_1":"Lean","Fantasy Lean":"Lean","FanDuel Lean":"Lean",Prediction:"PredictionScore",Prediction_1:"PredictionScore",PredictionScore:"PredictionScore",PredictionScore_1:"PredictionScore","RotoWire Projection":"Projection","RotoWire Projection Difference":"ProjectionDifference","RotoWire Projection Difference %":"ProjectionDifferencePct","Line Change":"LineChange","Line Change_1":"LineChange","Line % Change":"LineChangePct","Line % Change_1":"LineChangePct","Previous Line":"PreviousLine","Previous Line_1":"PreviousLine","Opened At":"OpenedAt","Opened At_1":"OpenedAt","Updated At":"UpdatedAt","Updated At_1":"UpdatedAt","PrizePicks Line":"PrizePicks","PrizePicks Line_1":"PrizePicks","FanDuel Line":"FanDuel","FanDuel Line_1":"FanDuel","DraftKings Line":"DraftKings","DraftKings Line_1":"DraftKings","BetMGM Line":"BetMGM","BetMGM Line_1":"BetMGM","ESPN Line":"ESPN","ESPN Line_1":"ESPN","Fliff Line":"Fliff","Fliff Line_1":"Fliff","Hard Rock Line":"HardRock","Hard Rock Line_1":"HardRock","Bet365 Line":"bet365","Bet365 Line_1":"bet365","Underdog Line":"Underdog","Underdog Line_1":"Underdog","Sleeper Line":"Sleeper","Sleeper Line_1":"Sleeper","RTSports Line":"RTSports","RTSports Line_1":"RTSports","BetRivers Line":"BetRivers","BetRivers Line_1":"BetRivers","DraftKings Pick6 Line":"DraftKingsPick6","DraftKings Pick6 Line_1":"DraftKingsPick6","Caesars Line":"Caesars","Caesars Line_1":"Caesars",Site:"Site",Site_1:"Site","Average Line Variance":"AverageLineVariance","Hit Rate Factor":"HitRateFactor","DFS Pick'em Sites Factor":"DfsPickemFactor","RotoWire Projection Factor":"ProjectionFactor","Sportsbooks Factor":"SportsbooksFactor","Market Variation":"MarketVariation"},Zc={};for(const[s,a]of Object.entries(Jc))Zc[s.toLowerCase()]=a;const Xc=s=>{const a={};for(const[t,n]of Object.entries(s)){const r=Zc[t.toLowerCase()]||Jc[t]||t;a[r]=n}if(a.IsHome!==void 0){const t=String(a.IsHome).toLowerCase();a.IsHome=["y","yes","true","1","home"].includes(t)}return a},Tf=s=>{const a=[],t=[],n=s.map(r=>Xc(r));if(n.length>0){const r=Object.keys(n[0]);console.log("[Player Props Validation] Columns after normalization:",r);const l=["Player","Team","Opponent","MarketName"].filter(m=>!r.includes(m));l.length>0&&(console.warn("[Player Props Validation] Missing expected columns:",l),console.log("[Player Props Validation] First row sample:",JSON.stringify(n[0],null,2)))}
294return n.forEach((r,i)=>{const l=r.Player||r.player||r.Name||r.name||r.player_name,m=r.Team||r.team,o=r.Opponent||r.opponent||r.Opp,h=r.MarketName||r.market_name||r["Market Name"];!l&&l!==0&&a.push({row:i+1,column:"Player",value:r.Player,message:"Missing required field: Player"}),!m&&m!==0&&a.push({row:i+1,column:"Team",value:r.Team,message:"Missing required field: Team"}),!o&&o!==0&&a.push({row:i+1,column:"Opponent",value:r.Opponent,message:"Missing required field: Opponent"}),!h&&h!==0&&a.push({row:i+1,column:"MarketName",value:r.MarketName,message:"Missing required field: MarketName"}),r.ConsensusLine&&r.ConsensusLine<0&&t.push({row:i+1,column:"ConsensusLine",value:r.ConsensusLine,message:"Consensus line is negative - verify this is correct"}),["HitRateLast5","HitRateLast10","HitRateLast20","HitRateLast30","HitRateSeason","WeightedHitRate"].forEach(d=>{r[d]!==void 0&&r[d]!==null&&(r[d]<0||r[d]>100)&&t.push({row:i+1,column:d,value:r[d],message:`${d} should be between 0-100`})}),r.Lean&&!["More","Less","more","less","OVER","UNDER","over","under"].includes(r.Lean)&&t.push({row:i+1,column:"Lean",value:r.Lean,message:"Lean should be More/Less or Over/Under"})}),{valid:a.length===0,errors:a,warnings:t,duplicates:0,totalRows:s.length}},Lf=s=>{const a=[],t=[];return s.forEach((n,r)=>{xi.required.forEach(i=>{!n[i]&&n[i]!==0&&a.push({row:r+1,column:i,value:n[i],message:`Missing required field: ${i}`})}),Object.entries(xi.types).forEach(([i,l])=>{n[i]!==void 0&&n[i]!==null&&l==="number"&&typeof n[i]!="number"&&a.push({row:r+1,column:i,value:n[i],message:`Expected ${l}, got ${typeof n[i]}`})}),n.Salary&&(n.Salary<3e3||n.Salary>11e3)&&t.push({row:r+1,column:"Salary",value:n.Salary,message:"Salary outside typical DFS range (3000-11000)"}),n.Projected&&(n.Projected<0||n.Projected>50)&&t.push({row:r+1,column:"Projected",value:n.Projected,message:"Projection outside typical range (0-50)"})}),{valid:a.length===0,errors:a,warnings:t,duplicates:0,totalRows:s.length}},Ef=s=>{const a=[],t=[];return s.forEach((n,r)=>{hi.required.forEach(i=>{!n[i]&&n[i]!==0&&a.push({row:r+1,column:i,value:n[i],message:`Missing required field: ${i}`})}),Object.entries(hi.types).forEach(([i,l])=>{n[i]!==void 0&&n[i]!==null&&l==="number"&&typeof n[i]!="number"&&a.push({row:r+1,column:i,value:n[i],message:`Expected ${l}, got ${typeof n[i]}`})}),n.Projection&&(n.Projection<0||n.Projection>60)&&t.push({row:r+1,column:"Projection",value:n.Projection,message:"Projection outside typical NFL range (0-60)"}),n.Ownership&&(n.Ownership<0||n.Ownership>1)&&t.push({row:r+1,column:"Ownership",value:n.Ownership,message:"Ownership should be between 0 and 1 (percentage)"}),n["Captain Ownership"]&&(n["Captain Ownership"]<0||n["Captain Ownership"]>1)&&t.push({row:r+1,column:"Captain Ownership",value:n["Captain Ownership"],message:"Captain Ownership should be between 0 and 1 (percentage)"})}),{valid:a.length===0,errors:a,warnings:t,duplicates:0,totalRows:s.length}},Df=s=>{const a=[],t=[];return s.forEach((n,r)=>{pi.required.forEach(i=>{!n[i]&&n[i]!==0&&a.push({row:r+1,column:i,value:n[i],message:`Missing required field: ${i}`})}),Object.entries(pi.types).forEach(([i,l])=>{n[i]!==void 0&&n[i]!==null&&l==="number"&&typeof n[i]!="number"&&a.push({row:r+1,column:i,value:n[i],message:`Expected ${l}, got ${typeof n[i]}`})}),n.Salary&&(n.Salary<3e3||n.Salary>1e4)&&t.push({row:r+1,column:"Salary",value:n.Salary,message:"Salary outside typical NFL DFS range (3000-10000)"}),n.Projected&&(n.Projected<0||n.Projected>50)&&t.push({row:r+1,column:"Projected",value:n.Projected,message:"Projection outside typical NFL range (0-50)"})}),{valid:a.length===0,errors:a,warnings:t,duplicates:0,totalRows:s.length}},Mf=s=>{const a=[],t=[];return s.forEach((n,r)=>{gi.required.forEach(i=>{!n[i]&&n[i]!==0&&a.push({row:r+1,column:i,value:n[i],message:`Missing required field: ${i}`})}),Object.entries(gi.types).forEach(([i,l])=>{n[i]!==void 0&&n[i]!==null&&l==="number"&&typeof n[i]!="number"&&a.push({row:r+1,column:i,value:n[i],message:`Expected ${l}, got ${typeof n[i]}`})}),n.Salary&&(n.Salary<2500||n.Salary>1e4)&&t.push({row:r+1,column:"Salary",value:n.Salary,message:"Salary outside typical NHL DFS range (2500-10000)"}),n.Projected&&(n.Projected<0||n.Projected>
29440)&&t.push({row:r+1,column:"Projected",value:n.Projected,message:"Projection outside typical NHL range (0-40)"})}),{valid:a.length===0,errors:a,warnings:t,duplicates:0,totalRows:s.length}},If=s=>{const a=[],t=[];return s.forEach((n,r)=>{ji.required.forEach(i=>{!n[i]&&n[i]!==0&&a.push({row:r+1,column:i,value:n[i],message:`Missing required field: ${i}`})}),Object.entries(ji.types).forEach(([i,l])=>{n[i]!==void 0&&n[i]!==null&&l==="number"&&typeof n[i]!="number"&&a.push({row:r+1,column:i,value:n[i],message:`Expected ${l}, got ${typeof n[i]}`})}),n.Salary&&(n.Salary<2500||n.Salary>12e3)&&t.push({row:r+1,column:"Salary",value:n.Salary,message:"Salary outside typical Soccer DFS range (2500-12000)"}),n.Projected&&(n.Projected<0||n.Projected>30)&&t.push({row:r+1,column:"Projected",value:n.Projected,message:"Projection outside typical Soccer range (0-30)"})}),{valid:a.length===0,errors:a,warnings:t,duplicates:0,totalRows:s.length}},Rf=(s,a,t)=>{const n=[],r=[];let i;if(a==="nfl")i=t==="Showdown"||t==="SingleGame"?kf:Cf;else if(a==="mlb")i=Pf;else if(a==="nhl")i=Ff;else if(a==="soccer")i=Af;else return{valid:!0,errors:[],warnings:[],duplicates:0,totalRows:s.length};return s.forEach((l,m)=>{i.required.forEach(o=>{!l[o]&&l[o]!==0&&n.push({row:m+1,column:o,value:l[o],message:`Missing required field: ${o}`})}),l.Salary&&(l.Salary<2500||l.Salary>2e4)&&r.push({row:m+1,column:"Salary",value:l.Salary,message:"Salary outside typical DFS range (2500-20000)"}),(t==="Showdown"||t==="SingleGame")&&l["Roster Position"]&&(["CPT","FLEX"].includes(l["Roster Position"])||r.push({row:m+1,column:"Roster Position",value:l["Roster Position"],message:"Expected CPT or FLEX for Showdown contests"}))}),{valid:n.length===0,errors:n,warnings:r,duplicates:0,totalRows:s.length}},qf=(s,a,t,n)=>{if(s==="salaries")return Rf(a,t||"mlb",n||"Classic");if(s==="projections"){if(a.length>0&&a[0].Salary!==void 0&&a[0].Name!==void 0&&a[0].Projected!==void 0&&t==="nfl"&&(n==="Showdown"||n==="SingleGame")){const i=[],l=[];return a.forEach((m,o)=>{Sf.required.forEach(h=>{!m[h]&&m[h]!==0&&i.push({row:o+1,column:h,value:m[h],message:`Missing required field: ${h}`})}),m.Salary&&(m.Salary<2500||m.Salary>2e4)&&l.push({row:o+1,column:"Salary",value:m.Salary,message:"Salary outside typical DFS range (2500-20000)"}),m.Projected&&(m.Projected<0||m.Projected>60)&&l.push({row:o+1,column:"Projected",value:m.Projected,message:"Projection outside typical NFL range (0-60)"})}),{valid:i.length===0,errors:i,warnings:l,duplicates:0,totalRows:a.length}}return t==="mlb"?Lf(a):t==="nfl"?n==="Showdown"||n==="SingleGame"?Ef(a):Df(a):t==="nhl"?Mf(a):t==="soccer"?If(a):{valid:!0,errors:[],warnings:[],duplicates:0,totalRows:a.length}}return s==="player_props"?Tf(a):{valid:!0,errors:[],warnings:[],duplicates:0,totalRows:a.length}};function $f({duplicates:s,onResolved:a,onCancel:t,totalRows:n}){const[r,i]=v.useState(()=>{const u={};return s.forEach(x=>{const g=x.entries.reduce((f,_)=>_.scored>f.scored?_:f,x.entries[0]);u[x.playerName]=g.rowIndex}),u}),l=s.every(u=>r[u.playerName]!==void 0),m=new Set(s.flatMap(u=>u.entries.map(x=>x.rowIndex))),o=m.size-s.length,h=n-o,N=()=>{const u={};s.forEach(x=>{const g=x.entries.reduce((f,_)=>_.scored>f.scored?_:f,x.entries[0]);u[x.playerName]=g.rowIndex}),i(u)},d=()=>{i({})},y=()=>{const u=Object.values(r),x=[];for(let f=0;f<n;f++)m.has(f)||x.push(f);const g=[...x,...u].sort((f,_)=>f-_);a(g)};return e.jsxs(G,{className:"border-yellow-500/50 bg-yellow-500/5",children:[e.jsx(je,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-yellow-600",children:[e.jsx(ls,{className:"h-5 w-5"}),"Duplicate Players Detected (",s.length," players)"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"The following players appear multiple times in the file (likely due to trades). Select which entry to keep for each player."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:N,children:[e.jsx(rs,{className:"h-4 w-4 mr-2"}),"Select All Highest Score"]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:d,children:"Clear All"})]}),e.jsx("div",{className:"space-y-4 max-h-96 overflow-auto pr-2",children:s.map(u=>{var x;return e.jsxs("div",{className:"border rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:u.playerName}),e.jsxs(B,{variant:"outline",className:"text-xs",children:[u.entries.length," entries"]})]}),e.jsx(Ut,{value:(x=r[u.playerName])==null?void 0:x.toString(),onValueChange:g=>i(f=>({...f,[u.playerName]:parseInt(g)})),children:e.jsx("div",{className:"space-y-2",children:u.entries.map(g=>{var _;const f=r[u.playerName]===g.rowIndex;return e.jsxs("div",{className:Le("flex items-center gap-3 p-2 rounded-md border transition-colors",f?"bg-green-500/10 border-green-500/50":"bg-muted/30 border-transparent opacity-60"),children:[e.jsx(nt,{value:g.rowIndex.toString(),id:`${u.playerName}-${g.rowIndex}`}),e.jsx(Q,{htmlFor:`${u.playerName}-${g.rowIndex}`,className:"flex-1 cursor-pointer",children:e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsx("span",{className:"font-medium w-16",children:g.team}),e.jsx("span",{className:"text-muted-foreground w-12",children:g.position}),e.jsxs("span",{className:Le("font-mono",g.scored>0?"text-green-500":"text-muted-foreground"),children:[g.scored.toFixed(1)," pts"]}),e.jsxs("span",{className:"text-muted-foreground",children:["$",((_=g.salary)==null?void 0:_.toLocaleStr
294ing())||"N/A"]}),g.projected>0&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(proj: ",g.projected.toFixed(1),")"]})]})}),f&&e.jsx(B,{variant:"default",className:"bg-green-500 text-xs",children:"Keep"})]},g.rowIndex)})})})]},u.playerName)})}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:l?e.jsxs("span",{className:"text-green-500",children:["✓ All duplicates resolved • ",o," entries will be removed"]}):e.jsxs("span",{className:"text-yellow-500",children:[s.filter(u=>r[u.playerName]===void 0).length," players need selection"]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"outline",onClick:t,children:"Cancel"}),e.jsxs(R,{onClick:y,disabled:!l,children:["Continue with ",h," Records"]})]})]})]})]})}function Of({entries:s,onResolved:a,onCancel:t,totalRows:n,sport:r}){const[i,l]=v.useState({}),[m,o]=v.useState(""),h=Object.keys(i).length,N=h===s.length,d=(g,f)=>{l(_=>({..._,[g]:f}))},y=()=>{if(!m)return;const g={};s.forEach(f=>{g[f.rowIndex]=m}),l(g)},u=()=>{l({}),o("")},x=()=>{a(i)};return new Date().toISOString().split("T")[0],e.jsxs(G,{className:"border-yellow-500/50 bg-yellow-500/5",children:[e.jsx(je,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-yellow-600",children:[e.jsx(ls,{className:"h-5 w-5"}),"Missing Game Dates (",s.length," rows)"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"The following player props are missing a GameDate value. Assign a game date to each row before importing. This is required for accurate game matching and auto-settlement."}),e.jsxs("div",{className:"flex items-end gap-4 p-3 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(Q,{htmlFor:"bulk-date",className:"text-sm font-medium",children:"Apply Same Date to All"}),e.jsx(pe,{id:"bulk-date",type:"date",value:m,onChange:g=>o(g.target.value),className:"mt-1"})]}),e.jsxs(R,{variant:"outline",onClick:y,disabled:!m,children:[e.jsx(xt,{className:"h-4 w-4 mr-2"}),"Apply to All"]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:u,children:"Clear All"})]}),e.jsx("div",{className:"border rounded-lg max-h-96 overflow-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-12",children:"#"}),e.jsx(U,{children:"Player"}),e.jsx(U,{children:"Team"}),e.jsx(U,{children:"Opponent"}),e.jsx(U,{children:"Market"}),e.jsx(U,{children:"Line"}),e.jsx(U,{className:"w-44",children:"Game Date"})]})}),e.jsx($e,{children:s.map(g=>{const f=!!i[g.rowIndex];return e.jsxs(he,{className:Le(f?"bg-green-500/5":"bg-yellow-500/5"),children:[e.jsx(M,{className:"font-mono text-xs text-muted-foreground",children:g.rowIndex+1}),e.jsx(M,{className:"font-medium",children:g.playerName}),e.jsx(M,{children:g.team}),e.jsx(M,{children:g.opponent}),e.jsx(M,{children:g.market}),e.jsx(M,{className:"font-mono",children:g.line}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"date",value:i[g.rowIndex]||"",onChange:_=>d(g.rowIndex,_.target.value),className:Le("h-8 text-sm",f?"border-green-500/50":"border-yellow-500/50")}),f&&e.jsx(rs,{className:"h-4 w-4 text-green-500 shrink-0"})]})})]},g.rowIndex)})})]})}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:N?e.jsxs("span",{className:"text-green-500 flex items-center gap-1",children:[e.jsx(rs,{className:"h-4 w-4"}),"All dates assigned"]}):e.jsxs("span",{className:"text-yellow-500",children:[s.length-h," rows still need dates"]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(R,{onClick:x,disabled:!N,children:"Continue with Import"})]})]})]})]})}function Uf(s){const a=[];return s.forEach((t,n)=>{const r=t.GameDate||t.game_date||t.Date||t.DATE||t.date||t["Game Date"]||t.Date_1||t.Date_2||t.date_1||t.date_2,i=r&&String(r).trim()!=="";n===0&&(console.log("[detectMissingDates] First row keys:",Object.keys(t)),console.log("[detectMissingDates] First row date values:",{GameDate:t.GameDate,Date:t.Date,DATE:t.DATE,Date_1:t.Date_1,game_date:t.game_date}),console.log("[detectMissingDates] Resolved gameDate:",r,"hasValidDate:",i)),i||a.push({rowIndex:n,playerName:t.Player||t.player_name||t.Name||t.PLAYER||t.name||"Unknown",team:t.Team||t.team||t.TEAM||"",opponent:t.Opponent||t.Opp||t.opponent||t.OPPONENT||"",market:t.MarketName||t.market_name||t.Market||t["Market Name"]||"",line:t.ConsensusLine||t.Line||t.line||t.LINE||0})}),a}function Bf(s,a){return s.map((t,n)=>a[n]?{...t,GameDate:a[n],game_date:a[n]}:t)}function zf(s){const a=new Map;
294return s.forEach((t,n)=>{const r=t.Name||t.player_name||t.Player||"";if(!r)return;const i={rowIndex:n,playerName:r,team:t.Team||t.team||t.TeamAbbrev||"",position:t.Position||t.position||t.Pos||"",scored:parseFloat(t.Scored||t.actual_points||t.FPTS||t.Points||0)||0,salary:parseFloat(t.Salary||t.salary||0)||0,projected:parseFloat(t.projected_points||t.Proj||0)||0};a.has(r)||a.set(r,[]),a.get(r).push(i)}),Array.from(a.entries()).filter(([t,n])=>n.length>1).map(([t,n])=>({playerName:t,entries:n}))}function fi({parsedData:s,file:a,sport:t,league:n,dataType:r,platform:i,source:l,slateDate:m,contestType:o,contestId:h,contestSubtype:N,strategy:d,onImportComplete:y}){const[u,x]=v.useState(null),[g,f]=v.useState(!1),[_,k]=v.useState(0),[b,j]=v.useState(null),[c,p]=v.useState(null),[w,S]=v.useState(0),[P,C]=v.useState(""),[O,$]=v.useState(!1),{toast:z}=Ws();v.useEffect(()=>{(async()=>{if(r!=="projections"||!h||!l){S(0);return}const{count:le,error:ve}=await T.from("dfs_projections").select("*",{count:"exact",head:!0}).eq("contest_id",h).eq("source",l);!ve&&le!==null&&S(le)})()},[r,h,l]),v.useEffect(()=>{(async()=>{if(!h){C("");return}const{data:le,error:ve}=await T.from("dfs_contests").select("contest_name, slate_date").eq("id",h).single();!ve&&le&&C(`${le.contest_name} (${le.slate_date})`)})()},[h]);const D=v.useMemo(()=>r!=="dfs_results"?[]:zf(s.rows),[s.rows,r]),A=v.useMemo(()=>{if(r!=="player_props")return s.rows;s.rows.length>0&&(console.log("[Props Import] Raw CSV columns:",Object.keys(s.rows[0])),console.log("[Props Import] Raw first row Date values:",{Date:s.rows[0].Date,Date_1:s.rows[0].Date_1,DATE:s.rows[0].DATE,date:s.rows[0].date}));const ee=s.rows.map(le=>Xc(le));return ee.length>0&&(console.log("[Props Import] Normalized columns:",Object.keys(ee[0])),console.log("[Props Import] Normalized first row GameDate:",ee[0].GameDate)),ee},[s.rows,r]),F=v.useMemo(()=>{if(r!=="player_props")return[];const ee=Uf(A);return console.log("[Props Import] Missing dates detected:",ee.length,"out of",A.length,"rows"),ee},[A,r]),q=r==="dfs_results"&&D.length>0&&b===null,E=r==="player_props"&&F.length>0&&c===null,L=ee=>{const le=ee.toLowerCase(),ve=["nba","nfl","mlb","nhl","soccer","mma","tennis","golf"];for(const te of ve)if(le.includes(te)&&le.includes("injur"))return te;return null},H=()=>{let ee=r==="player_props"?A:s.rows;if(b!==null){const le=r==="player_props"?A:s.rows;ee=b.map(ve=>le[ve])}return c!==null&&Object.keys(c).length>0&&(ee=Bf(ee,c)),ee};v.useEffect(()=>{if(q||E){x(null);return}const ee=H();if(r==="injuries"){const te=L(a.name),X=t.toLowerCase();if(te&&te!==X){x({valid:!1,totalRows:ee.length,errors:[{row:0,column:"filename",value:a.name,message:`Filename contains "${te.toUpperCase()}" but you selected "${t.toUpperCase()}". Please verify you're uploading the correct file for the selected sport.`}],warnings:[],duplicates:0});return}}let le=$l(ee);le=Ol(le);const ve=qf(r,le,t,o);x(ve)},[s,r,t,o,a.name,q,E,b,c]);const Z=ee=>{j(ee)},se=()=>{y()},ie=ee=>{p(ee)},Y=()=>{y()},I=async()=>{if(!(u!=null&&u.valid)){z({title:"Validation Failed",description:"Please fix all errors before importing",variant:"destructive"});return}f(!0),k(0);try{const{data:{user:ee}}=await T.auth.getUser(),le=crypto.randomUUID(),ve=setInterval(()=>{k(Pe=>Math.min(Pe+10,90))},200);let X=H();(r==="projections"||r==="salaries")&&(X=$l(X,t),X=Ol(X));const ae=3e3,W=[];for(let Pe=0;Pe<X.length;Pe+=ae)W.push(X.slice(Pe,Pe+ae));const re={recordsProcessed:0,recordsSucceeded:0,recordsFailed:0,errors:[],gameMatchStats:{matched:0,unmatched:0}};for(let Pe=0;Pe<W.length;Pe++){k(Math.round(Pe/W.length*80)+10),W.length>1&&z({title:`Importing chunk ${Pe+1} of ${W.length}...`});const{data:Fe,error:Ae}=await T.functions.invoke("import-sport-data",{body:{sport:t,league:n,dataType:r,platform:i,source:l,slateDate:m,contestType:o,contestId:h,contestSubtype:N,strategy:d,records:W[Pe],importBatchId:le,userId:ee==null?void 0:ee.id,fileName:a.name}});if(Ae)throw Ae;re.recordsProcessed+=Fe.recordsProcessed||0,re.recordsSucceeded+=Fe.recordsSucceeded||0,re.recordsFailed+=Fe.recordsFailed||0,Fe.errors&&re.errors.push(...Fe.errors),Fe.gameMatchStats&&(re.gameMatchStats.matched+=Fe.gameMatchStats.matched||0,re.gameMatchStats.unmatched+=Fe.gameMatchStats.unmatched||0)}const ce=re;if(clearInterval(ve),k(100),ce.recordsFailed>0&&ce.errors.length>0)z({title:"Partial Import",description:`${ce.recordsSucceeded} succeeded, ${ce.recordsFailed} failed. Check console for details.`,variant:"destructive"}),console.error("Import errors:",ce.errors);else{let Pe=`${ce.recordsSucceeded||0} records imported successfully`;if(r==="player_props"&&(ce.gameMatchStats.matched>0||ce.gameMatchStats.unmatched>0)){const{matched:Fe,unmatched:Ae}=ce.gameMatchStats;Ae>0?Pe+=`. ${Fe} game IDs matched, ${Ae} not found (will use date-only matching for settlement).`:Fe>0&&(Pe+=`. All ${Fe} props matched to game IDs.`)}z({title:"Import Successful",description:Pe}),r==="dfs_results"&&h&&(console.log(`Triggering background perfect lineup calculation for contest: ${h}`),T.functions.invoke("calculate-perfect-lineup",{body:{contestId:h,triggerSource:"results_import"}}).then(({data:Fe,error:Ae})=>{Ae?console.error("Perfect lineup calculation trigger failed:",Ae):console.log("Perfect lineup calculation triggered successfully")}))}y()}catch(ee){console.error("Import error:",ee),z({title:"Import Failed",description:ee.message||"An error occurred during import",variant:"destructive"})}finally{f(!1),k(0)}};
294return E?e.jsx(Of,{entries:F,onResolved:ie,onCancel:Y,totalRows:s.rows.length,sport:t}):q?e.jsx($f,{duplicates:D,onResolved:Z,onCancel:se,totalRows:s.rows.length}):u?e.jsxs("div",{className:"space-y-4",children:[h&&P&&e.jsxs(ss,{className:"bg-blue-500/10 border-blue-500/30",children:[e.jsx(Ys,{className:"h-4 w-4 text-blue-500"}),e.jsxs(ts,{children:["Importing to: ",e.jsx("strong",{children:P})]})]}),r==="player_props"&&e.jsxs(ss,{className:"bg-blue-500/10 border-blue-500/30",children:[e.jsx(Ys,{className:"h-4 w-4 text-blue-500"}),e.jsxs(ts,{children:[e.jsx("strong",{children:"Game Matching:"})," Props will be matched to games using team names and dates. CST dates from your CSV will be converted to UTC for matching. Game IDs will be stored for accurate auto-settlement."]})]}),w>0&&r==="projections"&&e.jsxs(ss,{className:"bg-yellow-500/10 border-yellow-500/30",children:[e.jsx(ls,{className:"h-4 w-4 text-yellow-500"}),e.jsxs(ts,{children:[e.jsxs("strong",{children:[w," ",l]})," projections already exist for this contest.",d==="add_source"&&' With "Add Source" strategy, existing records will be skipped.',d==="upsert"&&' With "Upsert" strategy, existing records will be updated.',d==="replace"&&' With "Replace" strategy, existing records for this source will be deleted first.']})]}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Validation Results"})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Rows"}),e.jsx("p",{className:"text-2xl font-bold",children:u.totalRows})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Errors"}),e.jsx("p",{className:"text-2xl font-bold text-destructive",children:u.errors.length})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Warnings"}),e.jsx("p",{className:"text-2xl font-bold text-yellow-500",children:u.warnings.length})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:u.valid?"default":"destructive",children:u.valid?"Valid":"Invalid"}),e.jsxs(R,{variant:"ghost",size:"sm",onClick:()=>$(!0),className:"h-6 px-2",children:[e.jsx(us,{className:"h-4 w-4 mr-1"}),"Preview"]})]})]})]}),u.errors.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(xs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Errors Found"})]}),e.jsx("div",{className:"max-h-48 overflow-auto border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Row"}),e.jsx(U,{children:"Column"}),e.jsx(U,{children:"Value"}),e.jsx(U,{children:"Message"})]})}),e.jsx($e,{children:u.errors.slice(0,10).map((ee,le)=>e.jsxs(he,{children:[e.jsx(M,{children:ee.row}),e.jsx(M,{children:ee.column}),e.jsx(M,{className:"font-mono text-xs",children:String(ee.value)}),e.jsx(M,{children:ee.message})]},le))})]})})]}),u.warnings.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-yellow-600",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Warnings"})]}),e.jsx("div",{className:"max-h-48 overflow-auto border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Row"}),e.jsx(U,{children:"Column"}),e.jsx(U,{children:"Value"}),e.jsx(U,{children:"Message"})]})}),e.jsx($e,{children:u.warnings.slice(0,10).map((ee,le)=>e.jsxs(he,{children:[e.jsx(M,{children:ee.row}),e.jsx(M,{children:ee.column}),e.jsx(M,{className:"font-mono text-xs",children:String(ee.value)}),e.jsx(M,{children:ee.message})]},le))})]})})]}),g&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Importing data..."}),e.jsxs("span",{children:[_,"%"]})]}),e.jsx(Ct,{value:_})]}),r==="projections"&&(!h||!l)&&e.jsxs(ss,{variant:"destructive",children:[e.jsx(xs,{className:"h-4 w-4"}),e.jsxs(ts,{children:[!h&&"Contest selection is required for projection imports. ",!l&&"Projection source selection is required. ","Please complete the required fields to enable import."]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(R,{onClick:I,disabled:!u.valid||g||r==="projections"&&(!h||!l),className:"flex-1",children:g?"Importing...":`Import ${u.totalRows} Records`})})]})]}),e.jsx(Ue,{open:O,onOpenChange:$,children:e.jsxs(Be,{className:"max-w-4xl max-h-[80vh]",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Data Preview"})}),e.jsx("div",{className:"max-h-[60vh] overflow-auto border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsx(he,{children:s.headers.map(ee=>e.jsx(U,{children:ee},ee))})}),e.jsx($e,{children:s.preview.map((ee,le)=>e.jsx(he,{children:s.headers.map(ve=>e.jsx(M,{className:"font-mono text-xs",children:String(ee[ve])},ve))},le))})]})})]})})]}):null}function on({initialSport:s,initialLeague:a,initialDataType:t,initialPlatform:n,initialSource:r,initialSlateDate:i,initialContestType:l,initialContestId:m,initialContestSubtype:o,initialStrategy:h,onImportComplete:N,hideSelectors:d=!1}={}){const[y,u]=v.useState(s||"mlb"),[x,g]=v.useState(a||""),[f,_]=v.useState(t||""),[k,b]=v.useState(n||"DraftKings"),[j,c]=v.useState(r||""),[p,w]=v.useState(i||""),[S,P]=v.useState(l||"Classic"),[C,O]=v.useState(m||""),[$,z]=v.useState(h||"upsert"),[D,A]=v.useState(null),[F,q]=v.useState(null),[E,L]=v.useState(!1),[H,Z]=v.useState([]),[se,ie]=v.useState(o||""),{getRootProps:Y,getInputProps:I,isDragActive:ee}=sl({accept:{"text/csv":[".csv"],"application/json":[".json"]},maxSize:10*1024*1024,multiple:!1,onDrop:async X=>{const ae=X[0];
294if(ae){A(ae),L(!0);try{let W;ae.name.endsWith(".csv")?W=await xh(ae):ae.name.endsWith(".json")&&(W=await hh(ae)),q(W)}catch(W){console.error("Error parsing file:",W)}finally{L(!1)}}}}),le=()=>{A(null),q(null),N==null||N()};v.useEffect(()=>{(f==="projections"||f==="salaries"||f==="dfs_results")&&y&&k&&p&&ve()},[y,k,p,f]),v.useEffect(()=>{if(C&&H.length>0){const X=H.find(ae=>ae.id===C);X&&(P(X.contest_type||"Classic"),ie(X.contest_subtype||""))}},[C,H]),v.useEffect(()=>{h||(f==="salaries"?z("merge_salaries"):f==="projections"?z("add_source"):(f==="dfs_results"||f==="player_props")&&z("upsert"))},[f,h]);const ve=async()=>{const{data:X,error:ae}=await T.from("dfs_contests").select("*").eq("sport",y).eq("platform",k).eq("slate_date",p).order("created_at",{ascending:!1});!ae&&X&&Z(X)},te=X=>{const ae=`${X.contest_name} (${X.contest_type}`;if(X.contest_type==="Showdown"&&X.home_team&&X.away_team)return`${ae} - ${X.away_team} @ ${X.home_team})`;if(X.contest_subtype){const W=X.contest_subtype.charAt(0).toUpperCase()+X.contest_subtype.slice(1);return`${ae} - ${W})`}return`${ae})`};return d?e.jsxs("div",{className:"space-y-4",children:[f==="projections"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{children:["Projection Source ",e.jsx("span",{className:"text-destructive",children:"* Required"})]}),e.jsxs(oe,{value:j,onValueChange:c,children:[e.jsx(de,{className:j?"":"border-destructive",children:e.jsx(ue,{placeholder:"Select source"})}),e.jsx(me,{children:mi.map(X=>e.jsx(V,{value:X.value,children:X.label},X.value))})]}),!j&&e.jsx("p",{className:"text-xs text-destructive",children:"Source selection is required for projection imports"})]}),D?e.jsxs("div",{className:"border rounded-lg p-4 flex items-center justify-between bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fl,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(D.size/1024).toFixed(2)," KB"]})]})]}),e.jsx(R,{variant:"ghost",size:"icon",onClick:le,children:e.jsx(rt,{className:"h-4 w-4"})})]}):e.jsxs("div",{...Y(),className:`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors ${ee?"border-primary bg-primary/5":"border-border hover:border-primary/50"}`,children:[e.jsx("input",{...I()}),e.jsx(fa,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm mb-1",children:ee?"Drop file here":"Drag & drop or click to browse"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"CSV or JSON (max 10MB)"})]}),F&&D&&e.jsx(fi,{parsedData:F,file:D,sport:y,dataType:f,platform:k,source:j,slateDate:p,contestType:S,contestId:C,contestSubtype:se,strategy:$,onImportComplete:le})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Upload Sport Data"})}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Sport"}),e.jsxs(oe,{value:y,onValueChange:u,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:cn.map(X=>e.jsx(V,{value:X.value,children:X.label},X.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Data Type"}),e.jsxs(oe,{value:f,onValueChange:_,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select data type"})}),e.jsx(me,{children:Aa.map(X=>e.jsx(V,{value:X.value,children:X.label},X.value))})]})]}),f==="injuries"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Report Date"}),e.jsx("input",{type:"date",value:p,onChange:X=>w(X.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"})]}),e.jsx("div",{className:"col-span-2",children:e.jsxs(ss,{children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsxs(ts,{children:[e.jsx("strong",{children:"Injury Report CSV Format:"})," Player, Team, Pos, Injury, Status, Est. Return. Importing will replace all existing injuries for the selected sport."]})]})})]}),f==="player_props"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Game Date"}),e.jsx("input",{type:"date",value:p,onChange:X=>w(X.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"})]}),e.jsx("div",{className:"col-span-2",children:e.jsxs(ss,{children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsxs(ts,{children:[e.jsx("strong",{children:"Player Props CSV Format:"})," Player, Team, Opponent, MarketName, ConsensusLine, Sportsbook lines (PrizePicks, FanDuel, DraftKings, etc.), Hit Rates (Last5/10/20/30, Season, VsOpponent), Prediction (Lean, Projection), Line Movement. Upsert will update existing props for same player/date/market."]})]})})]}),(f==="projections"||f==="salaries"||f==="dfs_results")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Platform"}),e.jsxs(oe,{value:k,onValueChange:b,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:Yc.map(X=>e.jsx(V,{value:X.value,children:X.label},X.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Slate Date"}),e.jsx("input",{type:"date",value:p,onChange:X=>w(X.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{children:["Select Contest ",f==="projections"&&e.jsx("span",{className:"text-destructive",children:"* Required"})]}),e.jsxs(oe,{value:C,onValueChange:O,children:[e.jsx(de,{className:f==="projections"&&!C?"border-destructive":"",children:e.jsx(ue,{placeholder:"Select a contest"})}),e.jsx(me,{children:H.length===0?e.jsx("div",{className:"p-2 text-sm text-muted-foreground",children:"No contests found. Create one in DFS Contests tab first."}):H.map(X=>e.jsx(V,{value:X.id,children:te(X)},X.id))})]}),f==="projections"&&!C&&e.jsx("p",{className:"text-xs text-destructive",children:"Contest selection is required for projection imports to generate player pools"})]}),f==="projections"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{children:["Projection Source ",e.jsx("span",{className:"text-destructive",children:"* Required"})]}),e.jsxs(oe,{value:j,onValueChange:c,children:[e.jsx(de,{className:j?"":"border-destructive",children:e.jsx(ue,{placeholder:"Select source"})}),e.jsx(me,{children:mi.map(X=>e.jsx(V,{value:X.value,children:X.label},X.value))})]})]})]}),f==="projections"&&e.jsx("div",{className:"col-span-2",children:e.jsxs(ss,{children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsxs(ts,{children:[e.jsx("strong",{children:"Tip:"}),' If your projection file includes a "Salary" column (like Stokastic format), salaries will be imported automatically. No need for a separate salary import!']})]})}),f==="dfs_results"&&e.jsx("div",{className:"col-span-2",children:e.jsxs(ss,{children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsxs(ts,{children:[e.jsx("strong",{children:"Column Mapping:"}),' "Scored" → actual points, "Projected" → projected points, "ProjOwn" or "ActualOwn" → ownership %. Select the contest these results are for (important for Captain/Showdown vs Classic).']})]})}),f!=="injuries"&&f!=="player_props"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Import Strategy"}),e.jsxs(oe,{value:$,onValueChange:z,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:wf.filter(X=>f==="salaries"?X.value==="merge_salaries":f==="projections"?X.value!=="merge_salaries":f==="dfs_results"?X.value==="insert"||X.value==="upsert":!0).map(X=>e.jsx(V,{value:X.value,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:X.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:X.description})]})},X.value))})]})]})]}),D?e.jsxs("div",{className:"border rounded-lg p-4 flex items-center justify-between bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fl,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(D.size/1024).toFixed(2)," KB"]}
294)]})]}),e.jsx(R,{variant:"ghost",size:"icon",onClick:le,children:e.jsx(rt,{className:"h-4 w-4"})})]}):e.jsxs("div",{...Y(),className:`border-2 border-dashed rounded-lg p-12 text-center cursor-pointer transition-colors ${ee?"border-primary bg-primary/5":"border-border hover:border-primary/50"}`,children:[e.jsx("input",{...I()}),e.jsx(fa,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"text-lg mb-2",children:ee?"Drop file here":"Drag & drop file here"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"or click to browse"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supports CSV and JSON files (max 10MB)"})]})]})]}),F&&D&&e.jsx(fi,{parsedData:F,file:D,sport:y,league:x,dataType:f,platform:k,source:j,slateDate:p,contestType:S,contestId:C,contestSubtype:se,strategy:$,onImportComplete:le})]})}const Kf=[{label:"Mode"},{label:"Sport"},{label:"League"},{label:"Platform"},{label:"Contest"},{label:"Import"}],Vf=[{label:"Mode"},{label:"Date"},{label:"Sport"},{label:"League"},{label:"Platform"},{label:"Contest"},{label:"Import"}];function Hf({open:s,onClose:a}){var X;const[t,n]=v.useState(0),[r,i]=v.useState(null),[l,m]=v.useState(void 0),[o,h]=v.useState(null),[N,d]=v.useState(null),[y,u]=v.useState(null),[x,g]=v.useState(null),[f,_]=v.useState(!1),[k,b]=v.useState(!1),j=Me(),c=an(new Date,"America/Chicago"),p=ke(c,"yyyy-MM-dd"),w=r==="by-date"?Vf:Kf,{data:S=[],isLoading:P}=ge({queryKey:["contests-needing-results",p],queryFn:async()=>{const{data:ae,error:W}=await T.rpc("get_contests_needing_results",{p_before_date:p});if(W)throw W;return(ae||[]).map(re=>{var ce,Pe;return{...re,league:(ce=re.contest_subtype)!=null&&ce.includes("NCAA")?"NCAA":(Pe=re.sport)==null?void 0:Pe.toUpperCase(),hasResults:!1}})},enabled:s}),C=l?ke(l,"yyyy-MM-dd"):null,{data:O=[],isLoading:$}=ge({queryKey:["contests-by-date",C,k],queryFn:async()=>{const{data:ae,error:W}=await T.from("dfs_contests").select("*").eq("slate_date",C);if(W)throw W;const re=(ae==null?void 0:ae.map(Fe=>Fe.id))||[];if(re.length===0)return[];const{data:ce}=await T.rpc("get_distinct_contest_ids_with_results",{contest_ids:re}),Pe=new Set((ce==null?void 0:ce.map(Fe=>Fe.contest_id).filter(Boolean))||[]);return(ae||[]).filter(Fe=>k||!Pe.has(Fe.id)).map(Fe=>{var Ae,Ve;return{...Fe,league:(Ae=Fe.contest_subtype)!=null&&Ae.includes("NCAA")?"NCAA":(Ve=Fe.sport)==null?void 0:Ve.toUpperCase(),hasResults:Pe.has(Fe.id)}})},enabled:s&&r==="by-date"&&!!C}),z=r==="by-date"?O:S,D=r==="by-date"?$:P,A=z.reduce((ae,W)=>{var ce;const re=((ce=W.sport)==null?void 0:ce.toUpperCase())||"UNKNOWN";return ae[re]=(ae[re]||0)+1,ae},{}),F=z.filter(ae=>{var W;return((W=ae.sport)==null?void 0:W.toUpperCase())===o}).reduce((ae,W)=>{var ce;const re=W.league||((ce=W.sport)==null?void 0:ce.toUpperCase())||"UNKNOWN";return ae[re]=(ae[re]||0)+1,ae},{}),q=z.filter(ae=>{var W,re;return((W=ae.sport)==null?void 0:W.toUpperCase())===o&&(ae.league===N||((re=ae.sport)==null?void 0:re.toUpperCase())===N)}).reduce((ae,W)=>{const re=W.platform||"UNKNOWN";return ae[re]=(ae[re]||0)+1,ae},{}),E=z.filter(ae=>{var W,re;return((W=ae.sport)==null?void 0:W.toUpperCase())===o&&(ae.league===N||((re=ae.sport)==null?void 0:re.toUpperCase())===N)&&ae.platform===y}),L=ae=>w.findIndex(W=>W.label===ae),H=()=>{var ae;if(t===0)a();else if(t===1&&r!==null)i(null),m(void 0),n(0);else{n(t-1);const W=(ae=w[t])==null?void 0:ae.label;W==="Sport"&&(h(null),r==="by-date"&&m(void 0)),W==="League"&&d(null),W==="Platform"&&u(null),W==="Contest"&&g(null)}},Z=ae=>{i(ae),n(1)},se=ae=>{ae&&(m(ae),_(!1),n(L("Sport")))},ie=ae=>{h(ae),n(L("League"))},Y=ae=>{d(ae),n(L("Platform"))},I=ae=>{u(ae),n(L("Contest"))},ee=ae=>{g(ae),n(L("Import"))},le=()=>{j.invalidateQueries({queryKey:["contests-needing-results"]}),j.invalidateQueries({queryKey:["contests-by-date",C]}),j.invalidateQueries({queryKey:["import-dashboard-stats"]}),j.invalidateQueries({queryKey:["dfs-contests"]}),j.invalidateQueries({queryKey:["contest-data-stats"]}),K.success("Results imported successfully"),E.filter(W=>W.id!==(x==null?void 0:x.id)).length>0?(g(null),n(L("Contest"))):ve()},ve=()=>{n(0),i(null),m(void 0),h(null),d(null),u(null),g(null),b(!1),a()};v.useEffect(()=>{s||(n(0),i(null),m(void 0),h(null),d(null),u(null),g(null),b(!1))},[s]);const te=(X=w[t])==null?void 0:X.label;return e.jsx(Ue,{open:s,onOpenChange:ae=>!ae&&ve(),children:e.jsxs(Be,{className:"max-w-3xl h-[90vh] flex flex-col overflow-hidden",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Import Results"})}),e.jsx(ln,{steps:w,currentStep:t,className:"mb-6"}),e.jsxs(cs,{className:"flex-1 min-h-0 h-0 pr-4",children:[te==="Mode"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to import results?"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>Z("needs-results"),children:e.jsxs(J,{className:"p-6 flex flex-col items-center text-center space-y-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Vi,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Contests Needing Results"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Past contests that don't have results yet"})]}),e.jsxs(B,{variant:"secondary",className:"mt-2",children:[S.length," contest",S.length!==1?"s":""]})]})}),e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>Z("by-date"),children:e.jsxs(J,{className:"p-6 flex flex-col items-center text-center space-y-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-accent/50 flex items-center justify-center",children:e.jsx(xt,{className:"h-6 w-6 text-accent-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Import by Date"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Select a date to find contests (including today)"})]}),e.jsx(B,{variant:"outline",className:"mt-2",children:"Early Import"})]})})]})]}),te==="Date"&&r==="by-date"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a date to find contests"}),e.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[e.jsxs(Ba,{open:f,onOpenChange:_,children:[e.jsx(za,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:Le("w-[280px] justify-start text-left font-normal",!l&&"text-muted-foreground"),children:[e.jsx(xt,{className:"mr-2 h-4 w-4"}),l?ke(l,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Ka,{className:"w-auto p-0",align:"center",children:e.jsx(Va,{mode:"single",selected:l,onSelect:se,initialFocus:!0,className:Le("p-3 pointer-events-auto")})})]}),e.jsxs("div",{className:"flex items-center space-x-2 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Ge,{id:"show-all-contests",checked:k,onCheckedChange:b}),e.jsx(Q,{htmlFor:"show-all-contests",className:"text-sm cursor-pointer",children:"Show contests with existing results"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use this for same-day or early results import"})]})]}),D&&te!=="Mode"&&te!=="Date"&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!D&&te==="Sport"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:r==="by-date"?`Select a sport for ${l?ke(l,"PPP"):"selected date"}`:"Select a sport to view contests needing results"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(A).map(([ae,W])=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>ie(ae),children:e.jsxs(J,{className:"p-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:ae}),e.jsx(B,{variant:"secondary",children:W})]})},ae))}),Object.keys(A).length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8",children:r==="by-date"?"No contests found for this date":"No contests need results"})]}),!D&&te==="League"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a league for ",o]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(F).map(([ae,W])=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>Y(ae),children:e.jsxs(J,{className:"p-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:ae}),e.jsx(B,{variant:"secondary",children:W})]})},ae))})]}),!D&&te==="Platform"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a platform for ",o," - ",N]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(q).map(([ae,W])=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>I(ae),children:e.jsxs(J,{className:"p-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:ae}),e.jsx(B,{variant:"secondary",children:W})]})},ae))})]}),!D&&te==="Contest"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a contest to import results (",
294E.length," available)"]}),e.jsx("div",{className:"space-y-2",children:E.map(ae=>e.jsx(G,{className:Le("cursor-pointer hover:border-primary transition-colors",ae.hasResults&&"border-amber-500/50"),onClick:()=>ee(ae),children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:ae.contest_name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:ae.slate_date}),ae.contest_type&&e.jsx(B,{variant:"secondary",className:"text-xs",children:ae.contest_type}),ae.hasResults&&e.jsx(B,{className:"text-xs bg-amber-500 hover:bg-amber-600 text-white",children:"Has Results"})]})]}),e.jsx(st,{className:"h-5 w-5 text-muted-foreground flex-shrink-0 ml-2"})]})})},ae.id))})]}),te==="Import"&&x&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(G,{className:"bg-muted/50",children:e.jsxs(J,{className:"p-4",children:[e.jsx("p",{className:"font-medium",children:x.contest_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x.platform," • ",x.slate_date," • ",x.contest_type]})]})}),e.jsx(on,{initialSport:x.sport,initialDataType:"dfs_results",initialPlatform:x.platform,initialSlateDate:x.slate_date,initialContestId:x.id,initialContestType:x.contest_type||void 0,initialContestSubtype:x.contest_subtype||void 0,onImportComplete:le,hideSelectors:!0})]})]}),e.jsx("div",{className:"flex justify-between mt-6 pt-4 border-t",children:e.jsxs(R,{variant:"outline",onClick:H,children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),t===0?"Cancel":"Back"]})})]})})}const Wf=[{label:"Date"},{label:"Sport"},{label:"League"},{label:"Platform"},{label:"Type"},{label:"Details"},{label:"Import"}];function Gf({open:s,onClose:a}){const[t,n]=v.useState(0),[r,i]=v.useState(new Date),[l,m]=v.useState(null),[o,h]=v.useState(null),[N,d]=v.useState(null),[y,u]=v.useState(null),[x,g]=v.useState(null),[f,_]=v.useState(""),[k,b]=v.useState(null),[j,c]=v.useState(null),[p,w]=v.useState(null),[S,P]=v.useState("draft"),[C,O]=v.useState(!1),$=Me(),{data:z=[]}=ge({queryKey:["active-sports-for-create"],queryFn:async()=>{const{data:le,error:ve}=await T.from("sport_statuses").select("sport_name, leagues_config").eq("is_active",!0);if(ve)throw ve;return(le||[]).map(te=>({sport:te.sport_name,leagues_config:te.leagues_config}))},enabled:s}),D=z.find(le=>{var ve;return((ve=le.sport)==null?void 0:ve.toLowerCase())===(l==null?void 0:l.toLowerCase())}),A=(()=>{const le=D==null?void 0:D.leagues_config;return Array.isArray(le)?le.filter(ve=>!(!ve.is_enabled||ve.is_grouped)).map(ve=>({key:ve.league_id,label:ve.league_name||ve.league_id})):l?[{key:l,label:l}]:[]})(),F=(le,ve)=>{var W;const te=le.toLowerCase(),X=ve.toLowerCase(),ae={football:{nfl:"americanfootball_nfl","ncaa-regular-season":"americanfootball_ncaaf","ncaa-division-i-fbs-post-season":"americanfootball_ncaaf","ncaa-division-i-fcs-national-championship":"americanfootball_ncaaf"},basketball:{nba:"basketball_nba",ncaa:"basketball_ncaab",wnba:"basketball_wnba"},hockey:{nhl:"icehockey_nhl",ncaa:"icehockey_ncaa"},baseball:{mlb:"baseball_mlb"},soccer:{epl:"soccer_epl","la-liga":"soccer_spain_la_liga",bundesliga:"soccer_germany_bundesliga","serie-a":"soccer_italy_serie_a","ligue-one":"soccer_france_ligue_one"}};return(W=ae[te])!=null&&W[X]?ae[te][X]:`${te}_${X}`},{data:q=[]}=ge({queryKey:["games-for-date",r,l,o],queryFn:async()=>{if(!r||!l||!o)return[];const le=F(l,o);console.log(`[Showdown] Looking for games with sport key: ${le}`);const ve=ke(r,"yyyy-MM-dd"),te=`${ve}T06:00:00Z`,X=new Date(new Date(`${ve}T06:00:00Z`).getTime()+24*60*60*1e3).toISOString(),{data:ae,error:W}=await T.from("master_games").select("id, home_team, away_team, commence_time").eq("odds_api_sport_key",le).gte("commence_time",te).lt("commence_time",X).order("commence_time");if(W)throw W;return(ae||[]).map(re=>({id:re.id,home_team:re.home_team,away_team:re.away_team,game_time:re.commence_time}))},enabled:s&&t===5&&y==="Showdown"&&!!r&&!!l&&!!o}),E=()=>
294{if(!N||!l||!o||!y||!r)return"";const le=ke(r,"yyyy-MM-dd");let ve=`${N}-${l}-${o}-${y}`;return y==="Classic"&&x?x==="multi-day"&&f?ve+=`-${f}`:ve+=`-${x}`:y==="Showdown"&&k&&(ve+=`-${k.away_team}@${k.home_team}`),ve+=`-${le}`,ve},L=async()=>{if(!r||!l||!o||!N||!y||y==="Classic"&&!x||y==="Showdown"&&!k)return null;const le=ke(r,"yyyy-MM-dd");let ve=T.from("dfs_contests").select("id, contest_name, status").eq("slate_date",le).eq("sport",l.toLowerCase()).ilike("league",o).eq("platform",N).eq("contest_type",y);y==="Classic"?ve=ve.eq("contest_subtype",x):ve=ve.eq("game_id",k.id);const{data:te}=await ve.maybeSingle();if(te){const{count:X}=await T.from("dfs_projections").select("*",{count:"exact",head:!0}).eq("contest_id",te.id),{count:ae}=await T.from("dfs_contest_player_pool").select("*",{count:"exact",head:!0}).eq("contest_id",te.id);return{...te,projectionCount:X||0,playerPoolCount:ae||0}}return null},H=_e({mutationFn:async()=>{const{data:{user:le}}=await T.auth.getUser(),ve=ke(r,"yyyy-MM-dd"),te=E(),X={contest_id:`${N==null?void 0:N.toLowerCase()}-${l==null?void 0:l.toLowerCase()}-${o==null?void 0:o.toLowerCase()}-${ve}-${y==null?void 0:y.toLowerCase()}`,contest_name:te,sport:l==null?void 0:l.toLowerCase(),league:o==null?void 0:o.toLowerCase(),platform:N,slate_date:ve,contest_type:y,contest_subtype:x||null,home_team:(k==null?void 0:k.home_team)||null,away_team:(k==null?void 0:k.away_team)||null,game_id:(k==null?void 0:k.id)||null,status:S,created_by:le==null?void 0:le.id},{data:ae,error:W}=await T.from("dfs_contests").insert(X).select("id").single();if(W)throw W;return ae.id},onSuccess:le=>{w(le),$.invalidateQueries({queryKey:["dfs-contests"]}),$.invalidateQueries({queryKey:["import-dashboard-stats"]}),K.success("Contest created successfully"),n(6)},onError:le=>{K.error("Failed to create contest"),console.error(le)}}),Z=async()=>{const le=await L();le?(c(le),w(le.id),P(le.status),n(6)):H.mutate()},se=async()=>{p&&await T.from("dfs_contests").update({status:S,updated_at:new Date().toISOString()}).eq("id",p),$.invalidateQueries({queryKey:["dfs-contests"]}),$.invalidateQueries({queryKey:["import-dashboard-stats"]}),$.invalidateQueries({queryKey:["contest-data-stats"]}),K.success("Projections imported successfully"),O(!0)},ie=()=>{O(!1),d(null),u(null),g(null),b(null),c(null),w(null),P("draft"),n(3)},Y=()=>{O(!1),ee()},I=()=>{t===0?a():(n(t-1),t===1&&i(void 0),t===2&&m(null),t===3&&h(null),t===4&&d(null),t===5&&(u(null),g(null),b(null)),t===6&&c(null))},ee=()=>{n(0),i(new Date),m(null),h(null),d(null),u(null),g(null),_(""),b(null),c(null),w(null),P("draft"),a()};return v.useEffect(()=>{s||(n(0),i(new Date),m(null),h(null),d(null),u(null),g(null),_(""),b(null),c(null),w(null),P("draft"))},[s]),e.jsxs(e.Fragment,{children:[e.jsx(Ue,{open:s,onOpenChange:le=>!le&&ee(),children:e.jsxs(Be,{className:"max-w-3xl h-[90vh] flex flex-col overflow-hidden",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Create Contest"})}),e.jsx(ln,{steps:Wf,currentStep:t,className:"mb-6"}),e.jsxs(cs,{className:"flex-1 min-h-0 h-0 pr-4",children:[t===0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select the contest date"}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Va,{mode:"single",selected:r,onSelect:i,className:Le("rounded-md border pointer-events-auto")})})]}),t===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a sport"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:z.map(le=>{var ve;return e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{var te;m(((te=le.sport)==null?void 0:te.toUpperCase())||""),n(2)},children:e.jsx(J,{className:"p-4 text-center",children:e.jsx("span",{className:"font-medium",children:(ve=le.sport)==null?void 0:ve.toUpperCase()})})},le.sport)})})]}),t===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a league for ",l]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:A.map(le=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{h(le.key),n(3)},children:e.jsx(J,{className:"p-4 text-center",children:e.jsx("span",{className:"font-medium",children:le.label})})},le.key))})]}),t===3&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a platform"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Yc.map(le=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{d(le.value),n(4)},children:e.jsx(J,{className:"p-4 text-center",children:e.jsx("span",{className:"font-medium",children:le.label})})},le.value))})]}),t===4&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select contest type"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{u("Classic"),n(5)},children:e.jsxs(J,{className:"p-6 text-center",children:[e.jsx("span",{className:"font-medium text-lg",children:"Classic"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Full slate contests"})]})}),e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{u("Showdown"),n(5)},children:e.jsxs(J,{className:"p-6 text-center",children:[e.jsx("span",{className:"font-medium text-lg",children:"Showdown"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Single game c
294ontests"})]})})]})]}),t===5&&e.jsx("div",{className:"space-y-4",children:y==="Classic"?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select contest subtype"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Qc.Classic.map(le=>e.jsx(G,{className:Le("cursor-pointer hover:border-primary transition-colors",x===le.value&&"border-primary bg-primary/5"),onClick:()=>g(le.value),children:e.jsx(J,{className:"p-4 text-center",children:e.jsx("span",{className:"font-medium",children:le.label})})},le.value))}),x==="multi-day"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:'Date Range (e.g., "Thur-Mon", "Sat-Sun")'}),e.jsx(pe,{value:f,onChange:le=>_(le.target.value),placeholder:"Enter date range"})]}),x&&(x!=="multi-day"||f)&&e.jsxs(R,{onClick:Z,className:"w-full mt-4",children:["Continue",e.jsx(st,{className:"h-4 w-4 ml-2"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a game for ",ke(r,"MMM d, yyyy")]}),q.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(xs,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"No games found for this date"})]}):e.jsx("div",{className:"space-y-2",children:q.map(le=>e.jsx(G,{className:Le("cursor-pointer hover:border-primary transition-colors",(k==null?void 0:k.id)===le.id&&"border-primary bg-primary/5"),onClick:()=>b(le),children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-medium",children:[le.away_team," @ ",le.home_team]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:le.game_time?ke(new Date(le.game_time),"h:mm a"):""})]})})},le.id))}),k&&e.jsxs(R,{onClick:Z,className:"w-full mt-4",children:["Continue",e.jsx(st,{className:"h-4 w-4 ml-2"})]})]})}),t===6&&e.jsxs("div",{className:"space-y-4",children:[j?e.jsx(G,{className:"bg-yellow-500/10 border-yellow-500/30",children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-1 min-w-0",children:[e.jsx(xs,{className:"h-5 w-5 text-yellow-500 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Contest Already Exists"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:j.contest_name}),e.jsxs("div",{className:"flex gap-4 mt-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Projections: ",j.projectionCount]}),e.jsxs("span",{children:["Pool: ",j.playerPoolCount]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Q,{className:"text-xs",children:"Status:"}),e.jsxs(oe,{value:S,onValueChange:le=>P(le),children:[e.jsx(de,{className:"w-28 h-8",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"draft",children:"Draft"}),e.jsx(V,{value:"active",children:"Active"}),e.jsx(V,{value:"completed",children:"Completed"}),e.jsx(V,{value:"cancelled",children:"Cancelled"})]})]})]})]})})}):e.jsx(G,{className:"bg-[#52b947]/10 border-[#52b947]/30",children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Ks,{className:"h-5 w-5 text-[#52b947] shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:"Contest Created"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:E()})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Q,{className:"text-xs",children:"Status:"}),e.jsxs(oe,{value:S,onValueChange:le=>P(le),children:[e.jsx(de,{className:"w-28 h-8",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"draft",children:"Draft"}),e.jsx(V,{value:"active",children:"Active"}),e.jsx(V,{value:"completed",children:"Completed"}),e.jsx(V,{value:"cancelled",children:"Cancelled"})]})]})]})]})})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Import projections for this contest"}),p&&l&&N&&e.jsx(on,{initialSport:l.toLowerCase(),initialDataType:"projections",initialPlatform:N,initialSlateDate:ke(r,"yyyy-MM-dd"),initialContestId:p,initialContestType:y||void 0,initialContestSubtype:x||void 0,onImportComplete:se,hideSelectors:!0})]})]}),e.jsxs("div",{className:"flex justify-between mt-6 pt-4 border-t",children:[e.jsxs(R,{variant:"outline",onClick:I,children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),t===0?"Cancel":"Back"]}),t===0&&r&&e.jsxs(R,{onClick:()=>n(1),children:["Continue with ",ke(r,"MMM d, yyyy"),e.jsx(st,{className:"h-4 w-4 ml-2"})]})]})]})}),e.jsx(ws,{open:C,onOpenChange:O,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Create Another Contest?"}),e.jsx(Ps,{asChild:!0,children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{children:"Would you like to create another contest with the same settings?"}),e.jsxs("ul",{className:"text-sm space-y-1 mt-3",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"Date:"})," ",r?ke(r,"MMM d, yyyy"):""]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"Sport:"})," ",l==null?void 0:l.toUpperCase()]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"League:"})," ",o==null?void 0:o.toUpperCase()]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"Platform:"})," ",N]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"Type:"})," ",y," - ",y==="Showdown"&&k?`${k.away_team} @ ${k.home_team}`:x||y]})]})]})})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{onClick:Y,children:"No, I'm Done"}),e.jsx(Ls,{onClick:ie,children:"Yes, Create Another"})]})]})})]})}const Qf=[{label:"Sport"},{label:"League"},{label:"Platform"},{label:"Contest"},{label:"Update"}];function Yf({open:s,onClose:a}){const[t,n]=v.useState(0),[r,i]=v.useState(null),[l,m]=v.useState(null),[o,h]=v.useState(null),[N,d]=v.useState(null),y=Me(),u=an(new Date,"America/Chicago"),x=ke(u,"yyyy-MM-dd"),{data:g=[],isLoading:f}=ge({queryKey:["active-contests-upcoming"],queryFn:async()=>{const{data:$,error:z}=await T.from("dfs_contests").select("*").gte("slate_date",x).eq("status","active").order("slate_date",{ascending:!0});if(z)throw z;return($||[]).map(D=>{var A,F;return{...D,league:((A=D.league)==null?void 0:A.toUpperCase())||((F=D.sport)==null?void 0:F.toUpperCase())||"UNKNOWN"}})},enabled:s}),_=g.reduce(($,z)=>{var A;const D=((A=z.sport)==null?void 0:A.toUpperCase())||"UNKNOWN";return $[D]=($[D]||0)+1,$},{}),k=g.filter($=>{var z;return((z=$.sport)==null?void 0:z.toUpperCase())===r}).reduce(($,z)=>{var A;const D=z.league||((A=z.sport)==null?void 0:A.toUpperCase())||"UNKNOWN";return $[D]=($[D]||0)+1,$},{}),b=g.filter($=>{var z,D;return((z=$.sport)==null?void 0:z.toUpperCase())===r&&($.league===l||((D=$.sport)==null?void 0:D.toUpperCase())===l)}).reduce(($,z)=>{const D=z.platform||"UNKNOWN";return $[D]=($[D]||0)+1,$},{}),j=g.filter($=>{var z,D;return((z=$.sport)==null?void 0:z.toUpperCase())===r&&($.league===l||((D=$.sport)==null?void 0:D.toUpperCase())===l)&&$.platform===o}),c=()=>{t===0?a():(n(t-1),t===1&&i(null),t===2&&m(null),t===3&&h(null),t===4&&d(null))},p=$=>{i($),n(1)},w=$=>{m($),n(2)},S=$=>{h($),n(3)},P=$=>{d($),n(4)},C=()=>{y.invalidateQueries({queryKey:["active-contests-upcoming"]}),y.invalidateQueries({queryKey:["import-dashboard-stats"]}),y.invalidateQueries({queryKey:["dfs-contests"]}),y.invalidateQueries({queryKey:["contest-data-stats"]}),K.success("Projections updated successfully"),window.confirm(`Update another contest for ${r} - ${l}?`)?(h(null),d(null),n(2)):O()},O=()=>{n(0),i(null),m(null),h(null),d(null),a()};return v.useEffect(()=>{s||(n(0),i(null),m(null),h(null),d(null))},[s]),e.jsx(Ue,{open:s,onOpenChange:$=>!$&&O(),children:e.jsxs(Be,{className:"max-w-3xl h-[90vh] flex flex-col overflow-hidden",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Update Contest Projections"})}),e.jsx(ln,{steps:Qf,currentStep:t,className:"mb-6"}),e.jsx(cs,{className:"flex-1 min-h-0 h-0 pr-4",children:f?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[t===0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a sport with upcoming active contests"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(_).map(([$,z])=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>p($),children:e.jsxs(J,{className:"p-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:$}),e.jsx(B,{variant:"secondary",children:z})]})},$))}),Object.keys(_).length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No active contests today"})]}),t===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a league for ",r]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(k).map(([$,z])=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>w($),children:e.jsxs(J,{className:"p-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:$}),e.jsx(B,{variant:"secondary",children:z})]})},$))})]}),t===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a platform for ",r," - ",l]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(b).map(([$,z])=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>S($),children:e.jsxs(J,{className:"p-4 flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:$}),e.jsx(B,{variant:"secondary",children:z})]})},$))})]}),t===3&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a contest to update (",j.length," available)"]}),e.jsx("div",{className:"space-y-2",children:j.map($=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>P($),children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:$.contest_name}),e.jsx(B,{variant:"outline",className:"text-xs",children:ke(new Date($.slate_date+"T00:00:00"),"MMM d")})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[$.contest_type,$.contest_subtype&&` • ${$.contest_subtype}`]})]}),e.jsx(st,{className:"h-5 w-5 text-muted-foreground"})]})})},$.id))})]}),t===4&&N&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(G,{className:"bg-muted/50",children:e.jsxs(J,{className:"p-4",children:[e.jsx("p",{className:"font-medium",children:N.contest_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[N.platform," • ",N.slate_date," • ",N.contest_type]})]})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Import projections to update this contest. Use "Upsert" strategy to update existing projections.'}),e.jsx(on,{initialSport:N.sport,initialDataType:"projections",initialPlatform:N.platform,initialSlateDate:N.slate_date,initialContestId:N.id,initialContestType:N.contest_type||void 0,initialContestSubtype:N.contest_subtype||void 0,initialStrategy:"upsert",onImportComplete:C,hideSelectors:!0})]})]})}),e.jsx("div",{className:"flex justify-between mt-6 pt-4 border-t",children:e.jsxs(R,{variant:"outline",onClick:c,children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),t===0?"Cancel":"Back"]})})]})})}const Jf=[{label:"Type"},{label:"Sport"},{label:"League"},{label:"Import"}];function Zf({open:s,onClose:a}){var k,b,j;const[t,n]=v.useState(0),[r,i]=v.useState(null),[l,m]=v.useState(null),[o,h]=v.useState(null),N=Me(),{data:d=[],isLoading:y}=ge({queryKey:["active-sports-for-players"],queryFn:async()=>{const{data:c,error:p}=await T.from("sport_statuses").select("sport_name, sport_code, leagues_config").eq("is_active",!0);if(p)throw p;return(c||[]).map(w=>({sport:w.sport_name,sportCode:w.sport_code,leagues_config:w.leagues_config}))},enabled:s}),u=d.find(c=>{var p;return((p=c.sport)==null?void 0:p.toUpperCase())===l}),x=u!=null&&u.leagues_config&&Array.isArray(u.leagues_config)?u.leagues_config.filter(c=>!(!c.is_enabled||c.is_grouped)).map(c=>{var p;return{key:c.league_id||c.odds_api_key,label:c.league_name,sportCode:((p=u==null?void 0:u.sportCode)==null?void 0:p.toLowerCase())||(l==null?void 0:l.toLowerCase())||""}}):[{key:((k=u==null?void 0:u.sportCode)==null?void 0:k.toLowerCase())||(l==null?void 0:l.toLowerCase())||"",label:l||"",sportCode:((b=u==null?void 0:u.sportCode)==null?void 0:b.toLowerCase())||(l==null?void 0:l.toLowerCase())||""}],g=()=>{t===0?a():(n(t-1),t===1&&i(null),t===2&&m(null),t===3&&h(null))},f=()=>{N.invalidateQueries({queryKey:["import-dashboard-stats"]}),K.success(r==="props"?"Props imported successfully":"Injuries imported successfully"),_()},_=()=>{n(0),i(null),m(null),h(null),a()};return v.useEffect(()=>{s||(n(0),i(null),m(null),h(null))},[s]),e.jsx(Ue,{open:s,onOpenChange:c=>!c&&_(),children:e.jsxs(Be,{className:"max-w-3xl h-[90vh] flex flex-col overflow-hidden",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Import Players Data"})}),e.jsx(ln,{steps:Jf,currentStep:t,className:"mb-6"}),e.jsx(cs,{className:"flex-1 min-h-0 h-0 pr-4",children:y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[t===0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select import type"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{i("props"),n(1)},children:e.jsxs(J,{className:"p-6 text-center",children:[e.jsx(tl,{className:"h-8 w-8 mx-auto mb-2 text-purple-500"}),e.jsx("span",{className:"font-medium",children:"Player Props"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Import player prop lines and hit rates"})]})}),e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{i("injuries"),n(1)},children:e.jsxs(J,{className:"p-6 text-center",children:[e.jsx(xs,{className:"h-8 w-8 mx-auto mb-2 text-red-500"}),e.jsx("span",{className:"font-medium",children:"Injury Report"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Import injury status and expected return dates"})]})})]})]}),t===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a sport"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:d.map(c=>{var p;return e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{var w;m(((w=c.sport)==null?void 0:w.toUpperCase())||""),n(2)},children:e.jsx(J,{className:"p-4 text-center",children:e.jsx("span",{className:"font-medium",children:(p=c.sport)==null?void 0:p.toUpperCase()})})},c.sport)})})]}),t===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Select a league for ",l]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:x.map(c=>e.jsx(G,{className:"cursor-pointer hover:border-primary transition-colors",onClick:()=>{h(c.key),n(3)},children:e.jsx(J,{className:"p-4 text-center",children:e.jsx("span",{className:"font-medium",children:c.label})})},c.key))})]}),t===3&&r&&l&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(G,{className:"bg-muted/50",children:e.jsxs(J,{className:"p-4",children:[e.jsxs("p",{className:"font-medium",children:["Import ",r==="props"?"Player Props":"Injury Report"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[l," • ",o]})]})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r==="props"?"Import player props CSV. Uses date/player as unique key for upsert.":"Import injury report CSV. Updates player 
294injury status and return dates."}),e.jsx(on,{initialSport:((j=u==null?void 0:u.sportCode)==null?void 0:j.toLowerCase())||l.toLowerCase(),initialLeague:o||void 0,initialDataType:r==="props"?"player_props":"injuries",initialSlateDate:ke(new Date,"yyyy-MM-dd"),initialStrategy:"upsert",onImportComplete:f,hideSelectors:!0})]})]})}),e.jsx("div",{className:"flex justify-between mt-6 pt-4 border-t",children:e.jsxs(R,{variant:"outline",onClick:g,children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),t===0?"Cancel":"Back"]})})]})})}function Dr({title:s,description:a,icon:t,count:n,bySport:r,onClick:i,colorClass:l}){const m=Object.entries(r).sort((o,h)=>h[1]-o[1]);return e.jsxs(G,{className:`cursor-pointer transition-all hover:shadow-lg hover:scale-[1.02] ${l}`,onClick:i,children:[e.jsxs(je,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"p-2 rounded-lg bg-background/50",children:t}),e.jsx("span",{className:"text-3xl font-bold",children:n})]}),e.jsx(fe,{className:"text-lg",children:s}),e.jsx(De,{children:a})]}),e.jsx(J,{children:m.length>0?e.jsx("div",{className:"flex flex-wrap gap-2",children:m.map(([o,h])=>e.jsxs(B,{variant:"secondary",className:"text-xs",children:[o,": ",h]},o))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items"})})]})}function Xf(){const{data:s,isLoading:a}=bf(),[t,n]=v.useState(null);return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Dr,{title:"Results",description:"Past contests needing results",icon:e.jsx(kt,{className:"h-5 w-5 text-orange-600"}),count:(s==null?void 0:s.results.total)||0,bySport:(s==null?void 0:s.results.bySport)||{},onClick:()=>n("results"),colorClass:"border-orange-200 bg-orange-50/50 dark:border-orange-900/50 dark:bg-orange-950/20"}),e.jsx(Dr,{title:"Create",description:"Today's draft contests",icon:e.jsx(Zs,{className:"h-5 w-5 text-blue-600"}),count:(s==null?void 0:s.create.total)||0,bySport:(s==null?void 0:s.create.bySport)||{},onClick:()=>n("create"),colorClass:"border-blue-200 bg-blue-50/50 dark:border-blue-900/50 dark:bg-blue-950/20"}),e.jsx(Dr,{title:"Update",description:"Today's active contests",icon:e.jsx(He,{className:"h-5 w-5 text-green-600"}),count:(s==null?void 0:s.update.total)||0,bySport:(s==null?void 0:s.update.bySport)||{},onClick:()=>n("update"),colorClass:"border-green-200 bg-green-50/50 dark:border-green-900/50 dark:bg-green-950/20"}),e.jsx(Dr,{title:"Players",description:"Props & Injury imports",icon:e.jsx(hs,{className:"h-5 w-5 text-purple-600"}),count:(s==null?void 0:s.props.total)||0,bySport:(s==null?void 0:s.props.bySport)||{},onClick:()=>n("players"),colorClass:"border-purple-200 bg-purple-50/50 dark:border-purple-900/50 dark:bg-purple-950/20"})]}),e.jsx(Hf,{open:t==="results",onClose:()=>n(null)}),e.jsx(Gf,{open:t==="create",onClose:()=>n(null)}),e.jsx(Yf,{open:t==="update",onClose:()=>n(null)}),e.jsx(Zf,{open:t==="players",onClose:()=>n(null)})]})}function ev(){var x;const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState(null),[l,m]=v.useState(!1),{data:o,isLoading:h,error:N,refetch:d}=ge({queryKey:["import-history",s,t],queryFn:async()=>{var b;const{data:{session:g}}=await T.auth.getSession();console.log("ImportHistory - Auth Session:",(b=g==null?void 0:g.user)==null?void 0:b.id),console.log("ImportHistory - Executing query with filters:",{sportFilter:s,dataTypeFilter:t});let f=T.from("data_import_history").select(`
295          *,
296          user_profiles!imported_by (
297            username,
298            avatar_url
299          )
300        `).order("import_date",{ascending:!1}).limit(100);s!=="all"&&(f=f.eq("sport",s)),t!=="all"&&(f=f.eq("data_type",t));const{data:_,error:k}=await f;if(k)throw console.error("ImportHistory - Query Error:",k),k;return console.log("ImportHistory - Query Success:",_==null?void 0:_.length,"records"),_},retry:2,retryDelay:1e3}),y=(g,f)=>{const _=JSON.stringify(g,null,2),k=new Blob([_],{type:"application/json"}),b=URL.createObjectURL(k),j=document.createElement("a");j.href=b,j.download=`error-log-${f}.json`,j.click()},u=async()=>
300{if(r){m(!0);try{const g=Aa.find(j=>j.value===r.data_type);if(!g){K.error("Unknown data type");return}const f=g.table;if(r.data_type==="historical_results"){const{data:j}=await T.from("dfs_historical_results").select("contest_id").eq("import_batch_id",r.id);if(j&&j.length>0){const c=[...new Set(j.map(p=>p.contest_id).filter(Boolean))];if(c.length>0){const{error:p,count:w}=await T.from("dfs_perfect_lineups").delete({count:"exact"}).in("contest_id",c);p?console.error("Failed to delete perfect lineups:",p):console.log(`Deleted ${w} perfect lineups for ${c.length} contests`)}}}let{error:_,count:k}=await T.from(f).delete({count:"exact"}).eq("import_batch_id",r.id);if(!_&&(k===0||k===null)&&f==="dfs_projections"){console.log("No records found by import_batch_id, trying fallback deletion by contest_id + source");const{data:j,error:c}=await T.from("dfs_projections").select("contest_id, source",{count:"exact",head:!0}).eq("sport",r.sport).limit(1);!c&&j&&K.info("No records matched batch ID. Check for orphaned projections in the database manually.")}if(_){K.error(`Failed to delete imported data: ${_.message}`);return}const{error:b}=await T.from("data_import_history").update({import_strategy:"deleted"}).eq("id",r.id);if(b){K.error(`Failed to mark history as deleted: ${b.message}`);return}K.success(`Deleted ${k||0} records from ${f}. Import marked as deleted.`),d(),i(null)}catch(g){console.error("Delete error:",g),K.error("Failed to delete import")}finally{m(!1)}}};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(fe,{children:"Import History"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-32",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),cn.map(g=>e.jsx(V,{value:g.value,children:g.label},g.value))]})]}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-40",children:e.jsx(ue,{placeholder:"Data Type"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Types"}),Aa.map(g=>e.jsx(V,{value:g.value,children:g.label},g.value))]})]})]})]})}),e.jsx(J,{children:h?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading history..."}):N?e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(kt,{className:"h-12 w-12 mx-auto mb-4 opacity-50 text-destructive"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-destructive font-medium",children:"Error loading import history"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:N.message}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>d(),className:"mt-4",children:"Retry"})]})]}):!o||o.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(kt,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No import history found"}),e.jsx("p",{className:"text-xs mt-2",children:"Try adjusting the filters above"})]}):e.jsx("div",{className:"overflow-auto border rounded-lg",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Date"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Data Type"}),e.jsx(U,{children:"File"}),e.jsx(U,{children:"Records"}),e.jsx(U,{children:"Success"}),e.jsx(U,{children:"Failed"}),e.jsx(U,{children:"Strategy"}),e.jsx(U,{children:"Imported By"}),e.jsx(U,{children:"Actions"})]})}),e.jsx($e,{children:o.map(g=>{var f;return e.jsxs(he,{children:[e.jsx(M,{className:"whitespace-nowrap",children:ke(new Date(g.import_date),"MMM d, yyyy h:mm a")}),e.jsx(M,{children:e.jsx(B,{variant:"outline",children:g.sport.toUpperCase()})}),e.jsx(M,{children:g.data_type}),e.jsx(M,{className:"font-mono text-xs",children:g.file_name}),e.jsx(M,{children:g.records_processed}),e.jsx(M,{className:"text-green-600 font-medium",children:g.records_succeeded}),e.jsx(M,{className:"text-red-600 font-medium",children:g.records_failed}),e.jsx(M,{children:e.jsx(B,{variant:g.import_strategy==="deleted"?"destructive":"secondary",children:g.import_strategy})}),e.jsx(M,{children:((f=g.user_profiles)==null?void 0:f.username)||"Unknown"}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[g.error_log&&g.records_failed>0&&e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>y(g.error_log,g.file_name),children:e.jsx(Gt,{className:"h-4 w-4"})}),g.import_strategy!=="deleted"&&e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>i(g),className:"text-destructive hover:text-destructive hover:bg-destructive/10",children:e.jsx(os,{className:"h-4 w-4"})})]})})]},g.id)})})]})})}),e.jsx(Ji,{open:!!r,onClose:()=>i(null),onConfirm:u,title:"Delete Import",description:"Are you sure you want to delete this import and its associated data?",warningItems:r?[`${r.records_succeeded} records from ${((x=Aa.find(g=>g.value===r.data_type))==null?void 0:x.table)||"database"}`,"Import will be marked as deleted in history","This action cannot be undone"]:[],itemName:"Import"})]})}function sv(){var c;const[s,a]=v.useState("mlb"),[t,n]=v.useState(""),[r,i]=v.useState(""),[l,m]=v.useState(""),[o,h]=v.useState(""),[N,d]=v.useState(!1),[y,u]=v.useState(!1),[x,g]=v.useState(null),{toast:f}=Ws(),_=Aa,k=(c=_.find(p=>
300p.value===t))==null?void 0:c.table,b=async()=>{if(k)try{let p=T.from(k).select("*",{count:"exact",head:!0});r&&(p=p.gte("created_at",r)),l&&(p=p.lte("created_at",l));const{count:w,error:S}=await p;if(S)throw S;g(w||0)}catch(p){console.error("Preview error:",p),f({title:"Preview Failed",description:p.message,variant:"destructive"})}},j=async()=>{if(o!=="DELETE"){f({title:"Confirmation Required",description:"Please type DELETE to confirm",variant:"destructive"});return}if(k){d(!0);try{let p=T.from(k).delete();r&&(p=p.gte("created_at",r)),l&&(p=p.lte("created_at",l));const{error:w}=await p;if(w)throw w;f({title:"Data Deleted",description:`Successfully deleted ${x||0} records`}),u(!1),h(""),g(null)}catch(p){console.error("Deletion error:",p),f({title:"Deletion Failed",description:p.message,variant:"destructive"})}finally{d(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs(fe,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(ls,{className:"h-5 w-5"}),"Bulk Data Deletion"]})}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs(ss,{variant:"destructive",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsxs(ts,{children:[e.jsx("strong",{children:"Warning:"})," This action is irreversible. Deleted data cannot be recovered. Please ensure you have backups before proceeding."]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Sport"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:cn.map(p=>e.jsx(V,{value:p.value,children:p.label},p.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Data Type"}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select data type"})}),e.jsx(me,{children:_.map(p=>e.jsx(V,{value:p.value,children:p.label},p.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Date From (Optional)"}),e.jsx(pe,{type:"date",value:r,onChange:p=>i(p.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Date To (Optional)"}),e.jsx(pe,{type:"date",value:l,onChange:p=>m(p.target.value)})]})]}),x!==null&&e.jsx(ss,{children:e.jsxs(ts,{children:[e.jsxs("strong",{children:[x," records"]})," will be deleted based on the selected filters."]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"outline",onClick:b,disabled:!t,children:"Preview Deletion"}),e.jsxs(R,{variant:"destructive",onClick:()=>u(!0),disabled:!t||x===null||x===0,children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete Data"]})]})]})]}),e.jsx(ws,{open:y,onOpenChange:u,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Are you absolutely sure?"}),e.jsxs(Ps,{children:["This will permanently delete ",e.jsxs("strong",{children:[x||0," records"]})," from the database. This action cannot be undone."]})]}),e.jsxs("div",{className:"space-y-2 py-4",children:[e.jsx(Q,{children:"Type DELETE to confirm"}),e.jsx(pe,{value:o,onChange:p=>h(p.target.value),placeholder:"DELETE"})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:j,disabled:o!=="DELETE"||N,className:"bg-destructive hover:bg-destructive/90",children:N?"Deleting...":"Delete Permanently"})]})]})})]})}function tv(){var f;const[s,a]=v.useState("mlb"),[t,n]=v.useState(""),[r,i]=v.useState(""),[l,m]=v.useState(""),[o,h]=v.useState("csv"),[N,d]=v.useState(!1),{toast:y}=Ws(),u=Aa,x=(f=u.find(_=>_.value===t))==null?void 0:f.table,g=async()=>{if(x){d(!0);try{let _=T.from(x).select("*");r&&(_=_.gte("created_at",r)),l&&(_=_.lte("created_at",l));const{data:k,error:b}=await _;if(b)throw b;if(!k||k.length===0){y({title:"No Data",description:"No records found for the selected filters",variant:"destructive"});return}const j=`${s}-${t}-${new Date().toISOString().split("T")[0]}`;o==="csv"?cl(k,`${j}.csv`):ph(k,`${j}.json`),y({title:"Export Successful",description:`Exported ${k.length} records as ${o.toUpperCase()}`})}catch(_){console.error("Export error:",_),y({title:"Export Failed",description:_.message,variant:"destructive"})}finally{d(!1)}}};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"Export Data"})}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Sport"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:cn.map(_=>e.jsx(V,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Data Type"}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select data type"})}),e.jsx(me,{children:u.map(_=>e.jsx(V,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Date From (Optional)"}),e.jsx(pe,{type:"date",value:r,onChange:_=>i(_.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Date To (Optional)"}
300),e.jsx(pe,{type:"date",value:l,onChange:_=>m(_.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Export Format"}),e.jsxs(oe,{value:o,onValueChange:_=>h(_),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"csv",children:"CSV"}),e.jsx(V,{value:"json",children:"JSON"})]})]})]})]}),e.jsxs(R,{onClick:g,disabled:!t||N,className:"w-full",children:[e.jsx(Gt,{className:"h-4 w-4 mr-2"}),N?"Exporting...":"Export Data"]})]})]})}function av(){return e.jsx("div",{className:"space-y-4",children:e.jsxs(yo,{type:"single",collapsible:!0,className:"w-full space-y-4",children:[e.jsxs(un,{value:"history",className:"border rounded-lg px-4",children:[e.jsx(mn,{className:"hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Pt,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-semibold",children:"Import History"}),e.jsx("p",{className:"text-sm text-muted-foreground font-normal",children:"View past imports and their status"})]})]})}),e.jsx(xn,{className:"pt-4",children:e.jsx(ev,{})})]}),e.jsxs(un,{value:"deletion",className:"border rounded-lg px-4",children:[e.jsx(mn,{className:"hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{className:"h-5 w-5 text-destructive"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-semibold",children:"Bulk Data Deletion"}),e.jsx("p",{className:"text-sm text-muted-foreground font-normal",children:"Delete data by type and date range"})]})]})}),e.jsx(xn,{className:"pt-4",children:e.jsx(sv,{})})]}),e.jsxs(un,{value:"export",className:"border rounded-lg px-4",children:[e.jsx(mn,{className:"hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Gt,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-semibold",children:"Export Data"}),e.jsx("p",{className:"text-sm text-muted-foreground font-normal",children:"Export data to CSV or JSON"})]})]})}),e.jsx(xn,{className:"pt-4",children:e.jsx(tv,{})})]})]})})}function rv(){const[s,a]=v.useState("import"),[t,n]=v.useState("import");return e.jsx("div",{className:"space-y-6",children:e.jsxs(js,{value:s,onValueChange:a,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start sm:max-w-md",children:[e.jsxs(Ne,{value:"import",className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-4 w-4"}),"Import"]}),e.jsxs(Ne,{value:"manage",className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"Manage"]})]}),e.jsx(we,{value:"import",className:"mt-6",children:e.jsxs(js,{value:t,onValueChange:n,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start sm:max-w-xs",children:[e.jsx(Ne,{value:"import",children:"Import"}),e.jsx(Ne,{value:"utilities",children:"Utilities"})]}),e.jsx(we,{value:"import",className:"mt-4",children:e.jsx(Xf,{})}),e.jsx(we,{value:"utilities",className:"mt-4",children:e.jsx(av,{})})]})}),e.jsx(we,{value:"manage",className:"mt-6",children:e.jsx(_f,{})})]})})}const nv=()=>{const{toast:s}=Ws(),a=Me(),[t,n]=v.useState(75),[r,i]=v.useState(30),[l,m]=v.useState(!1),{data:o,isLoading:h}=ge({queryKey:["dfs-win-threshold"],queryFn:async()=>{const{data:p,error:w}=await T.from("app_settings").select("*").eq("setting_key","dfs_win_threshold").maybeSingle();if(w)throw w;if(!p){const{data:C,error:O}=await T.from("app_settings").insert({setting_key:"dfs_win_threshold",setting_value:{percentage:75},description:"Percentage of perfect lineup score required to count as a win for tracked (non-wagered) lineups"}).select().single();if(O)throw O;return n(75),C}const S=p.setting_value,P=(S==null?void 0:S.percentage)||75;return n(P),p}}),{data:N,isLoading:d}=ge({queryKey:["dfs-set-win-threshold"],queryFn:async()=>{const{data:p,error:w}=await T.from("app_settings").select("*").eq("setting_key","dfs_set_win_threshold").maybeSingle();if(w)throw w;if(!p){const{data:C,error:O}=await T.from("app_settings").insert({setting_key:"dfs_set_win_threshold",setting_value:{percentage:30},description:"Percentage of lineups in a set that must beat individual threshold for the entire set to count as a win"}).select().single();if(O)throw O;return i(30),C}const S=p.setting_value,P=(S==null?void 0:S.percentage)||30;return i(P),p}}),y=async(p,w)=>{m(!0);try{const{data:S,error:P}=await T.functions.invoke("recalculate-tracked-results",{body:{lineupThreshold:p,setThreshold:w}});
300P?(console.error("Recalculation error:",P),s({title:"Recalculation Failed",description:P.message,variant:"destructive"})):(s({title:"Results Recalculated",description:`Updated ${(S==null?void 0:S.updated)||0} tracked results with new thresholds`}),a.invalidateQueries({queryKey:["model-performance"]}),a.invalidateQueries({queryKey:["saved-ai-outputs"]}))}catch(S){console.error("Recalculation error:",S)}finally{m(!1)}},u=_e({mutationFn:async p=>{const{data:{user:w}}=await T.auth.getUser(),{error:S}=await T.from("app_settings").update({setting_value:{percentage:p},updated_by:w==null?void 0:w.id,updated_at:new Date().toISOString()}).eq("setting_key","dfs_win_threshold");if(S)throw S;return p},onSuccess:async p=>{var S;a.invalidateQueries({queryKey:["dfs-win-threshold"]}),s({title:"Lineup Threshold Updated",description:`Individual lineup win threshold set to ${p}%`});const w=((S=N==null?void 0:N.setting_value)==null?void 0:S.percentage)||30;await y(p,w)},onError:p=>{s({title:"Update Failed",description:p.message,variant:"destructive"})}}),x=_e({mutationFn:async p=>{const{data:{user:w}}=await T.auth.getUser(),{error:S}=await T.from("app_settings").update({setting_value:{percentage:p},updated_by:w==null?void 0:w.id,updated_at:new Date().toISOString()}).eq("setting_key","dfs_set_win_threshold");if(S)throw S;return p},onSuccess:async p=>{var S;a.invalidateQueries({queryKey:["dfs-set-win-threshold"]}),s({title:"Set Threshold Updated",description:`Set win threshold set to ${p}%`});const w=((S=o==null?void 0:o.setting_value)==null?void 0:S.percentage)||75;await y(w,p)},onError:p=>{s({title:"Update Failed",description:p.message,variant:"destructive"})}}),g=()=>{u.mutate(t)},f=()=>{x.mutate(r)},_=o==null?void 0:o.setting_value,k=(_==null?void 0:_.percentage)!==t,b=N==null?void 0:N.setting_value,j=(b==null?void 0:b.percentage)!==r,c=h||d;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{className:"p-6",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx(ya,{className:"h-5 w-5 text-primary mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Lineup Win Threshold"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"What percentage of perfect lineup score does an individual lineup need to beat the threshold?"})]})]}),e.jsxs(ss,{className:"mb-6",children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsxs(ts,{className:"text-sm",children:[e.jsx("strong",{children:"How it works:"})," For tracked lineups, a lineup beats the threshold if its actual score reaches at least this percentage of the perfect lineup score.",e.jsx("br",{}),"Example: With 75% threshold, if perfect lineup scored 200 points, any lineup scoring 150+ beats the threshold."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("label",{className:"text-sm font-medium",children:"Lineup Win Threshold"}),e.jsxs("span",{className:"text-2xl font-bold text-primary",children:[t,"%"]})]}),e.jsx(jl,{value:[t],onValueChange:p=>n(p[0]),min:50,max:90,step:1,className:"w-full",disabled:c}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"50% (Easier)"}),e.jsx("span",{children:"90% (Harder)"})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:c?"Loading...":l?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-3 w-3 animate-spin"}),"Recalculating results..."]}):k?"You have unsaved changes":"No changes"}),e.jsx(R,{onClick:g,disabled:!k||u.isPending||l,children:u.isPending?"Saving...":l?"Recalculating...":"Save Changes"})]})]})]}),e.jsxs(G,{className:"p-6",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[e.jsx(hs,{className:"h-5 w-5 text-primary mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Set Win Threshold (Multi-Lineup)"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"What percentage of lineups in a set must beat the individual threshold for the entire set to count as a WIN?"})]})]}),e.jsxs(ss,{className:"mb-6",children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsxs(ts,{className:"text-sm",children:[e.jsx("strong",{children:"How it works:"})," Model performance is graded per lineup SET, not per individual lineup. For a 20-lineup set with a ",r,"% threshold, at least ",Math.
300ceil(20*(r/100))," lineups must beat the ",t,"% perfect score threshold for the set to be a WIN.",e.jsx("br",{}),e.jsx("strong",{children:"This prevents inflated win rates from per-lineup counting."})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("label",{className:"text-sm font-medium",children:"Set Win Threshold"}),e.jsxs("span",{className:"text-2xl font-bold text-primary",children:[r,"%"]})]}),e.jsx(jl,{value:[r],onValueChange:p=>i(p[0]),min:10,max:70,step:5,className:"w-full",disabled:c}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"10% (Very Easy)"}),e.jsx("span",{children:"70% (Very Hard)"})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-sm",children:[e.jsx("strong",{children:"Example with current settings:"}),e.jsxs("ul",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("li",{children:["• 20-lineup set with ",Math.ceil(20*(r/100)),"+ lineups beating ",t,"% = ",e.jsx("span",{className:"text-green-500 font-medium",children:"WIN"})]}),e.jsxs("li",{children:["• 20-lineup set with ",Math.ceil(20*(r/100))-1," lineups beating ",t,"% = ",e.jsx("span",{className:"text-red-500 font-medium",children:"LOSS"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:c?"Loading...":l?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-3 w-3 animate-spin"}),"Recalculating results..."]}):j?"You have unsaved changes":"No changes"}),e.jsx(R,{onClick:f,disabled:!j||x.isPending||l,children:x.isPending?"Saving...":l?"Recalculating...":"Save Changes"})]})]})]})]})};function lv(){const[s,a]=v.useState("basketball"),[t,n]=v.useState("DraftKings"),[r,i]=v.useState(!1),[l,m]=v.useState(null),{toast:o}=Ws(),{data:h,isLoading:N,refetch:d}=ge({queryKey:["player-profile-stats",s,t],queryFn:async()=>{const x=qd(s),{count:g,error:f}=await T.from("dfs_historical_results").select("*",{count:"exact",head:!0}).in("sport",x).ilike("platform",t);if(f)throw f;const{data:_}=await T.from("dfs_historical_results").select("created_at").in("sport",x).ilike("platform",t).order("created_at",{ascending:!1}).limit(1).maybeSingle(),{count:k,error:b}=await T.from("dfs_player_profiles").select("*",{count:"exact",head:!0}).in("sport",x).ilike("platform",t);if(b)throw b;const{data:j}=await T.from("dfs_player_profiles").select("updated_at").in("sport",x).ilike("platform",t).order("updated_at",{ascending:!1}).limit(1).maybeSingle();return{sport:s,platform:t,historical_count:g||0,profile_count:k||0,latest_historical_import:(_==null?void 0:_.created_at)||null,latest_profile_update:(j==null?void 0:j.updated_at)||null}}}),y=async()=>{i(!0),m(null);try{const{data:x,error:g}=await T.functions.invoke("build-dfs-player-profiles",{body:{sport:s,platform:t}});if(g)throw g;m({success:x.profiles_created||0,skipped:x.skipped_no_player_id||0,errors:x.errors||[]}),o({title:"Profile Build Complete",description:`Created ${x.profiles_created||0} profiles, skipped ${x.skipped_no_player_id||0}`}),d()}catch(x){console.error("Error building profiles:",x),o({title:"Error",description:x.message||"Failed to build player profiles",variant:"destructive"})}finally{i(!1)}},u=h&&h.latest_historical_import&&(!h.latest_profile_update||new Date(h.latest_historical_import)>new Date(h.latest_profile_update));return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-5 w-5"}),"Build Player Profiles"]}),e.jsx(De,{children:"Build player profiles from historical DFS results. Required for accurate player grading based on historical performance patterns."})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Sport"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"basketball",children:"Basketball"}),e.jsx(V,{value:"football",children:"Football"}),e.jsx(V,{value:"baseball",children:"Baseball"}),e.jsx(V,{value:"hockey",children:"Hockey"}),e.jsx(V,{value:"soccer",children:"Soccer"}),e.jsx(V,{value:"mma",children:"MMA"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Platform"}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"DraftKings",children:"DraftKings"}),e.jsx(V,{value:"FanDuel",children:"FanDuel"})]})]})]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:N?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"}),"Loading stats..."]}):h?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(tt,{className:"h-4 w-4"}),"Historical Results"]}),e.jsx("span",{className:"font-mono font-medium",children:h.historical_count.toLocaleStr
300ing()})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(hs,{className:"h-4 w-4"}),"Player Profiles"]}),e.jsx("span",{className:"font-mono font-medium",children:h.profile_count.toLocaleString()})]}),u&&e.jsxs("div",{className:"flex items-center gap-2 pt-2 text-amber-600 dark:text-amber-500",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Profiles need rebuild - new results imported since last build"})]}),!u&&h.profile_count>0&&e.jsxs("div",{className:"flex items-center gap-2 pt-2 text-green-600 dark:text-green-500",children:[e.jsx(rs,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Profiles up to date"})]})]}):null}),l&&e.jsx(ss,{className:l.errors.length>0?"border-amber-500/50":"border-green-500/50",children:e.jsx(ts,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Profiles created:"})," ",l.success]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Skipped (no player match):"})," ",l.skipped]}),l.errors.length>0&&e.jsxs("p",{className:"text-destructive",children:[e.jsx("strong",{children:"Errors:"})," ",l.errors.length]})]})})}),e.jsx(R,{onClick:y,disabled:r||(h==null?void 0:h.historical_count)===0,className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Building Profiles..."]}):"Build Profiles"})]})]})}function iv(){const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState([]),[l,m]=v.useState(!1),[o,h]=v.useState(!1),[N,d]=v.useState([]),y=async()=>{m(!0),i([]),d([]);try{const f=new Date().toISOString().split("T")[0];let _=T.from("dfs_contests").select(`
301          id, 
302          slate_date, 
303          sport, 
304          platform, 
305          contest_name, 
306          contest_type,
307          dfs_perfect_lineups (
308            id,
309            total_points,
310            lineup_data,
311            calculation_status,
312            error_message
313          )
314        `).lte("slate_date",f).order("slate_date",{ascending:!1}).range(0,2e3);s!=="all"&&(_=_.eq("sport",s)),t!=="all"&&(_=_.eq("contest_type",t));const{data:k,error:b}=await _;if(b)throw b;const c=(k||[]).map(p=>{var P;const w=(P=p.dfs_perfect_lineups)==null?void 0:P[0];let S="missing";return w&&(w.calculation_status==="failed"?S="failed":w.calculation_status==="no_results"?S="no_results":!w.total_points||w.total_points===0||!w.lineup_data?S="incomplete":S="complete"),{id:p.id,contest_date:p.slate_date,sport:p.sport,platform:p.platform,contest_name:p.contest_name,contest_type:p.contest_type||"Unknown",perfect_lineup_status:S,error_message:(w==null?void 0:w.error_message)||void 0}}).filter(p=>p.perfect_lineup_status!=="complete"&&p.perfect_lineup_status!=="no_results");i(c),c.length===0?K.info("No contests need perfect lineup calculation"):K.success(`Found ${c.length} contests needing perfect lineups`)}catch(f){K.error(`Failed to find contests: ${f.message}`),console.error("Error finding contests:",f)}finally{m(!1)}},u=async f=>{try{const{data:_,error:k}=await T.functions.invoke("calculate-perfect-lineup",{body:{contestId:f.id,triggerSource:"manual_backfill"}});if(k)throw k;return{contestId:f.id,status:_.status||"completed",message:_.message}}catch(_){return{contestId:f.id,status:"failed",message:_.message}}},x=async f=>{h(!0);const _=await u(f);d([_]),h(!1),_.status==="completed"||_.status==="pending"?(K.success(`Perfect lineup calculation initiated for ${f.contest_name}`),i(k=>k.filter(b=>b.id!==f.id))):K.error(`Failed: ${_.message}`)},g=async()=>{if(r.length===0){K.error("No contests to process");return}h(!0),d([]);const f=[];for(const b of r){const j=await u(b);f.push(j),d([...f]),await new Promise(c=>setTimeout(c,2e3))}h(!1);const _=f.filter(b=>b.status==="completed"||b.status==="pending").length,k=f.filter(b=>b.status==="failed").length;K.success(`Batch complete: ${_} initiated, ${k} failed`)};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-5 w-5"}),"Backfill Perfect Lineups"]}),e.jsx(De,{children:"Find contests with missing, incomplete, or failed perfect lineups and calculate them"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Sport Filter"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),e.jsx(V,{value:"football",children:"Football"}),e.jsx(V,{value:"basketball",children:"Basketball"}),e.jsx(V,{value:"baseball",children:"Baseball"}),e.jsx(V,{value:"hockey",children:"Hockey"}),e.jsx(V,{value:"soccer",children:"Soccer"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Contest Type"}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Types"}),e.jsx(V,{value:"Classic",children:"Classic"}),e.jsx(V,{value:"Showdown",children:"Showdown"})]})]})]})]}),e.jsx(R,{onClick:y,disabled:l,className:"w-full",children:l?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Searching..."]}):"Find Contests Needing Perfect Lineups"}),r.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(ss,{children:[e.jsx(xs,{className:"h-4 w-4"}),e.jsxs(ts,{children:["Found ",r.length," contest",r.length>
3141?"s":""," that need perfect lineup calculation. You can calculate them individually or process all in batch."]})]}),e.jsx(R,{onClick:g,disabled:o,variant:"default",className:"w-full",children:o?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Processing Batch..."]}):`Calculate All ${r.length} Perfect Lineups`}),e.jsx("div",{className:"max-h-96 overflow-y-auto space-y-2",children:r.map(f=>{const _=N.find(k=>k.contestId===f.id);return e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:f.contest_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[f.sport," • ",f.contest_type," • ",f.platform," • ",f.contest_date,f.perfect_lineup_status==="failed"&&e.jsxs("span",{className:"ml-2 text-destructive font-medium",children:["(Failed",f.error_message?`: ${f.error_message}`:"",")"]})]}),_&&e.jsxs("div",{className:"flex items-center gap-1 mt-1 text-xs",children:[_.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx($s,{className:"h-3 w-3 text-yellow-600"}),e.jsx("span",{className:"text-yellow-600",children:"Calculating..."})]}),_.status==="completed"&&e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-3 w-3 text-green-600"}),e.jsx("span",{className:"text-green-600",children:"Completed"})]}),_.status==="failed"&&e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"h-3 w-3 text-destructive"}),e.jsx("span",{className:"text-destructive",children:_.message})]})]})]}),e.jsx(R,{size:"sm",onClick:()=>x(f),disabled:o||!!_,children:_?"Done":"Calculate"})]},f.id)})})]})]})]})}function cv(){const[s,a]=v.useState("all"),[t,n]=v.useState(""),[r,i]=v.useState([]),[l,m]=v.useState(null),[o,h]=v.useState(null),[N,d]=v.useState(!1),[y,u]=v.useState(!1),[x,g]=v.useState(null),f=async()=>{d(!0),i([]),m(null),h(null),g(null);try{let b=T.from("dfs_contests").select("id, contest_id, contest_name, slate_date, sport, platform, home_team, away_team, contest_type").order("slate_date",{ascending:!1}).limit(50);s!=="all"&&(b=b.eq("sport",s)),t.trim()&&(b=b.or(`contest_name.ilike.%${t}%,home_team.ilike.%${t}%,away_team.ilike.%${t}%`));const{data:j,error:c}=await b;if(c)throw c;i(j||[]),!j||j.length===0?K.info("No contests found matching your criteria"):K.success(`Found ${j.length} contests`)}catch(b){K.error(`Failed to search contests: ${b.message}`),console.error("Error searching contests:",b)}finally{d(!1)}},_=async b=>{m(b),g(null),console.log("Selected contest:",b);try{const{data:j,error:c}=await T.functions.invoke("get-contest-stats",{body:{contestId:b.id}});if(c)throw console.error("Edge function error:",c),c;console.log("Contest stats from edge function:",j),h({totalLineups:j.totalLineups,scoredLineups:j.scoredLineups,unscoredLineups:j.unscoredLineups,hasResults:j.hasResults,hasPerformanceRecords:j.hasPerformanceRecords})}catch(j){console.error("Error fetching contest stats:",j),K.error("Failed to fetch contest stats")}},k=async()=>{if(l){u(!0),g(null);try{const{data:b,error:j}=await T.functions.invoke("process-contest-learning",{body:{contestId:l.id,sport:l.sport,platform:l.platform,slateDate:l.slate_date}});if(j)throw j;g({success:!0,message:`Processed successfully. Scored ${b.scoredCount||0} lineups, updated ${b.updatedModels||0} model versions.`}),K.success("Contest reprocessed successfully"),await _(l)}catch(b){g({success:!1,message:b.message||"Unknown error occurred"}),K.error(`Failed to reprocess: ${b.message}`)}finally{u(!1)}}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-5 w-5"}),"Reprocess Single Contest"]}),e.jsx(De,{children:"Find and reprocess a specific contest's learning data (scores, performance records, model learning)"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Sport Filter"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),e.jsx(V,{value:"nfl",children:"NFL"}),e.jsx(V,{value:"nba",children:"NBA"}),e.jsx(V,{value:"mlb",children:"MLB"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Search (name, team)"}),e.jsx(pe,{placeholder:"Search contests...",value:t,onChange:b=>n(b.target.value),onKeyDown:b=>b.key==="Enter"&&f()})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:" "}),e.jsx(R,{onClick:f,disabled:N,className:"w-full",children:N?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Searching..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"mr-2 h-4 w-4"}),"Search Contests"]})})]})]}),r.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Select Contest"}),e.jsxs(oe,{value:(l==null?void 0:l.id)||"",onValueChange:b=>{const j=r.find(c=>c.id===b);j&&_(j)},children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Choose a contest to reprocess..."})}),e.jsx(me,{children:r.map(b=>e.jsx(V,{value:b.id,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:b.contest_name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.sport.toUpperCase()," • ",b.platform," • ",b.slate_date,b.home_team&&b.away_team&&` • ${b.away_team} @ ${b.home_team}`]})]})},b.id))})]})]}),l&&o&&e.jsxs(ss,{children:[e.jsx(xs,{className:"h-4 w-4"}),e.jsxs(ts,{children:[e.jsx("div",{className:"font-medium mb-2",children:l.contest_name}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total Lineups:"})," ",e.jsx("span",{className:"font-medium",children:o.totalLineups})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Scored:"})," ",e.jsx("span",{className:"font-medium text-green-600",children:o.scoredLineups})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Unscored:"})," ",e.jsx("span",{className:`font-medium ${o.unscoredLineups>0?"text-yellow-600":""}`,children:o.unscoredLineups})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Has Results:"})," ",e.jsx("span",{className:`font-medium ${o.hasResults?"text-green-600":"text-destructive"}`,children:o.hasResults?"Yes":"No"})]})]})]})]}),l&&e.jsx(R,{onClick:k,disabled:y,className:"w-full",variant:"default",children:y?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Reprocessing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4"}),"Reprocess Contest Learning"]})}),x&&e.jsxs(ss,{variant:x.success?"default":"destructive",children:[x.success?e.jsx(Es,{className:"h-4 w-4 text-green-600"}):e.jsx(xs,{className:"h-4 w-4"}),e.jsx(ts,{children:x.message})]})]})]})}function ov(){const[s,a]=v.useState("wagered"),[t,n]=v.useState(!1),[r,i]=v.useState(null),[l,m]=v.useState(null),[o,h]=v.useState(75),[N,d]=v.useState(30);v.useEffect(()=>{(async()=>{const{data:f}=await T.from("app_settings").select("setting_value").eq("setting_key","dfs_win_threshold").maybeSingle();if(f){const k=f.setting_value;h((k==null?void 0:k.percentage)||75)}const{data:_}=await T.from("app_settings").select("setting_value").eq("setting_key","dfs_set_win_threshold").maybeSingle();if(_){const k=_.setting_value;d((k==null?void 0:k.percentage)||30)}})()},[]);const y=async()=>{n(!0),i(null),m(null);try{const{data:g,error:f}=await T.from("dfs_generated_lineups").select("*").eq("tracking_status","bet").not("actual_score","is",null).not("prize_won","is",null);if(f)throw f;if(!g||g.length===0){K.info("No placed bets with results found"),i({processed:0,inserted:0,skipped:0,setsProcessed:0}),n(!1);return}const _=new Map;for(const S of g){const P=S.lineup_set_id||S.id;_.has(P)||_.set(P,[]),_.get(P).push(S)}let k=0,b=0,j=0,c=0;const p=[],w=g.length;for(const[S,P]of _){const C=P[0],O=C.lineup_set_id!==null;if(!O){const{data:$}=await T.from("model_performance_results").select("id").eq("lineup_id",C.id).maybeSingle();if($){k+=1,c++,m({current:k,total:w});continue}}try{const $=P.reduce((L,H)=>L+(H.prize_won||0),0),z=P.reduce((L,H)=>L+(H.entry_fee||0),0),D=$-z;let A="push";D>0?A="win":D<0&&(A="loss");const F=P.reduce((L,H)=>L+(H.actual_score||0),0)/P.length;let q=C.model_version_id;if(!q&&C.model_id){const{data:L}=await T.from("user_ai_model_versions").select("id").eq("model_id",C.model_id).order("version_number",{ascending:!1}).limit(1).maybeSingle();q=(L==null?void 0:L.id)||null}let E;if(O){const{data:L}=await T.from("model_performance_results").select("id").eq("lineup_set_id",S).eq("result_type","fantasy").maybeSingle(),H={lineup_id:null,lineup_set_id:S,model_id:C.model_id,model_version_id:q,sport:C.sport,result_date:C.contest_date,result_type:"fantasy",actual_score:F,entry_fee:z,prize_won:$,profit_loss:D,result:A};if(L){const{error:Z}=await T.from("model_performance_results").update(H).eq("id",L.id);E=Z}else{const{error:Z}=await T.from("model_performance_results").insert(H);E=Z}}else{const{error:L}=await T.from("model_performance_results").insert({lineup_id:C.id,lineup_set_id:null,model_id:C.model_id,model_version_id:q,sport:C.sport,result_date:C.contest_date,result_type:"fantasy",actual_score:F,entry_fee:z,prize_won:$,profit_loss:D,result:A});E=L}if(E)throw E;await T.from("dfs_generated_lineups").update({result_tracked:!0}).in("id",P.map(L=>L.id)),j++,O&&b++,console.log(`${O?"Set":"Single"} ${S}: $${$.toFixed(2)} prize - $${z.toFixed(2)} entry = $${D.toFixed(2)} → ${A.toUpperCase()}`)}catch($){p.push({id:S,error:$.message})}k+=P.length,m({current:k,total:w})}i({processed:k,inserted:j,skipped:c,total:g.length,setsProcessed:b,errors:p}),K.success(`Backfill complete! ${j} performance records created (${b} from multi-lineup sets).`)}catch(g){K.error(`Backfill failed: ${g.message}`),console.error("Error during backfill:",g)}finally{n(!1),m(null)}},u=async()=>{n(!0),i(null),m(null);try{const{data:g}=await T.from("app_settings").select("setting_value").eq("setting_key","dfs_win_threshold").maybeSingle(),f=g==null?void 0:g.setting_value,_=((f==null?void 0:f.percentage)||75)/100,{data:k}=await T.from("app_settings").select("setting_value").eq("setting_key","dfs_set_win_threshold").maybeSingle(),b=k==null?void 0:k.setting_value,j=((b==null?void 0:b.percentage)||30)/100,{data:c,error:p}=await T.from("dfs_generated_lineups").select("*").eq("tracking_status","tracked").not("actual_score","is",null).is("bet_id",null);if(p)throw p;if(!c||c.length===0){K.info("No tracked lineups with results found"),i({processed:0,inserted:0,skipped:0}),n(!1);return}const w=new Map;for(const z of c){const D=z.lineup_set_id||z.id;w.has(D)||w.set(D,[]),w.get(D).push(z)}let S=0,P=0,C=0;const O=[],$=c.length;for(const[z,D]of w){const A=D[0],F=A.lineup_set_id!==null,{data:q}=await T.from("dfs_perfect_lineups").select("total_points").eq("contest_id",A.contest_id).maybeSingle();if(!q||!q.total_points){S+=D.length,m({current:S,total:$});continue}const L=q.total_points*_;if(F){const{data:H}=await T.from("model_performance_results").select("id").eq("lineup_set_id",z).maybeSingle();if(H){S+=D.length,m({current:S,total:$});continue}}else{const{data:H}=await T.from("model_performance_results").select("id").eq("lineup_id",A.id).maybeSingle();if(H){S+=1,m({current:S,total:$});continue}}
314try{if(F){const H=D.filter(I=>I.actual_score>=L).length,Z=H/D.length,se=Z>=j?"win":"loss",ie=D.reduce((I,ee)=>I+(ee.actual_score||0),0)/D.length,{error:Y}=await T.from("model_performance_results").insert({lineup_id:A.id,lineup_set_id:z,model_id:A.model_id,model_version_id:A.model_version_id,sport:A.sport,result_date:A.contest_date,result_type:"fantasy",actual_score:ie,entry_fee:0,prize_won:0,profit_loss:0,result:se});if(Y)throw Y;C++,P++,console.log(`Set ${z}: ${H}/${D.length} (${(Z*100).toFixed(1)}%) beat threshold → ${se.toUpperCase()}`)}else{const H=A.actual_score>=L?"win":"loss",{error:Z}=await T.from("model_performance_results").insert({lineup_id:A.id,model_id:A.model_id,model_version_id:A.model_version_id,sport:A.sport,result_date:A.contest_date,result_type:"fantasy",actual_score:A.actual_score,entry_fee:0,prize_won:0,profit_loss:0,result:H});if(Z)throw Z;C++}}catch(H){O.push({id:z,error:H.message})}S+=D.length,m({current:S,total:$})}i({processed:S,inserted:C,skipped:S-C,total:c.length,setsProcessed:P,errors:O}),K.success(`Backfill complete! ${C} performance records created (${P} from lineup sets).`)}catch(g){K.error(`Backfill failed: ${g.message}`),console.error("Error during backfill:",g)}finally{n(!1),m(null)}},x=()=>{s==="wagered"?y():u()};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-5 w-5"}),"Backfill Performance Records"]}),e.jsx(De,{children:"Create model_performance_results records for lineups with missing tracking data"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsxs(ts,{children:[e.jsxs("strong",{children:["Lineup Win Threshold: ",o,"%"]})," — Individual lineups must score ≥ ",o,"% of perfect score.",e.jsx("br",{}),e.jsxs("strong",{children:["Set Win Threshold: ",N,"%"]})," — For multi-lineup sets, ≥ ",N,"% of lineups must beat the ",o,"% threshold for the set to WIN."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Backfill Mode"}),e.jsxs(oe,{value:s,onValueChange:g=>a(g),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"wagered",children:"Wagered Lineups"}),e.jsx(V,{value:"tracked",children:"Tracked Lineups"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s==="wagered"?"Process lineups with entry fees (win/loss based on prize vs entry fee)":`Process tracked lineups (creates ONE record per lineup set using ${N}% threshold rule)`})]}),e.jsxs(ss,{children:[e.jsx(xs,{className:"h-4 w-4"}),e.jsx(ts,{children:s==="wagered"?"This will find DFS lineups with results but no performance tracking, and create performance records based on prizes won vs entry fees paid.":`This will find tracked lineup SETS with results. For each set, if ≥${N}% of lineups beat the ${o}% perfect score threshold, the set counts as a WIN. ONE performance record per set.`})]}),l&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Progress"}),e.jsxs("span",{children:[l.current," / ",l.total," lineups"]})]}),e.jsx(Ct,{value:l.current/l.total*100})]}),r&&e.jsxs(ss,{children:[e.jsx(Es,{className:"h-4 w-4"}),e.jsxs(ts,{className:"space-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Lineups Processed:"})," ",r.processed]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Records Created:"})," ",r.inserted||r.successful||0]}),r.setsProcessed!==void 0&&e.jsxs("div",{children:[e.jsx("strong",{children:"From Lineup Sets:"})," ",r.setsProcessed]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Skipped:"})," ",r.skipped]}),r.errors&&r.errors.length>0&&e.jsxs("div",{className:"mt-2 pt-2 border-t",children:[e.jsxs("strong",{children:["Errors (",r.errors.length,"):"]}),e.jsx("div",{className:"max-h-32 overflow-y-auto mt-1 text-xs space-y-1",children:r.errors.map((g,f)=>e.jsxs("div",{children:[g.id,": ",g.error]},f))})]})]})]}),e.jsx(R,{onClick:x,disabled:t,className:"w-full",children:t?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Processing ",s," lineups..."]}):`Backfill ${s==="wagered"?"Wagered":"Tracked"} Lineups`})]})]})}function dv(){const[s,a]=v.useState(!1),[t,n]=v.useState(!1),[r,i]=v.useState([]),[l,m]=v.useState(0),o=async d=>{const u=[];for(let x=0;x<d.length;
314x+=100){const g=d.slice(x,x+100),{data:f,error:_}=await T.from("model_performance_results").select("recommendation_id").in("recommendation_id",g);if(_)throw _;if(f)for(const k of f)k.recommendation_id&&u.push(k.recommendation_id)}return u},h=async()=>{a(!0),i([]);try{const{data:d,error:y}=await T.from("saved_betting_recommendations").select("id, sport, selection, result, model_id, model_version_id, odds, created_at").eq("tracking_status","tracked").not("result","is",null);if(y)throw y;const{data:u,error:x}=await T.from("saved_betting_recommendations").select("id, sport, selection, result, model_id, model_version_id, odds, created_at").eq("tracking_status","tracked").is("result",null);if(x)throw x;const g=[...d||[],...(u||[]).map(b=>({...b,isPending:!0}))];if(g.length===0){K.info("No tracked recommendations found"),a(!1);return}const f=g.map(b=>b.id),_=new Set(await o(f)),k=g.filter(b=>!_.has(b.id));if(i(k),k.length===0)K.success("All tracked betting recommendations have performance records");else{const b=k.filter(c=>c.isPending).length,j=k.length-b;K.info(`Found ${k.length} missing records (${j} settled, ${b} pending)`)}}catch(d){console.error("Error finding orphaned recommendations:",d),K.error("Failed to search: "+d.message)}finally{a(!1)}},N=async()=>{if(r.length!==0){n(!0),m(0);try{let d=0;for(const y of r){const{error:u}=await T.from("model_performance_results").insert({model_id:y.model_id,model_version_id:y.model_version_id,result_type:"betting",sport:y.sport,result:y.result||"pending",profit_loss:0,odds:y.odds,recommendation_id:y.id,result_date:new Date(y.created_at).toISOString().split("T")[0]});u?console.error(`Failed to backfill recommendation ${y.id}:`,u):(d++,m(d))}K.success(`Backfilled ${d} of ${r.length} performance records`),d===r.length?i([]):await h()}catch(d){console.error("Error during backfill:",d),K.error("Backfill failed: "+d.message)}finally{n(!1)}}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-5 w-5"}),"Backfill Betting Performance Records"]}),e.jsx(De,{children:"Find and backfill performance records for tracked betting recommendations that were created before the automatic tracking system"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{className:"border-yellow-500/50 bg-yellow-500/10",children:[e.jsx(ls,{className:"h-4 w-4 text-yellow-500"}),e.jsxs(ts,{className:"text-yellow-200",children:[e.jsx("strong",{children:"Use with caution:"}),' This tool creates performance records for old tracked recommendations. Run "Find Missing Records" first to preview what will be created.']})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{onClick:h,disabled:s||t,variant:"outline",children:[s?e.jsx(ne,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Rs,{className:"h-4 w-4 mr-2"}),"Find Missing Records"]}),r.length>0&&e.jsx(R,{onClick:N,disabled:t,className:"bg-primary",children:t?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 animate-spin mr-2"}),"Backfilling... (",l,"/",r.length,")"]}):e.jsxs(e.Fragment,{children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Backfill All (",r.length,")"]})})]}),r.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Recommendations missing performance records:"}),e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-2 border rounded-md p-2",children:r.map(d=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-2 bg-muted/50 rounded",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",children:d.sport}),e.jsx("span",{className:"truncate max-w-[200px]",children:d.selection})]}),e.jsx(B,{variant:d.isPending?"outline":d.result==="win"?"default":d.result==="loss"?"destructive":"secondary",className:d.isPending?"border-yellow-500/50 text-yellow-400":"",children:d.isPending?"pending":d.result})]},d.id))})]})]})]})}function uv(){const{toast:s}=Ws(),[a,t]=v.useState(!1),[n,r]=v.useState(null),i=async()=>{t(!0),r(null);try{const{data:{session:l}}=await T.auth.getSession(),o=await(await fetch("https://qqamfojeypfnjezyofqc.supabase.co/functions/v1/consolidate-dfs-bets",{method:"POST",headers:{Authorization:`Bearer ${l==null?void 0:l.access_token}`,"Content-Type":"application/json"}})).json();if(o.success)r(o.summary),s({title:"Consolidation Complete",description:`Consolidated ${o.summary.contestsConsolidated} contests. ${o.summary.betsDeleted} duplicate bets removed.`});else throw new Error(o.error)}catch(l){s({title:"Consolidation Failed",description:l.message,variant:"destructive"})}finally{t(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-5 w-5"}),"Consolidate DFS Bets"]}),e.jsx(De,{children:"Merge duplicate DFS bets per contest and clean up orphaned bet records."})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{variant:"destructive",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsx(pa,{children:"🔴 Destructive Operation"}),e.jsxs(ts,{children:["This operation ",e.jsx("strong",{children:"permanently deletes"})," duplicate bet records and cannot be undone. Only run if you have confirmed duplicates exist in the database."]})]}),e.jsxs(R,{onClick:i,disabled:a,className:"w-full",children:[a&&e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Consolidating...":"Run Consolidation"]}),n&&e.jsxs("div",{className:"p-4 bg-muted rounded-lg space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Consolidation Results:"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Contests Consolidated:"}),e.jsx("span",{className:"ml-2 font-medium text-foreground",children:n.contestsConsolidated})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Bets Deleted:"}),e.jsx("span",{className:"ml-2 font-medium text-foreground",children:n.betsDeleted})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Lineups Updated:"}),e.jsx("span",{className:"ml-2 font-medium text-foreground",children:n.lineupsUpdated})]})]})]})]})]})}const mv=["all","football","basketball","baseball","hockey","soccer"],xv=3;async function hv(s,a,t=xv){var n,r,i;for(let l=1;l<=t;l++){const{data:m,error:o}=await T.functions.invoke(s,{body:a});if(!o)return{data:m,error:null};if((((n=o.message)==null?void 0:n.includes("401"))||((r=o.message)==null?void 0:r.includes("Key length is zero"))||((i=o.message)==null?void 0:i.includes("unauthorized")))&&l<t){console.log(`Auth error on attempt ${l}, refreshing session...`);const{error:N}=await T.auth.refreshSession();N&&console.error("Failed to refresh session:",N),await new Promise(d=>setTimeout(d,500));continue}return{data:null,error:o}}return{data:null,error:new Error("Max retries exceeded")}}const pv=()=>{const[s,a]=v.useState(!1),[t,n]=v.useState(null),[r,i]=v.useState("all"),l=async()=>{a(!0),n({totalModels:0,processedModels:0,totalVersions:0,processedVersions:0,totalContests:0,processedContests:0,currentModel:"",currentVersion:"",perfectLineupsCalculated:0,analysesGenerated:0,modelsUpdated:0,errors:[]});try{let o=T.from("user_ai_models").select("id, model_name, sport").eq("model_type","fantasy");r!=="all"&&(o=o.eq("sport",r));const{data:h,error:N}=await o;
314if(N)throw N;if(!h||h.length===0){K.info("No DFS models found to process"),a(!1);return}n(d=>d?{...d,totalModels:h.length}:null);for(const d of h){n(x=>x?{...x,currentModel:d.model_name}:null);const{data:y,error:u}=await T.from("user_ai_model_versions").select("id, version_number").eq("model_id",d.id);if(u){n(x=>x?{...x,errors:[...x.errors,`${d.model_name}: Failed to fetch versions - ${u.message}`]}:null);continue}if(!y||y.length===0){n(x=>x?{...x,processedModels:x.processedModels+1}:null);continue}n(x=>x?{...x,totalVersions:x.totalVersions+y.length}:null);for(const x of y){n(c=>c?{...c,currentVersion:`v${x.version_number}`}:null);const{data:g,error:f}=await T.from("dfs_generated_lineups").select("contest_id, contest_date, sport, platform").eq("model_version_id",x.id).not("contest_id","is",null);if(f){n(c=>c?{...c,errors:[...c.errors,`${d.model_name} v${x.version_number}: Failed to fetch lineups - ${f.message}`],processedVersions:c.processedVersions+1}:null);continue}if(!g||g.length===0){n(c=>c?{...c,processedVersions:c.processedVersions+1}:null);continue}const _=new Map;g.forEach(c=>
314{c.contest_id&&!_.has(c.contest_id)&&_.set(c.contest_id,{contest_id:c.contest_id,date:c.contest_date,sport:c.sport,platform:c.platform})});const b=Array.from(_.keys()).filter(c=>{var p;return!((p=_.get(c))!=null&&p.date)});if(b.length>0){const{data:c}=await T.from("dfs_contests").select("id, slate_date").in("id",b);c==null||c.forEach(p=>{const w=_.get(p.id);w&&!w.date&&p.slate_date&&(w.date=p.slate_date)})}const j=Array.from(_.values()).filter(c=>c.date);n(c=>c?{...c,totalContests:c.totalContests+j.length}:null);for(const c of j)try{if(!c.date){console.warn(`Skipping contest ${c.contest_id} - no date available`),n(w=>w?{...w,processedContests:w.processedContests+1,errors:[...w.errors,`${d.model_name} v${x.version_number} - Contest ${c.contest_id}: No slate_date found`]}:null);continue}const{error:p}=await hv("process-contest-learning",{contestId:c.contest_id,sport:c.sport,platform:c.platform,slateDate:c.date});if(p)throw p;n(w=>w?{...w,processedContests:w.processedContests+1,perfectLineupsCalculated:w.perfectLineupsCalculated+1,analysesGenerated:w.analysesGenerated+1,modelsUpdated:w.modelsUpdated+1}:null)}catch(p){n(w=>w?{...w,processedContests:w.processedContests+1,errors:[...w.errors,`${d.model_name} v${x.version_number} - Contest ${c.contest_id}: ${p.message}`]}:null)}n(c=>c?{...c,processedVersions:c.processedVersions+1}:null)}n(x=>x?{...x,processedModels:x.processedModels+1}:null)}K.success("Model learning backfill completed")}catch(o){K.error(`Backfill failed: ${o.message}`),console.error("Error during backfill:",o)}finally{a(!1)}},m=t&&t.totalContests>0?Math.round(t.processedContests/t.totalContests*100):0;return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-5 w-5"}),"Backfill DFS Model Learning"]}),e.jsx(De,{children:"Process all DFS model versions against their historical contests to generate learning data"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{className:"border-yellow-500 bg-yellow-500/10",children:[e.jsx(ls,{className:"h-4 w-4 text-yellow-600"}),e.jsx(pa,{className:"text-yellow-700",children:"⚠️ AI Learning Impact"}),e.jsxs(ts,{className:"text-yellow-700",children:["Running this with ",e.jsx("strong",{children:"incorrect historical results will teach AI models bad patterns"}),". Ensure all DFS results data is accurate and perfect lineups are calculated before running."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Filter by Sport"}),e.jsxs(oe,{value:r,onValueChange:i,disabled:s,children:[e.jsx(de,{className:"w-48",children:e.jsx(ue,{})}),e.jsx(me,{children:mv.map(o=>e.jsx(V,{value:o,children:o==="all"?"All Sports":o.charAt(0).toUpperCase()+o.slice(1)},o))})]})]}),e.jsx(R,{onClick:l,disabled:s,className:"w-full",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Backfill..."]}):"Run Model Learning Backfill"}),t&&e.jsxs("div",{className:"space-y-3",children:[s&&t.currentModel&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Processing: ",e.jsx("strong",{children:t.currentModel})," ",t.currentVersion]}),t.totalContests>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Overall Progress"}),e.jsxs("span",{children:[m,"%"]})]}),e.jsx(Ct,{value:m})]}),e.jsx(ss,{children:e.jsx(ts,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:["Models: ",t.processedModels," / ",t.totalModels]})]}),e.jsxs("div",{className:"text-sm space-y-1 pl-6",children:[e.jsxs("div",{children:["Versions processed: ",t.processedVersions," / ",t.totalVersions]}),e.jsxs("div",{children:["Contests processed: ",t.processedContests," / ",t.totalContests]}),e.jsxs("div",{children:["Perfect lineups calculated: ",t.perfectLineupsCalculated]}),e.jsxs("div",{children:["Analyses generated: ",t.analysesGenerated]}),e.jsxs("div",{children:["Models updated: ",t.modelsUpdated]})]})]})})}),t.errors.length>0&&e.jsx(ss,{variant:"destructive",children:e.jsxs(ts,{children:[e.jsxs("div",{className:"font-medium mb-2",children:["Errors (",t.errors.length,"):"]}),e.jsx("div",{className:"max-h-32 overflow-y-auto space-y-1 text-xs",children:t.errors.map((o,h)=>e.jsx("div",{children:o},h))})]})})]})]})]})},gv=()=>{const[s,a]=v.useState(!1),[t,n]=v.useState(null),r=async()=>
314{a(!0),n({totalCombinations:0,processedCount:0,successfulCount:0,errors:[],results:[]});try{const{data:i,error:l}=await T.from("model_performance_results").select("model_id, sport").not("model_id","is",null).not("sport","is",null).eq("result_type","betting");if(l)throw l;const{data:m,error:o}=await T.from("user_ai_models").select("id, model_name, sport").eq("model_type","betting");if(o)throw o;const h=(m==null?void 0:m.map(u=>u.id))||[],{data:N,error:d}=await T.from("user_ai_model_versions").select("id, model_id, version_number").in("model_id",h);if(d)throw d;const y=[];N==null||N.forEach(u=>{const x=m==null?void 0:m.find(g=>g.id===u.model_id);x&&y.push({modelId:u.model_id,modelVersionId:u.id,sport:x.sport,label:`${x.model_name} v${u.version_number} (${x.sport})`})}),m==null||m.forEach(u=>{y.push({modelId:u.id,modelVersionId:null,sport:u.sport,label:`${u.model_name} aggregate (${u.sport})`})}),n(u=>u?{...u,totalCombinations:y.length}:null);for(const u of y)try{const{data:x,error:g}=await T.functions.invoke("process-betting-learning",{body:{modelId:u.modelId,modelVersionId:u.modelVersionId,sport:u.sport}});if(g)throw g;n(f=>f?{...f,processedCount:f.processedCount+1,successfulCount:f.successfulCount+1,results:[...f.results,`${u.label}: ${(x==null?void 0:x.message)||"Success"}`]}:null)}catch(x){n(g=>g?{...g,processedCount:g.processedCount+1,errors:[...g.errors,`${u.label}: ${x.message}`]}:null)}K.success("Betting learning backfill completed")}catch(i){K.error(`Backfill failed: ${i.message}`),console.error("Error during backfill:",i)}finally{a(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"h-5 w-5"}),"Backfill Betting Learning"]}),e.jsx(De,{children:"Process historical betting data to train AI models (analyzes patterns and generates improvement suggestions)"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{className:"border-yellow-500 bg-yellow-500/10",children:[e.jsx(ls,{className:"h-4 w-4 text-yellow-600"}),e.jsx(pa,{className:"text-yellow-700",children:"⚠️ AI Learning Impact"}),e.jsxs(ts,{className:"text-yellow-700",children:["Running this with ",e.jsx("strong",{children:"incorrect betting results will teach AI models bad patterns"}),". Ensure all betting historical data and game results are accurate before running."]})]}),e.jsx(R,{onClick:r,disabled:s,className:"w-full",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Backfill..."]}):"Run Betting Learning Backfill"}),t&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ss,{children:e.jsx(ts,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:["Processed: ",t.processedCount," / ",t.totalCombinations]})]}),e.jsx("div",{className:"text-sm",children:e.jsxs("div",{children:["Successful: ",t.successfulCount]})})]})})}),t.results.length>0&&e.jsx(ss,{children:e.jsxs(ts,{children:[e.jsx("div",{className:"font-medium mb-2",children:"Results:"}),e.jsx("div",{className:"max-h-32 overflow-y-auto space-y-1 text-xs",children:t.results.map((i,l)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(rs,{className:"h-3 w-3 text-green-600"}),i]},l))})]})}),t.errors.length>0&&e.jsx(ss,{variant:"destructive",children:e.jsxs(ts,{children:[e.jsxs("div",{className:"font-medium mb-2",children:["Errors (",t.errors.length,"):"]}),e.jsx("div",{className:"max-h-32 overflow-y-auto space-y-1 text-xs",children:t.errors.map((i,l)=>e.jsx("div",{children:i},l))})]})})]})]})]})};function jv(){const{toast:s}=Ws(),[a,t]=v.useState(!1),[n,r]=v.useState(null),i=async()=>{t(!0),r(null);try{const{data:l,error:m}=await T.functions.invoke("backfill-learning-patterns");if(m)throw m;if(l!=null&&l.success&&(l!=null&&l.stats))r(l.stats),s({title:"Pattern Backfill Complete",description:`Updated ${l.stats.updated} records and re-processed ${l.stats.reprocessedContexts} contexts.`});else throw new Error((l==null?void 0:l.error)||"Unknown error occurred")}catch(l){s({title:"Backfill Failed",description:l.message,variant:"destructive"})}finally{t(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"h-5 w-5"}),"Fix Learning Pattern Suggestions"]}),e.jsx(De,{children:"Regenerate pattern-based improvement suggestions and update model learning contexts (removes player names from suggestions)"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{className:"border-blue-500 bg-blue-500/10",children:[e.jsx(Ys,{className:"h-4 w-4 text-blue-600"}),e.jsxs(ts,{className:"text-blue-700",children:[e.jsx("strong",{children:"🟡 Caution:"})," This tool regenerates AI improvement suggestions based on learned patterns. It removes player names from suggestions and re-processes learning contexts. Only run if suggestions need to be updated or fixed."]})]}),e.jsxs(R,{onClick:i,disabled:a,className:"w-full",children:[a&&e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Processing...":"Run Pattern Fix"]}),n&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"p-4 bg-muted rounded-lg space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Results:"}),e.jsxs("div",{className:"space-y-1.5 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:["Total Records: ",n.totalRecords]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:["Records Updated: ",n.updated]})]}),e.jsx("div",{className:"flex items-center gap-2 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:["Records Skipped: ",n.skipped]})}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:["Contexts Re-processed: ",n.reprocessedContexts,"/",n.contextsToReprocess]})]})]})]}),n.reprocessErrors&&n.reprocessErrors.length>0&&e.jsxs("div",{className:"p-4 bg-destructive/10 rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive mb-2",children:["Re-processing Errors (",n.reprocessErrors.length,"):"]}),e.jsx("div",{className:"space-y-1 max-h-40 overflow-y-auto",children:n.reprocessErrors.map((l,m)=>e.jsxs("div",{className:"text-xs text-destructive/80",children:[l.modelId," (",l.sport,"/",l.platform,"): ",l.error]},m))})]})]})]})]})}function fv(){const{toast:s}=Ws(),[a,t]=v.useState(!1),[n,r]=v.useState(null),i=async()=>{t(!0),r(null);try{const{data:l,error:m}=await T.functions.invoke("cleanup-learning-positions");
314if(m)throw m;if(l!=null&&l.success&&(l!=null&&l.stats))r(l.stats),s({title:"Position Cleanup Complete",description:`Cleaned ${l.stats.positionGapsCleaned} records with roster slots and re-processed ${l.stats.reprocessedContexts} contexts.`});else throw new Error((l==null?void 0:l.error)||"Unknown error occurred")}catch(l){s({title:"Cleanup Failed",description:l.message,variant:"destructive"})}finally{t(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Xd,{className:"h-5 w-5"}),"Cleanup Learning Position Data"]}),e.jsx(De,{children:"Remove roster slots (FLEX, CPT, UTIL, ANY) from position analysis and regenerate improvement prompts"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{className:"border-yellow-500 bg-yellow-500/10",children:[e.jsx(ls,{className:"h-4 w-4 text-yellow-600"}),e.jsxs(ts,{className:"text-yellow-700",children:[e.jsx("strong",{children:"🟡 Caution:"})," This tool cleans historical position data that incorrectly stored roster slots (FLEX, CPT, UTIL, ANY) as player positions. It will update position_gaps, regenerate improvement_suggestions, and re-process all learning contexts."]})]}),e.jsxs(R,{onClick:i,disabled:a,className:"w-full",children:[a&&e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Cleaning...":"Run Position Cleanup"]}),n&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"p-4 bg-muted rounded-lg space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Results:"}),e.jsxs("div",{className:"space-y-1.5 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:["Total Records Processed: ",n.totalRecords]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:["Records Updated: ",n.updated]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:["Position Gaps Cleaned: ",n.positionGapsCleaned]})]}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:e.jsxs("span",{children:["Records Skipped (no changes): ",n.skipped]})}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-600"}),e.jsxs("span",{children:["Contexts Re-processed: ",n.reprocessedContexts,"/",n.contextsToReprocess]})]})]})]}),n.reprocessErrors&&n.reprocessErrors.length>0&&e.jsxs("div",{className:"p-4 bg-destructive/10 rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive mb-2",children:["Re-processing Errors (",n.reprocessErrors.length,"):"]}),e.jsx("div",{className:"space-y-1 max-h-40 overflow-y-auto",children:n.reprocessErrors.map((l,m)=>e.jsxs("div",{className:"text-xs text-destructive/80",children:[l.modelId.slice(0,8),"... (",l.sport,"/",l.platform,"): ",l.error]},m))})]})]})]})]})}function vv(){const[s,a]=v.useState(!1),[t,n]=v.useState(null),r=async()=>{a(!0),n(null);try{console.log("Starting duplicate cleanup...");const{data:i,error:l}=await T.from("model_performance_results").select("lineup_id").not("lineup_id","is",null);if(l)throw l;const m=new Map;i==null||i.forEach(g=>{const f=g.lineup_id;m.has(f)||m.set(f,[]),m.get(f).push(g.lineup_id)});const o=Array.from(m.entries()).filter(([g,f])=>f.length>1);console.log(`Found ${o.length} lineups with duplicates`);const{data:h,error:N}=await T.from("model_performance_results").select("bet_id").not("bet_id","is",null);if(N)throw N;const d=new Map;h==null||h.forEach(g=>{const f=g.bet_id;d.has(f)||d.set(f,[]),d.get(f).push(g.bet_id)});const y=Array.from(d.entries()).filter(([g,f])=>f.length>1);console.log(`Found ${y.length} bets with duplicates`);let u=0;for(const[g]of o){const{data:f}=await T.from("model_performance_results").select("id, created_at").eq("lineup_id",g).order("created_at",{ascending:!0});if(f&&f.length>1){const _=f.slice(1).map(b=>b.id),{error:k}=await T.from("model_performance_results").delete().in("id",_);if(k)throw console.error(`Error deleting duplicates for lineup ${g}:`,k),k;u+=_.length,console.log(`Deleted ${_.length} duplicate(s) for lineup ${g}`)}}for(const[g]of y){const{data:f}=await T.from("model_performance_results").select("id, created_at").eq("bet_id",g).order("created_at",{ascending:!0});if(f&&f.length>1){const _=f.slice(1).map(b=>b.id),{error:k}=await T.from("model_performance_results").delete().in("id",_);if(k)throw console.error(`Error deleting duplicates for bet ${g}:`,k),k;u+=_.length,console.log(`Deleted ${_.length} duplicate(s) for bet ${g}`)}}const x=`Cleanup complete! Deleted ${u} duplicate records.
315
316Lineups with duplicates: ${o.length}
317Bets with duplicates: ${y.length}`;n(x),K.success("Duplicate cleanup completed"),console.log(x)}catch(i){console.error("Error during cleanup:",i),K.error(`Cleanup failed: ${i.message}`),n(`Error: ${i.message}`)}finally{a(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-5 w-5"}),"Cleanup Duplicate Performance Records"]}),e.jsx(De,{children:"Remove duplicate entries in model_performance_results table (keeps oldest record per lineup/bet)"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{variant:"destructive",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsx(pa,{children:"🔴 Destructive Operation"}),e.jsxs(ts,{children:["This will ",e.jsx("strong",{children:"permanently delete"})," duplicate performance records, keeping only the oldest entry for each lineup_id and bet_id. This operation cannot be undone. After cleanup, you'll need to add unique indexes via SQL to prevent future duplicates."]})]}),t&&e.jsx(ss,{children:e.jsx(ts,{className:"whitespace-pre-wrap font-mono text-sm",children:t})}),e.jsx(R,{onClick:r,disabled:s,className:"w-full",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Cleaning up duplicates..."]}):"Run Cleanup"}),t&&!s&&e.jsx(ss,{children:e.jsxs(ts,{children:[e.jsx("strong",{children:"Next step:"})," Run this SQL in the Supabase SQL Editor to add unique indexes:",e.jsx("pre",{className:"mt-2 p-2 bg-muted rounded text-xs overflow-x-auto",children:`-- Prevent future duplicates for lineups
318CREATE UNIQUE INDEX idx_unique_lineup_performance 
319ON model_performance_results(lineup_id) 
320WHERE lineup_id IS NOT NULL;
321
322-- Prevent future duplicates for bets
323CREATE UNIQUE INDEX idx_unique_bet_performance 
324ON model_performance_results(bet_id) 
325WHERE bet_id IS NOT NULL;`})]})})]})]})}const yv=()=>{const[s,a]=v.useState(!1),[t,n]=v.useState(!1),[r,i]=v.useState(null),[l,m]=v.useState([]),o=async()=>{a(!0);try{const{data:N,error:d}=await T.from("model_performance_results").select("id, lineup_id").not("lineup_id","is",null).is("lineup_set_id",null).eq("result_type","fantasy");if(d)throw d;if(!N||N.length===0){i(0),m([]),K.info("No individual performance records foun
325d");return}const y=N.map(_=>_.lineup_id).filter(Boolean),{data:u,error:x}=await T.from("dfs_generated_lineups").select("id").in("id",y).not("lineup_set_id","is",null);if(x)throw x;const g=new Set((u==null?void 0:u.map(_=>_.id))||[]),f=N.filter(_=>_.lineup_id&&g.has(_.lineup_id));i(f.length),m(f.map(_=>_.id)),f.length>0?K.warning(`Found ${f.length} orphaned individual records that belong to multi-lineup sets`):K.success("No orphaned records found - data is clean!")}catch(N){console.error("Scan error:",N),K.error("Failed to scan for orphaned records")}finally{a(!1)}},h=async()=>{if(l.length===0){K.info("No orphaned records to delete");return}n(!0);try{let N=0;for(let d=0;d<l.length;d+=100){const y=l.slice(d,d+100),{error:u}=await T.from("model_performance_results").delete().in("id",y);if(u)throw u;N+=y.length}K.success(`Deleted ${N} orphaned performance records`),i(0),m([])}catch(N){console.error("Delete error:",N),K.error("Failed to delete orphaned records")}finally{n(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(os,{className:"h-5 w-5"}),"Cleanup Orphaned Performance Records"]}),e.jsx(De,{children:"Remove individual performance records that belong to multi-lineup sets. These should only have set-level records, not per-lineup records."})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{children:[e.jsx(xs,{className:"h-4 w-4"}),e.jsx(ts,{children:"This fixes the issue where multi-lineup DFS sets show incorrect win counts (e.g., 0W-19L instead of 1W-1L) due to orphaned individual records."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(R,{variant:"outline",onClick:o,disabled:s||t,children:[e.jsx(Rs,{className:"mr-2 h-4 w-4"}),s?"Scanning...":"Scan for Orphans"]}),r!==null&&r>0&&e.jsxs(R,{variant:"destructive",onClick:h,disabled:s||t,children:[e.jsx(os,{className:"mr-2 h-4 w-4"}),t?"Deleting...":`Delete ${r} Orphans`]})]}),r!==null&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r===0?"✓ No orphaned records found":`Found ${r} orphaned individual records to clean up`})]})]})};function Nv(){const{toast:s}=Ws(),[a,t]=v.useState(!1),[n,r]=v.useState(null),i=async()=>{t(!0),r(null);try{const{data:l,error:m}=await T.functions.invoke("migrate-legacy-configs");if(m)throw m;l.success&&(r(l),s({title:"Migration Complete",description:`Successfully migrated ${l.migrated} model configs to the new format. ${l.skipped} were already up to date.`}))}catch(l){s({title:"Migration Failed",description:l.message||"Failed to migrate configs",variant:"destructive"})}finally{t(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-5 w-5"}),"Migrate Legacy AI Model Configs"]}),e.jsx(De,{children:"Update all legacy AI model configurations to the new format, including V3 strategy allocations with explicit lineup counts per strategy."})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(R,{onClick:i,disabled:a,className:"w-full",children:[a&&e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Migrating...":"Run Migration"]}),n&&e.jsxs("div",{className:"p-4 bg-muted rounded-lg space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Migration Results:"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total Versions:"}),e.jsx("span",{className:"ml-2 font-medium text-foreground",children:n.total})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Migrated:"}),e.jsx("span",{className:"ml-2 font-medium text-foreground",children:n.migrated})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Skipped:"}),e.jsx("span",{className:"ml-2 font-medium text-foreground",children:n.skipped})]})]})]})]})]})}const _v=[{value:"all",label:"All Sports"},{value:"football",label:"Football"},{value:"basketball",label:"Basketball"},{value:"baseball",label:"Baseball"},{value:"hockey",label:"Hockey"},{value:"soccer",label:"Soccer"}],bv=[{value:"all",label:"All Platforms"},{value:"draftkings",label:"DraftKings"},{value:"fanduel",label:"FanDuel"}],vi={source_accuracy:As,player_bias:hs,position_pattern:Ds,salary_pattern:La},yi={signal:{label:"Signal",icon:ra,className:"bg-muted text-muted-foreground"},up_trend:{label:"↑ Up Trend",icon:Ds,className:"bg-green-500 text-white"},down_trend:{label:"↓ Down Trend",icon:qt,className:"bg-red-500 text-white"},pattern:{label:"Pattern",icon:_t,className:"bg-blue-500 text-white"},established:{label:"Established",icon:rs,className:"bg-purple-600 text-white"}},Ni={low:{label:"Low",className:"bg-muted text-muted-foreground border"},medium:{label:"Medium",className:"bg-yellow-500 text-black"},high:{label:"High",className:"bg-green-600 text-white"}};function wv(){const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState(!1),[l,m]=v.useState(!1),{toast:o}=Ws(),{data:h,isLoading:N,refetch:d}
325=ge({queryKey:["data-learning-patterns",s,t],queryFn:async()=>{let C=T.from("data_learning_patterns").select("*").order("impact_grade",{ascending:!1}).order("status").order("sample_size",{ascending:!1});s!=="all"&&(C=C.eq("sport",s)),t!=="all"&&(C=C.eq("platform",t));const{data:O,error:$}=await C;if($)throw $;return O}}),{data:y}=ge({queryKey:["data-learning-last-updated",s,t],queryFn:async()=>{var z;let C=T.from("data_learning_patterns").select("last_updated").order("last_updated",{ascending:!1}).limit(1);s!=="all"&&(C=C.eq("sport",s)),t!=="all"&&(C=C.eq("platform",t));const{data:O,error:$}=await C;if($)throw $;return(z=O==null?void 0:O[0])==null?void 0:z.last_updated}}),u=["football","basketball","hockey","baseball","soccer","mma"],x=["football","basketball","hockey"],g=["source_accuracy","position_pattern","salary_pattern"],f=["draftkings","fanduel"],_={source_accuracy:"Source Accuracy",player_bias:"Player Bias",position_pattern:"Position Patterns",salary_pattern:"Salary Patterns"},k={football:["QB","RB","WR","TE","K","DST"],basketball:["PG","SG","SF","PF","C"],hockey:["C","W","LW","RW","D","G"]},[b,j]=v.useState(""),c=async()=>{i(!0);try{const C=s==="all"?u:[s],O=C.reduce((z,D)=>{if(x.includes(D)){const A=k[D]||[];return z+g.length*f.length+A.length}return z+1},0);let $=0;for(const z of C)if(x.includes(z)){const D=k[z]||[];for(const A of g)for(const F of f){$++,j(`${z} - ${_[A]} (${F}) (${$}/${O})`);const{error:q}=await T.functions.invoke("process-data-learning",{body:{sport:z,platform:F,phase:A,triggerSource:"manual"}});q&&console.error(`Error processing ${z} ${A} ${F}:`,q),await new Promise(E=>setTimeout(E,1500))}for(const A of D){$++,j(`${z} - Player Bias (${A}) (${$}/${O})`);const{error:F}=await T.functions.invoke("process-data-learning",{body:{sport:z,platform:t==="all"?void 0:t,phase:"player_bias",position:A,triggerSource:"manual"}});F&&console.error(`Error processing ${z} player_bias ${A}:`,F),await new Promise(q=>setTimeout(q,1500))}}else{$++,j(`${z} (${$}/${O})`);const{error:D}=await T.functions.invoke("process-data-learning",{body:{sport:z,platform:t==="all"?void 0:t,triggerSource:"manual"}});D&&console.error(`Error processing ${z}:`,D),await new Promise(A=>setTimeout(A,2e3))}j(""),o({title:"Processing Complete",description:`Data learning finished for ${s==="all"?"all sports":s}.`}),setTimeout(()=>{d(),i(!1)},5e3)}catch(C){console.error("Error processing data learning:",C),o({title:"Error",description:C.message||"Failed to process data learning",variant:"destructive"}),j(""),i(!1)}},p=(h==null?void 0:h.reduce((C,O)=>{const $=O.pattern_type;return C[$]||(C[$]=[]),C[$].push(O),C},{}))||{},w={total:(h==null?void 0:h.length)||0,byStatus:{signal:(h==null?void 0:h.filter(C=>C.status==="signal").length)||0,up_trend:(h==null?void 0:h.filter(C=>C.status==="up_trend").length)||0,down_trend:(h==null?void 0:h.filter(C=>C.status==="down_trend").length)||0,pattern:(h==null?void 0:h.filter(C=>C.status==="pattern").length)||0,established:(h==null?void 0:h.filter(C=>C.status==="established").length)||0},byImpact:{high:(h==null?void 0:h.filter(C=>C.impact_grade==="high").length)||0,medium:(h==null?void 0:h.filter(C=>C.impact_grade==="medium").length)||0,low:(h==null?void 0:h.filter(C=>C.impact_grade==="low").length)||0}},S=C=>{const O=yi[C]||yi.signal;return e.jsx(B,{className:`${O.className} text-xs`,children:O.label})},P=C=>{const O=Ni[C]||Ni.low;return e.jsx(B,{className:`${O.className} text-xs`,children:O.label})};return e.jsx(vs,{open:l,onOpenChange:m,children:e.jsxs(G,{children:[e.jsx(ys,{asChild:!0,children:e.jsx(je,{className:"cursor-pointer hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ns,{className:`h-5 w-5 text-muted-foreground transition-transform duration-200 ${l?"rotate-180":""}`}),e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-5 w-5"}),"Data Learning Patterns"]}),e.jsx(De,{children:"Rolling 10-contest analysis with dynamic status classification (Signal → Trend → Pattern → Established) and ±5pt threshold."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[w.total>0&&e.jsxs(B,{variant:"secondary",className:"text-xs",children:[w.total," patterns"]}),y&&e.jsxs(B,{variant:"outline",className:"text-xs text-muted-foreground",children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),al(y)]})]})]})})}),e.jsx(_s,{children:e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Sport"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-32",children:e.jsx(ue,{})}),e.jsx(me,{children:_v.map(C=>e.jsx(V,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Platform"}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-32",children:e.jsx(ue,{})}),e.jsx(me,{children:bv.map(C=>e.jsx(V,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs(R,{onClick:c,disabled:r,children:[r?e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tt,{className:"h-4 w-4 mr-2"}),r?b||"Processing...":"Refresh All Patterns"]})]}),h&&h.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Impact:"}),e.jsxs(B,{className:"bg-green-600 text-white",children:[w.byImpact.high," High"]}),e.jsxs(B,{className:"bg-yellow-500 text-black",children:[w.byImpact.medium," Medium"]}),e.jsxs(B,{variant:"outline",children:[w.byImpact.low," Low"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Status:"}),w.byStatus.established>0&&e.jsxs(B,{className:"bg-purple-600 text-white",children:[w.byStatus.established," Established"]}),w.byStatus.pattern>0&&e.jsxs(B,{className:"bg-blue-500 text-white",children:[w.byStatus.pattern," Pattern"]}),w.byStatus.up_trend>0&&e.jsxs(B,{className:"bg-green-500 text-white",children:[w.byStatus.up_trend," Up Trend"]}),w.byStatus.down_trend>0&&e.jsxs(B,{className:"bg-red-500 text-white",children:[w.byStatus.down_trend," Down Trend"]}),w.byStatus.signal>0&&e.jsxs(B,{variant:"outline",children:[w.byStatus.signal," Signal"]})]})]}),h&&h.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:Object.entries(p).map(([C,O])=>{const $=vi[C]||tt,z=O.filter(D=>D.impact_grade==="high").length;return e.jsxs(G,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx($,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium capitalize",children:C.replace("_"," ")})]}),e.jsx("div",{className:"text-2xl font-bold",children:O.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:z>0?`${z} high impact`:"patterns found"})]},C)})}),N?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading patterns..."}):h&&h.length>0?e.jsx("div",{className:"space-y-2",children:Object.entries(p).map(([C,O])=>{const $=vi[C]||tt,z=O.sort((D,A)=>{const F={high:0,medium:1,low:2},q={established:0,pattern:1,up_trend:2,down_trend:2,signal:3},E=(F[D.impact_grade]||2)-(F[A.impact_grade]||2);if(E!==0)return E;const L=(q[D.status]||3)-(q[A.status]||3);return L!==0?L:(A.sample_size||0)-(D.sample_size||0)});return e.jsxs(vs,{defaultOpen:!1,children:[e.jsx(ys,{className:"w-full",children:e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg hover:bg-muted/50 border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-semibold capitalize",children:C.replace("_"," ")}),e.jsx(B,{variant:"secondary",className:"ml-1",children:z.length})]}),e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground transition-transform duration-200"})]})}),e.jsx(_s,{children:e.jsx("div",{className:"space-y-1 py-2 pl-2",children:z.map(D=>e.jsxs("div",{className:"text-sm p-3 rounded bg-muted/50 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:"flex-1",children:D.insight_text}),D.pattern_type==="player_bias"&&D.play_type&&e.jsx(hd,{playType:D.play_type})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[S(D.status||"signal"),P(D.impact_grade||"low"),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["n=",D.sample_size]}),D.within_threshold_rate!=null?e.jsxs("span",{className:"text-xs text-muted-foreground",children:["| ",Math.round(D.within_threshold_rate*100),"% within ±5"]}):D.consistency_rate!==null&&D.consistency_rate!==void 0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["| ",Math.round(D.c
325onsistency_rate),"% consistent"]}),D.play_type==="consistent"&&D.max_under_projection!=null&&D.max_over_projection!=null&&e.jsxs("span",{className:"text-xs text-blue-400",children:["Floor: ",D.max_under_projection.toFixed(0)," | Ceil: +",D.max_over_projection.toFixed(0)]}),D.play_type==="boom_bust"&&D.volatility!=null&&e.jsxs("span",{className:"text-xs text-purple-400",children:["±",D.volatility.toFixed(1)," var"]})]})]},D.id))})})]},C)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No patterns found. Click "Refresh All Patterns" to analyze historical data.'})]})})]})})}function Sv(){const[s,a]=v.useState(!1),[t,n]=v.useState(!1),[r,i]=v.useState(null),[l,m]=v.useState([]),[o,h]=v.useState(0),[N,d]=v.useState(!1),[y,u]=v.useState(null),x=k=>{if(!k||k.length>200)return!1;const b=["trending","averaging","based on","probability","expected","projection","analysis","recent games","last 5","season average","matchup","favorable","recommend","confidence","edge"],j=k.toLowerCase();return b.filter(p=>j.includes(p)).length<2},g=async()=>{a(!0),u(null);try{const{data:k,error:b}=await T.functions.invoke("find-pending-bets");if(b)throw b;const j=(k==null?void 0:k.settleable)||[],c=(k==null?void 0:k.all_pending)||[],p=j.filter(S=>S.has_game_data&&x(S.selection)).map(S=>({id:S.id,selection:S.selection,sport:S.sport,bet_type:S.bet_type,created_at:S.created_at,has_game_data:S.has_game_data,source:S.source||"tracked_recommendation"})),w=c.filter(S=>!S.has_game_data).length;m(p),h(w),d(!0),p.length===0?K.info("No bets ready to settle (games may not be completed yet)"):K.success(`Found ${p.length} bet(s) ready to settle`)}catch(k){console.error("Error finding ready bets:",k),K.error("Failed to search for ready bets")}finally{a(!1)}},f=async()=>{n(!0),u(null);try{const{data:k,error:b}=await T.functions.invoke("auto-settle-bets");if(b)throw b;u(k);const j=((k==null?void 0:k.tracked_recommendations_settled)||0)+((k==null?void 0:k.parlays_settled)||0)+((k==null?void 0:k.user_bets_settled)||0);j>0?(K.success(`Successfully settled ${j} bet(s)`),await g()):K.info("No bets were settled (games may not be completed yet)")}catch(k){console.error("Error running auto-settle:",k),K.error("Failed to run auto-settle")}finally{n(!1)}},_=async k=>{i(k.id);try{const b=k.source==="user_bet"?"user_bets":"saved_betting_recommendations",j={result:"void",result_tracked:!0};k.source==="user_bet"&&(j.settlement_notes="Manually voided - stats unavailable");const{error:c}=await T.from(b).update(j).eq("id",k.id);if(c)throw c;K.success("Bet voided successfully"),m(p=>p.filter(w=>w.id!==k.id))}catch(b){console.error("Error voiding bet:",b),K.error("Failed to void bet")}finally{i(null)}};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-5 w-5"}),"Re-run Auto-Settle"]}),e.jsx(De,{className:"mt-1",children:"Settle pending bets that have complete game data and completed games"})]}),e.jsx(B,{variant:"outline",className:"bg-primary/10 text-primary border-primary/30",children:"Safe"})]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(R,{variant:"outline",onClick:g,disabled:s||t,children:s?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}),"Searching..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"h-4 w-4 mr-2"}),"Find Ready Bets"]})}),e.jsx(R,{onClick:f,disabled:s||t||N&&l.length===0,children:t?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}),"Settling..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 mr-2"}),"Run Auto-Settle"]})})]}),N&&o>0&&e.jsxs(ss,{className:"border-yellow-500/50 bg-yellow-500/10",children:[e.jsx(ls,{className:"h-4 w-4 text-yellow-400"}),e.jsxs(ts,{className:"text-yellow-200",children:[o," bet(s) cannot be settled - missing game data. Use ",e.jsx("strong",{children:"Bet Game Matcher"})," to fix them first."]})]}),N&&e.jsxs("div",{className:"border rounded-lg p-4 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Es,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{className:"font-medium",children:["Ready to Settle: ",l.length]})]}),l.length>0?e.jsxs("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:[l.slice(0,10).map(k=>{var b;return e.jsxs("div",{className:"text-sm p-2 bg-background rounded border flex items-center justify-between",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("span",{className:"font-medium block truncate",title:k.selection,children:k.selection.length>80?k.selection.substring(0,80)+"...":k.selection})}),e.jsxs("div",{className:"flex items-center gap-2 ml-2",children:[e.jsx(B,{variant:"secondary",className:"text-xs",children:(b=k.sport)==null?void 0:b.toUpperCase()}),e.jsx(B,{variant:"outline",className:"text-xs",children:k.bet_type}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",disabled:r===k.id,onClick:j=>{j.stopPropagation(),_(k)},title:"Void this bet",children:r===k.id?e.jsx(He,{className:"h-3 w-3 animate-spin"}):e.jsx(rt,{className:"h-4 w-4"})})]})]},k.id)}),l.length>10&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center pt-2",children:["... and ",l.length-10," more"]})]}):e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4"}
325),"No bets ready to settle (waiting for game completion or missing data)"]})]}),y&&e.jsxs("div",{className:"border rounded-lg p-4 bg-green-500/10 border-green-500/30",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Es,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"font-medium text-green-600",children:"Settlement Results"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Tracked Recs"}),e.jsx("div",{className:"font-semibold",children:y.tracked_recommendations_settled||0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Parlays"}),e.jsx("div",{className:"font-semibold",children:y.parlays_settled||0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"User Bets"}),e.jsx("div",{className:"font-semibold",children:y.user_bets_settled||0})]})]}),y.prop_bet_stats&&(y.prop_bet_stats.attempted>0||y.prop_bet_stats.settled>0)&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-border/50",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-2",children:"Prop Bets"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground text-xs",children:"Attempted"}),e.jsx("div",{className:"font-semibold",children:y.prop_bet_stats.attempted})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground text-xs",children:"Settled"}),e.jsx("div",{className:"font-semibold text-green-600",children:y.prop_bet_stats.settled})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground text-xs",children:"Skipped"}),e.jsx("div",{className:"font-semibold text-yellow-600",children:y.prop_bet_stats.skipped})]})]})]}),y.games_processed!==void 0&&e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Games processed: ",y.games_processed]}),y.errors&&y.errors.length>0&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-yellow-500/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-yellow-600",children:[e.jsx(xs,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Warnings"})]}),e.jsx("ul",{className:"text-xs text-muted-foreground mt-1 space-y-1",children:y.errors.slice(0,3).map((k,b)=>e.jsxs("li",{children:["• ",k]},b))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only shows bets with complete game data and completed games. Bets missing game data must be matched first using the Bet Game Matcher utility."})]})]})}function kv(){var b;const[s,a]=v.useState(!1),[t,n]=v.useState("all"),[r,i]=v.useState("Showdown"),l=Me(),{data:m,isLoading:o}=ge({queryKey:["discovered-patterns",t,r],queryFn:async()=>{let j=T.from("dfs_lineup_predictive_rules").select("*").order("match_percentage",{ascending:!1});t!=="all"&&(j=j.eq("sport",t)),r!=="all"&&(j=j.eq("contest_type",r));const{data:c,error:p}=await j;if(p)throw p;return c}}),{data:h}=ge({queryKey:["pattern-discovery-last-updated",t,r],queryFn:async()=>{var w;let j=T.from("dfs_lineup_predictive_rules").select("updated_at").order("updated_at",{ascending:!1}).limit(1);t!=="all"&&(j=j.eq("sport",t)),r!=="all"&&(j=j.eq("contest_type",r));const{data:c,error:p}=await j;if(p)throw p;return(w=c==null?void 0:c[0])==null?void 0:w.updated_at}}),N=_e({mutationFn:async j=>{const{data:c,error:p}=await T.functions.invoke("analyze-lineup-patterns",{body:{sport:t,contest_type:r,force_reanalyze:j}});if(p)throw p;return c},onSuccess:j=>{K.success(`Discovered ${j.hard_rules} hard rules, ${j.strong_rules} strong rules, ${j.conditional_rules} conditional from ${j.analyzed} lineups`),l.invalidateQueries({queryKey:["discovered-patterns"]})},onError:j=>{K.error(`Analysis failed: ${j.message}`)}}),d=(m==null?void 0:m.filter(j=>j.pattern_category==="hard_rule"))||[],y=(m==null?void 0:m.filter(j=>j.pattern_category==="strong_rule"))||[],u=(m==null?void 0:m.filter(j=>j.pattern_category==="composition"))||[],x=(m==null?void 0:m.filter(j=>j.pattern_category==="conditional"))||[],g=((b=m==null?void 0:m[0])==null?void 0:b.sample_size)||0,f=()=>{const j=[];return d.forEach(c=>{j.push(`✓ ${c.rule_description}`)}
325),y.filter(c=>c.match_percentage>=85).forEach(c=>{j.push(`◆ ${c.rule_description} (${c.match_percentage}%)`)}),j.length>0?j:['Click "Full Reanalysis" to discover patterns from perfect lineups']},_=j=>{switch(j){case"hard_rule":return"bg-green-500/20 text-green-400 border-green-500/50";case"strong_rule":return"bg-primary/20 text-primary border-primary/50";case"composition":return"bg-blue-500/20 text-blue-400 border-blue-500/50";case"conditional":return"bg-orange-500/20 text-orange-400 border-orange-500/50";default:return"bg-muted text-muted-foreground border-border"}},k=({rule:j})=>e.jsxs("div",{className:`flex items-center justify-between p-3 rounded-lg border ${j.pattern_category==="hard_rule"?"bg-green-500/5 border-green-500/30":"bg-muted/30 border-border"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[j.pattern_category==="hard_rule"?e.jsx(mt,{className:"h-4 w-4 text-green-400 shrink-0"}):j.pattern_category==="conditional"?e.jsx(ra,{className:"h-4 w-4 text-orange-400 shrink-0"}):e.jsx(rs,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:j.rule_description}),j.condition_field&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["When: ",j.condition_field," ",j.condition_operator," ",j.condition_value]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",className:_(j.pattern_category),children:[j.match_percentage,"%"]}),e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:["(",j.match_count,"/",j.sample_size,")"]})]})]});return e.jsx(vs,{open:s,onOpenChange:a,children:e.jsxs(G,{children:[e.jsx(ys,{asChild:!0,children:e.jsx(je,{className:"cursor-pointer hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ns,{className:`h-5 w-5 text-muted-foreground transition-transform duration-200 ${s?"rotate-180":""}`}),e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"h-5 w-5 text-primary"}),"Pattern Discovery"]}),e.jsx(De,{children:"Automatically discovers what ALL perfect lineups have in common"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[h&&e.jsxs(B,{variant:"outline",className:"text-xs text-muted-foreground",children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),ke(new Date(h),"MMM d, yyyy h:mm a")]}),g>0&&e.jsxs(B,{variant:"outline",className:"text-xs",children:[g," lineups analyzed"]})]})]})})}),e.jsx(_s,{children:e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Sport:"}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-32",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),e.jsx(V,{value:"football",children:"Football"}),e.jsx(V,{value:"basketball",children:"Basketball"}),e.jsx(V,{value:"baseball",children:"Baseball"}),e.jsx(V,{value:"hockey",children:"Hockey"}),e.jsx(V,{value:"soccer",children:"Soccer"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Type:"}),e.jsxs(oe,{value:r,onValueChange:i,children:[e.jsx(de,{className:"w-32",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Types"}),e.jsx(V,{value:"Showdown",children:"Showdown"}),e.jsx(V,{value:"Classic",children:"Classic"})]})]})]}),e.jsxs("div",{className:"flex gap-2 ml-auto",children:[e.jsxs(R,{variant:"outline",onClick:()=>N.mutate(!1),disabled:N.isPending,children:[N.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Analyze"]}),e.jsxs(R,{variant:"default",onClick:()=>N.mutate(!0),disabled:N.isPending,children:[N.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(He,{className:"h-4 w-4 mr-2"}),"Full Reanalysis"]})]})]}),o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):m&&m.length>0?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{className:"bg-green-500/5 border-green-500/30",children:[e.jsxs(je,{className:"pb-2",children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(Sr,{className:"h-4 w-4 text-green-400"}),"Predictive Formula (Hard + Strong Rules)"]}),e.jsx(De,{children:"These patterns appear in 85%+ of all perfect lineups"})]}),e.jsxs(J,{children:[e.jsx("ul",{className:"space-y-1.5",children:f().map((j,c)=>e.jsx("li",{className:"text-sm font-mono",children:j},c))}),e.jsx("div",{className:"mt-3 pt-3 border-t border-green-500/20",children:e.jsxs("span",{className:"text-xs text-muted-foreground",children:[d.length," hard rules (100%) + ",y.filter(j=>j.match_percentage>=85).length," strong rules (85%+) from ",g," perfect lineups"]})})]})]}),d.length>0&&e.jsxs(G,{className:"bg-green-500/5 border-green-500/20",children:[e.jsxs(je,{className:"pb-2",children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(mt,{className:"h-4 w-4 text-green-400"}),"Hard Rules (100% Match)"]}),e.jsx(De,{children:"These are NEVER violated - every perfect lineup follows these"})]}),e.jsx(J,{className:"space-y-2",children:d.map(j=>e.jsx(k,{rule:j},j.id))})]}),y.length>0&&e.jsxs(G,{className:"bg-muted/30",children:[e.jsxs(je,{className:"pb-2",children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(As,{className:"h-4 w-4 text-primary"}),"Strong Rules (80%+ Match)"]}),e.jsx(De,{children:"Follow the 80/20 rule - these patterns hold most of the time"})]}),e.jsx(J,{className:"space-y-2",children:y.map(j=>e.jsx(k,{rule:j},j.id))})]}),u.length>0&&e.jsxs(G,{className:"bg-muted/30",children:[e.jsxs(je,{className:"pb-2",children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4 text-blue-400"}),"FLEX Composition Patterns"]}),e.jsx(De,{children:"How the 5 FLEX spots are typically composed as a group"})]}),e.jsx(J,{className:"space-y-2",children:u.map(j=>e.jsx(k,{rule:j},j.id))})]}),x.length>0&&e.jsxs(G,{className:"bg-muted/30",children:[e.jsxs(je,{className:"pb-2",children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4 text-orange-400"}),"Conditional Rules (When X → Then Y)"]}),e.jsx(De,{children:"Patterns that apply when specific conditions are met"})]}),e.jsx(J,{className:"space-y-2",children:x.map(j=>e.jsx(k,{rule:j},j.id))})]})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ft,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No patterns discovered yet for the selected filters."}),e.jsx("p",{className:"text-sm mt-2",children:'Click "Full Reanalysis" to discover what ALL perfect lineups have in common.'})]})]})})]})})}function Cv(){var u;const[s,a]=v.useState(!1),[t,n]=v.useState(!1),[r,i]=v.useState([]),[l,m]=v.useState([]),[o,h]=v.useState(null),N=async()=>{var x,g;a(!0),h(null);try{const{data:f,error:_}=await T.functions.invoke("backfill-bet-structure",{body:{action:"find"}});if(_)throw _;i(f.legacyBets||[]),m(f.legacyRecommendations||[]);const k=(((x=f.legacyBets)==null?void 0:x.length)||0)+(((g=f.legacyRecommendations)==null?void 0:g.length)||0);K.success(`Found ${k} legacy bets/recommendations without game_id`)}catch(f){console.error("Error finding legacy bets:",f),K.error(`Failed to find legacy bets: ${f.message}`)}finally{a(!1)}},d=async()=>
325{if(r.length===0&&l.length===0){K.error('No legacy bets to backfill. Run "Find Legacy Bets" first.');return}n(!0),h(null);try{const{data:x,error:g}=await T.functions.invoke("backfill-bet-structure",{body:{action:"backfill",betIds:r.map(j=>j.id),recommendationIds:l.map(j=>j.id)}});if(g)throw g;h(x.results);const{betsUpdated:f,recsUpdated:_,betsSkipped:k,recsSkipped:b}=x.results;K.success(`Updated ${f} bets and ${_} recommendations. Skipped ${k+b}.`),i([]),m([])}catch(x){console.error("Error backfilling:",x),K.error(`Failed to backfill: ${x.message}`)}finally{n(!1)}},y=r.length+l.length;return e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-5 w-5"}),"Backfill Legacy Bet Structure"]}),e.jsx(De,{children:"Migrate old bets to use structured game_id, home_team, away_team, picked_side fields for reliable auto-settlement"})]}),e.jsx(B,{variant:"outline",className:"bg-yellow-500/10 text-yellow-600 border-yellow-500/30",children:"Caution"})]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs(ss,{children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsx(ts,{children:'This utility finds bets without game_id and attempts to match them to games using team names from selection and reasoning text. Both teams must match for a successful backfill. Run "Re-run Auto-Settle" after this completes.'})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(R,{onClick:N,disabled:s||t,variant:"outline",children:[s?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rs,{className:"h-4 w-4 mr-2"}),"Find Legacy Bets"]}),e.jsxs(R,{onClick:d,disabled:t||s||y===0,children:[t?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tt,{className:"h-4 w-4 mr-2"}),"Backfill Structure (",y,")"]})]}),y>0&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-4",children:[e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30",children:[e.jsx("div",{className:"text-sm font-medium",children:"Placed Bets"}),e.jsx("div",{className:"text-2xl font-bold",children:r.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Missing game_id"})]}),e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30",children:[e.jsx("div",{className:"text-sm font-medium",children:"Tracked Recommendations"}),e.jsx("div",{className:"text-2xl font-bold",children:l.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Missing game_id"})]})]}),o&&e.jsxs("div",{className:"mt-4 p-4 rounded-lg border bg-muted/20",children:[e.jsxs("h4",{className:"font-medium mb-3 flex items-center gap-2",children:[e.jsx(Es,{className:"h-4 w-4 text-green-500"}),"Backfill Results"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Bets Processed"}),e.jsx("div",{className:"font-medium",children:o.betsProcessed})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Bets Updated"}),e.jsx("div",{className:"font-medium text-green-600",children:o.betsUpdated})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Bets Skipped"}),e.jsx("div",{className:"font-medium text-yellow-600",children:o.betsSkipped})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Recs Processed"}),e.jsx("div",{className:"font-medium",children:o.recsProcessed})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Recs Updated"}),e.jsx("div",{className:"font-medium text-green-600",children:o.recsUpdated})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Recs Skipped"}),e.jsx("div",{className:"font-medium text-yellow-600",children:o.recsSkipped})]})]}),((u=o.errors)==null?void 0:u.length)>0&&e.jsxs("div",{className:"mt-3 text-xs text-destructive",children:[o.errors.length," errors occurred. Check console for details."]})]})]})]})}function Pv(){const[s,a]=v.useState(!1),[t,n]=v.useState("all"),[r,i]=v.useState("all"),l=Me(),{data:m,isLoading:o}=ge({queryKey:["betting-predictive-rules",t,r],queryFn:async()=>{let S=T.from("betting_predictive_rules").select("*").order("match_percentage",{ascending:!1});t!=="all"&&(S=S.eq("sport",t)),r!=="all"&&(S=S.eq("bet_type",r));const{data:P,error:C}=await S;if(C)throw C;return P}}),{data:h}=ge({queryKey:["betting-patterns-last-updated",t,r],queryFn:async()=>{var O;let S=T.from("betting_predictive_rules").select("updated_at").order("updated_at",{ascending:!1}).limit(1);t!=="all"&&(S=S.eq("sport",t)),r!=="all"&&(S=S.eq("bet_type",r));const{data:P,error:C}=await S;if(C)throw C;return(O=P==null?void 0:P[0])==null?void 0:O.updated_at}}),N=_e({mutationFn:async S=>{const{data:P,error:C}=await T.functions.invoke("analyze-betting-patterns",{body:{sport:t==="all"?null:t,force_reanalyze:S}});if(C)throw C;return P},onSuccess:S=>
325{l.invalidateQueries({queryKey:["betting-predictive-rules"]}),K.success(`Analysis complete: ${(S==null?void 0:S.rules_discovered)||0} patterns discovered`)},onError:S=>{K.error(`Analysis failed: ${S.message}`)}}),d=_e({mutationFn:async({ruleId:S,isActive:P})=>{const{error:C}=await T.from("betting_predictive_rules").update({is_active:P}).eq("id",S);if(C)throw C},onSuccess:()=>{l.invalidateQueries({queryKey:["betting-predictive-rules"]})},onError:S=>{K.error(`Failed to toggle rule: ${S.message}`)}}),y=_e({mutationFn:async S=>{const{error:P}=await T.from("betting_predictive_rules").update({is_active:S}).or("rule_name.ilike.%inverse%,rule_name.ilike.%fade%");if(P)throw P;return S},onSuccess:S=>{l.invalidateQueries({queryKey:["betting-predictive-rules"]}),K.success(S?"All inverse rules enabled":"All inverse rules disabled")},onError:S=>{K.error(`Failed to toggle inverse rules: ${S.message}`)}}),u=(m==null?void 0:m.filter(S=>S.is_active))||[],x=(m==null?void 0:m.filter(S=>!S.is_active))||[],g=(m==null?void 0:m.filter(S=>S.rule_name.toLowerCase().includes("inverse")||S.rule_name.toLowerCase().includes("fade")))||[],f=g.filter(S=>S.is_active).length,_=u.filter(S=>S.pattern_category==="hard_rule"),k=u.filter(S=>S.pattern_category==="strong_rule"),b=u.filter(S=>S.pattern_category==="conditional"),j=(S,P)=>{if(!P)return"bg-muted/50 text-muted-foreground border-muted opacity-60";switch(S){case"hard_rule":return"bg-green-500/20 text-green-400 border-green-500/30";case"strong_rule":return"bg-primary/20 text-primary border-primary/30";case"conditional":return"bg-orange-500/20 text-orange-400 border-orange-500/30";default:return"bg-muted text-muted-foreground"}},c=S=>{switch(S){case"hard_rule":return e.jsx(mt,{className:"h-4 w-4"});case"strong_rule":return e.jsx(As,{className:"h-4 w-4"});case"conditional":return e.jsx(ra,{className:"h-4 w-4"});default:return null}},p=S=>S.toLowerCase().includes("inverse")||S.toLowerCase().includes("fade"),w=({rule:S})=>e.jsxs("div",{className:`p-3 rounded-lg border ${j(S.pattern_category,S.is_active)}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[c(S.pattern_category),e.jsx("span",{className:"font-medium text-sm",children:S.rule_name}),p(S.rule_name)&&e.jsxs(B,{variant:"outline",className:"text-xs bg-destructive/10 text-destructive border-destructive/30",children:[e.jsx(ls,{className:"h-3 w-3 mr-1"}),"Inverse"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",className:"text-xs",children:[S.match_percentage.toFixed(1),"%"]}),e.jsx(Ge,{checked:S.is_active,onCheckedChange:P=>d.mutate({ruleId:S.id,isActive:P}),disabled:d.isPending})]})]}),e.jsx("p",{className:"text-xs mt-2 opacity-80",children:S.rule_description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 text-xs opacity-60",children:[e.jsxs("span",{children:["Sample: ",S.sample_size]}),e.jsx("span",{children:"•"}),e.jsx("span",{className:"uppercase",children:S.sport}),e.jsx("span",{children:"•"}),e.jsx("span",{className:"capitalize",children:S.bet_type}),!S.is_active&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-destructive",children:"Disabled"})]})]})]});return e.jsx(vs,{open:s,onOpenChange:a,children:e.jsxs(G,{children:[e.jsx(ys,{asChild:!0,children:e.jsx(je,{className:"cursor-pointer hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ns,{className:`h-5 w-5 text-muted-foreground transition-transform duration-200 ${s?"rotate-180":""}`}),e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"h-5 w-5"}),"Betting Pattern Discovery"]}),e.jsx(De,{children:"Analyze historical betting data to discover predictive patterns for AI models"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g.length>0&&e.jsxs(B,{variant:f>0?"destructive":"secondary",className:"text-xs",children:[f,"/",g.length," Inverse Active"]}),h&&e.jsxs(B,{variant:"outline",className:"text-xs text-muted-foreground",children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),ke(new Date(h),"MMM d, yyyy h:mm a")]})]})]})})}),e.jsx(_s,{children:e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3 items-center",children:[e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),e.jsx(V,{value:"football",children:"Football"}),e.jsx(V,{value:"basketball",children:"Basketball"}),e.jsx(V,{value:"baseball",children:"Baseball"}),e.jsx(V,{value:"hockey",children:"Hockey"}),e.jsx(V,{value:"soccer",children:"Soccer"})]})]}),e.jsxs(oe,{value:r,onValueChange:i,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{placeholder:"Bet Type"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Types"}),e.jsx(V,{value:"moneyline",children:"Moneyline"}),e.jsx(V,{value:"spread",children:"Spread"}),e.jsx(V,{value:"totals",children:"Totals"})]})]}),e.jsxs(R,{onClick:()=>N.mutate(!1),disabled:N.isPending,size:"sm",children:[N.isPending?e.jsx(ne,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(He,{className:"h-4 w-4 mr-2"}),"Analyze"]}),e.jsx(R,{onClick:()=>N.mutate(!0),disabled:N.isPending,variant:"outline",size:"sm",children:"Full Reanalysis"}),g.length>0&&e.jsx("div",{className:"ml-auto flex items-center gap-2",children:e.jsxs(R,{onClick:()=>y.mutate(f===0),disabled:y.isPending,variant:f>0?"destructive":"secondary",size:"sm",children:[e.jsx(yl,{className:"h-4 w-4 mr-2"}),f>0?"Disable All Inverse":"Enable All Inverse"]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border",children:[e.jsx("div",{className:"text-2xl font-bold",children:u.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Rules"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border",children:[e.jsx("div",{className:"text-2xl font-bold text-muted-foreground",children:x.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disabled Rules"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-destructive/10 border border-destructive/30",children:[e.jsx("div",{className:"text-2xl font-bold text-destructive",children:f}),e.jsx("div",{className:"text-xs text-destructive/80",children:"Active Inverse Rules"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border",children:[e.jsx("div",{className:"text-2xl font-bold",children:g.length-f}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disabled Inverse Rules"})]})]}),o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):m&&m.length>0?e.jsxs("div",{className:"space-y-4",children:[_.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(mt,{className:"h-4 w-4 text-green-400"}),"Hard Rules (",_.length,")",e.jsx("span",{className:"text-xs text-muted-foreground",children:"65%+ consistency"})]}),e.jsx("div",{className:"grid gap-2",children:_.map(S=>e.jsx(w,{rule:S},S.id))})]}),k.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(As,{className:"h-4 w-4 text-primary"}),"Strong Rules (",k.length,")",e.jsx("span",{className:"text-xs text-muted-foreground",children:"58-65% consistency"})]}),e.jsx("div",{className:"grid gap-2",children:k.map(S=>e.jsx(w,{rule:S},S.id))})]}),b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4 text-orange-400"}),"Conditional Rules (",b.length,")",e.jsx("span",{className:"text-xs text-muted-foreground",children:"Context-dependent"})]}),e.jsx("div",{className:"grid gap-2",children:b.map(S=>e.jsx(w,{rule:S},S.id))})]}),x.length>0&&e.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2 text-muted-foreground",children:[e.jsx(yl,{className:"h-4 w-4"}),"Disabled Rules (",x.length,")"]}),e.jsx("div",{className:"grid gap-2",children:x.map(S=>e.jsx(w,{rule:S},S.id))})]})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No patterns discovered yet."}),e.jsx("p",{className:"text-sm",children:'Click "Full Reanalysis" to analyze historical betting data.'})]})]})})]})})}const _i=[{value:"team-roster",label:"Team Roster (Players)",requiredFields:["teamId"],description:"Get all players for a team"},{value:"team-details",label:"Team Details",requiredFields:["teamId"],description:"Get team info"},{value:"team-image",label:"Team Image",requiredFields:["teamId"],description:"Get team logo"},{value:"player-details",label:"Player Details",requiredFields:["playerId"],description:"Get player info"},{value:"player-stats",label:"Player Career Stats",requiredFields:["playerId"],description:"Get player career statistics"},{value:"player-image",label:"Player Image",requiredFields:["playerId"],description:"Get player photo"},{value:"event-details",label:"Event Details",requiredFields:["eventId"],description:"Get game/event info"},{value:"event-lineups",label:"Event Lineups",requiredFields:["eventId"],description:"Get player lineups for a game"},{value:"event-statistics",label:"Event Statistics",requiredFields:["eventId"],description:"Get game statistics"}
325,{value:"event-player-stats",label:"Event Player Stats",requiredFields:["eventId","playerId"],description:"Get player stats for specific game"},{value:"event-incidents",label:"Event Incidents",requiredFields:["eventId"],description:"Get game incidents (goals, cards, etc.)"},{value:"sport-schedule",label:"Sport Schedule",requiredFields:["sport","date"],description:"Get scheduled events for a sport"},{value:"sport-categories",label:"Sport Categories",requiredFields:["sport"],description:"Get leagues/categories for a sport"},{value:"sport-live",label:"Sport Live Events",requiredFields:["sport"],description:"Get live games for a sport"},{value:"category-tournaments",label:"Category Tournaments",requiredFields:["categoryId"],description:"Get tournaments in a category"},{value:"tournament-seasons",label:"Tournament Seasons",requiredFields:["tournamentId"],description:"Get seasons for a tournament"},{value:"tournament-standings",label:"Tournament Standings",requiredFields:["tournamentId","seasonId"],description:"Get standings for a season"},{value:"tournament-teams",label:"Tournament Teams",requiredFields:["tournamentId","seasonId"],description:"Get teams in a season"},{value:"season-events",label:"Season Events",requiredFields:["tournamentId","seasonId"],description:"Get recent events in a season"}],Fv=[{value:"american-football",label:"American Football"},{value:"basketball",label:"Basketball"},{value:"baseball",label:"Baseball"},{value:"ice-hockey",label:"Ice Hockey"},{value:"soccer",label:"Soccer"},{value:"tennis",label:"Tennis"},{value:"mma",label:"MMA"},{value:"golf",label:"Golf"}];function Av(){const[s,a]=v.useState(!1),[t,n]=v.useState(null),[r,i]=v.useState(!1),[l,m]=v.useState(null),{toast:o}=Ws(),[h,N]=v.useState(""),[d,y]=v.useState(""),[u,x]=v.useState(""),[g,f]=v.useState(""),[_,k]=v.useState(""),[b,j]=v.useState(""),[c,p]=v.useState(""),[w,S]=v.useState(""),[P,C]=v.useState(new Date().toISOString().split("T")[0]),[O,$]=v.useState(!1),[z,D]=v.useState(null),A=_i.find(I=>I.value===h),F=(A==null?void 0:A.requiredFields)||[],q=()=>{if(!h)return!1;for(const I of F)switch(I){case"sport":if(!d)return!1;break;case"teamId":if(!u)return!1;break;case"playerId":if(!g)return!1;break;case"eventId":if(!_)return!1;break;case"tournamentId":if(!b)return!1;break;case"seasonId":if(!c)return!1;break;case"categoryId":if(!w)return!1;break;case"date":if(!P)return!1;break}return!0},E=async()=>{$(!0),D(null);try{const{data:I,error:ee}=await T.functions.invoke("test-sportapi-endpoint",{body:{endpointType:h,sport:d||void 0,teamId:u||void 0,playerId:g||void 0,eventId:_||void 0,tournamentId:b||void 0,seasonId:c||void 0,categoryId:w||void 0,date:P||void 0}});if(ee)throw ee;D(I),o({title:I.success?"Endpoint Test Successful":"Endpoint Test Failed",description:I.success?`Found ${I.recordCount} records`:I.error||"Request failed",variant:I.success?"default":"destructive"})}catch(I){console.error("Explorer error:",I),o({title:"Test Failed",description:I instanceof Error?I.message:"Unknown error",variant:"destructive"})}finally{$(!1)}},L=async()=>{var I,ee,le,ve,te;a(!0),n(null);try{o({title:"Running SportAPI Evaluation",description:"Testing: Live Scores, Team Records, Player Stats, Logos, Images, Injuries, Lineups..."});const{data:X,error:ae}=await T.functions.invoke("test-sportapi");if(ae)throw ae;n(X);const W=(((I=X.phase1Tests)==null?void 0:I.length)||0)+(((ee=X.phase1_5Tests)==null?void 0:ee.length)||0)+(((le=X.phase2Tests)==null?void 0:le.length)||0)+(((ve=X.phase3Tests)==null?void 0:ve.length)||0)+(((te=X.phase3_5Tests)==null?void 0:te.length)||0),re=[...X.phase1Tests||[],...X.phase1_5Tests||[],...X.phase2Tests||[],...X.phase3Tests||[],...X.phase3_5Tests||[]].filter(ce=>ce.success&&ce.dataFound).length;o({title:"Evaluation Complete",description:`${re}/${W} endpoints returned data.`})}catch(X){console.error("Evaluation error:",X),o({title:"Evaluation Failed",description:X instanceof Error?X.message:"Unknown error occurred",variant:"destructive"})}finally{a(!1)}},H=I=>{navigator.clipboard.writeText(I),m(I),setTimeout(()=>m(null),2e3)},Z=I=>{navigator.clipboard.writeText(I),o({title:"Copied to clipboard"})},se=({success:I})=>I?e.jsx(rs,{className:"h-5 w-5 text-green-500"}):e.jsx(Is,{className:"h-5 w-5 text-red-500"}
325),ie=({title:I,available:ee,icon:le,detail:ve})=>e.jsxs("div",{className:`p-3 rounded-lg border ${ee?"bg-green-500/10 border-green-500/30":"bg-muted border-border"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(le,{className:`h-4 w-4 ${ee?"text-green-600":"text-muted-foreground"}`}),e.jsx("span",{className:"text-sm font-medium",children:I})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ee?ve||"Available":"Not found"})]}),Y=({test:I})=>{var ee,le,ve,te,X,ae;return e.jsxs("div",{className:`p-3 rounded border ${I.success&&I.dataFound?"bg-green-500/10 border-green-500/30":"bg-red-500/10 border-red-500/30"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{success:I.success&&I.dataFound}),e.jsx("span",{className:"font-medium text-sm",children:I.purpose})]}),e.jsx(B,{variant:I.success?"default":"destructive",children:I.statusCode})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-1 mb-2",children:[e.jsx("code",{className:"text-xs bg-muted px-2 py-0.5 rounded flex-1 overflow-x-auto",children:I.fullUrl}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>H(I.fullUrl),children:l===I.fullUrl?e.jsx(Ks,{className:"h-3 w-3 text-green-500"}):e.jsx(vt,{className:"h-3 w-3"})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[I.recordCount," records • ",I.sport]}),I.liveScoreData&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-blue-500/10 border border-blue-500/20",children:[e.jsx("p",{className:"text-xs font-medium text-blue-700",children:"📊 Live Score Data"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[typeof I.liveScoreData.homeScore=="object"?JSON.stringify(I.liveScoreData.homeScore):I.liveScoreData.homeScore," - ",typeof I.liveScoreData.awayScore=="object"?JSON.stringify(I.liveScoreData.awayScore):I.liveScoreData.awayScore," (",typeof I.liveScoreData.status=="object"?JSON.stringify(I.liveScoreData.status):I.liveScoreData.status,")"]})]}),I.imageUrlsFound&&I.imageUrlsFound.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-xs font-medium text-purple-600",children:"🖼️ Image URLs found:"}),e.jsx("div",{className:"space-y-1 mt-1",children:I.imageUrlsFound.slice(0,2).map((W,re)=>e.jsx("code",{className:"text-xs bg-muted px-1 rounded block truncate",children:W},re))})]}),I.injuriesDetected&&I.injuriesDetected.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-xs font-medium text-red-600",children:"🏥 Injuries detected:"}),e.jsx("div",{className:"space-y-1 mt-1",children:I.injuriesDetected.map((W,re)=>e.jsx("p",{className:"text-xs text-muted-foreground",children:W},re))})]}),I.extractedIds&&Object.values(I.extractedIds).some(W=>W&&W.length>0)&&e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground space-y-0.5",children:[(ee=I.extractedIds.eventIds)!=null&&ee.length?e.jsxs("div",{children:["Events: ",I.extractedIds.eventIds.join(", ")]}):null,(le=I.extractedIds.playerIds)!=null&&le.length?e.jsxs("div",{children:["Players: ",I.extractedIds.playerIds.join(", ")]}):null,(ve=I.extractedIds.teamIds)!=null&&ve.length?e.jsxs("div",{children:["Teams: ",I.extractedIds.teamIds.join(", ")]}):null,(te=I.extractedIds.uniqueTournamentIds)!=null&&te.length?e.jsxs("div",{className:"text-blue-600",children:["🏆 Unique Tournaments: ",I.extractedIds.uniqueTournamentIds.join(", ")]}):null,(X=I.extractedIds.tournamentIds)!=null&&X.length?e.jsxs("div",{className:"text-cyan-600",children:["Tournaments: ",I.extractedIds.tournamentIds.join(", ")]}):null,(ae=I.extractedIds.seasonIds)!=null&&ae.length?e.jsxs("div",{className:"text-purple-600",children:["📅 Seasons: ",I.extractedIds.seasonIds.join(", ")]}):null]}),I.notes.length>0&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:I.notes.join(" • ")}),I.error&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:I.error})]})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Rs,{className:"h-5 w-5"}),"SportAPI Endpoint Explorer"]}),e.jsx(De,{children:"Test individual API endpoints to debug missing players, teams, or data issues"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Endpoint Type"}),e.jsxs(oe,{value:h,onValueChange:N,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select an endpoint to test..."})}),e.jsx(me,{children:_i.map(I=>
325e.jsx(V,{value:I.value,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:I.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I.description})]})},I.value))})]})]}),h&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[F.includes("sport")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Sport"}),e.jsxs(oe,{value:d,onValueChange:y,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select sport..."})}),e.jsx(me,{children:Fv.map(I=>e.jsx(V,{value:I.value,children:I.label},I.value))})]})]}),F.includes("teamId")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Team ID"}),e.jsx(pe,{placeholder:"Enter team ID...",value:u,onChange:I=>x(I.target.value)})]}),F.includes("playerId")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Player ID"}),e.jsx(pe,{placeholder:"Enter player ID...",value:g,onChange:I=>f(I.target.value)})]}),F.includes("eventId")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Event ID"}),e.jsx(pe,{placeholder:"Enter event/game ID...",value:_,onChange:I=>k(I.target.value)})]}),F.includes("tournamentId")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Tournament ID"}),e.jsx(pe,{placeholder:"Enter tournament ID...",value:b,onChange:I=>j(I.target.value)})]}),F.includes("seasonId")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Season ID"}),e.jsx(pe,{placeholder:"Enter season ID...",value:c,onChange:I=>p(I.target.value)})]}),F.includes("categoryId")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Category ID"}),e.jsx(pe,{placeholder:"Enter category ID...",value:w,onChange:I=>S(I.target.value)})]}),F.includes("date")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Date"}),e.jsx(pe,{type:"date",value:P,onChange:I=>C(I.target.value)})]})]}),e.jsx(R,{onClick:E,disabled:!q()||O,className:"w-full",children:O?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Testing Endpoint..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"mr-2 h-4 w-4"}),"Test Endpoint"]})}),z&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx(is,{}),e.jsxs("div",{className:`p-4 rounded-lg border ${z.success?"bg-green-500/10 border-green-500/30":"bg-red-500/10 border-red-500/30"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{success:z.success}),e.jsx("span",{className:"font-medium",children:z.success?"Success":"Failed"})]}),e.jsxs(B,{variant:z.success?"default":"destructive",children:["HTTP ",z.statusCode]})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("code",{className:"text-xs bg-muted px-2 py-1 rounded flex-1 overflow-x-auto",children:z.fullUrl}),e.jsx(R,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>H(z.fullUrl),children:l===z.fullUrl?e.jsx(Ks,{className:"h-3 w-3 text-green-500"}):e.jsx(vt,{className:"h-3 w-3"})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[z.recordCount," records found"]}),z.error&&e.jsx("p",{className:"text-sm text-red-500 mt-2",children:z.error})]}),z.success&&z.extractedIds&&Object.entries(z.extractedIds).some(([I,ee])=>ee&&ee.length>0)&&e.jsxs("div",{className:"p-4 rounded-lg border bg-blue-500/10 border-blue-500/30",children:[e.jsxs("h4",{className:"text-sm font-medium mb-3 flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4"}),"Extracted IDs (click to copy)"]}),e.jsxs("div",{className:"space-y-2",children:[z.extractedIds.playerIds&&z.extractedIds.playerIds.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Players (",z.extractedIds.playerIds.length,"):"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[z.extractedIds.playerIds.slice(0,20).map(I=>e.jsx(B,{variant:"secondary",className:"cursor-pointer hover:bg-primary/20 text-xs",onClick:()=>Z(I),children:I},I)),z.extractedIds.playerIds.length>20&&e.jsxs(B,{variant:"outline",className:"text-xs",children:["+",z.extractedIds.playerIds.length-20," more"]})]})]}),z.extractedIds.teamIds&&z.extractedIds.teamIds.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Teams (",z.extractedIds.teamIds.length,"):"]}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:z.extractedIds.teamIds.map(I=>e.jsx(B,{variant:"secondary",className:"cursor-pointer hover:bg-primary/20 text-xs",onClick:()=>Z(I),children:I},I))})]}),z.extractedIds.eventIds&&z.extractedIds.eventIds.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Events (",z.extractedIds.eventIds.length,"):"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[z.extractedIds.eventIds.slice(0,10).map(I=>e.jsx(B,{variant:"secondary",className:"cursor-pointer hover:bg-primary/20 text-xs",onClick:()=>Z(I),children:I},I)),z.extractedIds.eventIds.length>10&&e.jsxs(B,{variant:"outline",className:"text-xs",children:["+",z.extractedIds.eventIds.length-10," more"]})]})]}),z.extractedIds.tournamentIds&&z.extractedIds.tournamentIds.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Tourn
325aments:"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:z.extractedIds.tournamentIds.map(I=>e.jsx(B,{variant:"secondary",className:"cursor-pointer hover:bg-primary/20 text-xs",onClick:()=>Z(I),children:I},I))})]}),z.extractedIds.seasonIds&&z.extractedIds.seasonIds.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Seasons:"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:z.extractedIds.seasonIds.map(I=>e.jsx(B,{variant:"secondary",className:"cursor-pointer hover:bg-primary/20 text-xs",onClick:()=>Z(I),children:I},I))})]}),z.extractedIds.categoryIds&&z.extractedIds.categoryIds.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Categories:"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:z.extractedIds.categoryIds.map(I=>e.jsx(B,{variant:"secondary",className:"cursor-pointer hover:bg-primary/20 text-xs",onClick:()=>Z(I),children:I},I))})]})]})]}),e.jsxs(vs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-between",children:[e.jsx("span",{children:"Raw JSON Response"}),e.jsx(Ns,{className:"h-4 w-4"})]})}),e.jsx(_s,{className:"mt-2",children:e.jsx("pre",{className:"p-3 rounded bg-muted text-xs overflow-auto max-h-96",children:JSON.stringify(z.rawData,null,2)})})]})]})]})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-5 w-5"}),"Full SportAPI Evaluation"]}),e.jsx(De,{children:"Run comprehensive tests for: Live Scores, Team Records, Player Stats, Team Logos, Player Images, Injuries, Lineups"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsx(R,{onClick:L,disabled:s,className:"w-full",size:"lg",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Evaluation..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vr,{className:"mr-2 h-4 w-4"}),"Run Full Evaluation"]})}),t&&e.jsxs("div",{className:"space-y-6 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-3",children:"Data Availability Summary"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ie,{title:"Live Scores",available:t.summary.liveScoresWorking,icon:_t,detail:t.summary.liveGamesFound>0?`${t.summary.liveGamesFound} live games`:"Endpoints working"}),e.jsx(ie,{title:"Team Records",available:t.summary.teamRecordsAvailable,icon:Js}),e.jsx(ie,{title:"Player Stats",available:t.summary.playerStatsAvailable,icon:hs}),e.jsx(ie,{title:"Team Logos",available:t.summary.teamLogosFound,icon:Ot}),e.jsx(ie,{title:"Player Images",available:t.summary.playerImagesFound,icon:bd}),e.jsx(ie,{title:"Injuries",available:t.summary.injuriesDetected,icon:gu}),e.jsx(ie,{title:"Lineups",available:t.summary.lineupsAvailable,icon:tl}),e.jsx(ie,{title:"Event-Player Stats",available:t.summary.eventPlayerStatsAvailable||!1,icon:As,detail:t.summary.eventPlayerStatsAvailable?"Prop Settlement Ready":void 0})]})]}),(t.summary.sampleTeamLogoUrl||t.summary.samplePlayerImageUrl)&&e.jsxs("div",{className:"p-3 rounded-lg border bg-purple-500/10 border-purple-500/30",children:[e.jsx("h4",{className:"text-sm font-medium mb-2 text-purple-700",children:"🖼️ Sample Image URLs"}),e.jsxs("div",{className:"space-y-2",children:[t.summary.sampleTeamLogoUrl&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Team Logo:"}),e.jsx("code",{className:"text-xs bg-white/50 px-2 py-0.5 rounded block truncate",children:t.summary.sampleTeamLogoUrl})]}),t.summary.samplePlayerImageUrl&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Player Image:"}),e.jsx("code",{className:"text-xs bg-white/50 px-2 py-0.5 rounded block truncate",children:t.summary.samplePlayerImageUrl})]})]})]}),e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30",children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"API Structure"}),e.jsx("code",{className:"text-xs bg-muted px-1 rounded",children:t.apiStructure.baseUrl}),e.jsxs("div",{className:"flex gap-4 mt-2",children:[e.jsxs("span",{className:"text-xs text-green-600",children:["✅ Working: ",t.apiStructure.workingEndpoints.length]}),e.jsxs("span",{className:"text-xs text-red-600",children:["❌ Failed: ",t.apiStructure.failedEndpoints.length]})]})]}),t.discoveredIds&&e.jsxs("div",{className:"p-3 rounded-lg border bg-blue-500/10 border-blue-500/30",children:[e.jsx("h4",{className:"text-sm font-medium mb-2 text-blue-700",children:"🔍 Discovered IDs"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{className:"p-2 rounded bg-white/50",children:[e.jsx("span",{className:"font-medium",children:"Events:"})," ",t.discoveredIds.eventIds.length]}),e.jsxs("div",{className:"p-2 rounded bg-white/50",children:[e.jsx("span",{className:"font-medium",children:"Teams:"})," ",t.discoveredIds.teamIds.length]}),e.jsxs("div",{className:"p-2 rounded bg-white/50",children:[e.jsx("span",{className:"font-medium",children:"Players:"})," ",t.discoveredIds.playerIds.length]}),e.jsxs("div",{className:"p-2 rounded bg-white/50",children:[e.jsx("span",{className:"font-medium",children:"Tourn
325aments:"})," ",t.discoveredIds.uniqueTournamentIds.length]}),e.jsxs("div",{className:"p-2 rounded bg-white/50",children:[e.jsx("span",{className:"font-medium",children:"Seasons:"})," ",t.discoveredIds.seasonIds.length]})]})]}),e.jsxs("div",{className:"p-3 rounded-lg border bg-card",children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Recommendations"}),e.jsx("div",{className:"space-y-1",children:t.recommendations.map((I,ee)=>e.jsx("p",{className:"text-sm",children:typeof I=="string"?I:JSON.stringify(I)},ee))})]}),e.jsxs(vs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-between",children:[e.jsxs("span",{children:["Phase 1: Discovery Endpoints (",t.phase1Tests.length," tests)"]}),e.jsx(Ns,{className:"h-4 w-4"})]})}),e.jsx(_s,{className:"mt-3",children:e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:t.phase1Tests.map((I,ee)=>e.jsx(Y,{test:I},ee))})})]}),t.phase1_5Tests&&t.phase1_5Tests.length>0&&e.jsxs(vs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-between",children:[e.jsxs("span",{children:["Phase 1.5: Tournament Seasons (",t.phase1_5Tests.length," tests)"]}),e.jsx(Ns,{className:"h-4 w-4"})]})}),e.jsx(_s,{className:"mt-3",children:e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:t.phase1_5Tests.map((I,ee)=>e.jsx(Y,{test:I},ee))})})]}),t.phase2Tests.length>0&&e.jsxs(vs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-between",children:[e.jsxs("span",{children:["Phase 2: Teams & Events (",t.phase2Tests.length," tests)"]}),e.jsx(Ns,{className:"h-4 w-4"})]})}),e.jsx(_s,{className:"mt-3",children:e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:t.phase2Tests.map((I,ee)=>e.jsx(Y,{test:I},ee))})})]}),t.phase3Tests&&t.phase3Tests.length>0&&e.jsxs(vs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-between",children:[e.jsxs("span",{children:["Phase 3: Players (",t.phase3Tests.length," tests)"]}),e.jsx(Ns,{className:"h-4 w-4"})]})}),e.jsx(_s,{className:"mt-3",children:e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:t.phase3Tests.map((I,ee)=>e.jsx(Y,{test:I},ee))})})]}),t.phase3_5Tests&&t.phase3_5Tests.length>0&&e.jsxs(vs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:"w-full justify-between bg-amber-500/10 border-amber-500/30 hover:bg-amber-500/20",children:[e.jsxs("span",{children:["Phase 3.5: Event-Player Stats / Prop Settlement (",t.phase3_5Tests.length," tests)"]}),e.jsx(Ns,{className:"h-4 w-4"})]})}),e.jsx(_s,{className:"mt-3",children:e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:t.phase3_5Tests.map((I,ee)=>e.jsx(Y,{test:I},ee))})})]}),e.jsxs(vs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{variant:"ghost",size:"sm",className:"w-full justify-between",children:[e.jsxs("span",{children:["Working Endpoints (",t.apiStructure.workingEndpoints.length,")"]}),e.jsx(Ns,{className:"h-4 w-4"})]})}),e.jsx(_s,{className:"mt-2",children:e.jsx("div",{className:"p-3 rounded bg-muted text-xs space-y-1 max-h-48 overflow-y-auto",children:t.apiStructure.workingEndpoints.map((I,ee)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-3 w-3 text-green-500"}),e.jsx("code",{children:I})]},ee))})})]}),e.jsxs(vs,{open:r,onOpenChange:i,children:[e.jsx(ys,{asChild:!0,children:e.jsxs(R,{variant:"ghost",size:"sm",className:"w-full justify-between",children:[e.jsx("span",{children:"View Raw JSON Response"}),e.jsx(Ns,{className:"h-4 w-4"})]})}),e.jsx(_s,{className:"mt-2",children:e.jsx("pre",{className:"p-3 rounded bg-muted text-xs overflow-auto max-h-96",children:JSON.stringify(t,null,2)})})]})]})]})]})]})}const Tv=[{value:"basketball_nba",label:"NBA"},{value:"americanfootball_nfl",label:"NFL"},{value:"icehockey_nhl",label:"NHL"},{value:"americanfootball_ncaaf",label:"NCAAF"},{value:"soccer_epl",label:"EPL"},{value:"soccer_spain_la_liga",label:"La Liga"},{value:"soccer_germany_bundesliga",label:"Bundesliga"},{value:"soccer_italy_serie_a",label:"Serie A"},{value:"soccer_france_ligue_one",label:"Ligue 1"},{value:"soccer_uefa_champs_league",label:"Champions League"},{value:"soccer_usa_mls",label:"MLS"},{value:"baseball_mlb",label:"MLB"}];function Lv(){const[s,a]=v.useState({bettingOddsGames:0,masterGames:0,gamesWithSportApi:0,gamesWithLineups:0,gamesWithDetails:0,gamesWithWeather:0}),[t,n]=v.useState(!0),[r,i]=v.useState(!1),[l,m]=v.useState(!0),[o,h]=v.useState(!1),[N,d]=v.useState(null),[y,u]=v.useState("basketball_nba"),[x,g]=v.useState(new Date),[f,_]=v.useState(!1),[k,b]=v.useState(!1),[j,c]=v.useState(null),[p,w]=v.useState(null),[S,P]=v.useState(!1),[C,O]=v.useState(!1),[$,z]=v.useState(!1),[D,A]=v.useState(null),F=async()=>{n(!0);try{const{data:I}=await T.from("betting_odds").select("game_id").limit(1e4),ee=new Set((I==null?void 0:I.map(W=>W.game_id))||[]).size,{count:le}=await T.from("master_games").select("*",{count:"exact",head:!0}),{count:ve}=await T.from("master_games").select("*",{count:"exact",head:!0}).not("sportapi_event_id","is",null),{count:te}=await T.from("master_games").select("*",{count:"exact",head:!0}).not("home_lineup","is",null),{count:X}=await T.from("master_games").select("*",{count:"exact",head:!0}).not("venue_details","is",null),{count:ae}=await T.from("master_games").select("*",{count:"exact",head:!0}).not("weather","is",null);a({bettingOddsGames:ee,masterGames:le||0,gamesWithSportApi:ve||0,gamesWithLineups:te||0,gamesWithDetails:X||0,gamesWithWeather:ae||0})}catch(I){console.error("Error fetching stats:",I)}finally{n(!1)}};v.useEffect(()=>{F()},[]);const q=async()=>{h(!0),d(null);try{const{data:I,error:ee}=await T.functions.invoke("backfill-master-games",{body:{dryRun:r,triggerSportApiMatch:l}});if(ee)throw ee;d({inserted:I.backfilled||I.inserted||0,skipped:I.skipped||0,errors:I.errors||0,bySport:I.b
325yKey||I.bySport||{}}),r?K.info(`Dry run complete: Would insert ${I.totalUniqueGames||0} games`):(K.success(`Backfilled ${I.backfilled||0} games`),F())}catch(I){console.error("Backfill error:",I),K.error(`Backfill failed: ${I.message}`)}finally{h(!1)}},E=async()=>{b(!0),c(null),w(null);let I=0,ee=0;const le=[];let ve=0;try{let te=!0;for(;te;){ve++,w(f?`Processing batch ${ve}...`:`Matching games for ${ke(x,"MMM d, yyyy")}...`);const{data:ae,error:W}=await T.functions.invoke("sync-games-data",{body:{sport:y,date:f?void 0:ke(x,"yyyy-MM-dd"),syncType:"match-sportapi",processAllDates:f,batchSize:100}});if(W)throw W;const re=ae.results||ae;I+=re.matched||0,ee+=re.recordsProcessed||0,re.datesCovered&&le.push(...re.datesCovered),te=f&&re.hasMore===!0,te&&w(`Matched ${I} games across ${le.length} dates, continuing...`)}c({matched:I,processed:ee,datesCovered:le.length>0?[...new Set(le)]:void 0});const X=f?`Matched ${I}/${ee} games across ${new Set(le).size} dates`:`Matched ${I} games for ${ke(x,"MMM d, yyyy")}`;K.success(X),F()}catch(te){console.error("Match error:",te),K.error(`Match failed: ${te.message}`)}finally{b(!1),w(null)}},L=async()=>{P(!0),A(null);try{const{data:I,error:ee}=await T.functions.invoke("enrich-master-games",{body:{enrichType:"details",limit:50}});if(ee)throw ee;A({type:"Details",processed:I.processed||0,success:I.success||0,errors:I.errors||0}),K.success(`Enriched details for ${I.success}/${I.processed} games`),F()}catch(I){console.error("Enrich details error:",I),K.error(`Enrich details failed: ${I.message}`)}finally{P(!1)}},H=async()=>{O(!0),A(null);try{const{data:I,error:ee}=await T.functions.invoke("enrich-master-games",{body:{enrichType:"weather",limit:50}});if(ee)throw ee;A({type:"Weather",processed:I.processed||0,success:I.success||0,errors:I.errors||0}),K.success(`Enriched weather for ${I.success}/${I.processed} games`),F()}catch(I){console.error("Enrich weather error:",I),K.error(`Enrich weather failed: ${I.message}`)}finally{O(!1)}},Z=async()=>{z(!0),A(null);try{const{data:I,error:ee}=await T.functions.invoke("enrich-master-games",{body:{enrichType:"lineups",limit:50}});if(ee)throw ee;A({type:"Lineups",processed:I.processed||0,success:I.success||0,errors:I.errors||0}),K.success(`Enriched lineups for ${I.success}/${I.processed} games`),F()}catch(I){console.error("Enrich lineups error:",I),K.error(`Enrich lineups failed: ${I.message}`)}finally{z(!1)}},se=s.gamesWithSportApi-s.gamesWithDetails,ie=s.gamesWithDetails-s.gamesWithWeather,Y=s.gamesWithSportApi-s.gamesWithLineups;return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-5 w-5"}),"Game Data Sync"]}),e.jsx(De,{children:"Sync games from betting odds to master_games and enrich with SportAPI data"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(tt,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Betting Odds"}),e.jsx("p",{className:"text-xl font-semibold",children:t?"...":s.bettingOddsGames})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(tt,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Master Games"}),e.jsx("p",{className:"text-xl font-semibold",children:t?"...":s.masterGames})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(Zr,{className:"h-5 w-5 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"SportAPI"}),e.jsx("p",{className:"text-xl font-semibold",children:t?"...":s.gamesWithSportApi})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(kt,{className:"h-5 w-5 text-orange-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"With Details"}),e.jsx("p",{className:"text-xl font-semibold",children:t?"...":s.gamesWithDetails})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(pn,{className:"h-5 w-5 text-cyan-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"With Weather"}),e.jsx("p",{className:"text-xl font-semibold",children:t?"...":s.gamesWithWeather})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(hs,{className:"h-5 w-5 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"With Lineups"}),e.jsx("p",{className:"text-xl font-semibold",children:t?"...":s.gamesWithLineups})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:"Step 1: Backfill Master Games"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Extract unique games from betting_odds and insert into master_games"})]}),e.jsx(B,{variant:"outline",children:"From betting_odds"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ms,{id:"dryRun",checked:r,onCheckedChange:I=>i(I)}),e.jsx(Q,{htmlFor:"dryRun",className:"text-sm",children:"Dry Run (preview only)"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ms,{id:"triggerMatch",checked:l,onCheckedChange:I=>m(I)}),e.jsx(Q,{htmlFor:"triggerMatch",className:"text-sm",children:"Auto-match with SportAPI"})]}),e.jsx(R,{onClick:q,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Analyzing...":"Backfilling..."]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-4 w-4 mr-2"}),r?"Preview Backfill":"Run Backfill"]})})]}),N&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:["Inserted: ",N.inserted," | Skipped: ",N.skipped," | Errors: ",N.errors]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:"Step 2: Match with SportAPI"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link master_games records to SportAPI events by matching teams"})]}),e.jsx(B,{variant:"outline",children:"Fuzzy matching"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs(oe,{value:y,onValueChange:u,children:[e.jsx(de,{className:"w-[160px]",children:e.jsx(ue,{placeholder:"Select sport"})}),e.jsx(me,{children:Tv.map(I=>
325e.jsx(V,{value:I.value,children:I.label},I.value))})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ms,{id:"matchAllGames",checked:f,onCheckedChange:I=>_(I)}),e.jsx(Q,{htmlFor:"matchAllGames",className:"text-sm",children:"Match ALL unmatched games"})]}),!f&&e.jsxs(Ba,{children:[e.jsx(za,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:Le("w-[160px] justify-start text-left font-normal"),children:[e.jsx(xt,{className:"mr-2 h-4 w-4"}),ke(x,"MMM d, yyyy")]})}),e.jsx(Ka,{className:"w-auto p-0",align:"start",children:e.jsx(Va,{mode:"single",selected:x,onSelect:I=>I&&g(I),initialFocus:!0})})]}),e.jsx(R,{onClick:E,disabled:k,children:k?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),f?"Matching All...":"Matching..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),f?"Match All Games":"Match Games"]})})]}),p&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:p})]}),j&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:["Matched ",j.matched,"/",j.processed," games",j.datesCovered&&j.datesCovered.length>0&&e.jsxs(e.Fragment,{children:[" across ",j.datesCovered.length," dates"]})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:"Step 3: Enrichment Operations"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Run each enrichment step individually to verify data extraction"})]}),e.jsx(B,{variant:"outline",children:"SportAPI + OpenWeather"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"h-5 w-5 text-orange-500"}),e.jsx("h5",{className:"font-medium",children:"1. Event Details"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Venue, form, season, tournament IDs"}),e.jsxs("div",{className:"text-sm",children:["Pending: ",e.jsx("span",{className:Le("font-medium",se>0&&"text-orange-500"),children:se})," games"]}),e.jsx(R,{onClick:L,disabled:S||se===0,className:"w-full",variant:se>0?"default":"secondary",children:S?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Enriching..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2"}),"Enrich Details"]})})]}),e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-cyan-500"}),e.jsx("h5",{className:"font-medium",children:"2. Weather Data"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uses venue coordinates from details"}),e.jsxs("div",{className:"text-sm",children:["Pending: ",e.jsx("span",{className:Le("font-medium",ie>0&&"text-cyan-500"),children:ie})," games"]}),e.jsx(R,{onClick:H,disabled:C||ie<=0,className:"w-full",variant:ie>0?"default":"secondary",children:C?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Enriching..."]}):e.jsxs(e.Fragment,{children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Enrich Weather"]})})]}),e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-5 w-5 text-blue-500"}),e.jsx("h5",{className:"font-medium",children:"3. Lineups & Injuries"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Player lineups and injury reports"}),e.jsxs("div",{className:"text-sm",children:["Pending: ",e.jsx("span",{className:Le("font-medium",Y>0&&"text-blue-500"),children:Y})," games"]}),e.jsx(R,{onClick:Z,disabled:$||Y===0,className:"w-full",variant:Y>0?"default":"secondary",children:$?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Enriching..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{className:"h-4 w-4 mr-2"}),"Enrich Lineups"]})})]})]}),D&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[D.type,": Processed ",D.processed," | Success: ",D.success," | Errors: ",D.errors]})]})]})]})]})}const bi=[{value:"basketball_nba",label:"NBA"},{value:"americanfootball_nfl",label:"NFL"},{value:"icehockey_nhl",label:"NHL"},{value:"baseball_mlb",label:"MLB"},{value:"americanfootball_ncaaf",label:"NCAAF"},{value:"basketball_ncaab",label:"NCAAB"},{value:"soccer_epl",label:"EPL"},{value:"soccer_spain_la_liga",label:"La Liga"},{value:"soccer_germany_bundesliga",label:"Bundesliga"},{value:"soccer_italy_serie_a",label:"Serie A"},{value:"soccer_france_ligue_one",label:"Ligue 1"},{value:"soccer_usa_mls",label:"MLS"},{value:"soccer_mexico_ligamx",label:"Liga MX"},{value:"soccer_netherlands_eredivisie",label:"Eredivisie"},{value:"soccer_uefa_champs_league",label:"Champions League"},{value:"soccer_uefa_europa_league",label:"Europa League"},{value:"soccer_fifa_world_cup",label:"FIFA World Cup"}];function Ev(){const[s,a]=v.useState(new Date),[t,n]=v.useState(["basketball_nba","americanfootball_nfl"]),[r,i]=v.useState("missing"),[l,m]=v.useState({gamesForDate:0,withMatchups:0,missingMatchups:0}),[o,h]=v.useState(!1),[N,d]=v.useState(!1),[y,u]=v.useState(null),[x,g]=v.useState(null),f=async()=>
325{if(t.length===0){m({gamesForDate:0,withMatchups:0,missingMatchups:0});return}h(!0);try{const c=ke(s,"yyyy-MM-dd"),{data:p,error:w}=await T.from("master_games").select("id").eq("game_date",c).in("odds_api_sport_key",t);if(w)throw w;const S=(p==null?void 0:p.map($=>$.id))||[],P=S.length;let C=0;if(S.length>0){const{data:$,error:z}=await T.from("game_matchup_views").select("game_id").in("game_id",S);if(z)throw z;C=($==null?void 0:$.length)||0}const O=Math.max(0,P-C);m({gamesForDate:P,withMatchups:C,missingMatchups:O})}catch(c){console.error("Error fetching stats:",c),K.error("Failed to fetch stats")}finally{h(!1)}};v.useEffect(()=>{f()},[s,t]);const _=c=>{n(p=>p.includes(c)?p.filter(w=>w!==c):[...p,c])},k=()=>{n(bi.map(c=>c.value))},b=()=>{n([])},j=async()=>{if(t.length===0){K.error("Please select at least one league");return}d(!0),u("Starting matchup view sync..."),g(null);try{const{data:c,error:p}=await T.functions.invoke("regenerate-all-matchups",{body:{date:ke(s,"yyyy-MM-dd"),leagues:t,mode:r}});if(p)throw p;const w=(c.results||[]).filter(C=>C.status==="error").map(C=>({game_id:C.game_id,error:C.error||"Unknown error"})),S={created:c.created||0,regenerated:c.regenerated||0,errors:c.failed||0,total:c.total_games||0,errorDetails:w};g(S);const P=S.created+S.regenerated;P>0?K.success(`Synced ${P} matchup views (${S.created} created, ${S.regenerated} regenerated)`):S.total===0?K.info("No games found for the selected date and leagues"):K.warning(`Sync completed with ${S.errors} errors`),f()}catch(c){console.error("Sync error:",c),K.error(`Sync failed: ${c.message}`)}finally{d(!1),u(null)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"h-5 w-5"}),"Matchup View Sync"]}),e.jsx(De,{children:"Generate or regenerate AI matchup summaries for games on a specific date"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(tt,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Games for Date"}),e.jsx("p",{className:"text-xl font-semibold",children:o?"...":l.gamesForDate})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(rs,{className:"h-5 w-5 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Have Matchups"}),e.jsx("p",{className:"text-xl font-semibold",children:o?"...":l.withMatchups})]})]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50",children:[e.jsx(xs,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Missing"}),e.jsx("p",{className:"text-xl font-semibold",children:o?"...":l.missingMatchups})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Select Date"}),e.jsxs(Ba,{children:[e.jsx(za,{asChild:!0,children:e.jsxs(R,{variant:"outline",className:Le("w-full justify-start text-left font-normal",!s&&"text-muted-foreground"),children:[e.jsx(xt,{className:"mr-2 h-4 w-4"}),s?ke(s,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Ka,{className:"w-auto p-0",align:"start",children:e.jsx(Va,{mode:"single",selected:s,onSelect:c=>c&&a(c),initialFocus:!0})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Q,{children:"Select Leagues"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"ghost",size:"sm",onClick:k,children:"Select All"}),e.jsx(R,{variant:"ghost",size:"sm",onClick:b,children:"Clear"})]})]}),e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-3",children:bi.map(c=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ms,{id:c.value,checked:t.includes(c.value),onCheckedChange:()=>_(c.value)}),e.jsx(Q,{htmlFor:c.value,className:"text-sm cursor-pointer",children:c.label})]},c.value))})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Q,{children:"Sync Mode"}),e.jsxs(Ut,{value:r,onValueChange:c=>i(c),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"missing",id:"missing"}),e.jsxs(Q,{htmlFor:"missing",className:"cursor-pointer",children:[e.jsx("span",{className:"font-medium",children:"Missing Only"}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:"— Only create matchup views for games without one"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"regenerate",id:"regenerate"}),e.jsxs(Q,{htmlFor:"regenerate",className:"cursor-pointer",children:[e.jsx("span",{className:"font-medium",children:"Regenerate All"}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:"— Recreate all matchup views for selected date/leagues"})]})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(R,{onClick:j,disabled:N||t.length===0,className:"w-full",children:N?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Syncing Matchup Views..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4"}),"Sync Matchup Views"]})}),y&&e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-muted/50",children:[e.jsx(ne,{className:"h-4 w-4 animate-spin text-primary"}),e.jsx("span",{className:"text-sm",children:y})]}),x&&e.jsxs("div",{children:[e.jsxs("div",{className:"grid grid-cols-4 gap-3 p-4 rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-semibold",children:x.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Games"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-green-500",children:x.created}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Created"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-blue-500",children:x.regenerated}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Regenerated"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg font-semibold text-red-500",children:x.errors}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Errors"})]})]}),x.errorDetails.length>0&&e.jsxs("div",{className:"mt-4 p-4 rounded-lg border border-red-500/30 bg-red-500/10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(xs,{className:"h-4 w-4 text-red-500"}),e.jsx("span",{className:"font-medium text-red-500",children:"Error Details"})]}),e.jsx("div",{className:"space-y-2 max-h-48 overflow-y-auto",children:x.errorDetails.map((c,p)=>e.jsxs("div",{className:"text-sm p-2 rounded bg-muted/50",children:[e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:c.game_id}),e.jsx("p",{className:"text-red-400 mt-1",children:c.error})]},p))})]})]})]})]})]})}function Dv(){const[s,a]=v.useState(!1),[t,n]=v.useState(!1),[r,i]=v.useState(!1),[l,m]=v.useState(!0),[o,h]=v.useState(""),[N,d]=v.useState(50),[y,u]=v.useState(null),{data:x,refetch:g}=ge({queryKey:["pending-props-stats"],queryFn:async()=>{const j=new Date().toISOString().split("T")[0],{count:c,error:p}=await T.from("player_props").select("*",{count:"exact",head:!0}
325).eq("result_status","pending").lte("game_date",j);if(p)throw p;const{count:w,error:S}=await T.from("player_props_settlement_ready").select("*",{count:"exact",head:!0});if(S)throw S;const{count:P,error:C}=await T.from("player_props").select("*",{count:"exact",head:!0}).eq("result_status","pending").lte("game_date",j).or("sportapi_event_id.is.null,sportapi_player_id.is.null");if(C)throw C;const{count:O,error:$}=await T.from("player_props").select("*",{count:"exact",head:!0}).eq("result_status","void").gte("settled_at",new Date(Date.now()-7*24*60*60*1e3).toISOString());if($)throw $;const z=new Date(Date.now()-7*24*60*60*1e3).toISOString().split("T")[0],{count:D,error:A}=await T.from("player_props").select("*",{count:"exact",head:!0}).eq("result_status","pending").lte("game_date",z).not("sportapi_event_id","is",null);if(A)throw A;const{data:F,error:q}=await T.from("player_props_settlement_ready").select("sport").limit(5e3);if(q)throw q;const E=(F==null?void 0:F.reduce((L,H)=>(L[H.sport]=(L[H.sport]||0)+1,L),{}))||{};return{total:c||0,withIds:w||0,missingIds:P||0,voidedRecently:O||0,staleProps:D||0,bySport:E}},refetchInterval:3e4}),f=async()=>{a(!0),u(null);try{const{data:j,error:c}=await T.functions.invoke("settle-player-props",{body:{sport:o||void 0,limit:N,dryRun:l}});if(c)throw c;u(j),j.success?l?K.info(`Dry run complete: ${j.stats.propsSettled} props would be settled`):(K.success(`Settled ${j.stats.propsSettled} props (${j.stats.propsWon}W / ${j.stats.propsLost}L / ${j.stats.propsPush}P)`),g()):K.error("Settlement completed with errors")}catch(j){console.error("Settlement error:",j),K.error(`Settlement failed: ${j.message}`)}finally{a(!1)}},_=async()=>{if(((x==null?void 0:x.missingIds)||0)!==0){n(!0);try{const{data:c,error:p}=await T.rpc("void_props_missing_ids");if(p)throw p;K.success(`Voided ${(c||0).toLocaleString()} props with missing IDs`),g()}catch(c){console.error("Void error:",c),K.error(`Failed to void props: ${c.message}`)}finally{n(!1)}}},k=async()=>{const j=(x==null?void 0:x.staleProps)||0;if(j!==0&&confirm(`This will void ~${j} pending props older than 7 days that are linked to non-completed games. Continue?`)){i(!0);try{const c=new Date(Date.now()-6048e5).toISOString().split("T")[0],p=new Date().toISOString(),{error:w}=await T.from("player_props").update({result_status:"void",settled_at:p}).eq("result_status","pending").lte("game_date",c).not("sportapi_event_id","is",null);if(w)throw w;K.success("Voided stale props older than 7 days"),g()}catch(c){console.error("Void stale error:",c),K.error(`Failed to void stale props: ${c.message}`)}finally{i(!1)}}},b=j=>{switch(j){case"win":return e.jsx(rs,{className:"h-4 w-4 text-green-500"});case"loss":return e.jsx(Is,{className:"h-4 w-4 text-red-500"});case"push":return e.jsx(Qi,{className:"h-4 w-4 text-yellow-500"})}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(As,{className:"h-5 w-5"}),"Settle Player Props"]}),e.jsx(De,{children:"Auto-settle player props using SportAPI game statistics"})]}),e.jsxs(J,{className:"space-y-6",children:[x&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4",children:[e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold",children:x.total.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Pending"})]}),e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-green-500",children:x.withIds.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Ready to Settle"})]}),e.jsx("div",{className:"p-3 bg-muted/50 rounded-lg",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-yellow-500",children:x.missingIds.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Missing IDs"})]}),x.missingIds>0&&e.jsx(R,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:bg-destructive/10",onClick:_,disabled:t,title:"Void all props with missing IDs",children:t?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(os,{className:"h-4 w-4"})})]})}),e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold text-orange-500",children:x.voidedRecently.toLocaleStr
325ing()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Voided (7d retry)"})]}),e.jsx("div",{className:"p-3 bg-muted/50 rounded-lg",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-red-500",children:(x.staleProps||0).toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Stale (7d+)"})]}),(x.staleProps||0)>0&&e.jsx(R,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:bg-destructive/10",onClick:k,disabled:r,title:"Void stale props older than 7 days on non-completed games",children:r?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(os,{className:"h-4 w-4"})})]})}),e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg",children:[e.jsx("div",{className:"text-sm font-medium",children:"By Sport:"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(x.bySport).slice(0,4).map(([j,c])=>e.jsxs(B,{variant:"outline",className:"text-xs",children:[j,": ",c]},j))})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Sport Filter"}),e.jsxs(oe,{value:o,onValueChange:j=>h(j==="all"?"":j),children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"All Sports"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Sports"}),e.jsx(V,{value:"basketball",children:"Basketball"}),e.jsx(V,{value:"football",children:"Football"}),e.jsx(V,{value:"hockey",children:"Hockey"}),e.jsx(V,{value:"baseball",children:"Baseball"}),e.jsx(V,{value:"mma",children:"MMA"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Limit"}),e.jsx(pe,{type:"number",value:N,onChange:j=>d(Number(j.target.value)),min:1,max:2e3})]}),e.jsxs("div",{className:"flex items-center space-x-2 pt-6",children:[e.jsx(Ms,{id:"dryRun",checked:l,onCheckedChange:j=>m(j)}),e.jsx(Q,{htmlFor:"dryRun",className:"cursor-pointer",children:"Dry Run (preview only)"})]}),e.jsx("div",{className:"pt-6",children:e.jsx(R,{onClick:f,disabled:s,className:"w-full",variant:l?"outline":"default",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Settling..."]}):l?"Preview Settlement":"Settle Props"})})]}),y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:y.stats.propsChecked}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Checked"})]}),e.jsxs("div",{className:"p-3 bg-green-500/10 rounded-lg text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-500",children:y.stats.propsWon}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Won"})]}),e.jsxs("div",{className:"p-3 bg-red-500/10 rounded-lg text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-red-500",children:y.stats.propsLost}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Lost"})]}),e.jsxs("div",{className:"p-3 bg-yellow-500/10 rounded-lg text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-yellow-500",children:y.stats.propsPush}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Push"})]})]}),y.stats.propsMissingData>0&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-yellow-500/10 rounded-lg",children:[e.jsx(xs,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("span",{className:"text-sm",children:[y.stats.propsMissingData," props skipped due to missing data"]})]}),y.settledProps.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[l?"Preview:":"Settled:"," ",y.settledProps.length," props"]}),e.jsx(cs,{className:"h-64 border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:y.settledProps.map(j=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-muted/30 rounded text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[b(j.result),e.jsx("span",{className:"font-medium",children:j.player_name}),e.jsx("span",{className:"text-muted-foreground",children:j.market_name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Line: ",j.line]}),e.jsxs("span",{className:"font-medium",children:["Actual: ",j.actual]})]})]},j.id))})})]}),y.errors.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium text-red-500",children:["Errors (",y.errors.length,"):"]}),e.jsx(cs,{className:"h-32 border border-red-500/20 rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-1 text-xs text-red-500",children:[y.errors.slice(0,20).map((j,c)=>e.jsx("div",{children:j},c)),y.errors.length>20&&e.jsxs("div",{children:["...and ",y.errors.length-20," more"]})]})})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-right",children:["Completed in ",(y.duration/1e3).toFixed(2),"s"]})]})]})]})}const Mv=[{value:"all",label:"All Sports"},{value:"football",label:"Football"},{value:"basketball",label:"Basketball"},{value:"hockey",label:"Hockey"},{value:"baseball",label:"Baseball"}];function Iv(){const[s,a]=v.useState("all"),[t,n]=v.useState(!1),[r,i]=v.useState(!1),[l,m]=v.useState(null),{toast:o}=Ws(),{data:h,refetch:N}=ge({queryKey:["prop-learning-stats"],queryFn:async()=>{const{data:u,error:x}=await T.rpc("get_prop_learning_stats");if(x)throw x;const g=u;return{totalRecords:(g==null?void 0:g.total_records)||0,bySport:(g==null?void 0:g.by_sport)||{},totalSamples:(g==null?void 0:g.total_samples)||0,highConfidence:(g==null?void 0:g.high_confidence)||0}}}),{data:d}=ge({queryKey:["prop-learning-last-updated"],queryFn:async()=>{var g;const{data:u,error:x}=await T.from("player_prop_learning").select("updated_at").order("updated_at",{ascending:!1}).limit(1);if(x)throw x;return(g=u==null?void 0:u[0])==null?void 0:g.updated_at}}),y=async u=>{var x;u?i(!0):n(!0),m(null);try{const{data:g,error:f}=await T.functions.invoke("process-prop-learning",{body:{sport:s==="all"?void 0:s,dryRun:u}});if(f)throw f;m(g),!u&&g.success&&(o({title:"Learning Processing Complete",description:`Processed ${((x=g.stats)==null?void 0:x.upserted)||0} player-market combinations`}),N())}catch(g){console.error("Process error:",g),m({success:!1,error:g instanceof Error?g.message:"Failed to process learning"}),o({title:"Processing Failed",description:g instanceof Error?g.message:"Unknown error",variant:"destructive"})}finally{n(!1),i(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-5 w-5 text-primary"}),"Process Prop Learning"]}),e.jsx(De,{children:"Aggregate settled prop data to generate AI learning insights and confidence scores"}),d&&e.jsxs(B,{variant:"outline",className:"text-xs text-muted-foreground mt-2 w-fit",children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),"Last run: ",al(d)]})]}),e.jsxs(J,{className:"space-y-4",children:[h&&h.totalRecords>0&&e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4"}),"Current Learning Data"]}),e.jsxs("div",{className:"grid grid-cols-4 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xl font-bold",children:h.totalRecords}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Player-Markets"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl font-bold",children:h.totalSamples.toLocaleStr
325ing()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Samples"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl font-bold text-green-500",children:h.highConfidence}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"High Confidence"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl font-bold",children:Object.keys(h.bySport).length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Sports"})]})]}),Object.entries(h.bySport).length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-3",children:Object.entries(h.bySport).map(([u,x])=>e.jsxs(B,{variant:"outline",className:"text-xs",children:[u,": ",String(x)]},u))})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{placeholder:"Select sport"})}),e.jsx(me,{children:Mv.map(u=>e.jsx(V,{value:u.value,children:u.label},u.value))})]}),e.jsxs(R,{variant:"outline",onClick:()=>y(!0),disabled:r||t,children:[r?e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(us,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(R,{onClick:()=>y(!1),disabled:t||r,children:[t?e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rt,{className:"h-4 w-4 mr-2"}),"Process Learning"]})]}),l&&e.jsxs(ss,{className:l.success?"border-green-500/50":"border-destructive/50",children:[l.success?e.jsx(Es,{className:"h-4 w-4 text-green-500"}):e.jsx(xs,{className:"h-4 w-4 text-destructive"}),e.jsx(ts,{children:l.success?e.jsxs("div",{className:"space-y-3",children:[l.dryRun?e.jsx("p",{className:"font-medium",children:"Preview Results (No changes made)"}):e.jsx("p",{className:"font-medium",children:"Processing Complete"}),l.stats&&e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.stats.totalSettledProps}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Settled Props"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.stats.uniquePlayerMarkets}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Player-Markets"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-green-500",children:l.stats.highConfidenceCount}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"High Confidence"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.stats.avgConfidence??l.stats.avgSampleSize??"-"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l.stats.avgConfidence?"Avg Confidence":"Avg Sample Size"})]})]}),l.preview&&l.preview.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-xs font-medium mb-2",children:"Sample Records:"}),e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted/50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2",children:"Player"}),e.jsx("th",{className:"text-left p-2",children:"Market"}),e.jsx("th",{className:"text-center p-2",children:"Samples"}),e.jsx("th",{className:"text-center p-2",children:"Over %"}),e.jsx("th",{className:"text-center p-2",children:"Lean"}),e.jsx("th",{className:"text-center p-2",children:"Confidence"})]})}),e.jsx("tbody",{children:l.preview.map((u,x)=>{var g;return e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"p-2",children:u.player_name}),e.jsx("td",{className:"p-2",children:u.market_name}),e.jsx("td",{className:"p-2 text-center",children:u.sample_size}),e.jsxs("td",{className:"p-2 text-center",children:[(g=u.over_rate)==null?void 0:g.toFixed(1),"%"]}),e.jsx("td",{className:"p-2 text-center",children:e.jsx(B,{variant:"outline",className:`text-xs ${u.recommended_lean==="More"?"text-green-500":u.recommended_lean==="Less"?"text-red-500":""}`,children:u.recommended_lean})}),e.jsx("td",{className:"p-2 text-center",children:e.jsxs("span",{className:u.confidence_score>=70?"text-green-500":u.confidence_score>=40?"text-yellow-500":"",children:[u.confidence_score,"%"]})})]},x)})})]})})]})]}):e.jsx("p",{children:l.error||"An error occurred"})})]})]})]})}const Rv=[{value:"all",label:"All Sports"},{value:"football",label:"Football"},{value:"basketball",label:"Basketball"},{value:"hockey",label:"Hockey"},{value:"baseball",label:"Baseball"}];function qv(){var u,x;const[s,a]=v.useState("all"),[t,n]=v.useState(!1),[r,i]=v.useState(!1),[l,m]=v.useState(null),{toast:o}=Ws(),{data:h,refetch:N}=ge({queryKey:["game-bet-learning-stats"],queryFn:async()=>{const{data:g,error:f}=await T.from("sportsbook_accuracy_learning").select("id, sharpness_score, sample_size, sport, market_name, market_type").eq("market_type","game").limit(1e3);if(f)throw f;const _=new Map;let k=0,b=0;for(const j of g||[])_.set(j.sport,(_.get(j.sport)||0)+1),k+=j.sample_size||0,(j.sharpness_score??0)>=70&&b++;return{totalRecords:(g==null?void 0:g.length)||0,bySport:Object.fromEntries(_),totalSamples:k,sharpCount:b}}}),{data:d}=ge({queryKey:["game-bet-learning-last-updated"],queryFn:async()=>{var _;const{data:g,error:f}=await T.from("sportsbook_accuracy_learning").select("updated_at").order("updated_at",{ascending:!1}).limit(1);if(f)throw f;return(_=g==null?void 0:g[0])==null?void 0:_.updated_at}}),y=async g=>{var f;g?i(!0):n(!0),m(null);try{const{data:_,error:k}=await T.functions.invoke("process-game-bet-learning",{body:{sport:s==="all"?void 0:s,dryRun:g}});if(k)throw k;m(_),!g&&_.success&&(o({title:"Game Bet Learning Complete",description:`Processed ${((f=_.stats)==null?void 0:f.sportsbookRecords)||0} sportsbook-market combinations`}),N())}catch(_){console.error("Process error:",_),m({success:!1,error:_ instanceof Error?_.message:"Failed to process learning"}),o({title:"Processing Failed",description:_ instanceof Error?_.message:"Unknown error",variant:"destructive"})}finally{n(!1),i(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"h-5 w-5 text-primary"}),"Process Game Bet Learning (Vig/Sharpness)"]}),e.jsx(De,{children:"Analyze sportsbook accuracy for spreads, totals, and moneylines to identify sharp vs soft books"}),d&&e.jsxs(B,{variant:"outline",className:"text-xs text-muted-foreground mt-2 w-fit",children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),"Last run: ",al(d)]})]}),e.jsxs(J,{className:"space-y-4",children:[h&&h.totalRecords>0&&e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4"}),"Current Game Bet Learning Data"]}),e.jsxs("div",{className:"grid grid-cols-4 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xl font-bold",children:h.totalRecords}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Book-Market Combos"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl font-bold",children:h.totalSamples.toLocaleStr
325ing()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Samples"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl font-bold text-green-500",children:h.sharpCount}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Sharp Books"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl font-bold",children:Object.keys(h.bySport).length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Sports"})]})]}),Object.entries(h.bySport).length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-3",children:Object.entries(h.bySport).map(([g,f])=>e.jsxs(B,{variant:"outline",className:"text-xs",children:[g,": ",f]},g))})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{placeholder:"Select sport"})}),e.jsx(me,{children:Rv.map(g=>e.jsx(V,{value:g.value,children:g.label},g.value))})]}),e.jsxs(R,{variant:"outline",onClick:()=>y(!0),disabled:r||t,children:[r?e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(us,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(R,{onClick:()=>y(!1),disabled:t||r,children:[t?e.jsx(He,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rt,{className:"h-4 w-4 mr-2"}),"Process Learning"]})]}),l&&e.jsxs(ss,{className:l.success?"border-green-500/50":"border-destructive/50",children:[l.success?e.jsx(Es,{className:"h-4 w-4 text-green-500"}):e.jsx(xs,{className:"h-4 w-4 text-destructive"}),e.jsx(ts,{children:l.success?e.jsxs("div",{className:"space-y-3",children:[l.dryRun?e.jsx("p",{className:"font-medium",children:"Preview Results (No changes made)"}):e.jsx("p",{className:"font-medium",children:"Processing Complete"}),l.stats&&e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.stats.gamesProcessed}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Games"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(u=l.stats.oddsRecords)==null?void 0:u.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Odds Records"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-green-500",children:l.stats.sportsbookRecords}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Book-Markets"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.stats.uniqueSportsbooks}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Sportsbooks"})]})]}),((x=l.stats)==null?void 0:x.sportBreakdown)&&e.jsx("div",{className:"flex flex-wrap gap-1",children:Object.entries(l.stats.sportBreakdown).map(([g,f])=>e.jsxs(B,{variant:"outline",className:"text-xs",children:[g,": ",f.count," (",f.avgSharpness," avg sharpness)"]},g))}),l.topBooks&&l.topBooks.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-xs font-medium mb-2",children:"🏆 Top Sharp Books:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.topBooks.map((g,f)=>e.jsxs(B,{variant:"default",className:"text-xs",children:[g.sportsbook," (",g.sport," ",g.market,"): ",g.sharpness]},f))})]}),l.preview&&l.preview.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-xs font-medium mb-2",children:"Sharpness Rankings:"}),e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted/50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2",children:"Sportsbook"}),e.jsx("th",{className:"text-left p-2",children:"Sport"}),e.jsx("th",{className:"text-left p-2",children:"Market"}),e.jsx("th",{className:"text-center p-2",children:"Samples"}),e.jsx("th",{className:"text-center p-2",children:"Accuracy"}),e.jsx("th",{className:"text-center p-2",children:"Sharpness"})]})}),e.jsx("tbody",{children:l.preview.map((g,f)=>{var _;return e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"p-2 font-medium",children:g.sportsbook}),e.jsx("td",{className:"p-2",children:g.sport}),e.jsx("td",{className:"p-2",children:g.market_name}),e.jsx("td",{className:"p-2 text-center",children:g.sample_size}),e.jsxs("td",{className:"p-2 text-center",children:[(_=g.line_accuracy_pct)==null?void 0:_.toFixed(1),"%"]}),e.jsx("td",{className:"p-2 text-center",children:e.jsx("span",{className:g.sharpness_score>=70?"text-green-500 font-bold":g.sharpness_score>=50?"text-yellow-500":"text-red-500",children:g.sharpness_score})})]},f)})})]})})]})]}):e.jsx("p",{children:l.error||"An error occurred"})})]})]})]})}const $v=[/###\s/,/trending/i,/averaging/i,/based on/i,/probability/i,/elite defense/i,/straight up/i,/combined L\d+/i,/pattern/i,/analysis/i,/historical/i,/\*\*/,/\n/,/projection/i,/confidence/i],Ov=(s,a)=>
325{if(!s)return!1;if(a==="parlay"&&s.includes(",")){const t=s.split(",");if(t.length>=2&&t.every(n=>n.trim().length<100))return!1}return s.length>200&&a!=="parlay"?!0:$v.some(t=>t.test(s))},Uv=s=>{const a=s.recommendation_data;if(a){if(a.picked_side&&a.bet_line!==void 0)return`${a.picked_side.charAt(0).toUpperCase()+a.picked_side.slice(1)} ${a.bet_line}`;if(a.bet_type==="moneyline"&&a.picked_side)return a.picked_side;if(a.bet_type==="spread"&&a.picked_side&&a.bet_line!==void 0)return`${a.picked_side} ${a.bet_line>0?"+":""}${a.bet_line}`}const t=s.selection.match(/###\s*(Over|Under|ML|Moneyline|Spread)?\s*([\d.+-]+)?/i);if(t){const n=t[0].replace("### ","").trim();if(n.length<50)return n}return null};function Bv(){const[s,a]=v.useState(!1),[t,n]=v.useState(!1),[r,i]=v.useState([]),[l,m]=v.useState(new Set),[o,h]=v.useState(null),N=async()=>{n(!0),h(null);try{const{data:b,error:j}=await T.from("saved_betting_recommendations").select("id, selection, bet_type, sport, created_at, recommendation_data").not("tracking_status","eq","archived").order("created_at",{ascending:!1}).limit(500);if(j)throw j;const c=[];for(const p of b||[])if(Ov(p.selection||"",p.bet_type||"")){const w=Uv({...p,isFixable:!1,suggestedFix:null});c.push({id:p.id,selection:p.selection||"",bet_type:p.bet_type||"",sport:p.sport||"",created_at:p.created_at||"",recommendation_data:p.recommendation_data,suggestedFix:w,isFixable:!!w})}i(c),c.length===0?K.success("No malformed bets found!"):K.info(`Found ${c.length} malformed bet(s)`)}catch(b){console.error("Error scanning for malformed bets:",b),K.error("Failed to scan for malformed bets")}finally{n(!1)}},d=async()=>{const b=r.filter(c=>l.has(c.id)&&c.isFixable);if(b.length===0){K.error("No fixable bets selected");return}a(!0);let j=0;try{for(const c of b){const{error:p}=await T.from("saved_betting_recommendations").update({selection:c.suggestedFix}).eq("id",c.id);p||j++}h(c=>({fixed:((c==null?void 0:c.fixed)||0)+j,archived:(c==null?void 0:c.archived)||0})),K.success(`Fixed ${j} bet(s)`),i(c=>c.filter(p=>!b.find(w=>w.id===p.id)||!p.isFixable)),m(new Set)}catch(c){console.error("Error fixing bets:",c),K.error("Failed to fix some bets")}finally{a(!1)}},y=async()=>{const b=r.filter(c=>l.has(c.id));if(b.length===0){K.error("No bets selected");return}a(!0);let j=0;try{for(const c of b){const{error:p}=await T.from("saved_betting_recommendations").update({tracking_status:"archived",result:"void"}).eq("id",c.id);p||j++}h(c=>({fixed:(c==null?void 0:c.fixed)||0,archived:((c==null?void 0:c.archived)||0)+j})),K.success(`Archived ${j} bet(s)`),i(c=>c.filter(p=>!b.find(w=>w.id===p.id))),m(new Set)}catch(c){console.error("Error archiving bets:",c),K.error("Failed to archive some bets")}finally{a(!1)}},u=async()=>{const b=r.filter(j=>j.isFixable);if(b.length===0){K.error("No fixable bets found");return}m(new Set(b.map(j=>j.id))),await d()},x=async()=>{const b=r.filter(j=>!j.isFixable);if(b.length===0){K.error("No unfixable bets to archive");return}m(new Set(b.map(j=>j.id))),await y()},g=b=>{m(j=>{const c=new Set(j);return c.has(b)?c.delete(b):c.add(b),c})},f=()=>{l.size===r.length?m(new Set):m(new Set(r.map(b=>b.id)))},_=r.filter(b=>b.isFixable).length,k=r.filter(b=>!b.isFixable).length;return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"h-5 w-5 text-warning"}),e.jsx(fe,{children:"Cleanup Malformed Bets"})]}),r.length>0&&e.jsxs(B,{variant:"destructive",children:[r.length," found"]})]}),e.jsx(De,{children:"Find and fix betting recommendations with invalid selection fields containing AI reasoning"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(R,{onClick:N,disabled:t,variant:"outline",children:[t?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rs,{className:"h-4 w-4 mr-2"}),"Scan for Malformed Bets"]}),r.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(R,{onClick:u,disabled:s||_===0,variant:"default",children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Fix All Fixable (",_,")"]}),e.jsxs(R,{onClick:x,disabled:s||k===0,variant:"secondary",children:[e.jsx(Nt,{className:"h-4 w-4 mr-2"}),"Archive Unfixable (",k,")"]})]})]}),o&&e.jsxs(ss,{className:"border-success/50 bg-success/10",children:[e.jsx(Es,{className:"h-4 w-4 text-success"}),e.jsxs(ts,{children:["Results: ",o.fixed," fixed, ",o.archived," archived"]})]}),r.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ms,{checked:l.size===r.length,onCheckedChange:f}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[l.size," selected"]})]}),l.size>0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{size:"sm",onClick:d,disabled:s,children:[e.jsx(ga,{className:"h-3 w-3 mr-1"}),"Fix Selected"]}),e.jsxs(R,{size:"sm",variant:"secondary",onClick:y,disabled:s,children:[e.jsx(Nt,{className:"h-3 w-3 mr-1"}),"Archive Selected"]})]})]}),e.jsx(cs,{className:"h-[400px] border rounded-md",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-10"}),e.jsx(U,{children:"Current Selection"}),e.jsx(U,{children:"Suggested Fix"}),e.jsx(U,{children:"Type"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Status"})]})}),e.jsx($e,{children:r.map(b=>e.jsxs(he,{children:[e.jsx(M,{children:e.jsx(Ms,{checked:l.has(b.id),onCheckedChange:()=>g(b.id)})}),e.jsx(M,{className:"max-w-[200px]",children:e.jsxs("div",{className:"truncate text-xs text-muted-foreground",title:b.selection,children:[b.selection.substring(0,80),"..."]})}),e.jsx(M,{children:b.suggestedFix?e.jsx(B,{variant:"outline",className:"text-success border-success",children:b.suggestedFix}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(M,{children:e.jsx(B,{variant:"secondary",children:b.bet_type})}),e.jsx(M,{className:"text-sm",children:b.sport}),e.jsx(M,{children:b.isFixable?e.jsx(B,{className:"bg-success/20 text-success",children:"Fixable"}
325):e.jsx(B,{variant:"destructive",children:"Unfixable"})})]},b.id))})]})})]}),!t&&r.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(He,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:'Click "Scan for Malformed Bets" to find issues'})]})]})]})}function ia(s){return s===null?"bg-muted/20 text-muted-foreground border-muted/30":s>=70?"bg-green-500/10 text-green-500 border-green-500/30":s>=50?"bg-yellow-500/10 text-yellow-500 border-yellow-500/30":"bg-red-500/10 text-red-500 border-red-500/30"}function wi(s){return s===null?"No Data":s>=70?"Sharp":s>=50?"Average":"Soft"}const zv=[{value:"all",label:"All Sports"},{value:"basketball",label:"Basketball"},{value:"hockey",label:"Hockey"},{value:"football",label:"Football"},{value:"baseball",label:"Baseball"},{value:"soccer",label:"Soccer"}],Kv=[{value:"all",label:"All Markets"},{value:"game",label:"Game Bets"},{value:"props",label:"Player Props"}];function Vv(){var j,c,p,w,S;const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState(""),[l,m]=v.useState("sharpness_score"),[o,h]=v.useState("desc"),[N,d]=v.useState("detailed"),{data:y,isLoading:u}=ge({queryKey:["sharpness-dashboard-data"],queryFn:async()=>{const{data:P,error:C}=await T.from("sportsbook_accuracy_learning").select("*").order("sharpness_score",{ascending:!1});if(C)throw C;return P},staleTime:2*60*1e3}),x=v.useMemo(()=>{if(!y)return[];let P=y.filter(C=>{if(s!=="all"&&C.sport!==s||t!=="all"&&C.market_type!==t)return!1;if(r){const O=r.toLowerCase();return C.sportsbook.toLowerCase().includes(O)||C.market_name.toLowerCase().includes(O)}return!0});return P.sort((C,O)=>{const $=C[l],z=O[l];return $===null?1:z===null?-1:typeof $=="string"&&typeof z=="string"?o==="asc"?$.localeCompare(z):z.localeCompare($):o==="asc"?$-z:z-$}),P},[y,s,t,r,l,o]),g=v.useMemo(()=>{if(!x.length)return[];const P=new Map;return x.forEach(C=>{const O=`${C.sportsbook}|${C.sport}`;P.has(O)||P.set(O,{sportsbook:C.sportsbook,sport:C.sport,totalSharpness:0,totalSamples:0,count:0});const $=P.get(O);$.totalSharpness+=(C.sharpness_score??0)*(C.sample_size??0),$.totalSamples+=C.sample_size??0,$.count++}),Array.from(P.values()).filter(C=>C.totalSamples>0).map(C=>({sportsbook:C.sportsbook,sport:C.sport,sharpness_score:Math.round(C.totalSharpness/C.totalSamples*10)/10,sample_size:C.totalSamples,markets_tracked:C.count})).sort((C,O)=>O.sharpness_score-C.sharpness_score)},[x]),f=v.useMemo(()=>{if(!x.length)return[];const P=new Map;x.forEach(O=>{const $=`${O.sport}|${O.market_name}`;P.has($)||P.set($,[]),P.get($).push(O)});const C=[];return P.forEach((O,$)=>{var F,q,E,L;const z=O.sort((H,Z)=>(Z.sharpness_score??0)-(H.sharpness_score??0)),[D,A]=$.split("|");C.push({sport:D,market_name:A,sharpest_book:((F=z[0])==null?void 0:F.sportsbook)??"N/A",sharpest_score:((q=z[0])==null?void 0:q.sharpness_score)??0,second_book:((E=z[1])==null?void 0:E.sportsbook)??null,second_score:((L=z[1])==null?void 0:L.sharpness_score)??null,total_books:z.length})}),C.sort((O,$)=>$.sharpest_score-O.sharpest_score)},[x]),_=v.useMemo(()=>{if(!x.length)return[];const P=new Map;return x.forEach(C=>{P.has(C.sportsbook)||P.set(C.sportsbook,{sportsbook:C.sportsbook,Spread:0,"Over/Under":0,Moneyline:0,count:0});const O=P.get(C.sportsbook);C.market_name==="Spread"?O.Spread=C.sharpness_score??0:C.market_name==="Over/Under"?O["Over/Under"]=C.sharpness_score??0:C.market_name==="Moneyline"&&(O.Moneyline=C.sharpness_score??0),O.count++}),Array.from(P.values()).filter(C=>C.count>0).sort((C,O)=>{const $=(C.Spread+C["Over/Under"]+C.Moneyline)/3;return(O.Spread+O["Over/Under"]+O.Moneyline)/3-$}).slice(0,10)},[x]),k=v.useMemo(()=>{if(!x.length)return null;const P=[...x].sort((D,A)=>(A.sharpness_score??0)-(D.sharpness_score??0))[0],C=x.filter(D=>D.market_name==="Spread"),O=C.length>0?[...C].sort((D,A)=>(A.sharpness_score??0)-(D.sharpness_score??0))[0]:null,$=x.filter(D=>D.market_name==="Over/Under"),z=$.length>0?[...$].sort((D,A)=>(A.sharpness_score??0)-(D.sharpness_score??0))[0]:null;return{sharpestOverall:P,sharpestSpread:O,sharpestTotal:z}},[x]),b=P=>{l===P?h(C=>C==="asc"?"desc":"asc"):(m(P),h("desc"))};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Ds,{className:"h-5 w-5"}),"Sportsbook Sharpness Dashboard"]}),e.jsx(De,{children:"Analyze sportsbook accuracy and sharpness across sports and bet types"})]}),e.jsxs(B,{variant:"outline",className:"text-xs",children:[x.length," records"]})]})}),e.jsxs(J,{className:"space-y-6",children:[k&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(G,{className:"bg-muted/30",children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Mt,{className:"h-4 w-4"}),"Sharpest Overall"]}),e.jsx("div",{className:"font-semibold text-lg",children:(j=k.sharpestOverall)==null?void 0:j.sportsbook}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(B,{className:ia(((c=k.sharpestOverall)==null?void 0:c.sharpness_score)??null),
325children:((p=k.sharpestOverall)==null?void 0:p.sharpness_score)??0}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(w=k.sharpestOverall)==null?void 0:w.sport," - ",(S=k.sharpestOverall)==null?void 0:S.market_name]})]})]})}),k.sharpestSpread&&e.jsx(G,{className:"bg-muted/30",children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(As,{className:"h-4 w-4"}),"Best Spread Book"]}),e.jsx("div",{className:"font-semibold text-lg",children:k.sharpestSpread.sportsbook}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(B,{className:ia(k.sharpestSpread.sharpness_score),children:k.sharpestSpread.sharpness_score??0}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.sharpestSpread.sport})]})]})}),k.sharpestTotal&&e.jsx(G,{className:"bg-muted/30",children:e.jsxs(J,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Ds,{className:"h-4 w-4"}),"Best Totals Book"]}),e.jsx("div",{className:"font-semibold text-lg",children:k.sharpestTotal.sportsbook}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(B,{className:ia(k.sharpestTotal.sharpness_score),children:k.sharpestTotal.sharpness_score??0}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.sharpestTotal.sport})]})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{placeholder:"Sport"})}),e.jsx(me,{children:zv.map(P=>e.jsx(V,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{placeholder:"Market Type"})}),e.jsx(me,{children:Kv.map(P=>e.jsx(V,{value:P.value,children:P.label},P.value))})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search sportsbook or market...",value:r,onChange:P=>i(P.target.value),className:"pl-9"})]})]}),e.jsxs(js,{value:N,onValueChange:P=>d(P),children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsx(Ne,{value:"detailed",children:"Detailed View"}),e.jsx(Ne,{value:"by-sport",children:"By Sport"}),e.jsx(Ne,{value:"by-bet-type",children:"By Bet Type"})]}),e.jsxs(we,{value:"detailed",className:"mt-4",children:[e.jsx("div",{className:"rounded-md border",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"cursor-pointer",onClick:()=>b("sportsbook"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Sportsbook",e.jsx(Jt,{className:"h-3 w-3"})]})}),e.jsx(U,{className:"cursor-pointer",onClick:()=>b("sport"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Sport",e.jsx(Jt,{className:"h-3 w-3"})]})}),e.jsx(U,{className:"cursor-pointer",onClick:()=>b("market_name"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Bet Type",e.jsx(Jt,{className:"h-3 w-3"})]})}),e.jsx(U,{className:"cursor-pointer text-right",onClick:()=>b("sample_size"),children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["Samples",e.jsx(Jt,{className:"h-3 w-3"})]})}),e.jsx(U,{className:"cursor-pointer text-right",onClick:()=>b("over_under_accuracy"),children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["Accuracy %",e.jsx(Jt,{className:"h-3 w-3"})]})}),e.jsx(U,{className:"cursor-pointer text-right",onClick:()=>b("sharpness_score"),children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["Sharpness",e.jsx(Jt,{className:"h-3 w-3"})]})})]})}),e.jsx($e,{children:u?e.jsx(he,{children:e.jsx(M,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"Loading data..."})}):x.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No data found"})}):x.slice(0,50).map(P=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:P.sportsbook}),e.jsx(M,{className:"capitalize",children:P.sport}),e.jsx(M,{children:P.market_name}),e.jsx(M,{className:"text-right",children:P.sample_size}),e.jsx(M,{className:"text-right",children:P.over_under_accuracy!==null?`${P.over_under_accuracy}%`:"-"}),e.jsx(M,{className:"text-right",children:e.jsxs(B,{className:ia(P.sharpness_score),children:[P.sharpness_score??0," - ",wi(P.sharpness_score)]})})]},P.id))})]})}),x.length>50&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Showing 50 of ",x.length," records"]})]}),e.jsx(we,{value:"by-sport",className:"mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Sportsbook"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{className:"text-right",children:"Total Samples"}),e.jsx(U,{className:"text-right",children:"Markets Tracked"}),e.jsx(U,{className:"text-right",children:"Avg Sharpness"})]})}),e.jsx($e,{children:g.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No data found"})}):g.slice(0,30).map((P,C)=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:P.sportsbook}),e.jsx(M,{className:"capitalize",children:P.sport}),e.jsx(M,{className:"text-right",children:P.sample_size}),e.jsx(M,{className:"text-right",children:P.markets_tracked}),e.jsx(M,{className:"text-right",children:e.jsxs(B,{className:ia(P.sharpness_score),children:[P.sharpness_score," - ",wi(P.sharpness_score)]})})]},`${P.sportsbook}-${P.sport}-${C}`))})]})})}),e.jsx(we,{value:"by-bet-type",className:"mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Bet Type"}),e.jsx(U,{children:"Sharpest Book"}),e.jsx(U,{className:"text-right",children:"Score"}),e.jsx(U,{children:"2nd Best"}),e.jsx(U,{className:"text-right",children:"Score"}),e.jsx(U,{className:"text-right",children:"Books Tracked"})]})}),e.jsx($e,{children:f.length===0?e.jsx(he,{children:e.jsx(M,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No data found"})}):f.map((P,C)=>e.jsxs(he,{children:[e.jsx(M,{className:"capitalize",children:P.sport}),e.jsx(M,{children:P.market_name}),e.jsx(M,{className:"font-medium",children:P.sharpest_book}),e.jsx(M,{className:"text-right",children:e.jsx(B,{className:ia(P.sharpest_score),children:P.sharpest_score})}),e.jsx(M,{className:"text-muted-foreground",children:P.second_book??"-"}),e.jsx(M,{className:"text-right",children:P.second_score!==null?e.jsx(B,{variant:"outline",className:ia(P.second_score),children:P.second_score}):"-"}),e.jsx(M,{className:"text-right",children:P.total_books})]},`${P.sport}-${P.market_name}-${C}`))})]})})})]}),_.length>0&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h4",{className:"text-sm font-medium mb-4",children:"Sharpness by Sportsbook & Bet Type"}),e.jsx("div",{className:"h-[350px]",children:e.jsx(Hi,{width:"100%",height:"100%",children:e.jsxs(pd,{data:_,margin:{top:20,right:30,left:2
3250,bottom:60},children:[e.jsx(Xo,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Wi,{dataKey:"sportsbook",angle:-45,textAnchor:"end",height:80,tick:{fontSize:12},className:"fill-muted-foreground"}),e.jsx(ed,{domain:[0,100],className:"fill-muted-foreground"}),e.jsx(Gi,{contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(sd,{}),e.jsx(hn,{dataKey:"Spread",fill:"hsl(var(--chart-1))",radius:[4,4,0,0]}),e.jsx(hn,{dataKey:"Over/Under",fill:"hsl(var(--chart-2))",radius:[4,4,0,0]}),e.jsx(hn,{dataKey:"Moneyline",fill:"hsl(var(--chart-3))",radius:[4,4,0,0]})]})})})]})]})]})}const Si=s=>{var a,t;return s.bet_type!=="parlay"||!((t=(a=s.parlay_details)==null?void 0:a.legs)!=null&&t.length)?!1:s.parlay_details.legs.some(n=>!n.game_id)},Hv=s=>{var a;return(a=s.parlay_details)!=null&&a.legs?s.parlay_details.legs.filter(t=>!t.game_id).length:0};function Wv(){var as,Oe,Ie,ds,be,Qe,et,Gs;const[s,a]=v.useState(!1),[t,n]=v.useState([]),[r,i]=v.useState(null),[l,m]=v.useState([]),[o,h]=v.useState(""),[N,d]=v.useState(!1),[y,u]=v.useState(!1),[x,g]=v.useState(!1),[f,_]=v.useState(!1),[k,b]=v.useState(null),[j,c]=v.useState("select-game"),[p,w]=v.useState(null),[S,P]=v.useState("home"),[C,O]=v.useState("moneyline"),[$,z]=v.useState(""),[D,A]=v.useState(""),[F,q]=v.useState(!1),[E,L]=v.useState(!1),[H,Z]=v.useState(0),[se,ie]=v.useState([]),Y=async()=>{a(!0);try{const{data:xe,error:Ce}=await T.functions.invoke("find-pending-bets");if(Ce)throw Ce;const ye=(xe.all_pending||[]).filter(We=>We.needs_matching);if(n(ye),ye.length===0)K.success("All pending bets have complete data! Use Re-run Auto Settle to settle them.");else{const We=ye.filter(bs=>!bs.has_game_data).length,ps=ye.filter(bs=>bs.has_game_data&&!bs.has_odds_data).length;K.success(`Found ${We} bet(s) missing game data, ${ps} missing odds`)}}catch(xe){console.error("Error fetching pending bets:",xe),K.error(`Failed to fetch pending bets: ${xe.message}`)}finally{a(!1)}},I=xe=>{i(xe),u(!0)},ee=async xe=>{var Ce,Se;i(xe),d(!0),c("select-game"),w(null),P("home"),O(xe.bet_type||"moneyline"),z(((Ce=xe.bet_line)==null?void 0:Ce.toString())||""),A(((Se=xe.odds)==null?void 0:Se.toString())||""),h(""),await ve(xe)},le=xe=>{const Ce=xe.toLowerCase().trim();return Ce.includes("mlb")||Ce.includes("baseball")?"baseball":Ce.includes("nba")||Ce.includes("ncaab")||Ce.includes("basketball")?"basketball":Ce.includes("nfl")||Ce.includes("ncaaf")||Ce.includes("football")&&!Ce.includes("soccer")?"football":Ce.includes("nhl")||Ce.includes("hockey")?"hockey":Ce.includes("soccer")||Ce.includes("epl")||Ce.includes("mls")||Ce.includes("liga")||Ce.includes("serie")||Ce.includes("bundesliga")?"soccer":Ce.includes("mma")||Ce.includes("ufc")?"mma":null},ve=async xe=>{_(!0);try{const Ce=jt(xe.created_at),Se=ke(No(Ce,30),"yyyy-MM-dd"),ye=ke(Oi(Ce,60),"yyyy-MM-dd");let We=T.from("master_games").select("id, home_team, away_team, game_date, commence_time, game_status, sport, odds_api_game_id").gte("game_date",Se).lte("game_date",ye).order("commence_time",{ascending:!1});const ps=xe.sport?le(xe.sport):null;ps&&(We=We.eq("sport",ps)),We=We.limit(2e3);const{data:bs,error:Os}=await We;if(Os)throw Os;m(bs||[])}catch(Ce){console.error("Error fetching games:",Ce),K.error(`Failed to fetch games: ${Ce.message}`)}finally{_(!1)}},te=xe=>{if(w(xe),c("fix-pick"),r){const Ce=jt(xe.commence_time),Se=jt(r.created_at),ye=hl(new Date),We=hl(Se),ps=Nu(We,ye);q(Ce<Se&&xe.game_status==="completed"&&!ps)}},X=()=>{if(!p)return"";if(C==="total")return`${S==="over"?"Over":"Under"} ${$}`;if(C==="prop")return`${S==="over"?"Over":"Under"} ${$||""}`.trim();{const xe=S==="home"?p.home_team:p.away_team;if(C==="spread"&&$){const Ce=parseFloat($);return`${xe} ${Ce>=0?"+":""}${Ce}`}else return`${xe} Moneyline`}},ae=async()=>{if(!(!r||!p)){g(!0);try{const xe=X(),{data:Ce,error:Se}=await T.functions.invoke("update-bet-game-data",{body:{bet_id:r.id,bet_source:r.source,game_id:p.id,home_team:p.home_team,away_team:p.away_team,selection:xe,picked_side:S,bet_line:$?parseFloat($):null,bet_type:C,odds:D?parseInt(D):null}});if(Se)throw Se;
325if(Ce!=null&&Ce.error)throw new Error(Ce.error);K.success("Game matched and pick corrected!"),d(!1),n(ye=>ye.filter(We=>We.id!==r.id))}catch(xe){console.error("Error updating bet:",xe),K.error(`Failed to match game: ${xe.message}`)}finally{g(!1)}}},W=async()=>{if(!(!r||!p)){g(!0);try{const xe=X(),{data:Ce,error:Se}=await T.functions.invoke("update-bet-game-data",{body:{bet_id:r.id,bet_source:r.source,game_id:p.id,home_team:p.home_team,away_team:p.away_team,selection:xe,picked_side:S,bet_line:$?parseFloat($):null,bet_type:C,odds:D?parseInt(D):null}});if(Se)throw Se;if(Ce!=null&&Ce.error)throw new Error(Ce.error);const{data:ye,error:We}=await T.functions.invoke("update-bet-game-data",{body:{bet_id:r.id,bet_source:r.source,action:"void",void_reason:"Matched to completed game - potential fraud (game ended before bet was placed)"}});if(We)throw We;if(ye!=null&&ye.error)throw new Error(ye.error);K.success("Bet matched and voided successfully"),d(!1),n(ps=>ps.filter(bs=>bs.id!==r.id))}catch(xe){console.error("Error matching and voiding bet:",xe),K.error(`Failed to match and void bet: ${xe.message}`)}finally{g(!1)}}},re=async xe=>{const Ce=xe.source==="user_bet"&&xe.source_type==="manual",Se=Ce?"UNSETTLEABLE":"VOID",ye=Ce?"unsettleable":"void",We=Ce?"Marked as unsettleable - requires manual settlement by user":"Marked as void - excluded from ROI and win rate calculations",ps=Ce?`Mark this bet as UNSETTLEABLE?
326
327"${xe.selection}"
328
329The user will need to manually settle this bet in their Bet History.`:`Mark this bet as VOID?
330
331"${xe.selection}"
332
333This will exclude it from ROI and win rate calculations.`;if(confirm(ps)){b(xe.id);try{const{data:bs,error:Os}=await T.functions.invoke("update-bet-game-data",{body:{bet_id:xe.id,bet_source:xe.source,action:ye,void_reason:We}});if(Os)throw Os;if(bs!=null&&bs.error)throw new Error(bs.error);K.success(`Bet marked as ${Se.toLowerCase()}`),n(Ft=>Ft.filter(pt=>pt.id!==xe.id))}catch(bs){console.error(`Error marking bet as ${Se.toLowerCase()}:`,bs),K.error(`Failed to mark bet: ${bs.message}`)}finally{b(null)}}},ce=async xe=>{var Se;i(xe),L(!0),Z(0),w(null),h("");const Ce=((Se=xe.parlay_details)==null?void 0:Se.legs)||[];ie(Ce),await ve(xe)},Pe=async xe=>{if(r){g(!0);try{const Ce=se[H],{data:Se,error:ye}=await T.functions.invoke("update-bet-game-data",{body:{bet_id:r.id,bet_source:r.source,action:"update_parlay_leg",leg_index:H,game_id:xe.id,home_team:xe.home_team,away_team:xe.away_team,leg_sport:xe.sport,selection:(Ce==null?void 0:Ce.selection)||(Ce==null?void 0:Ce.pick)||(Ce==null?void 0:Ce.game)}});if(ye)throw ye;if(Se!=null&&Se.error)throw new Error(Se.error);const We=[...se];We[H]={...We[H],game_id:xe.id,home_team:xe.home_team,away_team:xe.away_team},ie(We),K.success(`Leg ${H+1} matched to ${xe.away_team} @ ${xe.home_team}`);const ps=We.findIndex((bs,Os)=>Os>H&&!bs.game_id);ps>=0?(Z(ps),w(null),h("")):We.every(Os=>!!Os.game_id)&&(K.success("All parlay legs matched!"),L(!1),n(Os=>Os.filter(Ft=>Ft.id!==r.id)))}catch(Ce){console.error("Error matching parlay leg:",Ce),K.error(`Failed to match leg: ${Ce.message}`)}finally{g(!1)}}},Fe=l.filter(xe=>{var Se,ye;if(!o)return!0;const Ce=o.toLowerCase();return((Se=xe.home_team)==null?void 0:Se.toLowerCase().includes(Ce))||((ye=xe.away_team)==null?void 0:ye.toLowerCase().includes(Ce))}),Ae=xe=>{const Ce=(xe==null?void 0:xe.toLowerCase())||"";return Ce.includes("nba")||Ce.includes("basketball")?"bg-orange-500/20 text-orange-400":Ce.includes("nfl")||Ce.includes("football")?"bg-green-500/20 text-green-400":Ce.includes("mlb")||Ce.includes("baseball")?"bg-red-500/20 text-red-400":Ce.includes("nhl")||Ce.includes("hockey")?"bg-blue-500/20 text-blue-400":"bg-muted text-muted-foreground"},Ve=xe=>xe==="completed"?e.jsx(B,{variant:"outline",className:"bg-green-500/20 text-green-400",children:"Completed"}):xe==="scheduled"?e.jsx(B,{variant:"outline",className:"bg-blue-500/20 text-blue-400",children:"Scheduled"}):xe==="live"?e.jsx(B,{variant:"outline",className:"bg-yellow-500/20 text-yellow-400",children:"Live"}):e.jsx(B,{variant:"outline",children:xe});return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5"}),"Bet Game Matcher"]}),e.jsx(De,{children:"Find and match pending bets that are missing game data before they can be auto-settled"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsx(R,{onClick:Y,disabled:s,children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Finding Bets..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4"}),"Find Bets Missing Data"]})}),t.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(G,{className:"bg-yellow-500/10 border-yellow-500/30",children:e.jsx(J,{className:"pt-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{className:"h-6 w-6 text-yellow-400"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-yellow-400",children:t.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"bet(s) need game data matched or voided"})]})]})})}),e.jsx(cs,{className:"h-[400px] border rounded-md",children:e.jsx("div",{className:"p-4 space-y-2",children:t.map(xe=>{var Ce,Se,ye,We,ps;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx(ls,{className:"h-5 w-5 text-yellow-400 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"font-medium truncate",title:xe.selection,children:[(Ce=xe.selection)==null?void 0:Ce.substring(0,60),((Se=xe.selection)==null?void 0:Se.length)>60?"...":""]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground flex-wrap",children:[e.jsxs(B,{variant:"outline",className:"text-xs bg-slate-500/20 text-slate-400",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),xe.user_display]}),e.jsx(B,{variant:"outline",className:Ae(xe.sport),children:((ye=xe.sport)==null?void 0:ye.toUpperCase())||"Unknown"}),e.jsx(B,{variant:"outline",children:xe.bet_type}),e.jsx("span",{children:ke(jt(xe.created_at),"MMM d, yyyy")}),e.jsx(B,{variant:"outline",className:"text-xs",children:xe.source==="tracked_recommendation"?"Tracked":"Placed"}),xe.source==="user_bet"&&xe.source_type==="manual"&&e.jsx(B,{variant:"outline",className:"text-xs bg-orange-500/20 text-orange-400",children:"Manual"}),xe.source==="user_bet"&&xe.source_type==="ai_recommendation"&&e.jsx(B,{variant:"outline",className:"text-xs bg-blue-500/20 text-blue-400",children:"AI Rec"}),Si(xe)&&e.jsxs(B,{variant:"outline",className:"text-xs bg-purple-500/20 text-purple-400",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),Hv(xe),"/",(ps=(We=xe.parlay_details)==null?void 0:We.legs)==null?void 0:ps.length," legs unmatched"]}),xe.has_game_data&&!xe.has_odds_data&&xe.source_type!=="manual"&&e.jsx(B,{variant:"outline",className:"text-xs bg-red-500/20 text-red-400",children:"Missing Odds"}),!xe.has_game_data&&e.jsx(B,{variant:"outline",className:"text-xs bg-yellow-500/20 text-yellow-400",children:"Missing Game"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>I(xe),title:"View Details",children:e.jsx(us,{className:"h-4 w-4"})}
333),Si(xe)?e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>ce(xe),children:[e.jsx(xr,{className:"h-4 w-4 mr-1"}),"Match Legs"]}):e.jsx(R,{size:"sm",variant:"outline",onClick:()=>ee(xe),children:"Match"}),e.jsx(R,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>re(xe),disabled:k===xe.id,title:xe.source==="user_bet"&&xe.source_type==="manual"?"Mark as unsettleable - user settles manually":"Void - exclude from ROI/stats",children:k===xe.id?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):xe.source==="user_bet"&&xe.source_type==="manual"?"Unsettleable":"Void"})]})]},`${xe.source}-${xe.id}`)})})})]}),e.jsx(Ue,{open:y,onOpenChange:u,children:e.jsxs(Be,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Bet Details"}),e.jsx(Vs,{children:"Full recommendation context"})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Selection"}),e.jsx("p",{className:"font-medium",children:r.selection||"N/A"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Sport"}),e.jsx(B,{variant:"outline",className:Ae(r.sport),children:((as=r.sport)==null?void 0:as.toUpperCase())||"Unknown"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Bet Type"}),e.jsx("p",{children:r.bet_type||"N/A"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Odds"}),e.jsx("p",{children:r.odds||"N/A"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Picked Side"}),e.jsx("p",{children:r.picked_side||((Oe=r.recommendation_context)==null?void 0:Oe.picked_side)||"N/A"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Bet Line"}),e.jsx("p",{children:r.bet_line??((Ie=r.recommendation_context)==null?void 0:Ie.bet_line)??"N/A"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Home Team"}),e.jsx("p",{children:r.home_team||((ds=r.recommendation_context)==null?void 0:ds.home_team)||"N/A"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Away Team"}),e.jsx("p",{children:r.away_team||((be=r.recommendation_context)==null?void 0:be.away_team)||"N/A"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Source"}),e.jsx(B,{variant:"outline",children:r.source==="tracked_recommendation"?"Tracked":"Placed"})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Created"}),e.jsx("p",{children:ke(jt(r.created_at),"MMM d, yyyy h:mm a")})]})]}),(r.notes||((Qe=r.recommendation_context)==null?void 0:Qe.reasoning))&&e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"AI Reasoning / Notes"}),e.jsx("div",{className:"mt-1 p-3 rounded-lg bg-muted/50 text-sm whitespace-pre-wrap",children:r.notes||((et=r.recommendation_context)==null?void 0:et.reasoning)})]}),r.recommendation_data&&e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Recommendation Data"}),e.jsx(cs,{className:"h-[200px] mt-1",children:e.jsx("pre",{className:"p-3 rounded-lg bg-muted/50 text-xs overflow-x-auto",children:JSON.stringify(r.recommendation_data,null,2)})})]}),r.recommendation_context&&e.jsxs("div",{children:[e.jsx(Q,{className:"text-muted-foreground text-xs",children:"Full AI Context"}),e.jsx(cs,{className:"h-[200px] mt-1",children:e.jsx("pre",{className:"p-3 rounded-lg bg-muted/50 text-xs overflow-x-auto",children:JSON.stringify(r.recommendation_context,null,2)})})]}),!r.has_game_data&&e.jsxs(R,{className:"w-full",onClick:()=>{u(!1),ee(r)},children:[e.jsx(Zr,{className:"mr-2 h-4 w-4"}),"Match to Game"]})]})]})}),e.jsx(Ue,{open:N,onOpenChange:d,children:e.jsxs(Be,{className:"max-w-2xl max-h-[80vh]",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:j==="select-game"?"Step 1: Select Game":"Step 2: Fix Pick"}),e.jsx(Vs,{children:j==="select-game"?"Search and select the correct game for this bet":"Correct the team selection and bet type"})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50",children:[e.jsx("div",{className:"font-medium",children:r.selection}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-muted-foreground",children:[e.jsx(B,{variant:"outline",className:Ae(r.sport),children:(Gs=r.sport)==null?void 0:Gs.toUpperCase()}),e.jsxs("span",{children:["Created: ",ke(jt(r.created_at),"MMM d, yyyy h:mm a")]})]})]}),j==="select-game"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by team name...",value:o,onChange:xe=>h(xe.target.value),className:"pl-9"})]}),e.jsx(cs,{className:"h-[300px] border rounded-md",children:f?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(ne,{className:"h-6 w-6 animate-spin"})}):Fe.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No matching games found"}):e.jsx("div",{className:"p-2 space-y-1",children:Fe.map(xe=>{const Ce=jt(xe.commence_time),Se=jt(r.created_at),ye=Ce<Se&&xe.game_status==="completed";return e.jsxs("div",{className:Le("flex items-center justify-between p-3 rounded-lg hover:bg-muted/50 transition-colors cursor-pointer",ye&&"border-2 border-destructive/50 bg-destructive/5"),onClick:()=>te(xe),children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[xe.away_team," @ ",xe.home_team]}),ye&&e.jsx(B,{variant:"destructive",className:"text-xs",children:"⚠️ FRAUD RISK"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-muted-foreground",children:[e.jsx("span",{children:ke(Ce,"MMM d, yyyy h:mm a")}),Ve(xe.game_status),ye&&e.jsx("span",{className:"text-destructive text-xs",children:"Game started before bet was placed"})]})]}),e.jsx(aa,{className:"h-4 w-4 text-muted-foreground"})]},xe.id)})})})]}),j==="fix-pick"&&p&&e.jsx("div",{className:"max-h-[50vh] overflow-y-auto",children:e.jsxs("div",{className:"space-y-4 pr-2",children:[F&&e.jsxs(ss,{variant:"destructive",className:"border-2",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsxs(ts,{className:"space-y-2",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"POTENTIAL FRAUD DETECTED:"})," This game was completed BEFORE the bet was placed."]}),e.jsx("p",{className:"text-sm",children:'Use "Match & Void" to link this bet to the game for record-keeping, while excluding it from ROI calculations and AI learning.'})]})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-primary/10 border border-primary/30",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Selected Game"}),e.jsxs("div",{className:"font-medium",children:[p.away_team," @ ",p.home_team]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:ke(jt(p.game_date),"MMM d, yyyy")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Bet Type"}),e.jsxs(oe,{value:C,onValueChange:xe=>{O(xe),P(xe==="total"||xe==="prop"?"over":"home")},children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"moneyline",children:"Moneyline"}),e.jsx(V,{value:"spread",children:"Spread"}),e.jsx(V,{value:"total",children:"Total (Over/Under)"}),e.jsx(V,{value:"prop",children:"Prop"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:C==="total"||C==="prop"?"Over or Under?":"Which team was picked?"}),e.jsx(Ut,{value:S,onValueChange:xe=>P(xe),children:C==="total"||C==="prop"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"over",id:"over"}),e.jsx(Q,{htmlFor:"over",className:"cursor-pointer",children:"Over"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"under",id:"under"}),e.jsx(Q,{htmlFor:"under",className:"cursor-pointer",children:"Under"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"home",id:"home"}),e.jsxs(Q,{htmlFor:"home",className:"cursor-pointer",children:[p.home_team," (Home)"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"away",id:"away"}),e.jsxs(Q,{htmlFor:"away",className:"cursor-pointer",children:[p.away_team," (Away)"]})]})]})})]}),(C==="spread"||C==="total"||C==="prop")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:C==="spread"?"Spread Line (e.g., +6.5 or -3)":C==="total"?"Total Line (e.g., 220.5)":"Prop Line (e.g., 24.5)"}),e.jsx(pe,{type:"text",placeholder:C==="spread"?"+6.5":"220.5",value:$,onChange:xe=>z(xe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Odds (American format)"}),e.jsx(pe,{type:"text",placeholder:"-110",value:D,onChange:xe=>A(xe.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter American odds (e.g., -110, +150). Required for AI/KLUTCH bets."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"outline",onClick:()=>c("select-game"),className:"flex-1",children:"Back"}),F?e.jsxs(R,{onClick:W,disabled:x,variant:"destructive",className:"flex-1",children:[x?e.jsx(ne,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(ls,{className:"h-4 w-4 mr-2"}),"Match & Void"]}):e.jsx(R,{onClick:ae,disabled:x,className:"flex-1",children:x?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):"Confirm Match"})]})]})})]})]})}),e.jsx(Ue,{open:E,onOpenChange:L,children:e.jsxs(Be,{className:"max-w-2xl max-h-[80vh]",children:[e.jsxs(ze,{children:[e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-5 w-5"}),"Match Parlay Legs"]}),e.jsx(Vs,{children:"Match each parlay leg to its corresponding game"})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/30",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Matching Leg ",H+1," of ",se.length]}),e.jsx("div",{className:"flex items-center gap-1",children:se.map((xe,Ce)=>e.jsx("div",{className:Le("w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium cursor-pointer transition-colors",xe.game_id?"bg-green-500/20 text-green-400":Ce===H?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),onClick:()=>{xe.game_id||Z(Ce)},title:xe.game_id?"Matched":"Click to match",children:xe.game_id?e.jsx(Ks,{className:"h-3 w-3"}):Ce+1},Ce))})]}),se[H]&&e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"text-sm text-muted-foreground mb-1",children:["Leg ",H+1]}),e.jsx("div",{className:"font-medium",children:se[H].selection||se[H].pick||se[H].game||"Unknown selection"}),se[H].odds&&e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Odds: ",se[H].odds]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by team name...",value:o,onChange:xe=>h(xe.target.value),className:"pl-9"})]}),e.jsx(cs,{className:"h-[300px] border rounded-md",children:f?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(ne,{className:"h-6 w-6 animate-spin"})}):Fe.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No matching games found"}):e.jsx("div",{className:"p-2 space-y-1",children:Fe.map(xe=>e.jsxs("div",{className:Le("flex items-center justify-between p-3 rounded-lg hover:bg-muted/50 transition-colors cursor-pointer",x&&"opacity-50 pointer-events-none"),onClick:()=>Pe(xe),children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-medium",children:[xe.away_team," @ ",xe.home_team]})}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-muted-foreground",children:[e.jsx("span",{children:ke(jt(xe.commence_time),"MMM d, yyyy h:mm a")}),Ve(xe.game_status)]})]}),x?e.jsx(ne,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(aa,{className:"h-4 w-4 text-muted-foreground"})]},xe.id))})}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-sm font-medium mb-2",children:"All Legs"}),e.jsx("div",{className:"space-y-1",children:se.map((xe,Ce)=>e.jsxs("div",{className:Le("flex items-center justify-between p-2 rounded text-sm",Ce===H?"bg-primary/10":"bg-muted/30"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("span",{className:"text-muted-foreground shrink-0",children:["Leg ",Ce+1,":"]}),e.jsx("span",{className:"truncate",children:xe.selection||xe.pick||xe.game||"Unknown"})]}),xe.game_id?e.jsxs(B,{variant:"outline",className:"bg-green-500/20 text-green-400 shrink-0",children:[e.jsx(Ks,{className:"h-3 w-3 mr-1"}),"Matched"]}):e.jsx(B,{variant:"outline",className:"text-muted-foreground shrink-0",children:"Unmatched"})]},Ce))})]})]})]})})]})]})}const ki=[{code:"nfl",name:"Football"},{code:"nba",name:"Basketball"},{code:"mlb",name:"Baseball"},{code:"nhl",name:"Hockey"},{code:"soccer",name:"Soccer"}
333,{code:"mma",name:"MMA"},{code:"golf",name:"Golf"},{code:"tennis",name:"Tennis"},{code:"racing",name:"Racing"}],Gv=[{value:"none",label:"No Subscription"},{value:"insider",label:"Insider (No Sports)"},{value:"single",label:"Single Sport"},{value:"triple",label:"Triple Sport"},{value:"full",label:"Full Access"}],Qv=[{value:"active",label:"Active"},{value:"trial",label:"Trial"},{value:"paused",label:"Paused"},{value:"past_due",label:"Past Due"}];function Yv(){const{simulation:s,startSimulation:a,stopSimulation:t}=_o(),[n,r]=v.useState("single"),[i,l]=v.useState(["nba"]),[m,o]=v.useState("active"),h=x=>{const g=n==="single"?1:n==="triple"?3:9;i.includes(x)?l(f=>f.filter(_=>_!==x)):i.length<g&&l(f=>[...f,x])},N=x=>{r(x),x==="none"||x==="insider"?l([]):x==="full"?l(ki.map(g=>g.code)):x==="single"?l(i.slice(0,1)):x==="triple"&&l(i.slice(0,3))},d=()=>{a(n==="none"?null:n,i,m)},y=()=>n==="single"?1:n==="triple"?3:9,u=n==="single"||n==="triple";return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-5 w-5 text-primary"}),"Subscription Simulator"]}),e.jsx(De,{children:"Test the app as a user with different subscription types. Your admin access will be temporarily hidden."})]}),e.jsxs(J,{className:"space-y-6",children:[s.isActive&&e.jsxs(ss,{className:"border-amber-500/50 bg-amber-500/10",children:[e.jsx(xs,{className:"h-4 w-4 text-amber-500"}),e.jsxs(ts,{className:"text-amber-200",children:[e.jsx("span",{className:"font-semibold",children:"Simulation Active:"})," ",s.packageType?`${s.packageType} package`:"No subscription",s.sports.length>0&&` (${s.sports.join(", ").toUpperCase()})`,s.status&&` - ${s.status}`]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Package Type"}),e.jsxs(oe,{value:n||"none",onValueChange:x=>N(x),disabled:s.isActive,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select package"})}),e.jsx(me,{children:Gv.map(x=>e.jsx(V,{value:x.value||"none",children:x.label},x.value||"none"))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Subscription Status"}),e.jsxs(oe,{value:m||"active",onValueChange:x=>o(x),disabled:s.isActive||n==="none",children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select status"})}),e.jsx(me,{children:Qv.map(x=>e.jsx(V,{value:x.value||"active",children:x.label},x.value||"active"))})]})]})]}),u&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Q,{children:["Sports (",i.length,"/",y(),")"]}),n==="single"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Select 1 sport"}),n==="triple"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Select up to 3 sports"})]}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-5 gap-2",children:ki.map(x=>e.jsxs("label",{className:`flex items-center gap-2 p-2 rounded-md border cursor-pointer transition-colors ${i.includes(x.code)?"border-primary bg-primary/10":"border-border hover:border-primary/50"} ${s.isActive?"opacity-50 cursor-not-allowed":""}`,children:[e.jsx(Ms,{checked:i.includes(x.code),onCheckedChange:()=>h(x.code),disabled:s.isActive||!i.includes(x.code)&&i.length>=y()}),e.jsx("span",{className:"text-sm font-medium",children:x.name})]},x.code))})]}),n==="insider"&&!s.isActive&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Insider package has no sport-specific access. Users can access KASH AI, Kommunity, KLUTCH picks, and content only."}),n==="full"&&!s.isActive&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Full access includes all sports automatically."}),e.jsx("div",{className:"flex gap-3",children:s.isActive?e.jsxs(R,{onClick:t,variant:"destructive",className:"flex-1",children:[e.jsx($d,{className:"h-4 w-4 mr-2"}),"Stop Simulation"]}):e.jsxs(R,{onClick:d,className:"flex-1",children:[e.jsx(Rt,{className:"h-4 w-4 mr-2"}),"Start Simulation"]})}),s.isActive&&e.jsxs("div",{className:"pt-4 border-t border-border",children:[e.jsx(Q,{className:"text-muted-foreground",children:"Currently Simulating:"}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-2",children:[e.jsx(B,{variant:"outline",className:"bg-primary/10",children:s.packageType||"No Subscription"}),s.status&&e.jsx(B,{variant:"outline",className:s.status==="active"?"bg-emerald-500/10 text-emerald-400":s.status==="trial"?"bg-blue-500/10 text-blue-400":s.status==="paused"?"bg-amber-500/10 text-amber-400":"bg-red-500/10 text-red-400",children:s.status}),s.sports.map(x=>e.jsx(B,{variant:"secondary",children:x.toUpperCase()},x))]})]})]})]})}function Jv(){const[s,a]=v.useState(!1),[t,n]=v.useState(!1),[r,i]=v.useState(null),l=async()=>{a(!0),i(null);try{const{data:m,error:o}=await T.functions.invoke("settle-kontest-picks",{body:{force_recalc:t}});if(o)throw o;const h={picksSettled:(m==null?void 0:m.picksSettled)||(m==null?void 0:m.picks_settled)||0,entriesUpdated:(m==null?void 0:m.entriesUpdated)||(m==null?void 0:m.entries_updated)||0,leaderboardRepaired:(m==null?void 0:m.leaderboardRepaired)||(m==null?void 0:m.leaderboard_repaired)||0,kontestsCompleted:(m==null?void 0:m.kontestsCompleted)||(m==null?void 0:m.kontests_completed)||0,errors:(m==null?void 0:m.errors)||[]};i(h),t?K.success(`Force recalc complete: ${h.picksSettled} picks, ${h.entriesUpdated} entries updated`):K.success(`Settled ${h.picksSettled} kontest picks`)}catch(m){console.error("Settlement error:",m),K.error(m.message||"Failed to settle kontest picks"),i({picksSettled:0,entriesUpdated:0,leaderboardRepaired:0,k
333ontestsCompleted:0,errors:[m.message||"Unknown error"]})}finally{a(!1)}};return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Js,{className:"h-5 w-5 text-primary"}),"Settle Kontest Picks"]}),e.jsx(De,{children:"Settle pending kontest picks based on KLUTCH pick results and update entry scores"})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ge,{id:"force-recalc",checked:t,onCheckedChange:n}),e.jsx(Q,{htmlFor:"force-recalc",className:"text-sm",children:"Force Recalc (re-settle already settled picks)"})]}),e.jsx(R,{onClick:l,disabled:s,variant:t?"default":"outline",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Settling..."]}):t?"Force Recalc All":"Settle Pending"})]}),r&&e.jsxs("div",{className:"mt-4 p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r.errors.length===0?e.jsx(rs,{className:"h-5 w-5 text-green-500"}):e.jsx(xs,{className:"h-5 w-5 text-yellow-500"}),e.jsx("span",{className:"font-medium",children:"Settlement Results"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Picks Settled:"}),e.jsx("span",{className:"font-medium text-green-600",children:r.picksSettled})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Entries Updated:"}),e.jsx("span",{className:"font-medium",children:r.entriesUpdated})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Leaderboard Repaired:"}),e.jsx("span",{className:"font-medium",children:r.leaderboardRepaired})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Kontests Completed:"}),e.jsx("span",{className:"font-medium",children:r.kontestsCompleted})]})]}),r.errors.length>0&&e.jsxs("div",{className:"mt-3 p-3 rounded bg-destructive/10 border border-destructive/20",children:[e.jsxs("div",{className:"flex items-center gap-2 text-destructive mb-2",children:[e.jsx(Is,{className:"h-4 w-4"}),e.jsxs("span",{className:"font-medium text-sm",children:["Errors (",r.errors.length,")"]})]}),e.jsxs("ul",{className:"text-xs text-destructive/80 space-y-1",children:[r.errors.slice(0,5).map((m,o)=>e.jsxs("li",{children:["• ",m]},o)),r.errors.length>5&&e.jsxs("li",{className:"text-muted-foreground",children:["...and ",r.errors.length-5," more errors"]})]})]})]})]})]})}function Zv(){const{toast:s}=Ws();Me();const[a,t]=v.useState(!1),{data:n,isLoading:r,refetch:i}=ge({queryKey:["pending-bets-cancelled-games"],queryFn:async()=>{var j;const{data:d,error:y}=await T.from("user_bets").select(`
334          id,
335          selection,
336          bet_type,
337          sport,
338          created_at,
339          game_id,
340          user_id
341        `).is("result",null).not("game_id","is",null);if(y)throw y;if(!d||d.length===0)return[];const u=[...new Set(d.map(c=>c.game_id).filter(Boolean))],{data:x,error:g}=await T.from("master_games").select("id, odds_api_game_id, game_status, home_team, away_team, game_date, commence_time").or(`id.in.(${u.join(",")}),odds_api_game_id.in.(${u.join(",")})`);if(g)throw g;const f=new Map,_=new Map;(x||[]).forEach(c=>{f.set(c.id,c),c.odds_api_game_id&&_.set(c.odds_api_game_id,c)});const k=[],b=new Date(Date.now()-6*60*60*1e3);for(const c of d){const p=f.get(c.game_id)||_.get(c.game_id);if(!p)continue;const w=(j=p.game_status)==null?void 0:j.toLowerCase(),S=p.commence_time?new Date(p.commence_time):new Date(`${p.game_date}T12:00:00`);w==="postponed"||w==="canceled"||w==="cancelled"||w==="suspended"?k.push({id:c.id,selection:c.selection,bet_type:c.bet_type,sport:c.sport,created_at:c.created_at,game_id:c.game_id,game_status:w,home_team:p.home_team,away_team:p.away_team,game_date:p.game_date,commence_time:p.commence_time,issue_type:"cancelled"}):w==="scheduled"&&S<b&&k.push({id:c.id,selection:c.selection,bet_type:c.bet_type,sport:c.sport,created_at:c.created_at,game_id:c.game_id,game_status:"stale_scheduled",home_team:p.home_team,away_team:p.away_team,game_date:p.game_date,commence_time:p.commence_time,issue_type:"stale"})}return k}}),l=async()=>
341{if(!(!n||n.length===0)){t(!0);try{const d=n.map(g=>g.id),{data:y,error:u}=await T.from("user_bets").update({result:"void",result_tracked:!0,settlement_notes:"Game cancelled/postponed - bulk voided by admin"}).in("id",d).select("id");if(u)throw u;const x=(y==null?void 0:y.length)||0;if(x===0)throw new Error("Update blocked - you may not have permission to modify these bets");s({title:"Bets Voided",description:`Successfully voided ${x} bets on cancelled/postponed games.`}),await i()}catch(d){console.error("Error voiding bets:",d),s({title:"Error",description:d.message||"Failed to void bets",variant:"destructive"})}finally{t(!1)}}},m=async(d,y)=>{try{const{data:u,error:x}=await T.from("user_bets").update({result:"void",result_tracked:!0,settlement_notes:`Game ${y} - voided by admin`}).eq("id",d).select("id");if(x)throw x;if(!u||u.length===0)throw new Error("Update blocked - you may not have permission to modify this bet");s({title:"Bet Voided",description:"Successfully voided the bet."}),await i()}catch(u){console.error("Error voiding bet:",u),s({title:"Error",description:u.message||"Failed to void bet",variant:"destructive"})}},o=d=>{switch(d){case"postponed":return"secondary";case"canceled":case"cancelled":return"destructive";case"suspended":return"outline";case"stale_scheduled":return"outline";default:return"default"}},h=(n==null?void 0:n.filter(d=>d.issue_type==="cancelled"))||[],N=(n==null?void 0:n.filter(d=>d.issue_type==="stale"))||[];return e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fa,{className:"h-5 w-5 text-destructive"}),e.jsx(fe,{children:"Void Cancelled Game Bets"})]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>i(),disabled:r,children:[e.jsx(He,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),"Refresh"]})]}),e.jsx(De,{children:"Find and void pending bets on cancelled/postponed games, or stale scheduled games (6+ hours past start)"})]}),e.jsx(J,{className:"space-y-4",children:r?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Scanning for affected bets..."})]}):n&&n.length>0?e.jsxs("div",{className:"space-y-6",children:[h.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ss,{variant:"destructive",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsxs(ts,{children:["Found ",e.jsx("strong",{children:h.length})," pending bet",h.length>1?"s":""," on cancelled/postponed games. These should be voided."]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(R,{onClick:l,disabled:a,variant:"destructive",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Voiding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fa,{className:"h-4 w-4 mr-2"}),"Void All (",n.length,")"]})})}),e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:h.map(d=>{var y;return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(B,{variant:o(d.game_status),children:d.game_status.toUpperCase()}),e.jsx(B,{variant:"outline",children:(y=d.sport)==null?void 0:y.toUpperCase()}),e.jsxs("span",{className:"text-sm font-medium truncate",children:[d.away_team," @ ",d.home_team]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:d.selection}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Game: ",d.commence_time?ke(new Date(d.commence_time),"MMM d, yyyy h:mm a"):ke(new Date(`${d.game_date}T12:00:00`),"MMM d, yyyy")," • Bet placed: ",ke(new Date(d.created_at),"MMM d, yyyy")]})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>m(d.id,d.game_status),className:"ml-2 shrink-0",children:e.jsx(Fa,{className:"h-4 w-4"})})]},d.id)})})]}),N.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ss,{children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsxs(ts,{children:["Found ",e.jsx("strong",{children:N.length})," pending bet",N.length>
3411?"s":""," on stale scheduled games (started 6+ hours ago but status never updated). These may need investigation or manual voiding."]})]}),e.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:N.map(d=>{var y;return e.jsxs("div",{className:"flex items-center justify-between p-3 bg-amber-500/10 rounded-lg border border-amber-500/30",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(B,{variant:"outline",className:"border-amber-500 text-amber-600",children:"STALE SCHEDULED"}),e.jsx(B,{variant:"outline",children:(y=d.sport)==null?void 0:y.toUpperCase()}),e.jsxs("span",{className:"text-sm font-medium truncate",children:[d.away_team," @ ",d.home_team]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:d.selection}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Game: ",d.commence_time?ke(new Date(d.commence_time),"MMM d, yyyy h:mm a"):ke(new Date(`${d.game_date}T12:00:00`),"MMM d, yyyy")," • Bet placed: ",ke(new Date(d.created_at),"MMM d, yyyy")]})]}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>m(d.id,"stale_scheduled"),className:"ml-2 shrink-0",children:e.jsx(Fa,{className:"h-4 w-4"})})]},d.id)})})]})]}):e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(rs,{className:"h-5 w-5 mr-2 text-green-500"}),"No pending bets found on cancelled or postponed games"]})})]})}const Xv=[{value:"all",label:"All Sports"},{value:"american-football",label:"American Football"},{value:"baseball",label:"Baseball"},{value:"basketball",label:"Basketball"},{value:"hockey",label:"Hockey"},{value:"soccer",label:"Soccer"}];function ey({status:s}){return s==="hot"?e.jsxs(B,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/50 gap-1",children:[e.jsx(Oa,{className:"h-3 w-3"})," Hot"]}):s==="cold"?e.jsxs(B,{className:"bg-sky-500/20 text-sky-400 border-sky-500/50 gap-1",children:[e.jsx(Bd,{className:"h-3 w-3"})," Cold"]}):e.jsx(B,{variant:"secondary",children:"Neutral"})}function sy({trend:s}){return s==="up"?e.jsx(Ds,{className:"h-4 w-4 text-emerald-400"}):s==="down"?e.jsx(qt,{className:"h-4 w-4 text-red-400"}):e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"})}function ty(){const[s,a]=v.useState("all"),[t,n]=v.useState(!1),{toast:r}=Ws(),{data:i,isLoading:l,refetch:m}
341=ge({queryKey:["team-learning-patterns",s],queryFn:async()=>{let _=T.from("team_learning_patterns").select("*").order("status",{ascending:!0}).order("team_name",{ascending:!0});s!=="all"&&(_=_.eq("sport",s));const{data:k,error:b}=await _;if(b)throw b;return k??[]}}),o=async()=>{n(!0);try{const{error:_}=await T.functions.invoke("process-team-learning",{body:{time:"manual"}});if(_)throw _;r({title:"Team learning refresh started",description:"Patterns will update shortly."}),setTimeout(()=>m(),5e3)}catch(_){r({title:"Error",description:_.message,variant:"destructive"})}finally{n(!1)}},h=(_,k=1)=>_!=null?_.toFixed(k):"—",N=_=>_!=null?`${(_*100).toFixed(0)}%`:"—",d=_=>_?`${_.wins}-${_.losses}`:"—",y=(i==null?void 0:i.filter(_=>_.status==="hot").length)??0,u=(i==null?void 0:i.filter(_=>_.status==="cold").length)??0,x=(i==null?void 0:i.reduce((_,k)=>k.last_updated&&(!_||k.last_updated>_)?k.last_updated:_,""))||null,g=_=>{if(!_)return"bg-muted-foreground";const b=(Date.now()-new Date(_).getTime())/36e5;return b<24?"bg-emerald-500":b<48?"bg-yellow-500":"bg-red-500"},f=_=>{if(!_)return"—";try{return new Date(_).toLocaleString("en-US",{timeZone:"America/Chicago",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})+" CT"}catch{return"—"}};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(fe,{className:"text-lg",children:"Team Learning Patterns"}),e.jsxs(De,{children:["Form, scoring trends & streaks mined from completed master_games",i&&e.jsxs("span",{className:"ml-2 text-xs",children:["(",i.length," teams · ",y," 🔥 · ",u," ❄️)"]})]}),x&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:`inline-block h-2 w-2 rounded-full ${g(x)}`}),"Last synced: ",f(x)]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-[160px]",children:e.jsx(ue,{})}),e.jsx(me,{children:Xv.map(_=>e.jsx(V,{value:_.value,children:_.label},_.value))})]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:o,disabled:t,children:[e.jsx(He,{className:`h-4 w-4 mr-1 ${t?"animate-spin":""}`}),"Refresh"]})]})]})}),e.jsx(J,{children:l?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading patterns…"}):i!=null&&i.length?e.jsx("div",{className:"overflow-auto max-h-[600px]",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Team"}),e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Record"}),e.jsx(U,{children:"Win%"}),e.jsx(U,{children:"Home"}),e.jsx(U,{children:"Away"}),e.jsx(U,{children:"Avg Scored"}),e.jsx(U,{children:"Avg Allowed"}),e.jsx(U,{children:"Trend"}),e.jsx(U,{children:"Streak"}),e.jsx(U,{children:"Games"}),e.jsx(U,{children:"Updated"})]})}),e.jsx($e,{children:i.map(_=>{var b;const k=_.pattern_data??{};return e.jsxs(he,{children:[e.jsx(M,{className:"font-medium whitespace-nowrap",children:_.team_name}),e.jsx(M,{className:"capitalize",children:_.sport}),e.jsx(M,{children:e.jsx(ey,{status:_.status})}),e.jsx(M,{children:d(k.record)}),e.jsx(M,{children:N((b=k.record)==null?void 0:b.win_pct)}),e.jsx(M,{children:d(k.home_record)}),e.jsx(M,{children:d(k.away_record)}),e.jsx(M,{children:h(k.avg_scored)}),e.jsx(M,{children:h(k.avg_allowed)}),e.jsx(M,{children:e.jsx(sy,{trend:k.scoring_trend})}),e.jsx(M,{children:k.streak?e.jsxs("span",{className:k.streak.type==="W"?"text-emerald-400":"text-red-400",children:[k.streak.type,k.streak.length]}):"—"}),e.jsx(M,{children:_.sample_size}),e.jsx(M,{className:"text-xs text-muted-foreground whitespace-nowrap",children:_.last_updated?new Date(_.last_updated).toLocaleDateString():"—"})]},_.id)})})]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No team patterns found. Run a refresh to generate."})})]})}const ay=[{value:"all",label:"All Sports"},{value:"basketball",label:"Basketball"},{value:"american-football",label:"American Football"},{value:"baseball",label:"Baseball"},{value:"hockey",label:"Hockey"},{value:"soccer",label:"Soccer"}],ry=[{value:"all",label:"All-Season"},{value:"30d",label:"Last 30 Days"},{value:"7d",label:"Last 7 Days"}],ny={basketball:[5,10],"american-football":[7,14],baseball:[2,5],hockey:[1,3],soccer:[1,3]},ly=[5,10];function iy(s){return ny[s]??ly}function Mn({label:s,value:a,sub:t}){return e.jsxs(G,{children:[e.jsx(je,{className:"pb-2",children:e.jsx(De,{className:"text-xs uppercase tracking-wide",children:s})}),e.jsxs(J,{children:[e.jsx("div",{className:"text-2xl font-bold",children:a}),t&&e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})}function cy({factors:s}){return!s||s.length===0?e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{className:"text-sm",children:"Key Factors"})}),e.jsx(J,{children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"No statistically significant factors yet — need ≥25 samples and ≥3% lift."})})]}):e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{className:"text-sm",children:"Key Factors"})}),e.jsx(J,{className:"space-y-2",children:s.map((a,t)=>e.jsxs("div",{className:"flex items-center justify-between border rounded-md p-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:a.label}),e.jsxs("div",{className:"text-xs text-muted-foreground capitalize",children:[a.source," · n=",a.sample]})]}),e.jsxs(B,{variant:a.lift_pct>=0?"default":"destructive",children:[a.lift_pct>=0?"+":"",a.lift_pct.toFixed(1),"%"]})]},t))})]})}
341function oy({sport:s,perPeriod:a}){const t=Math.max(...a,1);return e.jsxs(G,{children:[e.jsx(je,{className:"pb-2",children:e.jsx(De,{className:"text-xs uppercase tracking-wide",children:"Avg Per Period"})}),e.jsx(J,{className:"space-y-2",children:a.map((n,r)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"font-medium",children:Qr(s,r)}),e.jsx("span",{className:"text-muted-foreground",children:n.toFixed(1)})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${n/t*100}%`}})})]},r))})]})}function dy({row:s}){var t,n,r;const a=s.totals_data;return e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[e.jsx(Mn,{label:"Avg Per Game",value:((t=a.avg_total_per_game)==null?void 0:t.toFixed(1))??"—",sub:`Sample: ${s.sample_size} games`}),e.jsx(Mn,{label:"Avg Per Home",value:((n=a.avg_home_per_game)==null?void 0:n.toFixed(1))??"—"}),e.jsx(Mn,{label:"Avg Per Away",value:((r=a.avg_away_per_game)==null?void 0:r.toFixed(1))??"—"}),e.jsx(oy,{sport:s.sport,perPeriod:a.avg_per_period||[]}),e.jsx("div",{className:"md:col-span-2",children:e.jsx(cy,{factors:a.key_factors||[]})})]})}function uy({rows:s}){return e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Sport"}),e.jsx(U,{children:"Sample"}),e.jsx(U,{children:"Avg Total"}),e.jsx(U,{children:"Avg Home"}),e.jsx(U,{children:"Avg Away"}),e.jsx(U,{children:"Per-Period"})]})}),e.jsx($e,{children:s.map(a=>{var t,n,r,i,l,m,o;return e.jsxs(he,{children:[e.jsx(M,{className:"font-medium capitalize",children:a.sport.replace("-"," ")}),e.jsx(M,{children:a.sample_size}),e.jsx(M,{children:((n=(t=a.totals_data)==null?void 0:t.avg_total_per_game)==null?void 0:n.toFixed(1))??"—"}),e.jsx(M,{children:((i=(r=a.totals_data)==null?void 0:r.avg_home_per_game)==null?void 0:i.toFixed(1))??"—"}),e.jsx(M,{children:((m=(l=a.totals_data)==null?void 0:l.avg_away_per_game)==null?void 0:m.toFixed(1))??"—"}),e.jsx(M,{className:"text-xs text-muted-foreground",children:(((o=a.totals_data)==null?void 0:o.avg_per_period)||[]).map((h,N)=>`${Qr(a.sport,N)}:${h.toFixed(1)}`).join(" · ")})]},a.id)})})]})}function Mr({row:s,side:a}){var n;const t=(n=s.confidence_intervals)==null?void 0:n[a];return t?e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["95% CI ",t.low.toFixed(1),"–",t.high.toFixed(1),"%"]}):null}function my({rows:s,showConfidence:a}){return e.jsxs("div",{className:"overflow-x-auto rounded-md border",children:[e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"League"}),e.jsx(U,{children:"Completed"}),e.jsx(U,{children:"Graded"}),e.jsx(U,{children:"Consensus"}),e.jsx(U,{children:"Home"}),e.jsx(U,{children:"Away"}),e.jsx(U,{children:"Favorite"}),e.jsx(U,{children:"Underdog"}),e.jsx(U,{children:"Close quality"})]})}),e.jsx($e,{children:s.map(t=>{var n,r,i,l,m,o;return e.jsxs(he,{children:[e.jsxs(M,{children:[e.jsx("div",{className:"font-medium",children:t.league_name}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:t.league_key})]}),e.jsx(M,{children:t.completed_games.toLocaleString()}),e.jsx(M,{children:t.graded_games.toLocaleString()}),e.jsx(M,{children:t.consensus_games.toLocaleString()}),e.jsxs(M,{children:[((n=t.home_cover_pct)==null?void 0:n.toFixed(1))??"—","%",a&&e.jsx(Mr,{row:t,side:"home"})]}),e.jsxs(M,{children:[((r=t.away_cover_pct)==null?void 0:r.toFixed(1))??"—","%",a&&e.jsx(Mr,{row:t,side:"away"})]}),e.jsxs(M,{children:[((i=t.favorite_cover_pct)==null?void 0:i.toFixed(1))??"—","%",a&&e.jsx(Mr,{row:t,side:"favorite"})]}),e.jsxs(M,{children:[((l=t.underdog_cover_pct)==null?void 0:l.toFixed(1))??"—","%",a&&e.jsx(Mr,{row:t,side:"underdog"})]}),e.jsxs(M,{className:"text-xs",children:[((m=t.avg_consensus_book_count)==null?void 0:m.toFixed(1))??"—"," books",e.jsx("br",{}),e.jsxs("span",{className:"text-muted-foreground",children:[((o=t.avg_consensus_age_minutes)==null?void 0:o.toFixed(0))??"—","m avg age"]})]})]},t.id)})})]}),e.jsx("div",{className:"border-t bg-muted/30 px-3 py-2 text-xs text-muted-foreground",children:"Coverage results use every gradeable pregame spread. Consensus count, ROI, break-even, and confidence are separate context and never remove a result."})]})}function ca(s,a=2,t=""){return s==null||!Number.isFinite(s)?"—":`${Number(s).toFixed(a)}${t}`}function xy({rows:s,sportFilter:a}){if(!s.length)return e.jsx(G,{children:e.jsxs(J,{className:"py-6 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(xs,{className:"h-4 w-4"}),'No projection accuracy data yet. Run "Recompute Now" — needs completed games with live period snapshots.']})});const t=new Map;for(const r of s){const i=t.get(r.sport)||[];i.push(r),t.set(r.sport,i)}const n=Array.from(t.keys()).sort();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{children:[e.jsx(je,{className:"pb-2",children:e.jsx(fe,{className:"text-sm",children:"How to read this"})}),e.jsxs(J,{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"MAE"})," = mean absolute error vs final score (lower is sharper)."]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Bias"})," = avg(projected − final). Positive = system over-projects, negative = under-projects."]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Within ±near / ±wide"})," = % of projections within that many points of the final total. Thresholds vary by sport — Basketball 5/10, Football 7/14, Baseball 2/5, Hockey 1/3, Soccer 1/3."]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Sharpest"})," badge = period with lowest MAE for that sport (min 5 samples)."]})]})]}),n.map(r=>{const i=t.get(r).slice().sort((h,N)=>h.period_index-N.period_index),l=Math.max(...i.map(h=>h.total_mae??0),1),[m,o]=iy(r);return e.jsxs(G,{children:[e.jsxs(je,{className:"pb-2",children:[e.jsxs(fe,{className:"text-sm capitalize",children:[r.replace("-"," ")," — Projection Accuracy by Period"]}
341),e.jsx(De,{className:"text-xs",children:"Which in-game period produces the projection closest to the final score."})]}),e.jsxs(J,{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1.5",children:i.map(h=>{const N=h.total_mae!=null?h.total_mae/l*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"font-medium flex items-center gap-2",children:[Qr(h.sport,h.period_index),h.most_accurate_rank===1&&e.jsx(B,{variant:"default",className:"text-[10px] py-0 px-1.5 h-4",children:"Sharpest"}),e.jsxs("span",{className:"text-muted-foreground",children:["n=",h.sample_size]})]}),e.jsxs("span",{className:"text-muted-foreground",children:["MAE ",ca(h.total_mae)]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:`h-full ${h.most_accurate_rank===1?"bg-primary":"bg-muted-foreground/40"}`,style:{width:`${N}%`}})})]},h.id)})}),e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Period"}),e.jsx(U,{children:"Sample"}),e.jsx(U,{children:"Total MAE"}),e.jsx(U,{children:"Total Bias"}),e.jsxs(U,{children:["Within ±",m]}),e.jsxs(U,{children:["Within ±",o]}),e.jsx(U,{children:"Margin MAE"}),e.jsx(U,{children:"Margin Bias"}),e.jsx(U,{children:"Rank"})]})}),e.jsx($e,{children:i.map(h=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:Qr(h.sport,h.period_index)}),e.jsx(M,{children:h.sample_size}),e.jsx(M,{children:ca(h.total_mae)}),e.jsxs(M,{className:h.total_bias!=null&&h.total_bias>0?"text-orange-500":h.total_bias!=null&&h.total_bias<0?"text-blue-500":"",children:[h.total_bias!=null&&h.total_bias>0?"+":"",ca(h.total_bias)]}),e.jsx(M,{children:ca(h.total_within_5_pct,1,"%")}),e.jsx(M,{children:ca(h.total_within_10_pct,1,"%")}),e.jsx(M,{children:ca(h.margin_mae)}),e.jsxs(M,{children:[h.margin_bias!=null&&h.margin_bias>0?"+":"",ca(h.margin_bias)]}),e.jsx(M,{children:h.most_accurate_rank?e.jsxs(B,{variant:h.most_accurate_rank===1?"default":"secondary",className:"text-[10px]",children:["#",h.most_accurate_rank]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})})]},h.id))})]}),a==="all"&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Tip: select a single sport above to see the full per-period breakdown isolated."})]})]},r)})]})}function hy(){const[s,a]=v.useState("all"),[t,n]=v.useState("all"),[r,i]=v.useState("all"),[l,m]=v.useState(!1),[o,h]=v.useState(!1),{toast:N}=Ws(),d=Me(),{data:y,isLoading:u}=zd({sport:s,windowKey:t}),{data:x,isLoading:g}=Kd({sport:s,windowKey:t}),f=s==="basketball_wnba"?void 0:s,_=s==="basketball_wnba"?"basketball_wnba":void 0,{data:k,isLoading:b}=Vd({sport:f,leagueKey:_,windowKey:t,seasonPhase:r}),j=v.useMemo(()=>y??[],[y]),c=v.useMemo(()=>j.length?j.reduce((S,P)=>!S||P.last_updated>S?P.last_updated:S,null):null,[j]);async function p(){h(!0);try{const{error:w}=await T.functions.invoke("aggregate-game-pace-patterns",{});if(w)throw w;await d.invalidateQueries({queryKey:["game-pace-patterns"]}),await d.invalidateQueries({queryKey:["learned-period-weights"]}),await d.invalidateQueries({queryKey:["period-projection-accuracy"]}),await d.invalidateQueries({queryKey:["historical-ats-contexts"]}),await d.invalidateQueries({queryKey:["historical-ats-context"]}),N({title:"Game Pace Learning recomputed",description:"Aggregates updated for all sports & windows."})}catch(w){N({title:"Recompute failed",description:(w==null?void 0:w.message)??String(w),variant:"destructive"})}finally{h(!1)}}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Descriptive scoring and spread research. Live Game Hub totals use the validated Pace Anchor deployment instead."}),c&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last updated: ",new Date(c).toLocaleString()]})]}),e.jsxs(R,{onClick:p,disabled:o,size:"sm",children:[e.jsx(He,{className:`h-4 w-4 mr-2 ${o?"animate-spin":""}`}),o?"Recomputing…":"Recompute Now"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Sport"}),e.jsxs(oe,{value:s,onValueChange:a,children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{})}),e.jsx(me,{children:ay.map(w=>e.jsx(V,{value:w.value,children:w.label},w.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Season Phase"}),e.jsxs(oe,{value:r,onValueChange:w=>i(w),children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All phases"}),e.jsx(V,{value:"regular_season",children:"Regular season"}),e.jsx(V,{value:"postseason",children:"Postseason"}),e.jsx(V,{value:"preseason",children:"Preseason"})]})]})]}),e.jsxs("label",{className:"flex items-end gap-2 pb-2 text-xs text-muted-foreground",children:[e.jsx(Ge,{checked:l,onCheckedChange:m}),"Show 95% confidence intervals"]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Time Period"}),e.jsxs(oe,{value:t,onValueChange:w=>n(w),children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{})}),e.jsx(me,{children:ry.map(w=>e.jsx(V,{value:w.value,children:w.label},w.value))})]})]})]}),u?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):e.jsxs(js,{defaultValue:"totals",children:[e.jsxs(fs,{children:[e.jsx(Ne,{value:"totals",children:"Totals"}),e.jsx(Ne,{value:"spread",children:"Spread"}),e.jsx(Ne,{value:"accuracy",children:"Projection Accuracy"})]}),e.jsx(we,{value:"totals",className:"mt-4 space-y-4",children:j.length===0?e.jsx(G,{children:e.jsxs(J,{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[e.jsx(xs,{className:"h-4 w-4"}),'No learned data yet for this filter — click "Recompute Now" to generate aggregates.']})}):s==="all"?e.jsx(uy,{rows:j}):j.map(w=>e.jsx(dy,{row:w},w.id))}),e.jsx(we,{value:"spread",className:"mt-4 space-y-4",children:b?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading ATS authority…"}):(k??[]).length===0?e.jsx(G,{children:e.jsxs(J,{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground",children:[e.jsx(xs,{className:"h-4 w-4"}),'No historical ATS rows yet for this filter — click "Recompute Now" after the ATS migration is deployed.']})}):e.jsx(my,{rows:k??[],showConfidence:l})}),e.jsx(we,{value:"accuracy",className:"mt-4 space-y-4",children:g?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):e.jsx(xy,{rows:x??[],sportFilter:s})})]})]})}function Yt({title:s,description:a,children:t}){return e.jsxs(vs,{defaultOpen:!1,className:"border rounded-lg p-4",children:[e.jsxs(ys,{className:"flex items-center gap-2 w-full text-left group",children:[e.jsx(st,{className:"h-4 w-4 shrink-0 transition-transform duration-200 group-data-[state=open]:rotate-90"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:s}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a})]})]}),e.jsx(_s,{className:"mt-4 pt-4 border-t",children:e.jsx("div",{className:"grid gap-6",children:t})})]})}function py(){const[s,a]=v.useState("ai-learning");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Utilities & Tools"}),e.jsx("p",{className:"text-muted-foreground",children:"Administrative tools for data management, backfills, and system maintenance"})]}),e.jsxs(ss,{className:"border-primary/50 bg-primary/5",children:[e.jsx(Ys,{className:"h-4 w-4 text-primary"}),e.jsx(pa,{className:"text-primary",children:"Recommended Order of Operations"}),e.jsx(ts,{children:e.jsxs("ol",{className:"list-decimal ml-4 mt-2 space-y-1.5 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Sports Data:"})," Verify game data sync is working for accurate odds and scores"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"DFS Tools:"})," Set win thresholds, then build player profiles, perfect lineups, and performance records"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Betting:"})," Run auto-settle and cleanup malformed bets for accurate results"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"AI Learning:"})," Only run after DFS/Betting tools complete and data is accurate"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"KLUTCH:"})," Settle picks, review performance, and tune learning models"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Maintenance:"})," Run cleanup tools only when duplicates or orphans are confirmed"]})]})})]}),e.jsxs(js,{value:s,onValueChange:a,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"ai-learning",className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-4 w-4"}),e.jsx("span",{children:"AI Learning"})]}),e.jsxs(Ne,{value:"maintenance",className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsx("span",{children:"Maintenance"})]})]}),e.jsx(we,{value:"ai-learning",className:"mt-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Yt,{title:"DFS Learning",description:"Pattern analysis and model learning for DFS lineups",children:[e.jsx(kv,{}),e.jsx(wv,{}),e.jsx(pv,{})]}),e.jsxs(Yt,{title:"Betting Learning",description:"Pattern analysis and model learning for betting picks",children:[e.jsxs(vs,{defaultOpen:!1,className:"border rounded-lg p-4",children:[e.jsxs(ys,{className:"flex items-center gap-2 w-full text-left group",children:[e.jsx(st,{className:"h-4 w-4 shrink-0 transition-transform duration-200 group-data-[state=open]:rotate-90"}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-base font-semibold",children:"Team Learning"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Team-level learning patterns and insights"})]})]}),e.jsx(_s,{className:"mt-4 pt-4 border-t",children:e.jsx(ty,{})})]}),e.jsxs(vs,{defaultOpen:!1,className:"border rounded-lg p-4",children:[e.jsxs(ys,{className:"flex items-center gap-2 w-full text-left group",children:[e.jsx(st,{className:"h-4 w-4 shrink-0 transition-transform duration-200 group-data-[state=open]:rotate-90"}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-base font-semibold",children:"Game Pace Learning"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Historical scoring and spread research; validated Pace Anchor deployments power live totals"})]})]}),e.jsx(_s,{className:"mt-4 pt-4 border-t",children:e.jsx(hy,{})})]}),e.jsx(Iv,{}),e.jsx(qv,{}),e.jsx(Vv,{}),e.jsx(Pv,{}),e.jsx(gv,{})]}),e.jsxs(Yt,{title:"Learning Cleanup",description:"Fix and regenerate learning patterns and positions",children:[e.jsx(jv,{}),e.jsx(fv,{})]})]})}),e.jsx(we,{value:"maintenance",className:"mt-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Yt,{title:"General",description:"General maintenance and cleanup utilities",children:[e.jsx(Jv,{}),e.jsx(vv,{}),e.jsx(yv,{}),e.jsx(Nv,{})]}),e.jsxs(Yt,{title:"Testing",description:"Subscription simulation and API testing tools",children:[e.jsx(Yv,{}),e.jsx(Av,{})]}),e.jsxs(Yt,{title:"Sports Data",description:"Game data synchronization and matchup view tools",children:[e.jsx(Lv,{}),e.jsx(Ev,{})]}),e.jsxs(Yt,{title:"DFS",description:"Contest reprocessing, player profiles, lineups, and performance records",children:[e.jsx(nv,{}),e.jsx(cv,{}),e.jsx(lv,{}),e.jsx(iv,{}),e.jsx(ov,{}),e.jsx(uv,{})]}),e.jsxs(Yt,{title:"Betting",description:"Settlement, matching, and betting data tools",children:[e.jsx(Zv,{}),e.jsx(Wv,{}),e.jsx(Dv,{}),e.jsx(Sv,{}),e.jsx(Cv,{}),e.jsx(Bv,{}),e.jsx(dv,{})]})]})})]})]})}function Ta(s){const{greeting:a,body:t,signature:n,ctaButtonText:r,ctaButtonLink:i}=s,l=n.replace(/\n/g,"<br>");return`<!DOCTYPE html>
342<html>
343<head>
344  <meta charset="utf-8">
345  <meta name="viewport" content="width=device-width, initial-scale=1.0">
346  <title>Klever Bet</title>
347</head>
348<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #f4f4f4;">
349  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4; padding: 20px 0;">
350    <tr>
351      <td align="center">
352        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
353          <!-- Header -->
354          <tr>
355            <td style="background-color: #000000; padding: 30px; text-align: center;">
356              <img src="https://kleverbet.ai/images/klever-bet-logo.png" alt="Klever Bet" style="max-width: 180px; height: auto;" />
357            </td>
358          </tr>
359          
360          <!-- Content -->
361          <tr>
362            <td style="padding: 40px 30px;">
363              <!-- Greeting -->
364              <p style="color: #1f2937; font-size: 18px; margin: 0 0 20px 0; font-weight: 500;">
365                ${a}
366              </p>
367              
368              <!-- Body -->
369              <div style="color: #4b5563; line-height: 1.7; margin: 0 0 24px 0; font-size: 16px;">
370                ${t}
371              </div>
372              
373              <!-- CTA Button -->
374              ${r&&i?`
375              <table cellpadding="0" cellspacing="0" style="margin: 30px 0;">
376                <tr>
377                  <td style="background-color: #2fce2e; border-radius: 6px;">
378                    <a href="${i}" style="display: inline-block; padding: 14px 30px; color: #ffffff; text-decoration: none; font-weight: 600; font-size: 16px;">
379                      ${r}
380                    </a>
381                  </td>
382                </tr>
383              </table>
384              `:""}
385              
386              <!-- Signature -->
387              <p style="color: #4b5563; line-height: 1.6; margin: 24px 0 0 0; font-size: 16px;">
388                ${l}
389              </p>
390            </td>
391          </tr>
392          
393          <!-- Footer -->
394          <tr>
395            <td style="background-color: #f9fafb; padding: 30px; text-align: center; border-top: 1px solid #e5e7eb;">
396              <p style="color: #6b7280; font-size: 12px; margin: 0 0 10px 0;">
397                © ${new Date().getFullYear()} Klever Bet by Klever Boy AI. All rights reserved.
398              </p>
399              <p style="color: #9ca3af; font-size: 11px; margin: 0;">
400                <a href="https://kleverbet.ai/unsubscribe" style="color: #9ca3af;">Unsubscribe</a> | 
401                <a href="https://kleverbet.ai/contact" style="color: #9ca3af;">Contact Support</a>
402              </p>
403            </td>
404          </tr>
405        </table>
406      </td>
407    </tr>
408  </table>
409</body>
410</html>`}function qa(){return{greeting:"Hi there,",body:"<p>Your message here...</p>",signature:`Best regards,
411The Klever Bet Team`,ctaButtonText:"Visit Klever Bet",ctaButtonLink:"https://kleverbet.ai"}}function eo(s){var a,t,n,r,i;try{const o=new DOMParser().parseFromString(s,"text/html").querySelector('td[style*="padding: 40px"]');if(!o)return null;const N=((t=(a=o.querySelectorAll("p")[0])==null?void 0:a.textContent)==null?void 0:t.trim())||"Hi there,",d=o.querySelector("div"),y=(d==null?void 0:d.innerHTML)||"<p></p>",u=o.querySelectorAll("p"),x=u.length>1&&((r=(n=u[u.length-1])==null?void 0:n.innerHTML)==null?void 0:r.replace(/<br\s*\/?>/gi,`
412`))||`Best regards,
413The Klever Bet Team`,g=o.querySelector('a[style*="padding"]'),f=((i=g==null?void 0:g.textContent)==null?void 0:i.trim())||"",_=(g==null?void 0:g.getAttribute("href"))||"";return{greeting:N,body:y,signature:x,ctaButtonText:f,ctaButtonLink:_}}catch{return null}}function dl({content:s,onChange:a,showPreview:t=!1}){const{user:n}=bo(),[r,i]=v.useState(!1),l=Xi({extensions:[ec,sc,tc.configure({openOnClick:!1})],content:s.body,onUpdate:({editor:o})=>{a({...s,body:o.getHTML()})},editorProps:{attributes:{class:"prose prose-sm prose-invert max-w-none focus:outline-none min-h-[150px] p-3 text-foreground"}}});v.useEffect(()=>{l&&s.body!==l.getHTML()&&l.commands.setContent(s.body)},[s.body,l]);const m=()=>{const 
413o=window.prompt("Enter link URL:");o&&l&&l.chain().focus().setLink({href:o}).run()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"greeting",children:"Greeting"}),e.jsx(pe,{id:"greeting",placeholder:"Hi there, or Hi {first_name},",value:s.greeting,onChange:o=>a({...s,greeting:o.target.value})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{first_name}"," or ","{email}"," for personalization"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Email Body"}),e.jsxs("div",{className:"border rounded-md overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap gap-1 p-2 border-b bg-muted/50",children:[e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l==null?void 0:l.chain().focus().toggleBold().run(),className:l!=null&&l.isActive("bold")?"bg-accent":"",children:e.jsx(ac,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l==null?void 0:l.chain().focus().toggleItalic().run(),className:l!=null&&l.isActive("italic")?"bg-accent":"",children:e.jsx(rc,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l==null?void 0:l.chain().focus().toggleBulletList().run(),className:l!=null&&l.isActive("bulletList")?"bg-accent":"",children:e.jsx(nn,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l==null?void 0:l.chain().focus().toggleOrderedList().run(),className:l!=null&&l.isActive("orderedList")?"bg-accent":"",children:e.jsx(nc,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:m,className:l!=null&&l.isActive("link")?"bg-accent":"",children:e.jsx(Xn,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>i(!0),children:e.jsx(Ot,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l==null?void 0:l.chain().focus().undo().run(),disabled:!(l!=null&&l.can().undo()),children:e.jsx(pc,{className:"h-4 w-4"})}),e.jsx(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l==null?void 0:l.chain().focus().redo().run(),disabled:!(l!=null&&l.can().redo()),children:e.jsx(xc,{className:"h-4 w-4"})})]}),e.jsx(lc,{editor:l,className:"bg-background"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click the image icon to add images via URL"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"signature",children:"Signature"}),e.jsx(Xs,{id:"signature",placeholder:`Best regards,
414The Klever Bet Team`,value:s.signature,onChange:o=>a({...s,signature:o.target.value}),rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Call-to-Action Button"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx("div",{children:e.jsx(pe,{placeholder:"Button Text (e.g., Visit Klever Bet)",value:s.ctaButtonText,onChange:o=>a({...s,ctaButtonText:o.target.value})})}),e.jsx("div",{children:e.jsx(pe,{placeholder:"Button Link (e.g., https://kleverbet.ai)",value:s.ctaButtonLink,onChange:o=>a({...s,ctaButtonLink:o.target.value})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to hide the button"})]}),t&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Live Preview"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsx("iframe",{srcDoc:Ta(s),className:"w-full h-[400px] border-0",title:"Email Preview"})})]}),e.jsx(Fd,{open:r,onOpenChange:i,onInsert:o=>l==null?void 0:l.chain().focus().setImage({src:o}).run(),userId:(n==null?void 0:n.id)||""})]})}function gy(){const s=Me(),[a,t]=v.useState(""),[n,r]=v.useState(""),[i,l]=v.useState(qa()),[m,o]=v.useState("both"),[h,N]=v.useState(!1),[d,y]=v.useState(!1),[u,x]=v.useState(!1),[g,f]=v.useState(""),[_,k]=v.useState(!1),[b,j]=v.useState(""),{data:c}=ge({queryKey:["email-recipient-counts"],queryFn:async()=>{const[E,L]=await Promise.all([T.from("user_profiles").select("id",{count:"exact"}).eq("email_opt_out",!1),T.from("email_subscribers").select("id",{count:"exact"}).eq("is_active",!0)]);
414return{users:E.count||0,subscribers:L.count||0}}}),{data:p}=ge({queryKey:["email-lists"],queryFn:async()=>{const{data:E,error:L}=await T.from("email_lists").select("id, name").order("name");if(L)throw L;return await Promise.all((E||[]).map(async Z=>{const{count:se}=await T.from("email_list_members").select("*",{count:"exact",head:!0}).eq("list_id",Z.id);return{...Z,member_count:se||0}}))}}),{data:w}=ge({queryKey:["email-campaign-templates"],queryFn:async()=>{const{data:E,error:L}=await T.from("email_campaign_templates").select("id, name, subject, greeting, body, signature, cta_button_text, cta_button_link").order("name");if(L)throw L;return E}}),S=()=>{if(!c)return 0;if(m==="users")return c.users;if(m==="subscribers")return c.subscribers;if(m==="both")return c.users+c.subscribers;if(m.startsWith("list:")){const E=m.replace("list:",""),L=p==null?void 0:p.find(H=>H.id===E);return(L==null?void 0:L.member_count)||0}return 0},P=()=>{if(m==="both")return"All Users & Subscribers";if(m==="users")return"Registered Users";if(m==="subscribers")return"Subscribers";if(m.startsWith("list:")){const E=m.replace("list:",""),L=p==null?void 0:p.find(H=>H.id===E);return(L==null?void 0:L.name)||"Email List"}return m},C=_e({mutationFn:async()=>{const E=Ta(i),{data:L,error:H}=await T.from("email_campaigns").insert({name:a,subject:n,html_content:E,recipient_type:m,status:"draft"}).select().single();if(H)throw H;const{data:Z,error:se}=await T.functions.invoke("send-email-blast",{body:{campaignId:L.id,subject:n,htmlContent:E,recipientType:m}});if(se)throw se;return Z},onSuccess:E=>{K.success(`Email blast sent successfully! ${E.successCount} delivered, ${E.failCount} failed`),s.invalidateQueries({queryKey:["email-campaigns"]}),A(),y(!1)},onError:E=>{K.error(`Failed to send email blast: ${E.message}`)}}),O=_e({mutationFn:async E=>{const L=Ta(i),{data:H,error:Z}=await T.functions.invoke("send-test-email",{body:{testEmail:E,subject:n||"Test Email",htmlContent:L,emailType:"campaign"}});if(Z)throw Z;return H},onSuccess:()=>{K.success("Test email sent successfully!"),x(!1),f("")},onError:E=>{K.error("Failed to send test email: "+E.message)}}),$=_e({mutationFn:async E=>{const{error:L}=await T.from("email_campaign_templates").insert({name:E,subject:n,greeting:i.greeting,body:i.body,signature:i.signature,cta_button_text:i.ctaButtonText||null,cta_button_link:i.ctaButtonLink||null});if(L)throw L},onSuccess:()=>{K.success("Template saved successfully!"),s.invalidateQueries({queryKey:["email-campaign-templates"]}),k(!1),j("")},onError:E=>{var L,H;(L=E.message)!=null&&L.includes("duplicate")||(H=E.message)!=null&&H.includes("unique")?K.error("A template with that name already exists"):K.error("Failed to save template: "+E.message)}}),z=E=>{t(E.name),r(E.subject),l({greeting:E.greeting,body:E.body,signature:E.signature,ctaButtonText:E.cta_button_text||"",ctaButtonLink:E.cta_button_link||""}),K.success(`Template "${E.name}" loaded`)},D=()=>{b.trim()&&$.mutate(b.trim())},A=()=>{t(""),r(""),l(qa()),o("both")},F=()=>{g.trim()&&O.mutate(g.trim())},q=a.trim()&&n.trim()&&i.body.trim();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ut,{className:"h-5 w-5"}),"Compose Email Blast"]}),e.jsx(De,{children:"Send a mass email to all users and/or subscribers"})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("strong",{children:(c==null?void 0:c.users)||0})," registered users"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("strong",{children:(c==null?void 0:c.subscribers)||0})," subscribers"]}
414)]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Load Template"}),e.jsxs(oe,{onValueChange:E=>{const L=w==null?void 0:w.find(H=>H.id===E);L&&z(L)},children:[e.jsxs(de,{className:"w-full md:w-[280px]",children:[e.jsx(uc,{className:"h-4 w-4 mr-2"}),e.jsx(ue,{placeholder:"Select a template to load..."})]}),e.jsx(me,{children:w&&w.length>0?w.map(E=>e.jsx(V,{value:E.id,children:E.name},E.id)):e.jsx(V,{value:"_none",disabled:!0,children:"No templates saved"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"campaignName",children:"Campaign Name (internal)"}),e.jsx(pe,{id:"campaignName",placeholder:"e.g., December 2024 Newsletter",value:a,onChange:E=>t(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Recipients"}),e.jsxs(oe,{value:m,onValueChange:E=>o(E),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsxs(V,{value:"both",children:["All Users & Subscribers (~",c?c.users+c.subscribers:0,")"]}),e.jsxs(V,{value:"users",children:["Registered Users Only (",(c==null?void 0:c.users)||0,")"]}),e.jsxs(V,{value:"subscribers",children:["Newsletter Subscribers Only (",(c==null?void 0:c.subscribers)||0,")"]}),p&&p.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(wo,{}),e.jsxs(So,{children:[e.jsxs(ko,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-3 w-3"}),"Saved Email Lists"]}),p.map(E=>e.jsxs(V,{value:`list:${E.id}`,children:["📋 ",E.name," (",E.member_count," member",E.member_count!==1?"s":"",")"]},E.id))]})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"subject",children:"Email Subject"}),e.jsx(pe,{id:"subject",placeholder:"Enter email subject line...",value:n,onChange:E=>r(E.target.value)})]}),e.jsx(dl,{content:i,onChange:l}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(R,{variant:"outline",onClick:()=>{j(a),k(!0)},disabled:!n.trim()||!i.body.trim(),children:[e.jsx(It,{className:"h-4 w-4 mr-2"}),"Save Template"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(R,{variant:"outline",onClick:()=>N(!0),disabled:!i.body.trim(),children:[e.jsx(us,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(R,{variant:"outline",onClick:()=>x(!0),disabled:!i.body.trim(),children:[e.jsx(ut,{className:"h-4 w-4 mr-2"}),"Send Test"]}),e.jsxs(R,{onClick:()=>y(!0),disabled:!q||C.isPending,children:[C.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ut,{className:"h-4 w-4 mr-2"}),"Send Email Blast"]})]})]})]}),e.jsx(Ue,{open:h,onOpenChange:N,children:e.jsxs(Be,{className:"max-w-3xl max-h-[80vh] overflow-auto",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Email Preview"}),e.jsxs(Vs,{children:["Subject: ",n||"(No subject)"]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsx("iframe",{srcDoc:Ta(i),className:"w-full h-[500px] border-0",title:"Email Preview"})})]})}),e.jsx(Ue,{open:u,onOpenChange:()=>{x(!1),f("")},children:e.jsxs(Be,{children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Send Test Email"}),e.jsxs(Vs,{children:["Subject: ",n||"(No subject)"]})]}),e.jsx("div",{className:"space-y-4 pt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"testEmail",children:"Email Address"}),e.jsx(pe,{id:"testEmail",type:"email",placeholder:"Enter email address...",value:g,onChange:E=>f(E.target.value)})]})}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>{x(!1),f("")},children:"Cancel"}),e.jsxs(R,{onClick:F,disabled:!g.trim()||O.isPending,children:[O.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ut,{className:"h-4 w-4 mr-2"}),"Send Test"]})]})]})}),e.jsx(Ue,{open:d,onOpenChange:y,children:e.jsxs(Be,{children:[e.jsxs(ze,{children:[e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"h-5 w-5 text-yellow-500"}),"Confirm Email Blast"]}),e.jsxs(Vs,{children:["You are about to send an email to approximately ",e.jsx("strong",{children:S()})," recipients."]})]}),e.jsxs("div",{className:"space-y-3 py-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Campaign:"}),e.jsx("span",{className:"font-medium",children:a})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:n})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipients:"}),e.jsx(B,{variant:"secondary",children:P()})]})]}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsxs(R,{onClick:()=>C.mutate(),disabled:C.isPending,children:[C.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ut,{className:"h-4 w-4 mr-2"}),"Send Now"]})]})]})}),e.jsx(Ue,{open:_,onOpenChange:k,children:e.jsxs(Be,{children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Save as Template"}),e.jsx(Vs,{children:"Save the current email content as a reusable template."})]}),e.jsx("div",{className:"space-y-4 pt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"templateName",children:"Template Name"}),e.jsx(pe,{id:"templateName",placeholder:"e.g., Monthly Newsletter",value:b,onChange:E=>j(E.target.value)})]})}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>k(!1),children:"Cancel"}),e.jsxs(R,{onClick:D,disabled:!b.trim()||$.isPending,children:[$.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(It,{className:"h-4 w-4 mr-2"}),"Save Template"]})]})]})})]})}function jy(){const[s,a]=v.useState(null),[t,n]=v.useState(!1),[r,i]=v.useState(null),l=Me(),{data:m,isLoading:o}=ge({queryKey:["email-campaigns"],queryFn:async()=>{const{data:f,error:_}=await T.from("email_campaigns").select("*").order("created_at",{ascending:!1});if(_)throw _;return f}}),{data:h}=ge({queryKey:["email-campaign-failed-counts"],queryFn:async()=>{const{data:f,error:_}=await T.from("email_campaign_logs").select("campaign_id").eq("status","failed");if(_)throw _;
414const k={};return f==null||f.forEach(b=>{k[b.campaign_id]=(k[b.campaign_id]||0)+1}),k}}),{data:N,isLoading:d}=ge({queryKey:["email-campaign-logs",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:f,error:_}=await T.from("email_campaign_logs").select("*").eq("campaign_id",s.id).order("sent_at",{ascending:!1});if(_)throw _;return f},enabled:!!s&&t}),y=_e({mutationFn:async f=>{const{data:_,error:k}=await T.functions.invoke("send-email-blast",{body:{campaignId:f.id,subject:f.subject,htmlContent:f.html_content,recipientType:`retry:${f.id}`}});if(k)throw k;return _},onSuccess:f=>{Ee({title:"Retry complete!",description:`${f.successCount} delivered, ${f.failCount} still failed`}),l.invalidateQueries({queryKey:["email-campaign-logs"]}),l.invalidateQueries({queryKey:["email-campaign-failed-counts"]})},onError:f=>{Ee({title:"Retry failed",description:f.message,variant:"destructive"})},onSettled:()=>{i(null)}}),u=f=>{i(f.id),y.mutate(f)},x=f=>{switch(f){case"sent":return e.jsx(B,{className:"bg-green-500/20 text-green-400 border-green-500/30",children:"Sent"});case"sending":return e.jsx(B,{className:"bg-blue-500/20 text-blue-400 border-blue-500/30",children:"Sending"});case"failed":return e.jsx(B,{className:"bg-red-500/20 text-red-400 border-red-500/30",children:"Failed"});default:return e.jsx(B,{variant:"secondary",children:"Draft"})}},g=f=>{switch(f){case"users":return e.jsx(B,{variant:"outline",children:"Users"});case"subscribers":return e.jsx(B,{variant:"outline",children:"Subscribers"});default:return e.jsx(B,{variant:"outline",children:"All"})}};return o?e.jsx(G,{children:e.jsx(J,{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-5 w-5"}),"Email Campaign History"]}),e.jsx(De,{children:"View all sent email campaigns and their delivery status"})]}),e.jsx(J,{children:m!=null&&m.length?e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Campaign"}),e.jsx(U,{children:"Recipients"}),e.jsx(U,{children:"Count"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Sent"}),e.jsx(U,{children:"Actions"})]})}),e.jsx($e,{children:m.map(f=>{const _=(h==null?void 0:h[f.id])||0;return e.jsxs(he,{children:[e.jsx(M,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:f.name}),e.jsx("div",{className:"text-sm text-muted-foreground truncate max-w-[200px]",children:f.subject})]})}),e.jsx(M,{children:g(f.recipient_type)}),e.jsx(M,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(hs,{className:"h-3 w-3 text-muted-foreground"}),f.recipient_count,_>0&&e.jsxs("span",{className:"text-red-400 text-xs ml-1",children:["(",_," failed)"]})]})}),e.jsx(M,{children:x(f.status)}),e.jsx(M,{children:f.sent_at?ke(new Date(f.sent_at),"MMM d, yyyy h:mm a"):"-"}),e.jsx(M,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>{a(f),n(!1)},title:"Preview email",children:e.jsx(us,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>{a(f),n(!0)},title:"View delivery logs",children:e.jsx(Pt,{className:"h-4 w-4"})}),_>0&&e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>u(f),disabled:r===f.id,title:`Retry ${_} failed emails`,children:e.jsx(He,{className:`h-4 w-4 ${r===f.id?"animate-spin":""}`})})]})})]},f.id)})})]}):e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No email campaigns sent yet."})})]}),e.jsx(Ue,{open:!!s&&!t,onOpenChange:()=>a(null),children:e.jsxs(Be,{className:"max-w-3xl max-h-[80vh] overflow-auto",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:s==null?void 0:s.name}),e.jsxs(Vs,{children:["Subject: ",s==null?void 0:s.subject]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white text-black",dangerouslySetInnerHTML:{__html:(s==null?void 0:s.html_content)||""}})]})}),e.jsx(Ue,{open:!!s&&t,onOpenChange:()=>{a(null),n(!1)},children:e.jsxs(Be,{className:"max-w-2xl max-h-[80vh]",children:[e.jsxs(ze,{children:[e.jsxs(Ke,{children:["Delivery Logs: ",s==null?void 0:s.name]}),e.jsxs(Vs,{children:[(N==null?void 0:N.length)||0," recipients"]})]}),d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(cs,{className:"h-[400px]",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Email"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Opened"}),e.jsx(U,{children:"Clicked"}),e.jsx(U,{children:"Time"})]})}),e.jsx($e,{children:N==null?void 0:N.map(f=>e.jsxs(he,{children:[e.jsx(M,{className:"font-mono text-sm",children:f.recipient_email}),e.jsx(M,{children:f.status==="sent"?e.jsx(Es,{className:"h-4 w-4 text-green-500"}):f.status==="failed"?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4 text-red-500"}),f.error_message&&e.jsx("span",{className:"text-xs text-red-400 truncate max-w-[100px]",title:f.error_message,children:f.error_message})]}):e.jsx($s,{className:"h-4 w-4 text-yellow-500"})}),e.jsx(M,{children:f.opened_at?e.jsxs("div",{className:"flex items-center gap-1 text-blue-500",children:[e.jsx(us,{className:"h-3 w-3"}),e.jsx("span",{className:"text-xs",children:ke(new Date(f.opened_at),"h:mm a")})]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"-"})}),e.jsx(M,{children:f.clicked_at?e.jsxs("div",{className:"flex items-center gap-1 text-emerald-500",children:[e.jsx(Xr,{className:"h-3 w-3"}),e.jsxs("span",{className:"text-xs",children:[ke(new Date(f.clicked_at),"h:mm a"),(f.click_count??0)>1&&` (${f.click_count}x)`]})]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"-"})}),e.jsx(M,{className:"text-sm text-muted-foreground",children:f.sent_at?ke(new Date(f.sent_at),"h:mm:ss a"):"-"})]},f.id))})]})})]})})]})}function fy(){const[s,a]=v.useState(""),[t,n]=v.useState("all"),[r,i]=v.useState("all"),{data:l,isLoading:m}=ge({queryKey:["onboarding-email-history"],queryFn:async()=>{const{data:d,error:y}=await T.from("user_onboarding_emails").select("*").neq("day_number",0).order("sent_at",{ascending:!1}).limit(500);if(y)throw y;if(!(d!=null&&d.length))return[];const u=[...new Set(d.map(f=>f.user_id))],{data:x}=await T.from("user_profiles").select("id, full_name, username").in("id",u),g=new Map((x==null?void 0:x.map(f=>[f.id,f]))||[]);return d.map(f=>{var _,k;return{...f,full_name:(_=g.get(f.user_id))==null?void 0:_.full_name,username:(k=g.get(f.user_id))==null?void 0:k.username}})}}),o=l?{total:l.length,sent:l.filter(d=>d.status==="sent").length,failed:l.filter(d=>d.status==="failed").length,opened:l.filter(d=>d.opened_at).length,clicked:l.filter(d=>d.clicked_at).length,openRate:l.length>0?(l.filter(d=>d.opened_at).length/l.filter(d=>d.status==="sent").length*100).toFixed(1):"0",clickRate:l.length>0?(l.filter(d=>d.clicked_at).length/l.filter(d=>d.status==="sent").length*100).toFixed(1):"0"}:null,h=l==null?void 0:l.filter(d=>{var g,f;const y=!s||((g=d.full_name)==null?void 0:g.toLowerCase().includes(s.toLowerCase()))||((f=d.username)==null?void 0:f.toLowerCase().includes(s.toLowerCase())),u=t==="all"||d.day_number===parseInt(t),x=r==="all"||r==="opened"&&d.opened_at||r==="clicked"&&d.clicked_at||r==="sent"&&d.status==="sent"&&!d.opened_at||r==="failed"&&d.status==="failed";return y&&u&&x}),N=d=>d.status==="failed"?e.jsx(B,{className:"bg-red-500/20 text-red-400 border-red-500/30",children:"Failed"}):d.clicked_at?e.jsx(B,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:"Clicked"}):d.opened_at?e.jsx(B,{className:"bg-blue-500/20 text-blue-400 border-blue-500/30",children:"Opened"}):d.status==="sent"?e.jsx(B,{className:"bg-green-500/20 text-green-400 border-green-500/30",children:"Sent"}):e.jsx(B,{variant:"secondary",children:"Unknown"});return m?e.jsx(G,{children:e.jsx(J,{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsxs("div",{className:"space-y-4",children:[o&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3",children:[e.jsx(G,{children:e.jsx(J,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Sent"}),e.jsx("p",{className:"text-lg font-bold",children:o.sent})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4 text-red-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failed"}),e.jsx("p",{className:"text-lg font-bold",children:o.failed})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(us,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Opened"}),e.jsx("p",{className:"text-lg font-bold",children:o.opened})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicked"}),e.jsx("p",{className:"text-lg font-bold",children:o.clicked})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Open Rate"}),e.jsxs("p",{className:"text-lg font-bold",children:[o.openRate,"%"]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click Rate"}),e.jsxs("p",{className:"text-lg font-bold",children:[o.clickRate,"%"]})]})})})]}),e.jsxs(G,{children:[e.jsxs(je,{className:"pb-3",children:[e.jsxs(fe,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Pt,{className:"h-5 w-5"}),"Onboarding Email History"]}),e.jsx(De,{children:"Track individual email sends and engagement"})]}),e.jsxs(J,{children:[e.jsxs("div",{className:"flex flex-wrap gap-3 mb-4",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:d=>
414a(d.target.value),className:"pl-9"})]}),e.jsxs(oe,{value:t,onValueChange:n,children:[e.jsx(de,{className:"w-[130px]",children:e.jsx(ue,{placeholder:"Day"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Days"}),Array.from({length:10},(d,y)=>e.jsxs(V,{value:String(y+1),children:["Day ",y+1]},y+1))]})]}),e.jsxs(oe,{value:r,onValueChange:i,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{placeholder:"Status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Status"}),e.jsx(V,{value:"sent",children:"Sent Only"}),e.jsx(V,{value:"opened",children:"Opened"}),e.jsx(V,{value:"clicked",children:"Clicked"}),e.jsx(V,{value:"failed",children:"Failed"})]})]})]}),h!=null&&h.length?e.jsx(cs,{className:"h-[500px]",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"User"}),e.jsx(U,{className:"w-20",children:"Day"}),e.jsx(U,{children:"Sent At"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Opened"}),e.jsx(U,{children:"Clicked"})]})}),e.jsx($e,{children:h.map(d=>e.jsxs(he,{children:[e.jsx(M,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:d.full_name||"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:d.username||d.user_id})]})}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:"font-mono",children:d.day_number})}),e.jsx(M,{className:"text-sm",children:ke(new Date(d.sent_at),"MMM d, h:mm a")}),e.jsx(M,{children:N(d)}),e.jsx(M,{children:d.opened_at?e.jsxs("div",{className:"flex items-center gap-1 text-blue-500",children:[e.jsx(us,{className:"h-3 w-3"}),e.jsx("span",{className:"text-xs",children:ke(new Date(d.opened_at),"MMM d, h:mm a")})]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"-"})}),e.jsx(M,{children:d.clicked_at?e.jsxs("div",{className:"flex items-center gap-1 text-emerald-500",children:[e.jsx(Xr,{className:"h-3 w-3"}),e.jsxs("span",{className:"text-xs",children:[ke(new Date(d.clicked_at),"MMM d, h:mm a"),(d.click_count??0)>1&&` (${d.click_count}x)`]})]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"-"})})]},d.id))})]})}):e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No onboarding emails found matching your filters."}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-3",children:["Showing ",(h==null?void 0:h.length)||0," of ",(l==null?void 0:l.length)||0," records"]})]})]})]})}function vy(){const[s,a]=v.useState("templates"),t=Me(),[n,r]=v.useState(null),[i,l]=v.useState(null),[m,o]=v.useState({subject:"",description:""}),[h,N]=v.useState(qa()),[d,y]=v.useState(null),[u,x]=v.useState(""),[g,f]=v.useState(""),[_,k]=v.useState("all"),[b,j]=v.useState("all"),{data:c,isLoading:p}=ge({queryKey:["nurture-templates"],queryFn:async()=>{const{data:L,error:H}=await T.from("nurture_email_templates").select("*").order("email_number",{ascending:!0});if(H)throw H;return L}}),{data:w}=ge({queryKey:["nurture-stats"],queryFn:async()=>{const{data:L,error:H}=await T.from("user_nurture_emails").select("user_id, status, email_number");if(H)throw H;const Z=new Set,se=new Set,ie=new Set;return L==null||L.forEach(Y=>{Z.add(Y.user_id),Y.email_number>0&&Y.status==="sent"&&se.add(Y.user_id),Y.status==="converted"&&ie.add(Y.user_id)}),{enrolled:Z.size,started:se.size,converted:ie.size,conversionRate:Z.size>0?(ie.size/Z.size*100).toFixed(1):"0"}}}),{data:S}=ge({queryKey:["nurture-free-user-count"],queryFn:async()=>{const{data:L,error:H}=await T.from("user_profiles").select("id").is("deleted_at",null);if(H)throw H;const Z=new Set((L==null?void 0:L.map(ae=>ae.id))||[]),{data:se}=await T.from("user_nurture_emails").select("user_id"),ie=new Set((se==null?void 0:se.map(ae=>ae.user_id))||[]),{data:Y}=await T.from("user_subscriptions").select("user_id").in("status",["active","trialing"]),I=new Set((Y==null?void 0:Y.map(ae=>ae.user_id))||[]),{data:ee}=await T.from("user_roles").select("user_id").in("role",["admin","super_admin"]),le=new Set((ee==null?void 0:ee.map(ae=>ae.user_id))||[]),{data:ve}=await T.from("user_profiles").select("id").eq("email_opt_out",!0),te=new Set((ve==null?void 0:ve.map(ae=>ae.id))||[]);let X=0;for(const ae of Z)!ie.has(ae)&&!I.has(ae)&&!le.has(ae)&&!te.has(ae)&&X++;return X}}),{data:P,isLoading:C}=ge({queryKey:["nurture-history"],queryFn:async()=>{const{data:L,error:H}=await T.from("user_nurture_emails").select("*").neq("email_number",0).order("sent_at",{ascending:!1}).limit(500);if(H)throw H;if(!(L!=null&&L.length))return[];const Z=[...new Set(L.map(Y=>Y.user_id))],{data:se}=await T.from("user_profiles").select("id, full_name, username").in("id",Z),ie=new Map((se==null?void 0:se.map(Y=>[Y.id,Y]))||[]);return L.map(Y=>{var I,ee;return{...Y,full_name:(I=ie.get(Y.user_id))==null?void 0:I.full_name,username:(ee=ie.get(Y.user_id))==null?void 0:ee.username}})}}),O=_e({mutationFn:async({id:L,is_active:H})=>{const{error:Z}=await T.from("nurture_email_templates").update({is_active:H}).eq("id",L);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["nurture-templates"]}),K.success("Template status updated")}}),$=_e({mutationFn:async L=>{const{error:H}=await T.from("nurture_email_templates").update({subject:L.subject,description:L.description,html_content:L.html_content,updated_at:new Date().toISOString()}).eq("id",L.id);if(H)throw H},onSuccess:()=>{t.invalidateQueries({queryKey:["nurture-templates"]}),K.success("Template updated"),r(null)}}),z=_e({mutationFn:async()=>{const{data:L,error:H}=await T.functions.invoke("send-nurture-emails",{body:{}});if(H)throw H;return L},onSuccess:L=>{t.invalidateQueries({queryKey:["nurture-stats"]}),t.invalidateQueries({queryKey:["nurture-history"]}),K.success(L.message||"Nurture emails sent")},onError:L=>K.error("Failed: "+L.message)}),D=_e({mutationFn:async()=>{const{data:L,error:H}=await T.functions.invoke("send-nurture-emails",{body:{enrollExisting:!0}});if(H)throw H;return L},onSuccess:L=>{t.invalidateQueries({queryKey:["nurture-stats"]}),t.invalidateQueries({queryKey:["nurture-free-user-count"]}),K.success(L.message||"Free users enrolled")},onError:L=>K.error("Failed: "+L.message)}),A=_e({mutationFn:async({template:L,email:H})=>{const Z=await T.functions.invoke("send-test-email",{body:{to:H,subject:L.subject,html:L.html_content}});if(Z.error)throw Z.error;return Z.data},onSuccess:()=>{K.success("Test email sent"),y(null),x("")},onError:L=>K.error("Failed: "+L.message)}),F=L=>{o({subject:L.subject,description:L.description||""});const H=eo(L.html_content);N(H||qa()),r(L)},q=()=>{if(!n)return;const L=Ta(h);$.mutate({id:n.id,subject:m.subject,description:m.description,html_content:L})},E=P==null?void 0:P.filter(L=>{var ie,Y;const H=!g||((ie=L.full_name)==null?void 0:ie.toLowerCase().includes(g.toLowerCase()))||((Y=L.username)==null?void 0:Y.toLowerCase().includes(g.toLowerCase())),Z=_==="all"||L.email_number===parseInt(_),se=b==="all"||b==="opened"&&L.opened_at||b==="clicked"&&L.clicked_at||L.status===b;return H&&Z&&se});return p?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs(js,{value:s,onValueChange:a,className:"space-y-6",children:[e.jsxs(fs,{children:[e.jsxs(Ne,{value:"templates",className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4"}),"Templates"]}),e.jsxs(Ne,{value:"history",className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4"}),"Send History"]})]}),e.jsxs(we,{value:"templates",className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(R,{variant:"outline",onClick:()=>D.mutate(),disabled:D.isPending,children:[D.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Enroll Free Users (",S??"...",")"]}),e.jsxs(R,{onClick:()=>z.mutate(),disabled:z.isPending,children:[z.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rt,{className:"h-4 w-4 mr-2"}),"Send Nurture Emails Now"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Templates"}),e.jsx("p",{className:"text-2xl font-bold",children:(c==null?void 0:c.length)||0})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Es,{className:"h-8 w-8 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active"}),e.jsx("p",{className:"text-2xl font-bold",children:(c==null?void 0:c.filter(L=>L.is_active).length)||0})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wr,{className:"h-8 w-8 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Users Started"}),e.jsx("p",{className:"text-2xl font-bold",children:(w==null?void 0:w.started)||0})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ds,{className:"h-8 w-8 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Conversion Rate"}),e.jsxs("p",{className:"text-2xl font-bold",children:[(w==null?void 0:w.conversionRate)||"0","%"]})]})]})})})]}),e.jsx(G,{children:e.jsx(J,{className:"p-0",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-16",children:"#"}),e.jsx(U,{children:"Subject"}),e.jsx(U,{children:"Description"}),e.jsx(U,{className:"w-20",children:"Active"}),e.jsx(U,{className:"w-40",children:"Actions"})]})}),e.jsx($e,{children:c==null?void 0:c.map(L=>e.jsxs(he,{children:[e.jsx(M,{children:e.jsxs(B,{variant:"outline",children:["Email ",L.email_number]})}),e.jsx(M,{className:"font-medium",children:L.subject}),e.jsx(M,{className:"text-muted-foreground text-sm",children:L.description||"—"}),e.jsx(M,{children:e.jsx(Ge,{checked:L.is_active,onCheckedChange:H=>O.mutate({id:L.id,is_active:H})})}),e.jsx(M,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>l(L),children:e.jsx(us,{className:"h-4 w-4"})}),e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>F(L),children:e.jsx(cc,{className:"h-4 w-4"})}),e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>{y(L),x("")},children:e.jsx(dt,{className:"h-4 w-4"})})]})})]},L.id))})]})})})]}),e.jsxs(we,{value:"history",className:"space-y-6",children:[P&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"h-6 w-6 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Sent"}),e.jsx("p",{className:"text-xl font-bold",children:P.filter(L=>L.status==="sent").length})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{className:"h-6 w-6 text-destructive"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"}),e.jsx("p",{className:"text-xl font-bold",children:P.filter(L=>L.status==="failed").length})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(us,{className:"h-6 w-6 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Opened"}),e.jsx("p",{className:"text-xl font-bold",children:P.filter(L=>L.opened_at).length})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ds,{className:"h-6 w-6 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Converted"}),e.jsx("p",{className:"text-xl font-bold",children:P.filter(L=>L.status==="converted").length})]})]})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search users...",value:g,onChange:L=>
414f(L.target.value),className:"pl-10"})]}),e.jsxs(oe,{value:_,onValueChange:k,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{placeholder:"Email #"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Emails"}),e.jsx(V,{value:"1",children:"Email 1"}),e.jsx(V,{value:"2",children:"Email 2"}),e.jsx(V,{value:"3",children:"Email 3"}),e.jsx(V,{value:"4",children:"Email 4"}),e.jsx(V,{value:"5",children:"Email 5 (Pick)"}),e.jsx(V,{value:"6",children:"Email 6 (Result)"})]})]}),e.jsxs(oe,{value:b,onValueChange:j,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{placeholder:"Status"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Status"}),e.jsx(V,{value:"sent",children:"Sent"}),e.jsx(V,{value:"failed",children:"Failed"}),e.jsx(V,{value:"converted",children:"Converted"}),e.jsx(V,{value:"opened",children:"Opened"}),e.jsx(V,{value:"clicked",children:"Clicked"})]})]})]}),e.jsx(G,{children:e.jsx(J,{className:"p-0",children:e.jsx(cs,{className:"h-[500px]",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"User"}),e.jsx(U,{children:"Email #"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Sent At"}),e.jsx(U,{children:"Opened"}),e.jsx(U,{children:"Clicked"})]})}),e.jsx($e,{children:C?e.jsx(he,{children:e.jsx(M,{colSpan:6,className:"text-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin mx-auto"})})}):E!=null&&E.length?E.map(L=>e.jsxs(he,{children:[e.jsxs(M,{children:[e.jsx("div",{children:L.full_name||"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:L.username})]}),e.jsx(M,{children:e.jsxs(B,{variant:"outline",children:["Email ",L.email_number]})}),e.jsx(M,{children:e.jsx(B,{variant:L.status==="sent"?"default":L.status==="converted"?"secondary":"destructive",children:L.status})}),e.jsx(M,{className:"text-sm",children:ke(new Date(L.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(M,{children:L.opened_at?e.jsx(Es,{className:"h-4 w-4 text-green-500"}):"—"}),e.jsx(M,{children:L.clicked_at?e.jsx(Xr,{className:"h-4 w-4 text-blue-500"}):"—"})]},L.id)):e.jsx(he,{children:e.jsx(M,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No nurture emails sent yet"})})})]})})})})]}),e.jsx(Ue,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Be,{className:"max-w-3xl max-h-[80vh]",children:[e.jsxs(ze,{children:[e.jsxs(Ke,{children:["Preview: ",i==null?void 0:i.subject]}),e.jsxs(Vs,{children:["Email ",i==null?void 0:i.email_number," of 4"]})]}),e.jsx(cs,{className:"h-[60vh]",children:e.jsx("iframe",{srcDoc:(i==null?void 0:i.html_content)||"",className:"w-full h-[60vh] border-0",title:"Email Preview"})})]})}),e.jsx(Ue,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Be,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsxs(Ke,{children:["Edit Nurture Email ",n==null?void 0:n.email_number]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Q,{children:"Subject"}),e.jsx(pe,{value:m.subject,onChange:L=>o(H=>({...H,subject:L.target.value}))})]}),e.jsxs("div",{children:[e.jsx(Q,{children:"Description"}),e.jsx(pe,{value:m.description,onChange:L=>o(H=>({...H,description:L.target.value}))})]}),e.jsx(dl,{content:h,onChange:N})]}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>r(null),children:"Cancel"}),e.jsxs(R,{onClick:q,disabled:$.isPending,children:[$.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(It,{className:"h-4 w-4 mr-2"}),"Save"]})]})]})}),e.jsx(Ue,{open:!!d,onOpenChange:()=>y(null),children:e.jsxs(Be,{children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Send Test Email"}),e.jsxs(Vs,{children:['Send "',d==null?void 0:d.subject,'" to a test address']})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{children:[e.jsx(Q,{children:"Email Address"}),e.jsx(pe,{type:"email",value:u,onChange:L=>x(L.target.value),placeholder:"[email protected]"})]})}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>y(null),children:"Cancel"}),e.jsxs(R,{onClick:()=>d&&A.mutate({template:d,email:u}),disabled:A.isPending||!u,children:[A.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dt,{className:"h-4 w-4 mr-2"}),"Send Test"]})]})]})})]})}function yy(){const[s,a]=v.useState("templates"),t=Me(),[n,r]=v.useState(null),[i,l]=v.useState(null),[m,o]=v.useState(!1),[h,N]=v.useState("day1"),[d,y]=v.useState({subject:"",description:"",day_number:1}
414),[u,x]=v.useState(qa()),[g,f]=v.useState(null),[_,k]=v.useState(""),{data:b,isLoading:j}=ge({queryKey:["onboarding-templates"],queryFn:async()=>{const{data:E,error:L}=await T.from("onboarding_email_templates").select("*").order("day_number",{ascending:!0});if(L)throw L;return E}}),{data:c}=ge({queryKey:["onboarding-stats"],queryFn:async()=>{const{data:E,error:L}=await T.from("user_onboarding_emails").select("user_id, day_number");if(L)throw L;const H={};E==null||E.forEach(Y=>{const I=H[Y.user_id]||0;H[Y.user_id]=Math.max(I,Y.day_number)});const Z={};Object.values(H).forEach(Y=>{Z[Y]=(Z[Y]||0)+1});const se=Object.keys(H).length,ie=Z[10]||0;return{dayCounts:Z,totalStarted:se,completed:ie,completionRate:se>0?(ie/se*100).toFixed(1):"0"}}}),{data:p=0}=ge({queryKey:["unenrolled-users-count"],queryFn:async()=>{const{data:E}=await T.from("user_onboarding_emails").select("user_id"),L=new Set((E==null?void 0:E.map(ie=>ie.user_id))||[]),{data:H}=await T.from("user_subscriptions").select("user_id").in("status",["active","trialing"]),Z=new Set((H==null?void 0:H.map(ie=>ie.user_id))||[]),{data:se}=await T.from("user_profiles").select("id").is("deleted_at",null).or("email_opt_out.is.null,email_opt_out.eq.false");return(se==null?void 0:se.filter(ie=>Z.has(ie.id)&&!L.has(ie.id)).length)||0}}),w=_e({mutationFn:async E=>{const{error:L}=await T.from("onboarding_email_templates").update({subject:E.subject,description:E.description,day_number:E.day_number,html_content:E.html_content,updated_at:new Date().toISOString()}).eq("id",E.id);if(L)throw L},onSuccess:()=>{t.invalidateQueries({queryKey:["onboarding-templates"]}),K.success("Template updated successfully"),r(null)},onError:E=>{K.error("Failed to update template: "+E.message)}}),S=_e({mutationFn:async({id:E,is_active:L})=>{const{error:H}=await T.from("onboarding_email_templates").update({is_active:L,updated_at:new Date().toISOString()}).eq("id",E);if(H)throw H},onSuccess:()=>{t.invalidateQueries({queryKey:["onboarding-templates"]}),K.success("Template status updated")},onError:E=>{K.error("Failed to update status: "+E.message)}}),P=_e({mutationFn:async E=>{const{data:L,error:H}=await T.functions.invoke("send-onboarding-emails",{body:{enrollExisting:!0,startFromDay1:E}});if(H)throw H;return L},onSuccess:E=>{t.invalidateQueries({queryKey:["onboarding-stats"]}),t.invalidateQueries({queryKey:["unenrolled-users-count"]}),K.success(E.message||"Users enrolled successfully"),o(!1)},onError:E=>{K.error("Failed to enroll users: "+E.message)}}),C=_e({mutationFn:async()=>{const{data:E,error:L}=await T.functions.invoke("send-onboarding-emails",{body:{}});if(L)throw L;return E},onSuccess:E=>{t.invalidateQueries({queryKey:["onboarding-stats"]}),K.success(E.message||"Onboarding emails sent")},onError:E=>{K.error("Failed to send emails: "+E.message)}}),O=_e({mutationFn:async({template:E,email:L})=>{const{data:H,error:Z}=await T.functions.invoke("send-test-email",{body:{testEmail:L,subject:E.subject,htmlContent:E.html_content,emailType:"onboarding"}});if(Z)throw Z;return H},onSuccess:()=>{K.success("Test email sent successfully!"),f(null),k("")},onError:E=>{K.error("Failed to send test email: "+E.message)}}),$=_e({mutationFn:async({templateId:E,newDayNumber:L})=>{const{data:H,error:Z}=await T.functions.invoke("send-onboarding-emails",{body:{swapDays:!0,templateId:E,newDayNumber:L}});if(Z)throw Z;return H},onSuccess:E=>{t.invalidateQueries({queryKey:["onboarding-templates"]}),K.success(E.message||"Template day updated successfully")},onError:E=>{K.error("Failed to update day: "+E.message)}}),z=E=>{const L=eo(E.html_content);y({subject:E.subject,description:E.description,day_number:E.day_number}),x(L||qa()),r(E)},D=async()=>{if(!n)return;const E=Ta(u);d.day_number!==n.day_number?$.mutate({templateId:n.id,newDayNumber:d.day_number},{onSuccess:()=>{w.mutate({id:n.id,subject:d.subject,description:d.description,day_number:d.day_number,html_content:E})}}):w.mutate({id:n.id,subject:d.subject,description:d.description,day_number:d.day_number,html_content:E})},A=n&&(b==null?void 0:b.some(E=>
414E.day_number===d.day_number&&E.id!==n.id)),F=()=>{!g||!_.trim()||O.mutate({template:g,email:_.trim()})},q=()=>{const E=(b==null?void 0:b.map(H=>H.day_number))||[],L=Array.from({length:10},(H,Z)=>Z+1);return n?L:L.filter(H=>!E.includes(H))};return j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs(js,{value:s,onValueChange:a,className:"space-y-6",children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"templates",className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4"}),"Members"]}),e.jsxs(Ne,{value:"nurture",className:"flex items-center gap-2",children:[e.jsx(ut,{className:"h-4 w-4"}),"Nurture"]}),e.jsxs(Ne,{value:"history",className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4"}),"Send History"]})]}),e.jsxs(we,{value:"templates",className:"space-y-6",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(R,{onClick:()=>o(!0),variant:"outline",disabled:p===0,children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Enroll Existing Users (",p,")"]}),e.jsxs(R,{onClick:()=>C.mutate(),disabled:C.isPending,children:[C.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rt,{className:"h-4 w-4 mr-2"}),"Send Daily Emails Now"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(dt,{className:"h-8 w-8 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Templates"}),e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Es,{className:"h-8 w-8 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active"}),e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.filter(E=>E.is_active).length)||0})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xs,{className:"h-8 w-8 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Users Started"}),e.jsx("p",{className:"text-2xl font-bold",children:(c==null?void 0:c.totalStarted)||0})]})]})})}),e.jsx(G,{children:e.jsx(J,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Es,{className:"h-8 w-8 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Completion Rate"}),e.jsxs("p",{className:"text-2xl font-bold",children:[(c==null?void 0:c.completionRate)||0,"%"]})]})]})})})]}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{children:"10-Day Onboarding Email Templates"})}),e.jsx(J,{children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{className:"w-16",children:"Day"}),e.jsx(U,{children:"Subject"}),e.jsx(U,{children:"Description"}),e.jsx(U,{className:"w-24",children:"Active"}),e.jsx(U,{className:"w-24",children:"Users"}),e.jsx(U,{className:"w-40",children:"Actions"})]})}),e.jsx($e,{children:b==null?void 0:b.map(E=>{var L;return e.jsxs(he,{children:[e.jsx(M,{children:e.jsxs(B,{variant:"outline",className:"font-mono",children:["Day ",E.day_number]})}),e.jsx(M,{className:"font-medium",children:E.subject}),e.jsx(M,{className:"text-muted-foreground text-sm",children:E.description}),e.jsx(M,{children:e.jsx(Ge,{checked:E.is_active,onCheckedChange:H=>S.mutate({id:E.id,is_active:H})})}),e.jsx(M,{children:e.jsx(B,{variant:"secondary",children:((L=c==null?void 0:c.dayCounts)==null?void 0:L[E.day_number])||0})}),e.jsx(M,{children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>l(E),title:"Preview",children:e.jsx(us,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>z(E),title:"Edit",children:e.jsx(cc,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>f(E),title:"Send Test Email",children:e.jsx(ut,{className:"h-4 w-4"})})]})})]},E.id)})})]})})]})]}),e.jsx(we,{value:"history",children:e.jsx(fy,{})}),e.jsx(Ue,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Be,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Edit Onboarding Template"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Day Number"}),e.jsxs(oe,{value:String(d.day_number),onValueChange:E=>y({...d,day_number:parseInt(E)}),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:q().map(E=>e.jsxs(V,{value:String(E),children:["Day ",E]},E))})]}),A&&e.jsxs("p",{className:"text-sm text-amber-500 flex items-center gap-1",children:[e.jsx(Od,{className:"h-4 w-4"}),"Day ",d.day_number," is currently used. Templates will be swapped."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"subject",children:"Subject"}),e.jsx(pe,{id:"subject",value:d.subject,onChange:E=>y({...d,subject:E.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"description",children:"Description (internal)"}),e.jsx(pe,{id:"description",value:d.description,onChange:E=>y({...d,description:E.target.value})})]}),e.jsx(dl,{content:u,onChange:x,showPreview:!0}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(R,{variant:"outline",onClick:()=>r(null),children:"Cancel"}),e.jsxs(R,{onClick:D,disabled:w.isPending||$.isPending,children:[(w.isPending||$.isPending)&&e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),e.jsx(It,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})}),e.jsx(Ue,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Be,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsxs(Ke,{children:["Preview: ",i==null?void 0:i.subject]})}),e.jsx("div",{className:"border rounded-lg overflow-hidden mt-4",children:e.jsx("iframe",{srcDoc:i==null?void 0:i.html_content,className:"w-full h-[600px] border-0",title:"Email Preview"})})]})}),e.jsx(Ue,{open:!!g,onOpenChange:()=>{f(null),k("")},children:e.jsxs(Be,{children:[e.jsxs(ze,{children:[e.jsxs(Ke,{children:["Send Test Email - Day ",g==null?void 0:g.day_number]}),e.jsxs(Vs,{children:["Subject: ",g==null?void 0:g.subject]})]}),e.jsx("div",{className:"space-y-4 pt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"testEmail",children:"Email Address"}),e.jsx(pe,{id:"testEmail",type:"email",placeholder:"Enter email address...",value:_,onCh
414ange:E=>k(E.target.value)})]})}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>{f(null),k("")},children:"Cancel"}),e.jsxs(R,{onClick:F,disabled:!_.trim()||O.isPending,children:[O.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ut,{className:"h-4 w-4 mr-2"}),"Send Test"]})]})]})}),e.jsx(Ue,{open:m,onOpenChange:o,children:e.jsxs(Be,{children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Enroll Existing Users"}),e.jsxs(Vs,{children:["Choose how to start the onboarding campaign for ",p," unenrolled users."]})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs(Ut,{value:h,onValueChange:E=>N(E),children:[e.jsxs("div",{className:"flex items-start space-x-3 p-3 rounded-lg border hover:bg-muted/50 cursor-pointer",children:[e.jsx(nt,{value:"day1",id:"day1",className:"mt-1"}),e.jsxs(Q,{htmlFor:"day1",className:"cursor-pointer flex-1",children:[e.jsx("div",{className:"font-medium",children:"Start Everyone at Day 1"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"All users will receive the full 10-day campaign from the beginning."})]})]}),e.jsxs("div",{className:"flex items-start space-x-3 p-3 rounded-lg border hover:bg-muted/50 cursor-pointer",children:[e.jsx(nt,{value:"signup",id:"signup",className:"mt-1"}),e.jsxs(Q,{htmlFor:"signup",className:"cursor-pointer flex-1",children:[e.jsx("div",{className:"font-medium",children:"Start Based on Signup Date"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Users will start at the day matching their account age (e.g., 5 days old = Day 5)."})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(R,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(R,{onClick:()=>P.mutate(h==="day1"),disabled:P.isPending,children:[P.isPending&&e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Enroll ",p," Users"]})]})]})]})}),e.jsx(we,{value:"nurture",children:e.jsx(vy,{})})]})}const Ny=[{value:"America/New_York",label:"Eastern Time (ET)"},{value:"America/Chicago",label:"Central Time (CT)"},{value:"America/Denver",label:"Mountain Time (MT)"},{value:"America/Los_Angeles",label:"Pacific Time (PT)"},{value:"America/Phoenix",label:"Arizona (MST)"},{value:"America/Anchorage",label:"Alaska Time (AKT)"},{value:"Pacific/Honolulu",label:"Hawaii Time (HST)"},{value:"Europe/London",label:"London (GMT/BST)"},{value:"Europe/Paris",label:"Central European (CET)"},{value:"UTC",label:"UTC"}];function _y(){const[s,a]=v.useState("template"),[t,n]=v.useState(null),[r,i]=v.useState(""),[l,m]=v.useState(!1),[o,h]=v.useState(!1),[N,d]=v.useState(!1),[y,u]=v.useState({}),[x,g]=v.useState(!1),f=Me(),{data:_,isLoading:k}=ge({queryKey:["daily-insights-template"],queryFn:async()=>{const{data:z,error:D}=await T.from("daily_insights_template").select("*").single();if(D)throw D;return z}}),b=v.useRef(!1);v.useEffect(()=>{_&&!b.current&&(u({subject:_.subject,greeting:_.greeting,intro_text:_.intro_text,highlights_header:_.highlights_header,badges_header:_.badges_header,insights_header:_.insights_header,improvements_header:_.improvements_header,events_header:_.events_header,games_header:_.games_header,signature:_.signature,cta_button_text:_.cta_button_text,cta_button_link:_.cta_button_link,send_time:_.send_time,timezone:_.timezone}),g(!1),b.current=!0)},[_]);const{data:j}=ge({queryKey:["daily-insights-eligible-count"],queryFn:async()=>{const{data:z,error:D}=await T.from("user_subscriptions").select(`
415          user_id,
416          user_profiles!inner(
417            id,
418            email_opt_out,
419            deleted_at
420          )
421        `).in("status",["active","trial","paused"]).eq("user_profiles.email_opt_out",!1).is("user_profiles.deleted_at",null);if(D)throw D;return new Set((z==null?void 0:z.map(F=>F.user_id))||[]).size}}
421),{data:c}=ge({queryKey:["daily-insights-campaigns"],queryFn:async()=>{const{data:z,error:D}=await T.from("email_campaigns").select("id, name, recipient_count, status, sent_at").ilike("name","Daily Insights%").order("created_at",{ascending:!1}).limit(5);if(D)throw D;return z}}),p=_e({mutationFn:async z=>{const{error:D}=await T.from("daily_insights_template").update(z).eq("id",_.id);if(D)throw D},onSuccess:()=>{f.invalidateQueries({queryKey:["daily-insights-template"]})},onError:z=>{Ee({title:"Failed to update template",description:z.message,variant:"destructive"})}}),w=(z,D)=>{u(A=>({...A,[z]:D})),g(!0)},S=()=>{p.mutate(y,{onSuccess:()=>{g(!1),Ee({title:"Template saved successfully"}),b.current=!1}})},P=(z,D)=>{p.mutate({[z]:D})},C=async()=>{h(!0);try{const{data:z,error:D}=await T.functions.invoke("send-daily-insights",{body:{previewOnly:!0}});if(D)throw D;n(z.previewHtml),a("preview")}catch(z){Ee({title:"Failed to generate preview",description:z.message,variant:"destructive"})}finally{h(!1)}},O=async()=>{if(!r){Ee({title:"Please enter a test email",variant:"destructive"});return}m(!0);try{const{data:z,error:D}=await T.functions.invoke("send-daily-insights",{body:{testMode:!0,testEmail:r}});if(D)throw D;Ee({title:"Test email sent!",description:`Sent to ${r}`})}catch(z){Ee({title:"Failed to send test email",description:z.message,variant:"destructive"})}finally{m(!1)}},$=async()=>{if(confirm("This will send daily insights to all eligible users. Are you sure?")){d(!0);try{const{data:z,error:D}=await T.functions.invoke("send-daily-insights",{body:{}});if(D)throw D;Ee({title:"Daily insights sent!",description:`Sent to ${z.successCount} users. ${z.failCount} failed, ${z.skipCount} skipped.`}),f.invalidateQueries({queryKey:["daily-insights-campaigns"]}),f.invalidateQueries({queryKey:["daily-insights-template"]})}catch(z){Ee({title:"Failed to send daily insights",description:z.message,variant:"destructive"})}finally{d(!1)}}};return k?e.jsx(G,{children:e.jsx(J,{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):_?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:`p-3 rounded-lg ${_.is_active?"bg-green-500/10":"bg-muted"}`,children:_.is_active?e.jsx(Es,{className:"h-6 w-6 text-green-500"}):e.jsx($s,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx(B,{variant:_.is_active?"default":"secondary",children:_.is_active?"Active":"Inactive"})]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(hs,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:j==null?void 0:j.toLocaleString()}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Eligible Users"})]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-blue-500/10",children:e.jsx($s,{className:"h-6 w-6 text-blue-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:_.send_time.slice(0,5)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:_.timezone})]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-purple-500/10",children:e.jsx(dt,{className:"h-6 w-6 text-purple-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:_.last_sent_at?ke(new Date(_.last_sent_at),"MMM d, h:mm a"):"Never sent"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})]}),e.jsxs(js,{value:s,onValueChange:a,children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start lg:w-[400px]",children:[e.jsxs(Ne,{value:"template",className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"Template"]}),e.jsxs(Ne,{value:"preview",className:"flex items-center gap-2",children:[e.jsx(us,{className:"h-4 w-4"}),"Preview"]}),e.jsxs(Ne,{value:"send",className:"flex items-center gap-2",children:[e.jsx(ut,{className:"h-4 w-4"}),"Send"]})]}),e.jsx(we,{value:"template",className:"mt-6 space-y-6",children:e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"h-5 w-5"}),"Email Template Settings"]}),e.jsx(De,{children:"Customize the daily insights email template."})]}),e.jsxs(J,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{children:"Daily Emails Active"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enable or disable automatic daily insight emails"})]}),e.jsx(Ge,{checked:_.is_active,onCheckedChange:z=>P("is_active",z)})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"subject",children:"Email Subject"}),e.jsx(pe,{id:"subject",value:y.subject??"",onChange:z=>w("subject",z.target.value),placeholder:"Your Daily Klever Insights 🎯"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{first_name}"," for personalization"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"greeting",children:"Greeting"}),e.jsx(pe,{id:"greeting",value:y.greeting??"",onChange:z=>w("greeting",z.target.value),placeholder:"Hey {first_name},"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"intro",children:"Intro Text"}),e.jsx(Xs,{id:"intro",value:y.intro_text??"",onChange:z=>w("intro_text",z.target.value),rows:2})]}),e.jsx(is,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"highlights",children:"Highlights Header"}),e.jsx(pe,{id:"highlights",value:y.highlights_header??"",onChange:z=>w("highlights_header",z.target.value),placeholder:"🏆 Your Highlights"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"badges",children:"Badges Header"}),e.jsx(pe,{id:"badges",value:y.badges_header??"",onChange:z=>w("badges_header",z.target.value),placeholder:"🏅 Recent Achievements"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"insights",children:"Insights Header"}),e.jsx(pe,{id:"insights",value:y.insights_header??"",onChange:z=>w("insights_header",z.target.value),placeholder:"💡 KASH AI Insights"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"improvements",children:"Improvements Header"}),e.jsx(pe,{id:"improvements",value:y.improvements_header??"",onChange:z=>w("improvements_header",z.target.value),placeholder:"📈 Areas to Watch"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"events",children:"Events Header"}),e.jsx(pe,{id:"events",value:y.events_header??"",onChange:z=>w("events_header",z.target.value),placeholder:"📅 Upcoming Live Support"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"games",children:"Games Header"}),e.jsx(pe,{id:"games",value:y.games_header??"",onChange:z=>w("games_header",z.target.value),placeholder:"🏈 Upcoming Games"})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"signature",children:"Signature"}),e.jsx(Xs,{id:"signature",value:y.signature??"",onChange:z=>w("signature",z.target.value),rows:3,placeholder:`Keep betting smart,
422The Klever Bet Team`})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"ctaText",children:"CTA Button Text"}),e.jsx(pe,{id:"ctaText",value:y.cta_button_text??"",onChange:z=>w("cta_button_text",z.target.value),placeholder:"View Full Stats"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"ctaLink",children:"CTA Button Link"}),e.jsx(pe,{id:"ctaLink",value:y.cta_button_link??"",onChange:z=>w("cta_button_link",z.target.value),placeholder:"https://kleverbet.ai/profile"})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"sendTime",children:"Send Time"}),e.jsx(pe,{id:"sendTime",type:"time",value:(y.send_time??"08:00:00").slice(0,5),onChange:z=>w("send_time",z.target.value+":00")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"timezone",children:"Timezone"}
422),e.jsxs(oe,{value:y.timezone??"America/New_York",onValueChange:z=>w("timezone",z),children:[e.jsx(de,{id:"timezone",children:e.jsx(ue,{placeholder:"Select timezone"})}),e.jsx(me,{children:Ny.map(z=>e.jsx(V,{value:z.value,children:z.label},z.value))})]})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx("div",{children:x&&e.jsx("span",{className:"text-sm text-amber-600",children:"You have unsaved changes"})}),e.jsxs(R,{onClick:S,disabled:!x||p.isPending,children:[p.isPending?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})}),e.jsx(we,{value:"preview",className:"mt-6",children:e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(us,{className:"h-5 w-5"}),"Email Preview"]}),e.jsx(De,{children:"Preview how the email will look with sample data"})]}),e.jsxs(R,{onClick:C,disabled:o,children:[o?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(us,{className:"h-4 w-4 mr-2"}),"Generate Preview"]})]})}),e.jsx(J,{children:t?e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsx("iframe",{srcDoc:t,className:"w-full h-[600px] border-0",title:"Email Preview"})}):e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:'Click "Generate Preview" to see how the email will look'})})]})}),e.jsxs(we,{value:"send",className:"mt-6 space-y-6",children:[e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{children:"Send Test Email"}),e.jsx(De,{children:"Send a test email to verify the template looks correct"})]}),e.jsx(J,{children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx(pe,{placeholder:"Enter test email address",value:r,onChange:z=>i(z.target.value),className:"flex-1"}),e.jsxs(R,{onClick:O,disabled:l||!r,children:[l?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ut,{className:"h-4 w-4 mr-2"}),"Send Test"]})]})})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{children:"Manual Send"}),e.jsx(De,{children:"Manually trigger the daily insights email to all eligible users. This should only be used for testing or if the scheduled job failed."})]}),e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["Send to ",j==null?void 0:j.toLocaleString()," eligible users"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Users with activity data who haven't opted out"})]}),e.jsxs(R,{variant:"destructive",onClick:$,disabled:N||!_.is_active,children:[N?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rt,{className:"h-4 w-4 mr-2"}),"Send Now"]})]}),!_.is_active&&e.jsx("p",{className:"text-sm text-amber-500 mt-2",children:"Enable the template first to allow manual sending"})]})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsx(fe,{children:"Recent Daily Insight Emails"}),e.jsx(De,{children:"Last 5 daily insight email campaigns"})]}),e.jsx(J,{children:c!=null&&c.length?e.jsx("div",{className:"space-y-3",children:c.map(z=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:z.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:z.sent_at?ke(new Date(z.sent_at),"MMM d, yyyy h:mm a"):"Not sent yet"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{variant:"secondary",children:[z.recipient_count," sent"]}),e.jsx(B,{variant:z.status==="sent"?"default":"secondary",className:z.status==="sent"?"bg-green-500/20 text-green-400":"",children:z.status})]})]},z.id))}):e.jsx("p",{className:"text-center py-6 text-muted-foreground",children:"No daily insight campaigns sent yet"})})]})]})]})]}):e.jsx(G,{children:e.jsx(J,{className:"py-12 text-center text-muted-foreground",children:"Template not found. Please check the database."})})}function by(){const[s,a]=v.useState("subscribers"),[t,n]=v.useState(""),r=Me(),{data:i=[],isLoading:l}=ge({queryKey:["email-subscribers"],queryFn:async()=>{const{data:b,error:j}=await T.from("email_subscribers").select("*").order("subscribed_at",{ascending:!1});if(j)throw j;return b}}),{data:m=[]}=ge({queryKey:["emailable-users"],queryFn:async()=>{const{data:b,error:j}=await T.from("user_profiles").select("username, full_name, email_opt_out, 
422created_at").not("username","is",null).is("deleted_at",null);if(j)throw j;return(b??[]).filter(c=>typeof c.username=="string"&&c.username.includes("@"))}}),{data:o=[]}=ge({queryKey:["email-unsubscribes"],queryFn:async()=>{const{data:b,error:j}=await T.from("email_unsubscribes").select("email");if(j)throw j;return b??[]}}),h=v.useMemo(()=>new Set(o.map(b=>(b.email??"").toLowerCase()).filter(Boolean)),[o]),N=v.useMemo(()=>{const b=new Map;for(const j of i){if(!j.email)continue;const c=j.email.toLowerCase();b.set(c,{key:c,email:j.email,interested_sports:j.interested_sports??[],subscribed_at:j.subscribed_at,source:j.source??"email_subscribers",status:h.has(c)||!j.is_active?"Unsubscribed":"Active",subscriberId:j.id})}for(const j of m){if(!(j!=null&&j.username))continue;const c=String(j.username).toLowerCase();b.has(c)||b.set(c,{key:c,email:j.username,interested_sports:[],subscribed_at:j.created_at,source:"user_account",status:h.has(c)||j.email_opt_out?"Unsubscribed":"Active"})}return Array.from(b.values()).sort((j,c)=>(c.subscribed_at??"").localeCompare(j.subscribed_at??""))},[i,m,h]),d=_e({mutationFn:async b=>{const{data:j,error:c}=await T.functions.invoke("admin-unsubscribe-email",{body:{email:b}});if(c)throw c;if(j!=null&&j.error)throw new Error(j.error)},onSuccess:()=>{r.invalidateQueries({queryKey:["email-subscribers"]}
422),r.invalidateQueries({queryKey:["emailable-users"]}),r.invalidateQueries({queryKey:["email-unsubscribes"]}),Ee({title:"Email unsubscribed"})},onError:b=>{Ee({title:"Failed to unsubscribe",description:b==null?void 0:b.message,variant:"destructive"})}}),y=_e({mutationFn:async b=>{const{error:j}=await T.from("email_subscribers").delete().eq("id",b);if(j)throw j},onSuccess:()=>{r.invalidateQueries({queryKey:["email-subscribers"]}),Ee({title:"Subscriber deleted"})},onError:()=>{Ee({title:"Failed to delete subscriber",variant:"destructive"})}}),u=N.filter(b=>{const j=(t??"").toLowerCase();return!j||(b.email??"").toLowerCase().includes(j)?!0:(b.interested_sports??[]).some(p=>(p??"").toLowerCase().includes(j))}),x=N.length,g=N.filter(b=>b.status==="Active").length,f=N.filter(b=>b.status==="Unsubscribed").length,_=i.length,k=Math.max(x-_,0);return e.jsx("div",{className:"space-y-6",children:e.jsxs(js,{value:s,onValueChange:a,children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start lg:w-[750px]",children:[e.jsxs(Ne,{value:"subscribers",className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4"}),"Subscribers"]}
422),e.jsxs(Ne,{value:"blast",className:"flex items-center gap-2",children:[e.jsx(ut,{className:"h-4 w-4"}),"Email Blast"]}),e.jsxs(Ne,{value:"daily-insights",className:"flex items-center gap-2",children:[e.jsx(ft,{className:"h-4 w-4"}),"Daily Insights"]}),e.jsxs(Ne,{value:"onboarding",className:"flex items-center gap-2",children:[e.jsx(zi,{className:"h-4 w-4"}),"Onboarding"]}),e.jsxs(Ne,{value:"history",className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4"}),"History"]})]}),e.jsx(we,{value:"subscribers",className:"mt-6 space-y-6",children:l?e.jsx(G,{children:e.jsx(J,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"Loading subscribers..."})})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(hs,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:x}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Subscribers"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_," email + ",k," users"]})]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-green-500/10",children:e.jsx(Es,{className:"h-6 w-6 text-green-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:g}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active Subscribers"})]})]})}),e.jsx(G,{children:e.jsxs(J,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-red-500/10",children:e.jsx(Is,{className:"h-6 w-6 text-red-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:f}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Unsubscribed"})]})]})})]}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 justify-between items-start md:items-center",children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-5 w-5"}),"Email Subscribers"]}
422),e.jsxs("div",{className:"relative w-full md:w-64",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by email or sport...",value:t,onChange:b=>n(b.target.value),className:"pl-9"})]})]})}),e.jsx(J,{children:u.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(dt,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:t?"No subscribers match your search":"No subscribers yet"})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Email"}),e.jsx(U,{children:"Interested Sports"}),e.jsx(U,{children:"Subscribed"}),e.jsx(U,{children:"Source"}),e.jsx(U,{children:"Status"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:u.map(b=>{const j=b.status==="Unsubscribed";return e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:b.email}),e.jsx(M,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:b.interested_sports.map(c=>e.jsx(B,{variant:"secondary",className:"text-xs",children:c.toUpperCase()},c))})}),e.jsx(M,{className:"text-muted-foreground text-sm",children:b.subscribed_at?ke(new Date(b.subscribed_at),"MMM d, yyyy"):"—"}),e.jsx(M,{children:e.jsx(B,{variant:"outline",className:"text-xs",children:b.source})}),e.jsx(M,{children:e.jsx(B,{variant:j?"secondary":"default",className:j?"bg-red-500/20 text-red-500":"bg-green-500/20 text-green-500",children:j?"Unsubscribed":"Active"})}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{variant:"ghost",size:"sm",title:j?"Already unsubscribed":"Unsubscribe",disabled:j||d.isPending,onClick:()=>{confirm(`Unsubscribe ${b.email}? They will no longer receive any emails.`)&&d.mutate(b.email)},children:e.jsx(Is,{className:j?"h-4 w-4 text-muted-foreground/40":"h-4 w-4 text-muted-foreground"})}),b.subscriberId&&e.jsx(R,{variant:"ghost",size:"sm",title:"Delete subscriber",onClick:()=>{confirm("Delete this subscriber?")&&y.mutate(b.subscriberId)},children:e.jsx(os,{className:"h-4 w-4 text-destructive"})})]})})]},b.key)})})]})})})]})]})}),e.jsx(we,{value:"blast",className:"mt-6",children:e.jsx(gy,{})}),e.jsx(we,{value:"daily-insights",className:"mt-6",children:e.jsx(_y,{})}),e.jsx(we,{value:"onboarding",className:"mt-6",children:e.jsx(yy,{})}),e.jsx(we,{value:"history",className:"mt-6",children:e.jsx(jy,{})})]})})}function Pr(){const s=Me(),{data:a=[],isLoading:t}=ge({queryKey:["social-platforms"],queryFn:async()=>{const{data:r}=await T.functions.invoke("late-social-setup",{body:{action:"list-accounts"}}),{data:i}=await T.from("social_platforms").select("*").eq("is_connected",!0),l=i||[];if(l.length>0)return l;const m=(r==null?void 0:r.accounts)||[];return m.length===0?[]:m.map(o=>({id:o.id||o._id||crypto.randomUUID(),platform:(o.platform||o.provider||"").toLowerCase(),late_profile_id:o.profileId||null,late_account_id:o.id||o._id||null,platform_username:o.username||o.name||null,platform_avatar:o.avatar||o.picture||null,is_connected:!0,features:{},connected_at:o.connectedAt||null,created_at:o.createdAt||null}))}});return{connectedPlatforms:a,isLoading:t,invalidate:()=>{s.invalidateQueries({queryKey:["social-platforms"]})}}}function Ya(){const[s,a]=v.useState(!1),t=v.useCallback(async(f,_)=>{a(!0);try{const{data:k,error:b}=await T.functions.invoke(f,{body:_});if(b)throw b;return k}catch(k){console.error(`Late API error (${f}):`,k);let b=k.message||"Failed to communicate with Late API";try{const j=k==null?void 0:k.context;if(j&&typeof j.clone=="function"){const c=await j.clone().json();b=(c==null?void 0:c.error)||(c==null?void 0:c.message)||b}}catch{}throw K.error(b),new Error(b)}finally{a(!1)}},[]),n=v.useCallback(async()=>t("late-social-setup",{action:"setup-profile"}),[t]),r=v.useCallback(async(f,_)=>t("late-social-setup",{action:"connect-url",platform:f,redirectUrl:_}),[t]),i=v.useCallback(async()=>{const f=await t("late-social-setup",{action:"list-accounts"});return(f==null?void 0:f.accounts)||[]},[t]),l=v.useCallback(async f=>t("late-social-setup",{action:"disconnect",lateAccountId:f}),[t]),m=v.useCallback(async(f,_)=>t("late-social-setup",{action:"update-features",platform:f,features:_}),[t]),o=v.useCallback(async f=>t("late-analytics",{action:"engagement",...f}),[t]),h=v.useCallback(async f=>t("late-analytics",{action:"followers",platform:f}),[t]),N=v.useCallback(async f=>t("late-analytics",{action:"summary",...f}),[t]),d=v.useCallback(async()=>t("late-social-setup",{action:"setup-webhook"}),[t]),y=v.useCallback(async()=>t("late-social-setup",{action:"check-webhook-status"}),[t]),u=v.useCallback(async f=>t("late-social-setup",{action:"create-post",...f}),[t]),x=v.useCallback(async f=>t("late-social-setup",{action:"list-posts",...f}),[t]),g=v.useCallback(async f=>t("late-social-setup",{action:"delete-post",postId:f}),[t]);return{isLoading:s,setupProfile:n,getConnectUrl:r,listAccounts:i,disconnectAccount:l,updateFeatures:m,getAnalytics:o,getFollowerStats:h,getAnalyticsSummary:N,setupWebhook:d,checkWebhookStatus:y,createPost:u,listPosts:x,deletePost:g}}const wy=({platform:s,isSelected:a,isConnected:t,onToggle:n})=>{const r=s.comingSoon===!0;return e.jsxs("button",{type:"button",disabled:r,onClick:r?void 0:n,className:Le("relative flex flex-col items-center gap-2 p-4 rounded-xl border-2 transition-all text-left",a?"border-primary bg-primary/5 shadow-sm":"border-border hover:border-muted-foreground
422/30",t&&"opacity-60",r&&"opacity-50 cursor-not-allowed"),children:[!r&&(a||t)&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx(Ks,{className:"h-4 w-4 text-primary"})}),e.jsx("img",{src:s.icon,alt:s.name,className:"h-8 w-8 object-contain"}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:s.name}),r&&e.jsx(B,{variant:"secondary",className:"text-[10px]",children:"Coming Soon"}),!r&&t&&e.jsx("span",{className:"text-xs text-primary",children:"Connected"})]})},Sy="/assets/twitter-C1IowD1K.png",ky="/assets/instagram-sB5CWXCo.png",Cy="/assets/facebook-MI4ZFGas.png",Py="/assets/linkedin-BWWABoCa.png",Fy="/assets/tiktok-uKGz9uXX.png",Ay="/assets/youtube-f6bjmgr2.png",Ty="/assets/pinterest-DVzAFn3p.png",Ly="/assets/reddit-BJog9RUD.png",Ey="/assets/bluesky-CjiJAk5V.png",Dy="/assets/threads-CzWR6FPV.png",My="/assets/googlebusiness-BRqQhBn_.png",Iy="/assets/telegram-BV8ASPvO.png",Ry="/assets/snapchat-DpKf_vZf.png",yt=[{id:"twitter",name:"Twitter / X",icon:Sy,color:"#000000",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!0,supportsMessages:!0},{id:"instagram",name:"Instagram",icon:ky,color:"#E4405F",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!0,supportsMessages:!0},{id:"facebook",name:"Facebook",icon:Cy,color:"#1877F2",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!0,supportsMessages:!0},{id:"linkedin",name:"LinkedIn",icon:Py,color:"#0A66C2",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!0,supportsMessages:!1}
422,{id:"tiktok",name:"TikTok",icon:Fy,color:"#000000",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!0,supportsMessages:!1},{id:"youtube",name:"YouTube",icon:Ay,color:"#FF0000",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!0,supportsMessages:!1},{id:"pinterest",name:"Pinterest",icon:Ty,color:"#E60023",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!1,supportsMessages:!1},{id:"reddit",name:"Reddit",icon:Ly,color:"#FF4500",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!0,supportsMessages:!1},{id:"bluesky",name:"Bluesky",icon:Ey,color:"#0085FF",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!1,supportsMessages:!1},{id:"threads",name:"Threads",icon:Dy,color:"#000000",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!0,supportsMessages:!1},{id:"googlebusiness",name:"Google Business",icon:My,color:"#4285F4",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!1,supportsMessages:!1},{id:"telegram",name:"Telegram",icon:Iy,color:"#26A5E4",supportsPosting:!0,supportsAnalytics:!1,supportsComments:!1,supportsMessages:!0},{id:"snapchat",name:"Snapchat",icon:Ry,color:"#FFFC00",supportsPosting:!0,supportsAnalytics:!0,supportsComments:!1,supportsMessages:!1,comingSoon:!0}],qy=({sessionConnected:s=[]})=>{const{connectedPlatforms:a,invalidate:t}=Pr(),{updateFeatures:n}=Ya(),r=v.useMemo(()=>{const l=a.map(o=>o.platform),m=s.filter(o=>!l.includes(o)).map(o=>({id:`session-${o}`,platform:o,late_profile_id:null,late_account_id:null,platform_username:null,platform_avatar:null,is_connected:!0,features:{posting:!0,analytics:!0,comments:!1,messages:!1},connected_at:null,created_at:null}));return[...a,...m]},[a,s]),i=async(l,m,o)=>{const h={...o,[m]:!o[m]};await n(l,h),t()};return r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No platforms connected yet."}):e.jsx("div",{className:"space-y-4",children:r.map(l=>{const m=yt.find(h=>h.id===l.platform);if(!m)return null;const o=l.features||{posting:!0,analytics:!0,comments:!1,messages:!1};return e.jsxs("div",{className:"p-4 rounded-lg border border-border space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("img",{src:m.icon,alt:m.name,className:"h-5 w-5 object-contain"}),e.jsx("span",{className:"font-medium text-sm",children:m.name})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[m.supportsPosting&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{checked:o.posting??!0,onCheckedChange:()=>i(l.platform,"posting",o)}),e.jsx(Q,{className:"text-xs",children:"Posting"})]}),m.supportsAnalytics&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{checked:o.analytics??!0,onCheckedChange:()=>i(l.platform,"analytics",o)}),e.jsx(Q,{className:"text-xs",children:"Analytics"})]}),m.supportsComments&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{checked:o.comments??!1,onCheckedChange:()=>i(l.platform,"comments",o)}),e.jsx(Q,{className:"text-xs",children:"Comments"})]}),m.supportsMessages&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{checked:o.messages??!1,onCheckedChange:()=>i(l.platform,"messages",o)}),e.jsx(Q,{className:"text-xs",children:"Messages"})]})]})]},l.id)})})},$y=({open:s,onOpenChange:a})=>{const{setupProfile:t,getConnectUrl:n,listAccounts:r,isLoading:i}=Ya(),{connectedPlatforms:l,invalidate:m}=Pr(),[o,h]=v.useState(1),[N,d]=v.useState([]),[y,u]=v.useState(null),[x,g]=v.useState([]),f=l.map(c=>c.platform);v.useEffect(()=>{s&&(h(1),d([]),g([]))},[s]);const _=c=>{const p=yt.find(w=>w.id===c);p!=null&&p.comingSoon||d(w=>w.includes(c)?w.filter(S=>S!==c):[...w,c])},k=async()=>{await t(),h(2)},b=async c=>{u(c);try{await t();const p=`${window.location.origin}/oauth/social-callback`,w=await n(c,p),S=w==null?void 0:w.connectUrl;if(!S){K.error(`Could not get connection URL for ${c}. Please try again.`),u(null);return}let P=null;try{P=(window.top||window).open(S,"_blank","width=600,height=700")}catch{P=window.open(S,"_blank","width=600,height=700")}if(!P){K.error("Popup was blocked. Please allow popups and try again."),u(null);return}const C=async()=>{const $=await r();m(),$.some(D=>(D.platform||"").toLowerCase()===c.toLowerCase())?g(D=>[...D,c]):K.error(`${c} did not connect successfully. Please try again.`),u(null)},O=setInterval(async()=>{try{P!=null&&P.closed&&(clearInterval(O),await C())}catch{clearInterval(O),u(null)}},1500);setTimeout(async()=>{y===c&&(clearInterval(O),await C())},3e4),setTimeout(()=>{clearInterval(O),u(null)},3e5)}catch(p){console.error(`Failed to connect ${c}:`,p),K.error(`Failed to connect ${c}`),u(null)}},j=o===1?25:o===2?50:o===3?75:100;return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsx(Ke,{children:"Social Media Setup"})}),e.jsx(Ct,{value:j,className:"mb-6"}),o===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select the platforms you want to connect. You can add more later."}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:yt.map(c=>
422e.jsx(wy,{platform:c,isSelected:N.includes(c.id),isConnected:f.includes(c.id),onToggle:()=>_(c.id)},c.id))}),e.jsx("div",{className:"flex justify-end pt-4",children:e.jsxs(R,{onClick:k,disabled:N.length===0||i,children:[i?e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Continue ",e.jsx(aa,{className:"ml-2 h-4 w-4"})]})})]}),o===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect each platform by authorizing access. A new window will open for each."}),e.jsx("div",{className:"space-y-3",children:N.map(c=>{const p=yt.find(C=>C.id===c);if(!p)return null;const w=f.includes(c),S=x.includes(c),P=y===c;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:p.icon,alt:p.name,className:"h-6 w-6 object-contain"}),e.jsx("span",{className:"font-medium",children:p.name})]}),w||S?e.jsxs("span",{className:"flex items-center gap-1 text-sm text-primary",children:[e.jsx(Ks,{className:"h-4 w-4"})," Connected"]}):e.jsxs(R,{size:"sm",onClick:()=>b(c),disabled:P||!!y,children:[P?e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ma,{className:"mr-2 h-4 w-4"}),P?"Connecting...":"Connect"]})]},c)})}),e.jsxs("div",{className:"flex justify-between pt-4",children:[e.jsxs(R,{variant:"outline",onClick:()=>h(1),children:[e.jsx(na,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsxs(R,{onClick:()=>{m(),h(3)},children:["Configure Features ",e.jsx(aa,{className:"ml-2 h-4 w-4"})]})]})]}),o===3&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure which features are enabled for each connected platform."}),e.jsx(qy,{sessionConnected:[...f,...x]}),e.jsxs("div",{className:"flex justify-between pt-4",children:[e.jsxs(R,{variant:"outline",onClick:()=>h(2),children:[e.jsx(na,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsxs(R,{onClick:()=>h(4),children:["Finish ",e.jsx(aa,{className:"ml-2 h-4 w-4"})]})]})]}),o===4&&e.jsxs("div",{className:"space-y-4 text-center py-6",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Ks,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold",children:"Setup Complete!"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Your social media platforms are connected and configured. You can manage them from the Accounts tab."}),e.jsx("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[...f,...x].map(c=>{const p=yt.find(w=>w.id===c);return p?e.jsxs("span",{className:"inline-flex items-center gap-1 px-3 py-1 rounded-full bg-primary/10 text-primary text-sm",children:[e.jsx("img",{src:p.icon,alt:p.name,className:"h-5 w-5 object-contain"})," ",p.name]},c):null})}),e.jsx(R,{className:"mt-4",onClick:()=>a(!1),children:"Done"})]})]})})},Ci="https://qqamfojeypfnjezyofqc.supabase.co/functions/v1/late-webhook",Oy=()=>{const{setupWebhook:s,checkWebhookStatus:a,isLoading:t}=Ya(),[n,r]=v.useState(null),[i,l]=v.useState(!0),[m,o]=v.useState(!1);v.useEffect(()=>{h()},[]);const h=async()=>{l(!0);try{const y=await a();r(y)}catch{r({configured:!1})}finally{l(!1)}},N=async()=>{try{await s(),K.success("Webhook configured successfully"),await h()}catch{}},d=async()=>{await navigator.clipboard.writeText(Ci),o(!0),K.success("Webhook URL copied to clipboard"),setTimeout(()=>o(!1),2e3)};return e.jsxs(G,{className:"border-border mt-4",children:[e.jsxs(je,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsxs(fe,{className:"text-base font-medium flex items-center gap-2",children:[e.jsx(yu,{className:"h-4 w-4"}),"Late Webhook"]}),i?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):n!=null&&n.configured?e.jsxs(B,{variant:"secondary",className:"text-xs flex items-center gap-1",children:[e.jsx(rs,{className:"h-3 w-3 text-primary"})," Active"]}):e.jsxs(B,{variant:"destructive",className:"text-xs flex items-center gap-1",children:[e.jsx(Is,{className:"h-3 w-3"})," Not Configured"]})]}),e.jsxs(J,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"The webhook re
422ceives real-time notifications for comments, messages, and post status updates from connected platforms."}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Webhook URL (paste this into Late)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{readOnly:!0,value:Ci,className:"font-mono text-xs bg-muted"}),e.jsx(R,{size:"icon",variant:"outline",onClick:d,className:"shrink-0",children:m?e.jsx(Ks,{className:"h-4 w-4 text-primary"}):e.jsx(vt,{className:"h-4 w-4"})})]})]}),e.jsxs(R,{size:"sm",variant:n!=null&&n.configured?"outline":"default",onClick:N,disabled:t,children:[t?e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}):null,n!=null&&n.configured?"Reconfigure Webhook":"Setup Webhook"]})]})]})},Uy=()=>{const{connectedPlatforms:s,isLoading:a,invalidate:t}=Pr(),{disconnectAccount:n,isLoading:r}=Ya(),[i,l]=v.useState(!1),[m,o]=v.useState(null),h=async N=>{if(N.late_account_id){o(N.platform);try{await n(N.late_account_id),K.success(`Disconnected from ${N.platform}`),t()}catch{}finally{o(null)}}};return a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs(G,{className:"border-border",children:[e.jsxs(je,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(fe,{className:"text-base font-medium",children:"Connected Platforms"}),e.jsx(R,{size:"sm",onClick:()=>l(!0),children:s.length>0?e.jsxs(e.Fragment,{children:[e.jsx(gd,{className:"mr-2 h-4 w-4"})," Manage"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zs,{className:"mr-2 h-4 w-4"})," Setup Platforms"]})})]}),e.jsx(J,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:'No social media platforms connected yet. Click "Setup Platforms" to get started.'}):e.jsx("div",{className:"space-y-3",children:s.map(N=>{const d=yt.find(u=>u.id===N.platform),y=Object.entries(N.features||{}).filter(([,u])=>u).map(([u])=>u);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[d!=null&&d.icon?e.jsx("img",{src:d.icon,alt:d.name,className:"h-6 w-6 object-contain"}):e.jsx("span",{className:"text-xl",children:"🔗"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm text-foreground",children:(d==null?void 0:d.name)||N.platform}),N.platform_username&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["@",N.platform_username]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"hidden sm:flex gap-1",children:y.map(u=>e.jsx(B,{variant:"secondary",className:"text-[10px] capitalize",children:u},u))}),e.jsx(R,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>h(N),disabled:m===N.platform||r,children:m===N.platform?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(Do,{className:"h-4 w-4"})})]})]},N.id)})})})]}),e.jsx(Oy,{}),e.jsx($y,{open:i,onOpenChange:l})]})},By=()=>{const{getAnalyticsSummary:s,isLoading:a}=Ya(),{connectedPlatforms:t}=Pr(),[n,r]=v.useState(null),[i,l]=v.useState(null);v.useEffect(()=>{t.length>0&&m()},[t.length]);const m=async()=>{try{l(null);const p=await s();r(p)}catch(p){l(p.message||"Failed to load analytics")}};if(t.length===0)return e.jsx(G,{children:e.jsx(J,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"Connect social media platforms first to see analytics."})})});if(a&&!n)return e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})});if(i)return e.jsx(G,{children:e.jsxs(J,{className:"py-8 text-center",children:[e.jsx("p",{className:"text-destructive text-sm",children:i}),e.jsx("button",{onClick:m,className:"text-sm text-primary underline mt-2",children:"Retry"})]})});const o=n==null?void 0:n.analytics;n==null||n.followerStats;const h=n==null?void 0:n.aggregated,N=(o==null?void 0:o.accounts)||[],d=(o==null?void 0:o.posts)||[],y=N.reduce((p,w)=>p+(w.followersCount||0),0),u=d.reduce((p,w)=>{const S=w.analytics||{};return p+(S.likes||0)+(S.comments||0)+(S.shares||0)+(S.saves||0)},0),x=d.reduce((p,w)=>{var S;return p+(((S=w.analytics)==null?void 0:S.impressions)||0)},0),g=d.reduce((p,w)=>{const S=w.analytics||{};return p+(S.reach||S.views||0)},0),f=(h==null?void 0:h.totalEngagement)??u,_=(h==null?void 0:h.totalImpressions)??x,k=(h==null?void 0:h.totalReach)??g,b=(h==null?void 0:h.postCount)??d.length,j=h==null?void 0:h.windowFromDate,c=h==null?void 0:h.windowToDate;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Analytics Overview"}),e.jsxs(R,{variant:"ghost",size:"sm",onClick:m,disabled:a,children:[e.jsx(He,{className:`h-4 w-4 mr-1 ${a?"animate-spin":""}`}),"Refresh"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(G,{children:e.jsxs(J,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm mb-1",children:[e.jsx(hs,{className:"h-4 w-4"}),"Total Followers"]}),e.jsx("p",{className:"text-2xl font-bold",children:y.toLocaleStr
422ing()})]})}),e.jsx(G,{children:e.jsxs(J,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm mb-1",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Engagement"]}),e.jsx("p",{className:"text-2xl font-bold",children:f.toLocaleString()})]})}),e.jsx(G,{children:e.jsxs(J,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm mb-1",children:[e.jsx(us,{className:"h-4 w-4"}),"Impressions"]}),e.jsx("p",{className:"text-2xl font-bold",children:_.toLocaleString()})]})}),e.jsx(G,{children:e.jsxs(J,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm mb-1",children:[e.jsx(Ds,{className:"h-4 w-4"}),"Reach"]}),e.jsx("p",{className:"text-2xl font-bold",children:k.toLocaleString()})]})})]}),j&&c&&e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:["Engagement / Impressions / Reach window: ",j," → ",c," · ",b.toLocaleString()," posts"]}),n&&y===0&&f===0&&e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{className:"text-base text-muted-foreground",children:"API Response (Debug)"})}),e.jsx(J,{children:e.jsx("pre",{className:"text-xs bg-muted p-3 rounded overflow-auto max-h-48",children:JSON.stringify(n,null,2)})})]}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsx(fe,{className:"text-base",children:"Platform Breakdown"})}),e.jsx(J,{children:e.jsx("div",{className:"space-y-3",children:t.map(p=>{const w=yt.find(D=>D.id===p.platform),S=N.find(D=>D.platform===p.platform||D.socialPlatform===p.platform),P=d.filter(D=>D.platform===p.platform||D.socialPlatform===p.platform),C=(S==null?void 0:S.followersCount)||0,O=P.reduce((D,A)=>{const F=A.analytics||{};return D+(F.likes||0)+(F.comments||0)+(F.shares||0)+(F.saves||0)},0),$=P.reduce((D,A)=>{var F;return D+(((F=A.analytics)==null?void 0:F.impressions)||0)},0),z=P.reduce((D,A)=>{const F=A.analytics||{};return D+(F.reach||F.views||0)},0);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[w!=null&&w.icon?e.jsx("img",{src:w.icon,alt:w.name,className:"h-6 w-6 object-contain"}):e.jsx("span",{children:"🔗"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:(w==null?void 0:w.name)||p.platform}),p.platform_username&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["@",p.platform_username]})]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Followers"}),e.jsx("p",{className:"text-sm font-semibold",children:C.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Engagement"}),e.jsx("p",{className:"text-sm font-semibold",children:O.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Impressions"}),e.jsx("p",{className:"text-sm font-semibold",children:$.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Reach"}),e.jsx("p",{className:"text-sm font-semibold",children:z.toLocaleString()})]})]})]},p.id)})})})]})]})},zy={koach_blogs:{label:"Koach/Kap Blogs",description:"Auto-shares each new KOACH/KAP blog within minutes of publish (8 AM–9 PM CT window). Idempotent per blog; sweeper retries every 30 min."},kontests:{label:"KONTESTS",description:"Post upcoming contests to drive engagement"},klutch_potd:{label:"KLUTCH Pick of the Day",description:"Posts the highest-confidence v2.5 baseball moneyline pick once per day (skips when none qualifies). Audited at 75% WR over n=16 settled POTD picks."}},Ky=({connectedPlatforms:s})=>{const[a,t]=v.useState([]),[n,r]=v.useState(!0),i=v.useCallback(async()=>{try{const{data:d,error:y}=await T.from("social_auto_post_settings").select("*").order("content_type");if(y)throw y;t(d||[])}catch(d){console.error("Failed to load auto-post settings:",d)}finally{r(!1)}},[]);v.useEffect(()=>{i()},[i]);const l=async d=>{const y=!d.enabled;t(x=>x.map(g=>g.id===d.id?{...g,enabled:y}:g));const{error:u}=await T.from("social_auto_post_settings").update({enabled:y,updated_at:new Date().toISOString()}).eq("id",d.id);u&&(t(x=>x.map(g=>g.id===d.id?{...g,enabled:d.enabled}:g)),K.error("Failed to update setting"))},m=async(d,y)=>{const u=d.platforms||[],x=u.includes(y)?u.filter(f=>f!==y):[...u,y];t(f=>f.map(_=>_.id===d.id?{..._,platforms:x}:_));const{error:g}=await T.from("social_auto_post_settings").update({platforms:x,updated_at:new Date().toISOString()}).eq("id",d.id);g&&(t(f=>f.map(_=>_.id===d.id?{..._,platforms:u}:_)),K.error("Failed to update platforms"))},o=async(d,y)=>{const u=!d[y];t(g=>g.map(f=>f.id===d.id?{...f,[y]:u}:f));const{error:x}=await T.from("social_auto_post_settings").update({[y]:u,updated_at:new Date().toISOString()}).eq("id",d.id);x&&(t(g=>g.map(f=>f.id===d.id?{...f,[y]:d[y]}:f)),K.error("Failed to update setting"))},[h,N]=v.useState(!1);return e.jsx(vs,{open:h,onOpenChange:N,children:e.jsxs(G,{children:[e.jsx(ys,{asChild:!0,children:e.jsx(je,{className:"cursor-pointer",children:e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(oc,{className:"h-4 w-4"}),"Auto-Post Toggles",h?e.jsx(Ua,{className:"h-4 w-4 ml-auto"}):e.jsx(Ns,{className:"h-4 w-4 ml-auto"})]})})}),e.jsx(_s,{children:e.jsx(J,{children:n?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(ne,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No auto-post settings found."}):e.jsx("div",{className:"space-y-5",children:a.map(d=>{const y=zy[d.content_type]||{label:d.content_type,description:""};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-sm font-medium",children:y.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y.description})]}),e.jsx(Ge,{checked:d.enabled,onCheckedChange:()=>l(d)})]}),d.enabled&&s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 pl-1",children:s.map(u=>{const x=yt.find(f=>f.id===u.platform),g=(d.platforms||[]).includes(u.platform);return e.jsxs("button",{onClick:()=>m(d,u.platform),className:`flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-xs transition-colors ${g?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:border-primary/50"}`,children:[(x==null?void 0:x.icon)&&e.jsx("img",{src:x.icon,alt:"",className:"h-3.5 w-3.5 object-contain"}),(x==null?void 0:x.name)||u.platform]},u.id)})}
422),d.enabled&&d.content_type==="klutch_potd"&&e.jsxs("div",{className:"space-y-2 pl-1 pt-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs font-medium",children:"Use AI stadium background (v2)"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Generates a sport-specific stadium scene via Nano Banana. Adds ~8s render time."})]}),e.jsx(Ge,{checked:!!d.use_stadium_background,onCheckedChange:()=>o(d,"use_stadium_background")})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs font-medium",children:"Animated 9:16 video for Reels/TikTok"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"6-second branded MP4 for vertical platforms. Static PNG used elsewhere."})]}),e.jsx(Ge,{checked:!!d.use_animated_9x16,onCheckedChange:()=>o(d,"use_animated_9x16")})]})]}),d.enabled&&d.content_type==="koach_blogs"&&e.jsxs("div",{className:"space-y-2 pl-1 pt-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs font-medium",children:"AI image reframing per platform"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Uses Nano Banana to extend the blog image into 1:1, 9:16, and 16:9 with a brand bar overlay. Adds ~5–10s per platform group."})]}),e.jsx(Ge,{checked:d.use_ai_reframe!==!1,onCheckedChange:()=>o(d,"use_ai_reframe")})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-xs font-medium",children:"Animated 9:16 video for Reels/TikTok"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"6-second branded MP4 with title/excerpt animating in. Static PNG used elsewhere."})]}),e.jsx(Ge,{checked:!!d.use_animated_9x16,onCheckedChange:()=>o(d,"use_animated_9x16")})]})]})]},d.id)})})})})]})})},Pi=s=>{const a=(s||"").toLowerCase();return a==="published"?e.jsx(B,{className:"bg-green-600/20 text-green-400 border-green-600/30",children:"Published"}):a==="scheduled"?e.jsx(B,{className:"bg-blue-600/20 text-blue-400 border-blue-600/30",children:"Scheduled"}):a==="failed"?e.jsx(B,{variant:"destructive",children:"Failed"}):a==="draft"?e.jsx(B,{variant:"secondary",children:"Draft"}):e.jsx(B,{variant:"outline",children:s})},Vy=s=>/\.(mp4|mov|webm|m4v)(\?|$)/i.test(s),Hy=({post:s,open:a,onOpenChange:t,onDelete:n})=>{if(!s)return null;const r=s.id||s._id,i=s.text||s.content||"(no content)",l=s.platforms||[],m=s.scheduledAt||s.publishedAt||s.createdAt,o=s.errorMessage||s.error||s.failureReason||s.statusMessage,h=new Map,N=(u,x)=>{if(!u||typeof u!="string")return;const g=x==="video"||!x&&Vy(u)?"video":"image";h.has(u)||h.set(u,g)},d=u=>{if(u){if(Array.isArray(u))return u.forEach(d);if(typeof u=="string")return N(u);if(typeof u=="object"){const x=u.url||u.src||u.mediaUrl||u.image_url||u.videoUrl;N(x,u.type)}}};d(s.mediaItems),d(s.mediaUrls),d(s.media),d(s.attachments),d(s.images),d(s.videos),l.forEach(u=>{d(u.mediaItems),d(u.mediaUrls),d(u.media)});const y=Array.from(h.entries());return e.jsx(Ue,{open:a,onOpenChange:t,children:e.jsxs(Be,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(ze,{children:e.jsxs(Ke,{className:"flex items-center gap-2 flex-wrap",children:[Pi(s.status),e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:m?new Date(m).toLocaleString():""})]})}),e.jsxs("div",{className:"space-y-4",children:[l.length>0&&e.jsx("div",{className:"flex gap-2 flex-wrap",children:l.map((u,x)=>{const g=(u.platform||u||"").toString().toLowerCase(),f=yt.find(_=>_.id===g);return e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 rounded-md border border-border bg-muted/30",children:[(f==null?void 0:f.icon)&&e.jsx("img",{src:f.icon,alt:"",className:"h-4 w-4 object-contain"}),e.jsx("span",{className:"text-xs capitalize",children:(f==null?void 0:f.name)||g})]},x)})}),e.jsx(is,{}),e.jsx("div",{className:"whitespace-pre-wrap text-sm leading-relaxed",children:i}),o&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive",children:typeof o=="str
422ing"?o:o.message||JSON.stringify(o)}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:y.map(([u,x],g)=>x==="video"?e.jsx("video",{src:u,controls:!0,playsInline:!0,className:"w-full rounded-md border border-border bg-black"},g):e.jsx("img",{src:u,alt:`media-${g}`,className:"w-full rounded-md border border-border object-cover"},g))})]}),l.some(u=>u.postUrl||u.url||u.link||u.error||u.errorMessage||u.failureReason||u.status)&&e.jsxs(e.Fragment,{children:[e.jsx(is,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Platform Results"}),l.map((u,x)=>{const g=(u.platform||"").toString().toLowerCase(),f=yt.find(b=>b.id===g),_=u.postUrl||u.url||u.link,k=u.errorMessage||u.error||u.failureReason||u.statusMessage;return e.jsxs("div",{className:"flex items-center justify-between gap-2 p-2 rounded-md border border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[(f==null?void 0:f.icon)&&e.jsx("img",{src:f.icon,alt:"",className:"h-4 w-4 object-contain"}),e.jsx("span",{className:"text-sm capitalize",children:(f==null?void 0:f.name)||g}),u.status&&Pi(u.status)]}),_?e.jsxs("a",{href:_,target:"_blank",rel:"noreferrer noopener",className:"flex items-center gap-1 text-xs text-primary hover:underline shrink-0",children:["View ",e.jsx(Ma,{className:"h-3 w-3"})]}):k?e.jsx("span",{className:"text-xs text-destructive max-w-[60%] text-right",children:typeof k=="string"?k:k.message||JSON.stringify(k)}):null]},x)})]})]}),e.jsx(is,{}),e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsxs(R,{variant:"destructive",size:"sm",onClick:()=>{n(r),t(!1)},children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete"]}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>t(!1),children:"Close"})]})]})]})})},Wy=s=>{const a=(s||"").toLowerCase();return a==="published"?e.jsx(B,{className:"bg-green-600/20 text-green-400 border-green-600/30",children:"Published"}):a==="scheduled"?e.jsx(B,{className:"bg-blue-600/20 text-blue-400 border-blue-600/30",children:"Scheduled"}):a==="failed"?e.jsx(B,{variant:"destructive",children:"Failed"}):a==="draft"?e.jsx(B,{variant:"secondary",children:"Draft"}):e.jsx(B,{variant:"outline",children:s})},Gy=s=>{const a=(s==null?void 0:s.errorMessage)||(s==null?void 0:s.error)||(s==null?void 0:s.failureReason)||(s==null?void 0:s.statusMessage);if(a)return typeof a=="string"?a:a.message||JSON.stringify(a);const n=((s==null?void 0:s.platforms)||[]).flatMap(r=>[r==null?void 0:r.errorMessage,r==null?void 0:r.error,r==null?void 0:r.failureReason,r==null?void 0:r.statusMessage]).filter(Boolean)[0];return n?typeof n=="string"?n:n.message||JSON.stringify(n):null},Qy=({posts:s,postsLoading:a,onRefresh:t,onDelete:n})=>{const[r,i]=v.useState(null);return e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between",children:[e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Post History"]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:t,disabled:a,children:e.jsx(He,{className:`h-4 w-4 ${a?"animate-spin":""}`})})]}),e.jsx(J,{children:a&&s.length===0?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(ne,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No posts yet. Create your first post above!"}):e.jsx("div",{className:"space-y-3",children:s.map(l=>{const m=l.id||l._id,o=l.platforms||[],h=Gy(l);return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>i(l),onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),i(l))},className:"flex items-start justify-between p-3 rounded-lg border border-border cursor-pointer hover:bg-accent/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[Wy(l.status),e.jsx("div",{className:"flex gap-1",children:o.map((N,d)=>{const y=yt.find(u=>u.id===(N.platform||N).toLowerCase());return y!=null&&y.icon?e.jsx("img",{src:y.icon,alt:"",className:"h-4 w-4 object-contain"},d):null})})]}),e.jsx("p",{className:"text-sm truncate",children:l.text||l.content||"(no content)"}),h&&e.jsx("p",{className:"text-xs text-destructive mt-1 line-clamp-2",title:h,children:h}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:l.sc
422heduledAt||l.publishedAt||l.createdAt?new Date(l.scheduledAt||l.publishedAt||l.createdAt).toLocaleString():""})]}),e.jsx(R,{variant:"ghost",size:"icon",onClick:N=>{N.stopPropagation(),n(m)},className:"ml-2 shrink-0",children:e.jsx(os,{className:"h-4 w-4 text-destructive"})})]},m)})})}),e.jsx(Hy,{post:r,open:!!r,onOpenChange:l=>!l&&i(null),onDelete:n})]})},Yy=["Hype","Professional","Casual","Informative"],Jy=({connectedPlatforms:s,isLoading:a,createPost:t,onPostCreated:n})=>{const[r,i]=v.useState(""),[l,m]=v.useState({}),[o,h]=v.useState(!1),[N,d]=v.useState("idle"),[y,u]=v.useState(""),[x,g]=v.useState(""),[f,_]=v.useState([]),[k,b]=v.useState(!1),[j,c]=v.useState(!1),[p,w]=v.useState(null),S=v.useRef(null),[P,C]=v.useState(!1),[O,$]=v.useState(""),z=H=>{m(Z=>({...Z,[H]:!Z[H]}))},D=async()=>{if(!r.trim()){K.error("Write something in the post first");return}d("generating");try{const H=s.filter(Y=>l[Y.platform]).map(Y=>{const I=yt.find(ee=>ee.id===Y.platform);return(I==null?void 0:I.name)||Y.platform}),{data:Z,error:se}=await T.functions.invoke("ai-social-post-writer",{body:{goal:r.trim(),platforms:H.length?H:["general social media"],tone:y}});if(se)throw new Error(se.message);if(Z!=null&&Z.error)throw new Error(Z.error);const ie=(Z==null?void 0:Z.text)||"";if(!ie)throw new Error("No text generated");g(ie),d("preview")}catch(H){console.error("AI generate error:",H),K.error(H.message||"Failed to generate post"),d("ready")}},A=()=>{i(x),g(""),d("idle"),u(""),K.success("Generated post applied!")},F=async H=>{const Z=H.target.files;if(Z!=null&&Z.length){b(!0);try{const{data:{user:se}}=await T.auth.getUser();if(!se)throw new Error("Not authenticated");for(const ie of Array.from(Z)){const Y=Ad(ie);if(!Y.valid){K.error(Y.error);continue}const I=ie.name.split(".").pop(),ee=`${Date.now()}-${Math.random().toString(36).substring(7)}.${I}`,le=`social-posts/${se.id}/${ee}`,{error:ve}=await T.storage.from("community-media").upload(le,ie,{cacheControl:"3600",upsert:!1});if(ve){K.error(`Upload failed: ${ve.message}`);continue}const{data:{publicUrl:te}}=T.storage.from("community-media").getPublicUrl(le),X=ie.type.startsWith("video/");_(ae=>[...ae,{url:te,name:ie.name,type:X?"video":"image",size:ie.size}])}}catch(se){K.error(se.message||"Upload failed")}finally{b(!1),S.current&&(S.current.value="")}}},q=H=>_(Z=>Z.filter((se,ie)=>ie!==H)),E=async()=>{if(!r.trim()){K.error("Write a caption first so AI knows what image to make");return}c(!0);try{const H=s.filter(Y=>l[Y.platform]).map(Y=>Y.platform),{data:Z,error:se}=await T.functions.invoke("generate-social-post-image",{body:{content:r.trim(),platforms:H}});if(se)throw new Error(se.message);if(Z!=null&&Z.error)throw new Error(Z.error);const ie=Z==null?void 0:Z.url;if(!ie)throw new Error("No image returned");_(Y=>[...Y,{url:ie,name:(Z==null?void 0:Z.name)||"ai-generated.png",type:"image",size:0}]),K.success("AI image generated and attached")}catch(H){console.error("AI image error:",H),K.error(H.message||"Failed to generate image")}finally{c(!1)}},L=async H=>{if(!r.trim()){K.error("Post content is required");return}const Z=s.filter(se=>l[se.platform]).map(se=>({platform:se.platform,accountId:se.late_account_id||""}));if(Z.length===0){K.error("Select at least one platform");return}if(!H&&!O){K.error("Select a date and time to schedule");return}try{await t({content:r.trim(),platforms:Z,publishNow:H,...f.length>0?{mediaItems:f.map(se=>({url:se.url,type:se.type}))}:{},...!H&&O?{scheduledFor:O,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:{}}),K.success(H?"Post published!":"Post scheduled!"),i(""),m({}),_([]),C(!1),$(""),n()}catch{}};return e.jsx(vs,{open:o,onOpenChange:h,children:e.jsxs(G,{children:[e.jsx(ys,{asChild:!0,children:e.jsx(je,{className:"cursor-pointer",children:e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(ut,{className:"h-4 w-4"}),"Create Post",o?e.jsx(Ua,{className:"h-4 w-4 ml-auto"}):e.jsx(Ns,{className:"h-4 w-4 ml-auto"})]})})}),e.jsx(_s,{children:e.jsxs(J,{className:"space-y-4",children:[e.jsx(Xs,{placeholder:"What do you want to share?",value:r,onChange:H=>i(H.target.value),rows:4}),e.jsxs("div",{children:[e.jsx("input",{ref:S,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,video/quicktime",multiple:!0,className:"hidden",onChange:F}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{var H;return(H=S.current)==null?void 0:H.click()},disabled:k,children:[k?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(du,{className:"h-4 w-4 mr-2"}),"Attach Media"]}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",onClick:E,disabled:j||!r.trim(),title:"Creates an image based on your caption",children:[j?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ft,{className:"h-4 w-4 mr-2"}),"Generate Image with AI"]})]}),f.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:f.map((H,Z)=>e.jsxs("div",{className:"relative group",children:[e.jsx("button",{type:"button",onClick:()=>w(H),className:"block rounded-md overflow-hidden border border-border hover:ring-2 hover:ring-primary transition-all cursor-zoom-in",title:"Click to enlarge",children:H.type==="image"?e.jsx("img",{src:H.url,alt:H.name,className:"h-16 w-16 object-cover"}):e.jsx("div",{className:"h-16 w-16 bg-muted flex items-center justify-center text-xs text-muted-foreground",children:"Video"})}),e.jsx("button",{onClick:se=>{se.stopPropagation(),q(Z)},className:"absolute -top-1.5 -right-1.5 bg-destructive text-destructive-foreground rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:e.jsx(rt,{className:"h-3 w-3"})})]},Z))}),e.jsx(Ue,{open:!!p,onOpenChange:H=>!H&&w(null),children:e.jsx(Be,{className:"max-w-4xl p-2 bg-background",children:p&&(p.type==="image"?e.jsx("img",{src:p.url,alt:p.name,className:"w-full h-auto max-h-[80vh] object-contain rounded"}):e.jsx("video",{src:p.url,controls:!0,className:"w-full max-h-[80vh] rounded"}))})})]}),e.jsxs("div",{children:[e.jsx(Q,{className:"text-sm text-muted-foreground mb-2 block",children:"Post to:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map(H=>{const Z=yt.find(ie=>ie.id===H.platform),se=!!l[H.platform];return e.jsxs("button",{onClick:()=>z(H.platform),className:`flex items-center gap-2 px-3 py-1.5 rounded-full border text-sm transition-colors ${se?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:border-primary/50"}`,children:[(Z==null?void 0:Z.icon)&&e.jsx("img",{src:Z.icon,alt:"",className:"h-4 w-4 object-contain"}),(Z==null?void 0:Z.name)||H.platform]}
422,H.id)})}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"No platforms connected. Go to Accounts tab first."})]}),e.jsxs("div",{className:"space-y-3",children:[N==="idle"&&e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>d("tones"),children:[e.jsx(ft,{className:"h-4 w-4 mr-2"}),"Generate with AI"]}),N!=="idle"&&N!=="preview"&&e.jsxs("div",{className:"space-y-3 rounded-lg border border-border p-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ft,{className:"h-4 w-4 text-primary"}),"Choose a style"]}),e.jsx("button",{onClick:()=>{d("idle"),u("")},className:"text-xs text-muted-foreground hover:text-foreground",children:"Cancel"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Yy.map(H=>e.jsx("button",{onClick:()=>{u(H),d("ready")},className:`px-3 py-1.5 rounded-full border text-sm transition-colors ${y===H?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:border-primary/50"}`,children:H},H))}),N==="ready"&&e.jsxs(R,{onClick:D,size:"sm",disabled:!r.trim(),children:[e.jsx(ft,{className:"h-4 w-4 mr-2"}),"Generate"]}),N==="generating"&&e.jsxs(R,{size:"sm",disabled:!0,children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating…"]})]}),N==="preview"&&x&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-primary",children:[e.jsx(ft,{className:"h-4 w-4"}),"AI Generated Preview"]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:x}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{size:"sm",onClick:A,children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Use This"]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:D,children:[e.jsx(He,{className:"h-4 w-4 mr-2"}),"Regenerate"]}),e.jsx(R,{size:"sm",variant:"ghost",onClick:()=>{d("idle"),u(""),g("")},children:"Cancel"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 border-t border-border",children:[e.jsxs(R,{onClick:()=>L(!0),disabled:a||!r.trim(),children:[a?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ut,{className:"h-4 w-4 mr-2"}),"Publish Now"]}),e.jsxs(R,{variant:"outline",onClick:()=>C(H=>!H),disabled:a||!r.trim(),children:[e.jsx(xt,{className:"h-4 w-4 mr-2"}),"Schedule Post"]}),P&&e.jsxs(e.Fragment,{children:[e.jsx(pe,{type:"datetime-local",value:O,onChange:H=>$(H.target.value),className:"w-auto"}),e.jsx(R,{variant:"secondary",size:"sm",onClick:()=>L(!1),disabled:a||!O,children:"Confirm Schedule"})]})]})]})})]})})},Zy=()=>{var g,f;const[s,a]=v.useState(!1),[t,n]=v.useState(!1),[r,i]=v.useState(null),[l,m]=v.useState(!1),[o,h]=v.useState(null),N=v.useRef(null),d=()=>{N.current&&(window.clearInterval(N.current),N.current=null)},y=_=>{d(),N.current=window.setInterval(async()=>{var j;const{data:k,error:b}=await T.from("social_cleanup_jobs").select("status, progress, total, result, error").eq("id",_).maybeSingle();if(b){d(),n(!1),K.error(b.message);return}if(k)if(h({done:k.progress??0,total:k.total??0}),k.status==="complete"){d(),n(!1);const c=k.result;i(c),K.success(`Deleted ${c.deleted.length} · Manual (IG): ${((j=c.manual)==null?void 0:j.length)||0} · Failed: ${c.failed.length}`)}else k.status==="failed"&&(d(),n(!1),K.error(k.error||"Cleanup failed"))},2e3)},u=async()=>{a(!0);try{const{data:_,error:k}=await T.functions.invoke("cleanup-duplicate-social-posts",{body:{dryRun:!0,limit:500}});if(k)throw new Error(k.message);i(_),K.success(`Scan complete — ${_.duplicateGroups} duplicate groups, ${_.toDelete.length} posts to delete`)}catch(_){K.error(_.message||"Scan failed")}finally{a(!1)}},x=async()=>{n(!0),h({done:0,total:(r==null?void 0:r.toDelete.length)||0});try{const{data:_,error:k}=await T.functions.invoke("cleanup-duplicate-social-posts",{body:{dryRun:!1,limit:500}});if(k)throw new Error(k.message);_!=null&&_.jobId?(K.info(`Cleanup running in background (${_.total} posts)…`),y(_.jobId)):(i(_),n(!1))}catch(_){n(!1),K.error(_.message||"Cleanup failed")}};return e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(ls,{className:"h-4 w-4 text-amber-500"}),"Duplicate Post Cleanup"]})}),e.jsxs(J,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Scan all posts across connected platforms and remove duplicate copies (same blog or same content posted multiple times). The oldest copy is kept."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{onClick:u,disabled:s||t,variant:"outline",children:[s?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Rs,{className:"h-4 w-4 mr-2"}),"Scan for duplicates"]}),e.jsxs(R,{onClick:()=>m(!0),disabled:s||t||!r||r.toDelete.length===0,variant:"destructive",children:[t?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(os,{className:"h-4 w-4 mr-2"}),"Delete ",(r==null?void 0:r.toDelete.length)||0," duplicates"]})]}),t&&o&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Unpublishing posts…"}),e.jsxs("span",{children:[o.done," / ",o.total]})]}),e.jsx(Ct,{value:o.total?o.done/o.total*100:0})]}),r&&e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs",children:[e.jsxs(B,{variant:"outline",children:["Scanned: ",r.scanned]}),e.jsxs(B,{variant:"outline",children:["Groups: ",r.groupCount]}),e.jsxs(B,{className:"bg-amber-600/20 text-amber-400 border-amber-600/30",children:["Duplicate groups: ",r.duplicateGroups]}),e.jsxs(B,{variant:"destructive",children:["To delete: ",r.toDelete.length]}),(((g=r.manual)==null?void 0:g.length)||0)>0&&e.jsxs(B,{className:"bg-pink-600/20 text-pink-400 border-pink-600/30",children:[e.jsx(Ur,{className:"h-3 w-3 mr-1"}),"Manual (Instagram): ",r.manual.length]}),!r.dryRun&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"bg-green-600/20 text-green-400 border-green-600/30",children:["Deleted: ",r.deleted.length]}),r.failed.length>0&&e.jsxs(B,{variant:"destructive",children:["Failed: ",r.failed.length]})]})]}),r.toDelete.length>0&&e.jsxs("div",{className:"max-h-72 overflow-y-auto space-y-1 text-xs border border-border rounded-md p-2",children:[r.toDelete.slice(0,100).map(_=>e.jsxs("div",{className:"flex items-start gap-2 py-1 border-b border-border/50 last:border-b-0",children:[e.jsx("span",{className:"text-muted-foreground font-mono shrink-0",children:_.id.slice(-8)}),e.jsx("span",{className:"truncate",children:_.text})]},_.id)),r.toDelete.length>100&&e.jsxs("p",{className:"text-muted-foreground text-center pt-1",children:["…and ",r.toDelete.length-100," more"]})]}),(((f=r.manual)==null?void 0:f.length)||0)>0&&e.jsxs("div",{className:"text-xs",children:[e.jsxs("p",{className:"font-medium mb-1 flex items-center gap-1 text-pink-400",children:[e.jsx(Ur,{className:"h-3 w-3"})," Manual cleanup required (Instagram-only — delete in Instagram app):"]}),e.jsxs("div",{className:"max-h-60 overflow-y-auto space-y-1 border border-pink-600/30 rounded-md p-2",children:[r.manual.slice(0,100).map(_=>e.jsxs("div",{className:"flex items-start gap-2 py-1 border-b border-border/50 last:border-b-0",children:[e.jsx("span",{className:"text-muted-foreground font-mono shrink-0",children:_.id.slice(-8)}),e.jsx("span",{className:"truncate",children:_.text})]},_.id)),r.manual.length>100&&e.jsxs("p",{className:"text-muted-foreground text-center pt-1",children:["…and ",r.manual.length-100," more"]})]})]}),r.failed.length>0&&e.jsxs("div",{className:"text-xs text-destructive",children:[e.jsx("p",{className:"font-medium mb-1",children:"Failed deletions:"}),r.failed.slice(0,10).map(_=>e.jsxs("div",{children:[_.id,": ",_.error]},_.id))]})]})]}),e.jsx(Ji,{open:l,onClose:()=>m(!1),onConfirm:async()=>{m(!1),await x()},title:"Delete duplicate posts?",description:`This will permanently delete ${(r==null?void 0:r.toDelete.length)||0} duplicate posts from all connected social platforms. This cannot be undone.`,warningItems:["Posts will be removed from X, Facebook, Instagram, Threads, LinkedIn, etc.","The oldest copy of each duplicate set is kept","Late API deletions are permanent"],confirmPhrase:"DELETE DUPLICATES",itemName:"Duplicates"})]})},Xy=()=>{const{createPost:s,listPosts:a,deletePost:t,isLoading:n}=Ya(),{connectedPlatforms:r}=Pr(),[i,l]=v.useState([]),[m,o]=v.useState(!1);v.useEffect(()=>{h()},[]);const h=async()=>{o(!0);try{const d=await a({limit:20}),y=Array.isArray(d)?d:(d==null?void 0:d.posts)||(d==null?void 0:d.data)||[];l(y)}catch{}finally{o(!1)}},N=async d=>{try{await t(d),K.success("Post deleted"),l(y=>y.filter(u=>(u.id||u._id)!==d))}catch{}};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ky,{connectedPlatforms:r}
422),e.jsx(Jy,{connectedPlatforms:r,isLoading:n,createPost:s,onPostCreated:h}),e.jsx(Zy,{}),e.jsx(Qy,{posts:i,postsLoading:m,onRefresh:h,onDelete:N})]})},eN=s=>s&&yt.find(a=>a.id===s.toLowerCase())||null,sN=s=>{var u,x;const a=s.payload||{},t=a.normalized;if(t&&typeof t=="object"){const g=((u=a.comment)==null?void 0:u.attachments)||((x=a.message)==null?void 0:x.attachments)||t.attachments||[];let f=typeof t.text=="string"?t.text:"";!f&&g.length>0&&(f=`📎 Sent ${g.length} attachment${g.length>1?"s":""}`);const _=t.author&&(t.author.name||t.author.username)||"Unknown";return{author:String(_),text:f,platform:t.platform||s.platform||null,conversationId:t.conversation_id||null,accountId:t.account_id||null,attachments:g}}const n=a.message||a.comment||a.data||a,r=a.account||{},i=n.text||n.content||n.body;let l="";typeof i=="string"?l=i:i&&typeof i=="object"&&"text"in i&&(l=String(i.text));const m=n.attachments||[];!l&&m.length>0&&(l=`📎 Sent ${m.length} attachment${m.length>1?"s":""}`);const o=n.sender||n.author||{},h=(typeof o=="object"?o.name||o.username||o.displayName:null)||n.from||n.username||(n.user&&typeof n.user=="object"?n.user.name:null)||"Unknown",N=s.platform||r.platform||n.platform||null,d=n.conversationId||n.conversation_id||a.conversationId||null,y=r.id||r._id||a.accountId||n.accountId||null;return{author:String(h),text:l,platform:N,conversationId:d,accountId:y,attachments:m}},tN=()=>{var c;const[s,a]=v.useState([]),[t,n]=v.useState(!0),[r,i]=v.useState(null),[l,m]=v.useState(null),[o,h]=v.useState(""),[N,d]=v.useState(!1),y=Hd();v.useEffect(()=>{u()},[]);const u=async()=>{n(!0);try{const{data:p,error:w}=await T.from("social_webhook_events").select("*").in("event_type",["comment.received","message.received","message.sent"]).order("created_at",{ascending:!1}).limit(200);w&&console.error("Failed to load webhook events:",w),a(p||[])}catch(p){console.error("Error loading inbox:",p)}finally{n(!1)}},x=v.useMemo(()=>{const p=new Map;for(const S of s){const P=sN(S),C=P.conversationId?`${P.conversationId}::${P.platform||"unknown"}`:`${P.author}::${P.platform||"unknown"}`;p.has(C)||p.set(C,{key:C,author:P.author,platform:P.platform,config:eN(P.platform),events:[],latestText:P.text,latestTime:S.created_at,conversationId:P.conversationId,accountId:P.accountId,hasMessages:!1,kind:"orphan"});const O=p.get(C);O.events.push({event:S,...P}),(S.event_type==="message.received"||S.event_type==="message.sent")&&(O.hasMessages=!0),P.conversationId&&(O.conversationId=P.conversationId),P.accountId&&(O.accountId=P.accountId)}const w=Array.from(p.values()).sort((S,P)=>{const C=S.latestTime?new Date(S.latestTime).getTime():0;return(P.latestTime?new Date(P.latestTime).getTime():0)-C});for(const S of w){S.events.sort((O,$)=>{const z=O.event.created_at?new Date(O.event.created_at).getTime():0,D=$.event.created_at?new Date($.event.created_at).getTime():0;return z-D});const P=S.events.some(O=>O.event.event_type==="comment.received"),C=S.events.some(O=>O.event.event_type==="message.received");S.kind=P?"comment":C?"message":"orphan"}return w},[s]),g=v.useMemo(()=>r==="comment.received"?x.filter(p=>p.kind==="comment"):r==="message.received"?x.filter(p=>p.kind==="message"):x.filter(p=>p.kind!=="orphan"),[x,r]),f=g.find(p=>p.key===l)||null,_=async()=>{if(!(!f||!o.trim()||!f.conversationId||!f.accountId)){d(!0);try{const{error:p}=await T.functions.invoke("late-social-setup",{body:{action:"reply-message",conversationId:f.conversationId,accountId:f.accountId,text:o.trim(),platform:f.platform}});if(p)throw p;K.success("Reply sent!"),h("");const w=f.events.filter(S=>S.event.event_type!=="message.sent"&&!S.event.processed).map(S=>S.event.id);w.length>0&&await T.from("social_webhook_events").update({processed:!0}).in("id",w),u()}catch(p){console.error("Reply failed:",p),K.error((p==null?void 0:p.message)||"Failed to send reply")}finally{d(!1)}}},k=p=>{if(!p)return"";const w=new Date(p),C=(new Date().getTime()-w.getTime())/(1e3*60*60);return C<24?w.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):C<24*7?w.toLocaleDateString([],{weekday:"short"}):w.toLocaleDateString([],{month:"short",day:"numeric"})},b=y?l!==null:!0,j=y?l===null:!0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(R,{variant:r===null?"default":"outline",size:"sm",onClick:()=>i(null),children:"All"}),e.jsx(R,{variant:r==="comment.received"?"default":"outline",size:"sm",onClick:()=>i("comment.received"),children:"Comments"}),e.jsx(R,{variant:r==="message.received"?"default":"outline",size:"sm",onClick:()=>i("message.received"),children:"Messages"})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:u,disabled:t,children:e.jsx(He,{className:`h-4 w-4 ${t?"animate-spin":""}`})})]}),t?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ne,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(G,{children:e.jsx(J,{className:"py-12",children:e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"No comments or messages received yet. They'll appear here once the webhook starts receiving events."})})}):e.jsxs("div",{className:"flex gap-0 border rounded-lg overflow-hidden bg-card",style:{height:"70vh"},children:[j&&e.jsxs("div",{className:`${y?"w-full":"w-[35%] min-w-[260px]"} border-r border-border flex flex-col`,children:[e.jsx("div",{className:"px-3 py-2 border-b border-border",children:e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[g.length," conversation",g.length!==1?"s":""]})}),e.jsx(cs,{className:"flex-1",children:g.map(p=>{var S;const w=l===p.key;return e.jsxs("button",{onClick:()=>{m(p.key),h("")},className:`w-full text-left px-3 py-3 border-b border-border transition-colors hover:bg-muted/50 ${w?"bg-muted":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[(S=p.config)!=null&&S.icon?e.jsx("img",{src:p.config.icon,alt:"",className:"h-4 w-4 object-contain shrink-0"}):e.jsx(St,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:p.author}),e.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:k(p.latestTime)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground truncate flex-1",children:p.latestText}),e.jsx(B,{variant:"secondary",className:"text-[10px] shrink-0",children:p.events.length})]})]},p.key)})})]}),b&&e.jsx("div",{className:`${y?"w-full":"flex-1"} flex flex-col`,children:f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border flex items-center gap-3",children:[y&&e.jsx(R,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>m(null),children:e.jsx(na,{className:"h-4 w-4"})}),(c=f.config)!=null&&c.icon?e.jsx("img",{src:f.config.icon,alt:"",className:"h-5 w-5 object-contain shrink-0"}):e.jsx(St,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:f.author}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[f.config&&e.jsx(B,{variant:"outline",className:"text-[10px]",style:{borderColor:f.config.color,color:f.config.color},children:f.config.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[f.events.length," message",f.events.length!==1?"s":""]})]})]})]}),e.jsx(cs,{className:"flex-1 px-4 py-3",children:e.jsx("div",{className:"space-y-3",children:f.events.map(({event:p,text:w,attachments:S})=>{const P=p.event_type==="comment.received",C=p.event_type==="message.sent";return e.jsxs("div",{className:`flex flex-col gap-1 ${C?"items-end":"items-start"}`,children:[e.jsxs("div",{className:`rounded-lg px-3 py-2 max-w-[85%] ${C?"bg-primary/20":"bg-muted/50"}`,children:[e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:w}),S.length>0&&e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1.5",children:S.map((O,$)=>e.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-background rounded",children:[O.type||"file",": ",O.url?e.jsx("a",{href:O.url,target:"_blank",rel:"noopener noreferrer",className:"underline text-primary",children:"View"}):"No URL"]},$))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&e.jsx(B,{variant:"outline",className:"text-[10px] border-primary/30 text-primary",children:"You"}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:p.created_at?new Date(p.created_at).toLocaleStr
422ing():""}),!C&&e.jsx(B,{variant:P?"secondary":"outline",className:"text-[10px]",children:P?"Comment":"DM"})]})]},p.id)})})}),f.hasMessages&&f.conversationId&&f.accountId?e.jsxs("div",{className:"border-t border-border p-3 flex gap-2 items-end",children:[e.jsx(Xs,{placeholder:"Type your reply...",value:o,onChange:p=>h(p.target.value),rows:2,className:"text-sm flex-1 min-h-[40px] max-h-[120px]"}),e.jsx(R,{size:"icon",onClick:_,disabled:N||!o.trim(),className:"shrink-0 h-10 w-10",children:N?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(ut,{className:"h-4 w-4"})})]}):f.hasMessages?e.jsx("div",{className:"border-t border-border p-3",children:e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Reply not available — missing conversation or account ID."})}):null]}):e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(St,{className:"h-10 w-10 mx-auto mb-2 opacity-30"}),e.jsx("p",{className:"text-sm",children:"Select a conversation to view messages"})]})})})]}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs(fe,{className:"text-base flex items-center gap-2",children:[e.jsx(Co,{className:"h-4 w-4"}),"AI Auto-Responder"]})}),e.jsx(J,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Coming soon — an AI-powered auto-responder that can handle common comments and messages based on configurable rules and tone."})})]})]})};function aN(){const[s,a]=v.useState("accounts");return e.jsx("div",{className:"space-y-6",children:e.jsxs(js,{value:s,onValueChange:a,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start sm:max-w-lg",children:[e.jsxs(Ne,{value:"accounts",className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4"}),"Accounts"]}),e.jsxs(Ne,{value:"overview",className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4"}),"Overview"]}),e.jsxs(Ne,{value:"posts",className:"flex items-center gap-2",children:[e.jsx(ut,{className:"h-4 w-4"}),"Posts"]}),e.jsxs(Ne,{value:"inbox",className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-4 w-4"}),"Inbox"]})]}),e.jsx(we,{value:"accounts",className:"mt-6",children:e.jsx(Uy,{})}),e.jsx(we,{value:"overview",className:"mt-6",children:e.jsx(By,{})}),e.jsx(we,{value:"posts",className:"mt-6",children:e.jsx(Xy,{})}),e.jsx(we,{value:"inbox",className:"mt-6",children:e.jsx(tN,{})})]})})}function rN(){const[s,a]=v.useState("emails");return e.jsx("div",{className:"space-y-6",children:e.jsxs(js,{value:s,onValueChange:a,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start sm:max-w-md",children:[e.jsxs(Ne,{value:"emails",className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-4 w-4"}),"Emails"]}),e.jsxs(Ne,{value:"social",className:"flex items-center gap-2",children:[e.jsx(Wd,{className:"h-4 w-4"}),"Social"]}),e.jsxs(Ne,{value:"influencers",className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4"}),"Influencers"]})]}),e.jsx(we,{value:"emails",className:"mt-6",children:e.jsx(by,{})}),e.jsx(we,{value:"social",className:"mt-6",children:e.jsx(aN,{})}),e.jsx(we,{value:"influencers",className:"mt-6",children:e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"Influencer Program"]})}),e.jsx(J,{children:e.jsx("p",{className:"text-muted-foreground",children:"Coming soon — generate influencer codes to track signups from influencer links and codes."})})]})})]})})}const Pa=[{value:"odds",label:"Odds",description:"Betting odds from sportsbooks"},{value:"scores",label:"Scores",description:"Live and final scores"},{value:"players",label:"Players",description:"Player data, images, stats"},{value:"teams",label:"Teams",description:"Team data, form, records"},{value:"news",label:"News",description:"Sport news and updates"},{value:"lineups",label:"Lineups & Injuries",description:"Starting lineups and injury reports from missingPlayers"},{value:"weather",label:"Weather",description:"Game weather conditions"}
422,{value:"matchups",label:"Matchups",description:"AI-generated matchup analysis"}],so=[{value:"odds_api",label:"The Odds API"},{value:"sportapi",label:"SportAPI"},{value:"sportsdata",label:"SportsData.io"},{value:"newsnow",label:"NewsNow"},{value:"ai_researcher",label:"AI Researcher"},{value:"openweather",label:"OpenWeather API"}],In={odds:"odds_api",scores:"sportapi",players:"sportapi",teams:"sportapi",news:"ai_researcher",lineups:"sportapi",weather:"openweather",matchups:"ai_researcher"},nN=[{value:"*/5 * * * *",label:"Every 5 minutes"},{value:"*/15 * * * *",label:"Every 15 minutes"},{value:"*/30 * * * *",label:"Every 30 minutes"},{value:"0 * * * *",label:"Every hour"},{value:"0 */2 * * *",label:"Every 2 hours"},{value:"0 */4 * * *",label:"Every 4 hours"},{value:"0 */6 * * *",label:"Every 6 hours"},{value:"0 */12 * * *",label:"Every 12 hours"},{value:"0 0 * * *",label:"Daily"}],to=[{value:-1,label:"Always"},{value:0,label:"Game Time"},{value:1,label:"1 hour before"},{value:2,label:"2 hours before"},{value:4,label:"4 hours before"},{value:6,label:"6 hours before"},{value:12,label:"12 hours before"},{value:24,label:"1 day before"},{value:48,label:"2 days before"},{value:72,label:"3 days before"},{value:168,label:"1 week before"}],Fi=[{value:.0833,label:"Every 5 min"},{value:.25,label:"Every 15 min"},{value:.5,label:"Every 30 min"},{value:1,label:"Every hour"},{value:2,label:"Every 2 hours"},{value:4,label:"Every 4 hours"},{value:6,label:"Every 6 hours"},{value:12,label:"Every 12 hours"},{value:24,label:"Daily"}],ao=[{value:"keep_same",label:"Keep Same"},{value:.0833,label:"Every 5 min"},{value:.25,label:"Every 15 min"},{value:.5,label:"Every 30 min"},{value:1,label:"Every hour"},{value:2,label:"Every 2 hours"}],Or={baseball:"⚾",football:"🏈",basketball:"🏀",hockey:"🏒",mma:"🥊",soccer:"⚽",golf:"⛳",tennis:"🎾",mlb:"⚾",nfl:"🏈",nba:"🏀",nhl:"🏒"};async function lN(s,a){try{if(!["image/png","image/jpeg","image/jpg","image/webp"].includes(s.type))return{success:!1,error:"Invalid file type. Please upload PNG, JPG, or WEBP images."};const n=5*1024*1024;if(s.size>n)return{success:!1,error:"File size exceeds 5MB limit."};const r=Date.now(),i=s.name.split(".").pop(),l=`${a}-${r}.${i}`,{data:m,error:o}=await T.storage.from("sport-images").upload(l,s,{cacheControl:"3600",upsert:!1});if(o)return console.error("Upload error:",o),{success:!1,error:`Upload failed: ${o.message}`};const{data:h}=T.storage.from("sport-images").getPublicUrl(m.path);return{success:!0,url:h.publicUrl}}catch(t){return console.error("Unexpected error during upload:",t),{success:!1,error:"An unexpected error occurred during upload."}}}async function iN(s){try{const a=s.split("/"),t=a[a.length-1];if(!s.includes("sport-images"))return!0;const{error:n}=await T.storage.from("sport-images").remove([t]);return n?(console.error("Delete error:",n),!1):!0}catch(a){return console.error("Unexpected error during delete:",a),!1}}function cN({sport:s,onUpdate:a}){const[t,n]=v.useState(!1),[r,i]=v.useState(!1),[l,m]=v.useState(null),[o,h]=v.useState(null),[N,d]=v.useState(!1),y=v.useRef(null),[u,x]=v.useState({status:s.status,is_active:s.is_active,season_start_date:s.season_start_date||"",season_end_date:s.season_end_date||"",custom_message:s.custom_message||"",ticker_message:s.ticker_message||"",background_image_url:s.background_image_url||""});v.useEffect(()=>{x({status:s.status,is_active:s.is_active,season_start_date:s.season_start_date||"",season_end_date:s.season_end_date||"",custom_message:s.custom_message||"",ticker_message:s.ticker_message||"",background_image_url:s.background_image_url||""})},[s]);const g=j=>{var w;const c=(w=j.target.files)==null?void 0:w[0];if(!c)return;if(!["image/png","image/jpeg","image/jpg","image/webp"].includes(c.type)){Ee({title:"Invalid file type",description:"Please upload PNG, JPG, or WEBP images.",variant:"destructive"});return}if(c.size>5*1024*1024){Ee({title:"File too large",description:"Please upload an image under 5MB.",variant:"destructive"});return}m(c),h(URL.createObjectURL(c))},f=()=>{m(null),o&&(URL.revokeObjectURL(o),h(null)),y.current&&(y.current.value="")},_=async()=>{i(!0);try{let j=u.background_image_url;if(l){d(!0);const p=await lN(l,s.sport_code);
422if(!p.success)throw new Error(p.error||"Failed to upload image");s.background_image_url&&await iN(s.background_image_url),j=p.url||"",d(!1)}const{error:c}=await ms.from("sport_statuses").update({status:u.status,is_active:u.is_active,season_start_date:u.season_start_date||null,season_end_date:u.season_end_date||null,custom_message:u.custom_message||null,ticker_message:u.ticker_message||null,background_image_url:j||null,updated_at:new Date().toISOString()}).eq("id",s.id);if(c)throw c;Ee({title:"Sport status updated",description:`${s.sport_name} settings saved successfully.`}),f(),n(!1),a()}catch(j){Ee({title:"Error saving status",description:j.message,variant:"destructive"})}finally{i(!1),d(!1)}},k=()=>{f(),x({status:s.status,is_active:s.is_active,season_start_date:s.season_start_date||"",season_end_date:s.season_end_date||"",custom_message:s.custom_message||"",ticker_message:s.ticker_message||"",background_image_url:s.background_image_url||""}),n(!1)},b=o||u.background_image_url;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Sport Status & Season"}),t?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{variant:"ghost",size:"sm",onClick:k,children:"Cancel"}),e.jsxs(R,{size:"sm",onClick:_,disabled:r,children:[r?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(It,{className:"h-4 w-4 mr-1"}),N?"Uploading...":"Save"]})]}):e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>n(!0),children:"Edit"})]}),e.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg space-y-3",children:[e.jsxs(Q,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ot,{className:"h-3 w-3"}),"Background Image"]}),b?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:b,alt:`${s.sport_name} background`,className:"w-full h-32 object-cover rounded-md border border-border"}),t&&e.jsx(R,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{f(),x(j=>({...j,background_image_url:""}))},children:e.jsx(rt,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"w-full h-32 bg-muted rounded-md border border-dashed border-border flex items-center justify-center",children:e.jsx("span",{className:"text-sm text-muted-foreground",children:"No image uploaded"})}),t&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:y,type:"file",accept:"image/png,image/jpeg,image/jpg,image/webp",onChange:g,className:"hidden"}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>{var j;return(j=y.current)==null?void 0:j.click()},disabled:N,children:[e.jsx(fa,{className:"h-4 w-4 mr-1"}),l?"Change Image":"Upload Image"]}),l&&e.jsx("span",{className:"text-xs text-muted-foreground",children:l.name})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 p-4 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Status"}),t?e.jsxs(oe,{value:u.status,onValueChange:j=>x(c=>({...c,status:j})),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"in_season",children:"In Season"}),e.jsx(V,{value:"off_season",children:"Off Season"}),e.jsx(V,{value:"coming_soon",children:"Coming Soon"})]})]}):e.jsx("p",{className:"text-sm font-medium capitalize",children:s.status.replace("_"," ")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Active"}),t?e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(Ge,{checked:u.is_active,onCheckedChange:j=>x(c=>({...c,is_active:j}))}),e.jsx("span",{className:"text-sm",children:u.is_active?"Yes":"No"})]}):e.jsx("p",{className:"text-sm font-medium",children:s.is_active?"Yes":"No"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Season Start"}),t?e.jsx(pe,{type:"date",value:u.season_start_date,onChange:j=>x(c=>({...c,season_start_date:j.target.value}))}):e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(xt,{className:"h-3 w-3"}),s.season_start_date?ke(new Date(s.season_start_date),"MMM d, yyyy"):"Not set"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Season End"}),t?e.jsx(pe,{type:"date",value:u.season_end_date,onChange:j=>x(c=>({...c,season_end_date:j.target.value}))}):e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(xt,{className:"h-3 w-3"}),s.season_end_date?ke(new Date(s.season_end_date),"MMM d, yyyy"):"Not set"]})]})]}),t&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Custom Message"}),e.jsx(pe,{value:u.custom_message,onChange:j=>x(c=>({...c,custom_message:j.target.value})),placeholder:"Optional message to display"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Ticker Message"}),e.jsx(pe,{value:u.ticker_message,onChange:j=>x(c=>({...c,ticker_message:j.target.value})),placeholder:"Optional ticker message"})]})]}),e.jsx(is,{})]})}const oN={odds:Ds,scores:Js,players:hs,teams:Yd,news:oc,lineups:tl,weather:Gd,matchups:jd};function dN({sportCode:s,syncType:a,config:t,onUpdate:n}){var b,j,c;const[r,i]=v.useState(!1),[l,m]=v.useState(!1),o=oN[a.value],h=((b=t==null?void 0:t.config)==null?void 0:b.start_hours_before_game)??24,N=((j=t==null?void 0:t.config)==null?void 0:j.peak_hours_frequency)??"keep_same",d=async p=>{i(!0);try{if(t){const{error:w}=await ms.from("sport_data_sync_config").update({is_enabled:p,updated_at:new Date().toISOString()}).eq("id",t.id);if(w)throw w}else{const{error:w}=await ms.from("sport_data_sync_config").insert({sport_code:s,sync_type:a.value,is_enabled:p,api_source:a.value==="odds"||a.value==="scores"?"odds_api":"sportapi",cron_schedule:"0 * * * *",config:{start_hours_before_game:24,peak_hours_frequency:"keep_same"}}
422);if(w)throw w}Ee({title:p?"Sync enabled":"Sync disabled",description:`${a.label} sync for ${s.toUpperCase()}`}),n()}catch(w){Ee({title:"Error updating sync",description:w.message,variant:"destructive"})}finally{i(!1)}},y=async p=>{if(t){i(!0);try{const{error:w}=await ms.from("sport_data_sync_config").update({cron_schedule:p,updated_at:new Date().toISOString()}).eq("id",t.id);if(w)throw w;n()}catch(w){Ee({title:"Error updating schedule",description:w.message,variant:"destructive"})}finally{i(!1)}}},u=async p=>{if(t){i(!0);try{const{error:w}=await ms.from("sport_data_sync_config").update({api_source:p,updated_at:new Date().toISOString()}).eq("id",t.id);if(w)throw w;n()}catch(w){Ee({title:"Error updating source",description:w.message,variant:"destructive"})}finally{i(!1)}}},x=async p=>{if(t){i(!0);try{const w={...t.config,start_hours_before_game:parseInt(p)},{error:S}=await ms.from("sport_data_sync_config").update({config:w,updated_at:new Date().toISOString()}).eq("id",t.id);if(S)throw S;n()}catch(w){Ee({title:"Error updating start time",description:w.message,variant:"destructive"})}finally{i(!1)}}},g=async p=>{if(t){i(!0);try{const w={...t.config,peak_hours_frequency:p==="keep_same"?p:parseFloat(p)},{error:S}=await ms.from("sport_data_sync_config").update({config:w,updated_at:new Date().toISOString()}).eq("id",t.id);if(S)throw S;n()}catch(w){Ee({title:"Error updating peak frequency",description:w.message,variant:"destructive"})}finally{i(!1)}}},f=async()=>{m(!0);let p=0,w=0,S=0;const P=25;try{const C=a.value==="players";do{S++;const O={sport:s,syncType:a.value,forceRefresh:!0};C&&(O.batchSize=P,O.offset=w);const{data:$,error:z}=await ms.functions.invoke("sync-sport-data",{body:O});if(z)throw z;const D=$;if(p+=D.recordsProcessed||0,C&&D.hasMore){const A=D.totalTeams?Math.round((D.nextOffset||0)/D.totalTeams*100):S*P;Ee({title:`Syncing players... ${A}%`,description:`Batch ${S}: ${D.recordsProcessed} players synced`}),w=D.nextOffset||w+P}if(!C||!D.hasMore){Ee({title:D.success?"Sync completed":"Sync completed with warnings",description:C?`Total: ${p} players synced in ${S} batches`:D.message||`${a.label} sync for ${s.toUpperCase()}`});break}}while(!0);n()}catch(C){t&&await ms.from("sport_data_sync_config").update({last_sync_at:new Date().toISOString(),last_sync_status:"failed"}).eq("id",t.id),Ee({title:"Sync failed",description:C.message,variant:"destructive"})}finally{m(!1)}},_=()=>t!=null&&t.last_sync_at?t.last_sync_status==="success"?e.jsxs(B,{variant:"outline",className:"text-green-600 border-green-600/30 text-xs",children:[e.jsx(rs,{className:"h-3 w-3 mr-1"}),"Success"]}):t.last_sync_status==="failed"?e.jsxs(B,{variant:"outline",className:"text-red-600 border-red-600/30 text-xs",children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"Failed"]}):null:null,k=(t==null?void 0:t.is_enabled)??!1;return e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 w-28",children:[e.jsx(o,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:a.label})]}),e.jsx(Ge,{checked:k,onCheckedChange:d,disabled:r}),e.jsx("div",{className:"w-32",children:e.jsxs(oe,{value:h.toString(),onValueChange:x,disabled:!k||r,children:[e.jsxs(de,{className:"h-8 text-xs",children:[e.jsx(Ud,{className:"h-3 w-3 mr-1"}),e.jsx(ue,{})]}),e.jsx(me,{children:to.map(p=>e.jsx(V,{value:p.value.toString(),children:p.label},p.value))})]})}),e.jsx("div",{className:"w-32",children:e.jsxs(oe,{value:(t==null?void 0:t.cron_schedule)||"0 * * * *",onValueChange:y,disabled:!k||r,children:[e.jsxs(de,{className:"h-8 text-xs",children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),e.jsx(ue,{})]}),e.jsx(me,{children:nN.map(p=>e.jsx(V,{value:p.value,children:p.label},p.value))})]})}),e.jsx("div",{className:"w-32",children:e.jsxs(oe,{value:N.toString(),onValueChange:g,disabled:!k||r,children:[e.jsxs(de,{className:"h-8 text-xs",children:[e.jsx(ra,{className:"h-3 w-3 mr-1"}),e.jsx(ue,{})]}),e.jsx(me,{children:ao.map(p=>e.jsx(V,{value:p.value.toString(),children:p.label},p.value))})]})}),e.jsx("div",{className:"w-28",children:e.jsxs(oe,{value:(t==null?void 0:t.api_source)||"sportapi",onValueChange:u,disabled:!k||r,children:[e.jsx(de,{className:"h-8 text-xs",children:e.jsx(ue,{})}),e.jsx(me,{children:so.map(p=>e.jsx(V,{value:p.value,children:p.label},p.value))})]})}),e.jsx("div",{className:"flex-1 text-xs text-muted-foreground min-w-0",children:t!=null&&t.last_sync_at?e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[Dt(new Date(t.last_sync_at),{addSuffix:!0}),_(),((c=t.last_sync_stats)==null?void 0:c.recordsProcessed)!==void 0&&e.jsxs("span",{className:"text-muted-foreground
422/70",children:["(",t.last_sync_stats.recordsProcessed," records)"]})]}):e.jsx("span",{children:"Never"})}),e.jsx(R,{variant:"ghost",size:"sm",onClick:f,disabled:l||!k,className:"h-8",children:l?e.jsx(ne,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"})})]})}function uN({sportCode:s,syncConfigs:a,onUpdate:t}){const n=r=>a.find(i=>i.sync_type===r);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-sm font-semibold text-foreground",children:"Data Syncs"}),e.jsx("div",{className:"space-y-2",children:Pa.map(r=>e.jsx(dN,{sportCode:s,syncType:r,config:n(r.value),onUpdate:t},r.value))})]})}function mN({open:s,onOpenChange:a,leagues:t,onSaveGroup:n}){const[r,i]=v.useState(""),[l,m]=v.useState(""),[o,h]=v.useState([]),[N,d]=v.useState(""),[y,u]=v.useState(!1),x=t.filter(w=>!w.is_grouped&&!w.parent_league_id),g=t.filter(w=>{var S;return w.sportapi_tournament_id!==r&&!((S=w.child_tournament_ids)!=null&&S.length)&&!w.is_grouped&&!w.parent_league_id}),f=(w,S)=>{h(S?P=>[...P,w]:P=>P.filter(C=>C!==w))},_=async()=>{if(o.length!==0){u(!0);try{await n(r||null,l||null,o,N||o[0]),i(""),m(""),h([]),d(""),a(!1)}finally{u(!1)}}},k=()=>{i(""),m(""),h([]),d(""),a(!1)},b=r?t.find(w=>(w.sportapi_tournament_id||w.league_id)===r):null,j=t.filter(w=>o.includes(w.sportapi_tournament_id||w.league_id)),c=[...b?[b]:[],...j.filter(w=>(w.sportapi_tournament_id||w.league_id)!==r)],p=o.length>0&&(r||l.trim());return e.jsx(Ue,{open:s,onOpenChange:k,children:e.jsxs(Be,{className:"max-w-lg max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Create League Group"}),e.jsx(Vs,{children:'Group related tournaments under a parent league (e.g., group all NCAA divisions under "NCAAF")'})]}),e.jsx(cs,{className:"flex-1 overflow-auto pr-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Parent League"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(oe,{value:r,onValueChange:w=>{i(w),m("")},children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select existing league as parent..."})}),e.jsx(me,{children:x.map(w=>e.jsxs(V,{value:w.sportapi_tournament_id||w.league_id,children:[w.league_name," ",w.sportapi_tournament_id&&`(ID: ${w.sportapi_tournament_id})`]},w.sportapi_tournament_id||w.league_id))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 h-px bg-border"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"OR"}),e.jsx("div",{className:"flex-1 h-px bg-border"})]}),e.jsx(pe,{placeholder:"Create custom parent (e.g., NCAAF)",value:l,onChange:w=>{m(w.target.value),i("")}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{children:["Child Tournaments",o.length>0&&e.jsxs("span",{className:"text-muted-foreground ml-2",children:["(",o.length," selected)"]})]}),e.jsx(cs,{className:"h-[200px] border rounded-md p-3",children:e.jsx("div",{className:"space-y-2",children:g.map(w=>{const S=w.sportapi_tournament_id||w.league_id,P=o.includes(S),C=S===r;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded hover:bg-muted/50 ${C?"opacity-50":""}`,children:[e.jsx(Ms,{id:`child-${S}`,checked:P,disabled:C,onCheckedChange:O=>f(S,!!O)}),e.jsxs("label",{htmlFor:`child-${S}`,className:"flex-1 cursor-pointer",children:[e.jsx("div",{className:"text-sm font-medium",children:w.league_name}),w.sportapi_tournament_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",w.sportapi_tournament_id]})]})]},S)})})})]}),c.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Logo Source"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which league's logo to display for this group"}),e.jsxs(oe,{value:N||r||o[0]||"",onValueChange:d,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select logo source..."})}),e.jsx(me,{children:c.map(w=>{const S=w.sportapi_tournament_id||w.league_id,P=S===r;return e.jsxs(V,{value:S,children:[w.league_name," ",P&&"(Parent)"]},S)})})]})]})]})}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:k,children:"Cancel"}),e.jsx(R,{onClick:_,disabled:!p||y,children:y?"Creating...":`Create Group (${o.length} children)`})]})]})})}function xN({open:s,onOpenChange:a,leagues:t,editingGroup:n,onSaveChanges:r,onDissolveGroup:i}){var z;const[l,m]=v.useState(""),[o,h]=v.useState([]),[N,d]=v.useState([]),[y,u]=v.useState(""),[x,g]=v.useState(!1);if(v.useEffect(()=>{n&&(m(n.league_name),h([]),d([]),u(n.logo_source_tournament_id||""))},[n]),!n)return null;const f=n.sportapi_tournament_id||n.league_id,_=t.filter(D=>{var A;return(A=n.child_tournament_ids)==null?void 0:A.includes(D.sportapi_tournament_id||D.league_id)}),k=t.filter(D=>{var A;return!D.is_grouped&&!((A=D.child_tournament_ids)!=null&&A.length)&&(D.sportapi_tournament_id||D.league_id)!==f}),b=(D,A)=>{h(A?F=>[...F,D]:F=>F.filter(q=>q!==D))},j=(D,A)=>{d(A?F=>[...F,D]:F=>F.filter(q=>q!==D))},c=async()=>{g(!0);try{const D=y!==(n.logo_source_tournament_id||"");
422await r({parentId:f,newName:l!==n.league_name?l:void 0,addChildIds:N,removeChildIds:o,logoSourceTournamentId:D?y:void 0}),a(!1)}finally{g(!1)}},p=async()=>{g(!0);try{await i(f),a(!1)}finally{g(!1)}},w=()=>{m(""),h([]),d([]),u(""),a(!1)},S=[...((z=n.child_tournament_ids)==null?void 0:z.filter(D=>!o.includes(D)))||[],...N],P=t.filter(D=>S.includes(D.sportapi_tournament_id||D.league_id)),C=n.sportapi_tournament_id?t.find(D=>D.sportapi_tournament_id===n.sportapi_tournament_id):null,O=[...C?[C]:[],...P.filter(D=>D.sportapi_tournament_id!==n.sportapi_tournament_id)],$=l!==n.league_name||o.length>0||N.length>0||y!==(n.logo_source_tournament_id||"");return e.jsx(Ue,{open:s,onOpenChange:w,children:e.jsxs(Be,{className:"max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Edit League Group"}),e.jsx(Vs,{children:"Rename the group, add/remove leagues, or dissolve the group entirely"})]}),e.jsxs("div",{className:"space-y-4 flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"group-name",children:"Group Name"}),e.jsx(pe,{id:"group-name",value:l,onChange:D=>m(D.target.value),placeholder:"Enter group name..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{children:["Current Leagues in Group",o.length>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",o.length," to remove)"]})]}),e.jsx(cs,{className:"h-[150px] border rounded-md p-3",children:_.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No leagues in this group"}):e.jsx("div",{className:"space-y-2",children:_.map(D=>{const A=D.sportapi_tournament_id||D.league_id,F=o.includes(A);return e.jsxs("div",{className:`flex items-center justify-between p-2 rounded hover:bg-muted/50 ${F?"opacity-50 bg-destructive/10":""}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ms,{id:`remove-${A}`,checked:!F,onCheckedChange:q=>b(A,!q)}),e.jsxs("label",{htmlFor:`remove-${A}`,className:"cursor-pointer",children:[e.jsx("div",{className:"text-sm font-medium",children:D.league_name}),D.sportapi_tournament_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",D.sportapi_tournament_id]})]})]}),F&&e.jsx("span",{className:"text-xs text-destructive",children:"Will be ungrouped"})]},A)})})})]}),k.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Q,{children:["Add Leagues to Group",N.length>0&&e.jsxs("span",{className:"text-primary ml-2",children:["(",N.length," to add)"]})]}),e.jsx(cs,{className:"h-[150px] border rounded-md p-3",children:e.jsx("div",{className:"space-y-2",children:k.map(D=>{const A=D.sportapi_tournament_id||D.league_id,F=N.includes(A);return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded hover:bg-muted/50 ${F?"bg-primary/10":""}`,children:[e.jsx(Ms,{id:`add-${A}`,checked:F,onCheckedChange:q=>j(A,!!q)}),e.jsxs("label",{htmlFor:`add-${A}`,className:"flex-1 cursor-pointer",children:[e.jsx("div",{className:"text-sm font-medium",children:D.league_name}),D.sportapi_tournament_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",D.sportapi_tournament_id]})]})]},A)})})})]}),O.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Logo Source"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Select which league's logo to display for this group"}),e.jsxs(oe,{value:y||f||S[0]||"",onValueChange:u,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select logo source..."})}),e.jsx(me,{children:O.map(D=>{const A=D.sportapi_tournament_id||D.league_id,F=A===f;return e.jsxs(V,{value:A,children:[D.league_name," ",F&&"(Parent)"]},A)})})]})]}),e.jsx(is,{}),e.jsx("div",{className:"p-3 border border-destructive/30 rounded-lg bg-destructive/5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ls,{className:"h-5 w-5 text-destructive flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Dissolve Group"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This will ungroup all leagues and remove the parent. All leagues will become standalone."}),e.jsxs(ws,{children:[e.jsx(Po,{asChild:!0,children:e.jsxs(R,{variant:"destructive",size:"sm",className:"mt-2",disabled:x,children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Dissolve Group"]})}),e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsxs(Cs,{children:['Dissolve "',n.league_name,'" group?']}),e.jsxs(Ps,{children:["This will ungroup all ",_.length," leagues. They will become standalone leagues. This action cannot be undone."]})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:p,children:"Dissolve Group"})]})]})]})]})]})})]}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:w,children:"Cancel"}),e.jsx(R,{onClick:c,disabled:!$||x,children:x?"Saving...":"Save Changes"})]})]})})}const ur={nfl:"americanfootball_nfl",ncaaf:"americanfootball_ncaaf",ncaa:"americanfootball_ncaaf",cfl:"americanfootball_cfl",nba:"basketball_nba",ncaab:"basketball_ncaab",wnba:"basketball_wnba",euroleague:"basketball_euroleague",mlb:"baseball_mlb",nhl:"icehockey_nhl",epl:"soccer_epl",mls:"soccer_usa_mls",la_liga:"soccer_spain_la_liga",bundesliga:"soccer_germany_bundesliga",serie_a:"soccer_italy_serie_a",ligue_1:"soccer_france_ligue_one",champions_league:"soccer_uefa_champs_league",ufc:"mma_mixed_martial_arts",atp:"tennis_atp_us_open",wta:"tennis_wta_us_open",pga:"golf_pga_championship"};
422function hN({sportCode:s,leaguesConfig:a,onUpdate:t}){const[n,r]=v.useState(!1),[i,l]=v.useState(!1),[m,o]=v.useState(a||[]),[h,N]=v.useState(!1),[d,y]=v.useState(!1),[u,x]=v.useState(null),[g,f]=v.useState(new Set),_=async()=>{r(!0);try{const{data:A,error:F}=await ms.functions.invoke("sync-sportapi-data",{body:{sport:s,mode:"discover-leagues"}});if(F)throw F;if(console.log("Discover leagues response:",A),A!=null&&A.tournaments&&Array.isArray(A.tournaments)){const q=A.tournaments.map((H,Z)=>{var se;return{league_id:H.slug||((se=H.name)==null?void 0:se.toLowerCase().replace(/\s+/g,"_"))||`league_${H.id}`,league_name:H.name||`League ${Z+1}`,is_enabled:!1,priority:Z+1,sportapi_tournament_id:H.id,sportapi_category_id:A.categoryId,has_children:H.hasChildren||!1}}),E=new Map(m.map(H=>[H.sportapi_tournament_id||H.league_id,H])),L=q.map(H=>{const Z=E.get(H.sportapi_tournament_id)||E.get(H.league_id);return{...H,is_enabled:(Z==null?void 0:Z.is_enabled)??!1,priority:(Z==null?void 0:Z.priority)??H.priority,child_tournament_ids:Z==null?void 0:Z.child_tournament_ids}});o(L),await j(L,A.categoryId),Ee({title:"Leagues discovered",description:`Found ${q.length} leagues for ${s} (Category ID: ${A.categoryId})`})}else Ee({title:"No leagues found",description:"The API did not return any tournaments",variant:"destructive"})}catch(A){console.error("Discovery error:",A),Ee({title:"Discovery failed",description:A.message,variant:"destructive"})}finally{r(!1)}},k=A=>{const F=[];for(const q of A)if(q.is_enabled){const E=q.league_id.toLowerCase();if(ur[E])F.push(ur[E]);else{const L=q.league_name.toLowerCase();L.includes("nfl")||L==="national football league"?F.push("americanfootball_nfl"):L.includes("ncaa")&&(L.includes("football")||L.includes("fbs"))?F.push("americanfootball_ncaaf"):L.includes("nba")||L==="national basketball association"?F.push("basketball_nba"):L.includes("ncaa")&&L.includes("basketball")?F.push("basketball_ncaab"):L.includes("mlb")||L==="major league baseball"?F.push("baseball_mlb"):L.includes("nhl")||L==="national hockey league"?F.push("icehockey_nhl"):L.includes("ufc")||L.includes("mixed martial")?F.push("mma_mixed_martial_arts"):L.includes("premier league")||L.includes("epl")?F.push("soccer_epl"):L.includes("mls")||L.includes("major league soccer")?F.push("soccer_usa_mls"):L.includes("la liga")&&F.push("soccer_spain_la_liga")}}return[...new Set(F)]},b=A=>{const F=A.league_id.toLowerCase();if(ur[F])return ur[F];const q=A.league_name.toLowerCase();return q.includes("nfl")||q==="national football league"?"americanfootball_nfl":q.includes("ncaa")&&(q.includes("football")||q.includes("fbs"))?"americanfootball_ncaaf":q.includes("nba")||q==="national basketball association"?"basketball_nba":q.includes("ncaa")&&q.includes("basketball")?"basketball_ncaab":q.includes("mlb")||q==="major league baseball"?"baseball_mlb":q.includes("nhl")||q==="national hockey league"?"icehockey_nhl":q.includes("ufc")||q.includes("mixed martial")?"mma_mixed_martial_arts":q.includes("premier league")||q.includes("epl")?"soccer_epl":q.includes("mls")||q.includes("major league soccer")?"soccer_usa_mls":q.includes("la liga")?"soccer_spain_la_liga":null},j=async(A,F)=>{l(!0);try{const q=k(A);console.log(`Saving leagues for ${s} with odds_api_keys:`,q);const E=A.map(Y=>({...Y,odds_api_key:b(Y)})),L={leagues_config:E,odds_api_keys:q};F&&(L.sportapi_category_id=F);const{error:H}=await ms.from("sport_statuses").update(L).eq("sport_code",s);if(H)throw H;const Z=A.filter(Y=>Y.is_enabled);if(Z.length>0){const Y=Z.map(ee=>({sport_code:s,league_name:ee.league_name,league_abbrev:ee.league_id.toUpperCase(),sportapi_tournament_id:ee.sportapi_tournament_id||ee.league_id,sportapi_category_id:ee.sportapi_category_id||F,odds_api_key:ur[ee.league_id.toLowerCase()]||null,child_tournament_ids:ee.child_tournament_ids||null,priority:ee.priority,is_active:!0,updated_at:new Date().toISOString()})),{error:I}=await ms.from("master_leagues").upsert(Y,{onConflict:"sport_code,sportapi_tournament_id"});if(I){console.error("Error upserting leagues to master_leagues:",I);const{error:ee}=await ms.from("master_leagues").upsert(Y,{onConflict:"sport_code,league_name"});ee&&console.error("Fallback upsert also failed:",ee)}else console.log(`Upserted ${Y.length} leagues to master_leagues`)}const se=A.filter(Y=>!Y.is_enabled);for(const Y of se)Y.sportapi_tournament_id&&await ms.from("master_leagues").update({is_active:!1,updated_at:new Date().toISOString()}).eq("sportapi_tournament_id",Y.sportapi_tournament_id);if(Z.length>0){console.log("Triggering league image sync...");try{const{data:Y,error:I}=await ms.functions.invoke("sync-sportapi-data",{body:{sport:s,mode:"sync-league-images"}});I?console.error("Image sync error:",I):console.log("Image sync result:",Y)}catch(Y){console.error("Failed to sync images:",Y)}}const{data:ie}=await ms.from("master_leagues").select("sportapi_tournament_id, logo_url").eq("sport_code",s).not("logo_url","is",null);if(ie&&ie.length>0){const Y=new Map(ie.map(ee=>[ee.sportapi_tournament_id,ee.logo_url])),I=E.map(ee=>{const le=ee.sportapi_tournament_id||ee.league_id,ve=Y.get(le);return ve?{...ee,logo_url:ve}:ee});await ms.from("sport_statuses").update({leagues_config:I}).eq("sport_code",s),o(I),console.log(`Synced ${ie.length} league logos to leagues_config`)}Ee({title:"Leagues updated",description:q.length>0?`${q.length} API key(s) will be used for syncing`:"No leagues enabled for syncing"}),t()}catch(q){Ee({title:"Failed to save",description:q.message,variant:"destructive"})}finally{l(!1)}},c=async(A,F)=>{var L;const q=m.find(H=>H.league_id===A);let E=m.map(H=>H.league_id===A?{...H,is_enabled:F}:H);if(!F&&((L=q==null?void 0:q.child_tournament_ids)!=null&&L.length)){const H=q.child_tournament_ids;E=E.map(Z=>{const se=Z.sportapi_tournament_id||Z.league_id;return H.includes(se)?{...Z,is_enabled:!1}:Z})}F&&(q!=null&&q.parent_league_id)&&(E=E.map(H=>(H.sportapi_tournament_id||H.league_id)===q.parent_league_id?{...H,is_enabled:!0}:H)),o(E),await j(E)},p=async(A,F,q,E)=>{let L=[...m];if(F&&!A){const H={league_id:F.toLowerCase().replace(/\s+/g,"_"),league_name:F,is_enabled:!0,priority:0,child_tournament_ids:q,logo_source_tournament_id:E||q[0]};L.push(H),L=L.map(Z=>{const se=Z.sportapi_tournament_id||Z.league_id;return q.includes(se)?{...Z,is_grouped:!0,parent_league_id:H.league_id,is_enabled:!0}:Z})}else A&&(L=L.map(H=>{const Z=H.sportapi_tournament_id||H.league_id;return Z===A?{...H,child_tournament_ids:[...H.child_tournament_ids||[],...q],is_enabled:!0,logo_source_tournament_id:E||H.logo_source_tournament_id||q[0]}:q.includes(Z)?{...H,is_grouped:!0,parent_league_id:A,is_enabled:!0}:H}));o(L),await j(L),Ee({title:"Group created",description:`Grouped ${q.length} tournaments`})},w=A=>{f(F=>{const q=new Set(F);return q.has(A)?q.delete(A):q.add(A),q})},S=async A=>{let F=[...m];A.newName&&(F=F.map(q=>(q.sportapi_tournament_id||q.league_id)===A.parentId||q.league_id===A.parentId?{...q,league_name:A.newName}:q)),A.logoSourceTournamentId!==void 0&&(F=F.map(q=>(q.sportapi_tournament_id||q.league_id)===A.parentId||q.league_id===A.parentId?{...q,logo_source_tournament_id:A.logoSourceTournamentId}:q));for(const q of A.removeChildIds)F=F.map(E=>{var H;return(E.sportapi_tournament_id||E.league_id)===q?{...E,is_grouped:!1,parent_league_id:void 0}:(E.sportapi_tournament_id||E.league_id)===A.parentId||E.league_id===A.parentId?{...E,child_tournament_ids:(H=E.child_tournament_ids)==null?void 0:H.filter(Z=>Z!==q)}:E});for(const q of A.addChildIds)F=F.map(E=>{if((E.sportapi_tournament_id||E.league_id)===q)return{...E,is_grouped:!0,parent_league_id:A.parentId,is_enabled:!0};if((E.sportapi_tournament_id||E.league_id)===A.parentId||E.league_id===A.parentId){const H=E.child_tournament_ids||[];if(!H.includes(q))return{...E,child_tournament_ids:[...H,q]}}return E});o(F),await j(F),x(null),Ee({title:"Group updated",description:"League group changes saved successfully"})},P=async A=>{const F=m.find(E=>(E.sportapi_tournament_id||E.league_id)===A||E.league_id===A);if(!(F!=null&&F.child_tournament_ids))return;let q=m.map(E=>
422{const L=E.sportapi_tournament_id||E.league_id;return F.child_tournament_ids.includes(L)?{...E,is_grouped:!1,parent_league_id:void 0}:L===A||E.league_id===A?{...E,child_tournament_ids:void 0}:E});F.sportapi_tournament_id||(q=q.filter(E=>E.league_id!==A)),o(q),await j(q),x(null),Ee({title:"Group dissolved",description:"All leagues are now ungrouped"})},C=A=>{x(A),y(!0)},O=m.filter(A=>A.is_enabled).length,$=m.filter(A=>{var F;return(F=A.child_tournament_ids)==null?void 0:F.length}),z=m.filter(A=>{var F;return!A.is_grouped&&!((F=A.child_tournament_ids)!=null&&F.length)}),D=A=>{const F=m.find(q=>(q.sportapi_tournament_id||q.league_id)===A);return F!=null&&F.child_tournament_ids?m.filter(q=>{var E;return(E=F.child_tournament_ids)==null?void 0:E.includes(q.sportapi_tournament_id||q.league_id)}):[]};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Js,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold",children:"Leagues"}),m.length>0&&e.jsxs(B,{variant:"outline",className:"ml-2",children:[O,"/",m.length," enabled"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>N(!0),disabled:m.length<2,children:[e.jsx(vl,{className:"h-4 w-4 mr-2"}),"Create Group"]}),e.jsx(R,{size:"sm",variant:"outline",onClick:_,disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Discovering..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"h-4 w-4 mr-2"}),"Discover Leagues"]})})]})]}),m.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground border border-dashed rounded-lg",children:[e.jsx(Js,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No leagues configured"}),e.jsx("p",{className:"text-xs",children:'Click "Discover Leagues" to fetch available leagues from SportAPI'})]}):e.jsxs("div",{className:"space-y-3",children:[$.sort((A,F)=>A.priority-F.priority).map(A=>{const F=A.sportapi_tournament_id||A.league_id,q=D(F),E=g.has(F);return e.jsx(vs,{open:E,onOpenChange:()=>w(F),children:e.jsxs("div",{className:"rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx(ys,{asChild:!0,children:e.jsx(R,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:E?e.jsx(Ns,{className:"h-4 w-4"}):e.jsx(st,{className:"h-4 w-4"})})}),e.jsx(vl,{className:"h-4 w-4 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx(Q,{className:"cursor-pointer font-medium truncate",children:A.league_name}),A.sportapi_tournament_id&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["ID: ",A.sportapi_tournament_id]})]}),e.jsxs(B,{variant:"secondary",className:"ml-2",children:[q.length," grouped"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:L=>{L.stopPropagation(),C(A)},children:e.jsx(va,{className:"h-3.5 w-3.5"})}),e.jsx(Ge,{checked:A.is_enabled,onCheckedChange:L=>c(A.league_id,L),disabled:i})]})]}),e.jsx(_s,{children:e.jsx("div",{className:"border-t px-3 py-2 bg-muted/30 space-y-2",children:q.map(L=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-card ml-6",children:[e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:L.league_name}),L.sportapi_tournament_id&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["ID: ",L.sportapi_tournament_id]})]}),e.jsx(Ge,{checked:L.is_enabled,onCheckedChange:H=>c(L.league_id,H),disabled:i,className:"scale-90"})]},L.sportapi_tournament_id||L.league_id))})})]})},F)}),z.length>0&&e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:z.sort((A,F)=>A.priority-F.priority).map(A=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground cursor-grab flex-shrink-0"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx(Q,{htmlFor:`league-${A.league_id}`,className:"cursor-pointer font-medium truncate",children:A.league_name}),A.sportapi_tournament_id&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["ID: ",A.sportapi_tournament_id]})]})]}),e.jsx(Ge,{id:`league-${A.league_id}`,checked:A.is_enabled,onCheckedChange:F=>c(A.league_id,F),disabled:i})]},A.sportapi_tournament_id||A.league_id))})]}),e.jsx(mN,{open:h,onOpenChange:N,leagues:m,onSaveGroup:p}),e.jsx(xN,{open:d,onOpenChange:y,leagues:m,editingGroup:u,onSaveChanges:S,onDissolveGroup:P})]})}function pN({sport:s,syncConfigs:a,isExpanded:t,onToggleExpand:n,onRefresh:r}){const[i,l]=v.useState(!1),m=d=>{switch(d){case"in_season":return e.jsx(B,{className:"bg-green-600 hover:bg-green-700",children:"In Season"});case"off_season":return e.jsx(B,{variant:"secondary",children:"Off Season"});case"coming_soon":return e.jsx(B,{className:"bg-blue-600 hover:bg-blue-700",children:"Coming Soon"});default:return e.jsx(B,{variant:"outline",children:d})}},o=()=>a.filter(d=>d.is_enabled).length,h=async()=>{const d=a.filter(y=>y.is_enabled);if(d.length===0){Ee({title:"No syncs enabled",description:"Enable at least one sync type before running.",variant:"destructive"});return}l(!0);try{Ee({title:"Starting syncs...",description:`Running ${d.length} sync(s) for ${Qd(s.sport_code)}`});const y=[];for(const g of d)try{let f="sync-sportapi-data";const _={sport:s.sport_code};g.sync_type==="odds"||g.sync_type==="scores"?(f="sync-odds-data",_.syncType=g.sync_type):_.mode=g.sync_type==="players"?"players":g.sync_type==="teams"?"teams":"full";const k=await ms.functions.invoke(f,{body:_});y.push({status:"fulfilled",value:k}),await new Promise(b=>setTimeout(b,500))}catch(f){y.push({status:"rejected",reason:f})}const u=y.filter(g=>g.status==="fulfilled").length,x=y.filter(g=>g.status==="rejected").length;Ee({title:"Sync complete",description:`${u} succeeded, ${x} failed`,variant:x>0?"destructive":"default"}),r()}catch(y){Ee({title:"Sync failed",description:y.message,variant:"destructive"})}finally{l(!1)}},N=Or[s.sport_code.toLowerCase()]||"🎯";return e.jsx(G,{children:e.jsxs(vs,{open:t,onOpenChange:n,children:[e.jsx(ys,{asChild:!0,children:e.jsx(je,{className:"cursor-pointer hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-3xl",children:N}),e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[s.sport_name,m(s.status),!s.is_active&&e.jsx(B,{variant:"outline",className:"text-muted-foreground",children:"Inactive"})]}),e.jsx(De,{className:"flex gap-3 mt-1",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),o()," syncs active"]})})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(R,{size:"sm",onClick:d=>{d.stopPropagation(),h()},disabled:i||o()===0,children:i?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Running..."]}):e.jsxs(e.Fragment,{children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Run Sync"]})}),t?e.jsx(Ns,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(st,{className:"h-5 w-5 text-muted-foreground"})]})]})})}),e.jsx(_s,{children:e.jsxs(J,{className:"pt-0 space-y-6",children:[e.jsx(cN,{sport:s,onUpdate:r}),e.jsx(is,{}),e.jsx(hN,{sportCode:s.sport_code,leaguesConfig:s.leagues_config||[],onUpdate:r}),e.jsx(is,{}),e.jsx(uN,{sportCode:s.sport_code,syncConfigs:a,onUpdate:r})]})})]})})}const Rn={nfl:"americanfootball_nfl",ncaaf:"americanfootball_ncaaf",ncaa:"americanfootball_ncaaf",cfl:"americanfootball_cfl",nba:"basketball_nba",ncaab:"basketball_ncaab",wnba:"basketball_wnba",mlb:"baseball_mlb",nhl:"icehockey_nhl",epl:"soccer_epl",mls:"soccer_usa_mls",laliga:"soccer_spain_la_liga",ufc:"mma_mixed_martial_arts",pga:"golf_pga_championship"},gN=[{patterns:["australian open"],key:"tennis_atp_aus_open"},{patterns:["french open","roland garros","roland-garros"],key:"tennis_atp_french_open"},{patterns:["wimbledon"],key:"tennis_atp_wimbledon"},{patterns:["us open","u.s. open"],key:"tennis_atp_us_open"}];function jN(s){const a=(s.league_name||"").toLowerCase(),t=/wta|women/.test(a)||s.tourKey==="wta",n=gN.find(r=>r.patterns.some(i=>a.includes(i)));return n?t?n.key.replace("tennis_atp_","tennis_wta_"):n.key:null}const Sa=[{id:"leagues",label:"Discover Leagues",icon:e.jsx(Rs,{className:"h-4 w-4"})},{id:"seasons",label:"Configure Season",icon:e.jsx(xt,{className:"h-4 w-4"})},{id:"syncs",label:"Setup Data Syncs",icon:e.jsx(tt,{className:"h-4 w-4"})},{id:"review",label:"Review & Activate",icon:e.jsx(rs,{className:"h-4 w-4"})}],Ai=[{code:"mlb",name:"Baseball"},{code:"nfl",name:"Football"},{code:"nba",name:"Basketball"},{code:"nhl",name:"Hockey"}
422,{code:"mma",name:"Mixed Martial Arts"},{code:"soccer",name:"Soccer"},{code:"golf",name:"Golf"},{code:"tennis",name:"Tennis"}];function fN({open:s,onOpenChange:a,onComplete:t}){const[n,r]=v.useState("leagues"),[i,l]=v.useState(!1),[m,o]=v.useState(!1),[h,N]=v.useState([]),[d,y]=v.useState([]),[u,x]=v.useState({sportName:"",sportCode:"",status:"coming_soon",seasonStartDate:"",seasonEndDate:"",leagues:[],syncs:Pa.map(A=>({type:A.value,enabled:["odds","scores","players","teams","matchups"].includes(A.value),source:In[A.value]||"sportapi",startHoursBeforeGame:A.value==="matchups"?6:24,frequencyHours:A.value==="matchups"?2:1,peakHoursFrequency:A.value==="matchups"?1:"keep_same"}))});v.useEffect(()=>{(async()=>{const{data:F}=await ms.from("sport_statuses").select("sport_code, sport_name").eq("is_active",!0);F&&y(F)})()},[]);const g=async A=>{try{const{data:F,error:q}=await ms.from("sport_data_sync_config").select("*").eq("sport_code",A);if(q)throw q;if(F&&F.length>0){const E=Pa.map(H=>{const Z=F.find(se=>se.sync_type===H.value);if(Z){const se=Z.config;return{type:H.value,enabled:Z.is_enabled??!1,source:Z.api_source||In[H.value]||"sportapi",startHoursBeforeGame:(se==null?void 0:se.start_hours_before_game)??24,frequencyHours:(se==null?void 0:se.update_frequency_hours)??1,peakHoursFrequency:se!=null&&se.peak_hours_enabled?(se==null?void 0:se.peak_hours_frequency)??"keep_same":"keep_same"}}return u.syncs.find(se=>se.type===H.value)});x(H=>({...H,syncs:E}));const L=d.find(H=>H.sport_code===A);Ee({title:"Sync config copied",description:`Copied ${F.length} sync settings from ${(L==null?void 0:L.sport_name)||A}`})}else Ee({title:"No sync configs found",description:"The selected sport has no sync configurations to copy.",variant:"destructive"})}catch(F){console.error("Error copying sync config:",F),Ee({title:"Copy failed",description:F.message,variant:"destructive"})}},f=Sa.findIndex(A=>A.id===n),_=(f+1)/Sa.length*100,k=A=>{const F=Ai.find(q=>q.code===A);F&&x(q=>({...q,sportCode:A,sportName:F.name}))},b=async()=>{if(!u.sportCode){Ee({title:"Select a sport first",variant:"destructive"});return}o(!0);try{const{data:A,error:F}=await ms.functions.invoke("sync-sportapi-data",{body:{sport:u.sportCode,mode:"discover-leagues"}});if(F)throw F;if(console.log("Discover leagues response:",A),A!=null&&A.tournaments&&Array.isArray(A.tournaments)){const q=u.sportCode==="tennis",E=A.tournaments.map((L,H)=>{var Z;return{league_id:L.slug||((Z=L.name)==null?void 0:Z.toLowerCase().replace(/\s+/g,"_"))||`league_${L.id}`,league_name:L.name||`League ${H+1}`,is_enabled:q?L.tourKey==="atp"||L.tourKey==="wta"||L.tourKey==="grand-slams":H<3,priority:H+1,sportapi_tournament_id:L.id,sportapi_category_id:L.categoryId||A.categoryId,has_children:L.hasChildren||!1,child_tournament_ids:L.childTournamentIds||null,is_grouped:L.isGrouped||!1,parent_league_id:L.parentLeagueId||null,logo_source_tournament_id:L.logoSourceTournamentId||null,tourKey:L.tourKey,tourLabel:L.tourLabel,category_name:L.categoryName}});N(E),x(L=>({...L,leagues:E,sportapiCategoryId:A.categoryId})),Ee({title:"Leagues discovered",description:`Found ${E.length} leagues (Category ID: ${A.categoryId})`})}else{const q=j(u.sportCode);N(q),x(E=>({...E,leagues:q})),Ee({title:"Using default leagues",description:"Could not discover leagues from API, using defaults"})}}catch(A){console.error("League discovery error:",A);const F=j(u.sportCode);N(F),x(q=>({...q,leagues:F})),Ee({title:"Using default leagues",description:A.message||"Could not discover leagues from API"})}finally{o(!1)}},j=A=>({baseball:[{league_id:"mlb",league_name:"MLB",is_enabled:!0,priority:1}],football:[{league_id:"nfl",league_name:"NFL",is_enabled:!0,priority:1},{league_id:"ncaaf",league_name:"NCAA Football",is_enabled:!1,priority:2}],basketball:[{league_id:"nba",league_name:"NBA",is_enabled:!0,priority:1},{league_id:"ncaab",league_name:"NCAA Basketball",is_enabled:!1,priority:2}],hockey:[{league_id:"nhl",league_name:"NHL",is_enabled:!0,priority:1},{league_id:"ncaah",league_name:"NCAA Hockey",is_enabled:!1,priority:2}],mma:[{league_id:"ufc",league_name:"UFC",is_enabled:!0,priority:1},{league_id:"bellator",league_name:"Bellator",is_enabled:!1,priority:2},{league_id:"pfl",league_name:"PFL",is_enabled:!1,priority:3}],soccer:[{league_id:"epl",league_name:"Premier League",is_enabled:!0,priority:1},{league_id:"laliga",league_name:"La Liga",is_enabled:!0,priority:2},{league_id:"mls",league_name:"MLS",is_enabled:!1,priority:3}],golf:[{league_id:"pga",league_name:"PGA Tour",is_enabled:!0,priority:1},{league_id:"lpga",league_name:"LPGA Tour",is_enabled:!1,priority:2}],tennis:[{league_id:"atp",league_name:"ATP Tour",is_enabled:!0,priority:1},{league_id:"wta",league_name:"WTA Tour",is_enabled:!0,priority:2}]})[A]||[{league_id:`${A}_main`,league_name:"Main League",is_enabled:!0,priority:1}],c=A=>{x(F=>({...F,leagues:F.leagues.map(q=>q.league_id===A?{...q,is_enabled:!q.is_enabled}:q)}))},p=A=>{x(F=>({...F,syncs:F.syncs.map(q=>q.type===A?{...q,enabled:!q.enabled}:q)}))},w=(A,F,q)=>{x(E=>({...E,syncs:E.syncs.map(L=>L.type===A?{...L,[F]:q}:L)}))},S=()=>{const A=f+1;
422A<Sa.length&&r(Sa[A].id)},P=()=>{const A=f-1;A>=0&&r(Sa[A].id)},C=()=>{switch(n){case"leagues":return u.sportCode&&u.leagues.some(A=>A.is_enabled);case"seasons":return u.status&&u.seasonStartDate;case"syncs":return u.syncs.some(A=>A.enabled);case"review":return!0;default:return!1}},O=A=>{const F=[];for(const q of A)if(q.is_enabled){const E=q.league_id.toLowerCase();if(Rn[E])F.push(Rn[E]);else{const L=q.league_name.toLowerCase();L.includes("nfl")||L==="national football league"?F.push("americanfootball_nfl"):L.includes("ncaa")&&(L.includes("football")||L.includes("fbs"))?F.push("americanfootball_ncaaf"):L.includes("nba")?F.push("basketball_nba"):L.includes("mlb")?F.push("baseball_mlb"):L.includes("nhl")?F.push("icehockey_nhl"):L.includes("ufc")&&F.push("mma_mixed_martial_arts")}}return[...new Set(F)]},$=async()=>{l(!0);try{const A=O(u.leagues),F=u.sportName.replace(/\s*\([^)]*\)\s*/g,"").trim(),{data:q}=await ms.from("sport_statuses").select("id, sport_code").eq("sport_name",F).maybeSingle();q&&q.sport_code!==u.sportCode&&(console.log(`Migrating sport from ${q.sport_code} to ${u.sportCode}`),await ms.from("sport_data_sync_config").delete().eq("sport_code",q.sport_code),await ms.from("master_leagues").delete().eq("sport_code",q.sport_code),await ms.from("sport_statuses").delete().eq("id",q.id));const{error:E}=await ms.from("sport_statuses").upsert({sport_code:u.sportCode,sport_name:F,status:u.status,season_start_date:u.seasonStartDate||null,season_end_date:u.seasonEndDate||null,is_active:!0,leagues_config:u.leagues,odds_api_keys:A,sportapi_category_id:u.sportapiCategoryId||null},{onConflict:"sport_code"});if(E)throw E;const L=u.leagues.filter(se=>se.is_enabled);if(L.length>0){const se=u.sportCode==="tennis",ie=L.map(I=>({sport_code:u.sportCode,league_name:I.league_name,league_abbrev:I.league_id.toUpperCase(),sportapi_tournament_id:I.sportapi_tournament_id||I.league_id,sportapi_category_id:I.sportapi_category_id||u.sportapiCategoryId,odds_api_key:se?jN(I):Rn[I.league_id.toLowerCase()]||null,child_tournament_ids:I.child_tournament_ids||null,priority:I.priority,is_active:!0,discovered_at:new Date().toISOString(),updated_at:new Date().toISOString()})),{error:Y}=await ms.from("master_leagues").upsert(ie,{onConflict:"sport_code,league_name"});Y?console.error("Error inserting leagues:",Y):console.log(`Inserted ${ie.length} leagues into master_leagues with real IDs`)}const H=u.syncs.map(se=>{const ie=se.frequencyHours;let Y="0 * * * *";return ie===.25?Y="*/15 * * * *":ie===.5?Y="*/30 * * * *":ie===1?Y="0 * * * *":ie===2?Y="0 */2 * * *":ie===4?Y="0 */4 * * *":ie===6?Y="0 */6 * * *":ie===12?Y="0 */12 * * *":ie===24&&(Y="0 0 * * *"),{sport_code:u.sportCode,sync_type:se.type,is_enabled:se.enabled,cron_schedule:Y,api_source:se.source,config:{start_hours_before_game:se.startHoursBeforeGame,update_frequency_hours:se.frequencyHours,peak_hours_enabled:se.peakHoursFrequency!=="keep_same",peak_hours_frequency:se.peakHoursFrequency==="keep_same"?null:se.peakHoursFrequency}}}),{error:Z}=await ms.from("sport_data_sync_config").upsert(H,{onConflict:"sport_code,sync_type"});if(Z)throw Z;Ee({title:"Sport activated!",description:`${u.sportName} has been set up with ${L.length} league(s).`}),t(),a(!1),z()}catch(A){console.error("Activation error:",A),Ee({title:"Activation failed",description:A.message,variant:"destructive"})}finally{l(!1)}},z=()=>{r("leagues"),N([]),x({sportName:"",sportCode:"",status:"coming_soon",seasonStartDate:"",seasonEndDate:"",leagues:[],syncs:Pa.map(A=>({type:A.value,enabled:["odds","scores","players","teams"].includes(A.value),source:In[A.value]||"sportapi",startHoursBeforeGame:24,frequencyHours:1,peakHoursFrequency:"keep_same"}))})},D=()=>{switch(n){case"leagues":return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Q,{children:"Select Sport"}),e.jsxs(oe,{value:u.sportCode,onValueChange:k,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Choose a sport to set up"})}),e.jsx(me,{children:Ai.map(E=>e.jsx(V,{value:E.code,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{children:Or[E.code]||"🎯"}),E.name]})},E.code))})]})]}),u.sportCode&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Q,{children:"Available Leagues"}),e.jsx(R,{variant:"outline",size:"sm",onClick:b,disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Discovering..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ft,{className:"h-4 w-4 mr-2"}),"Discover Leagues"]})})]}),u.sportapiCategoryId&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Category ID: ",u.sportapiCategoryId]}),e.jsx(cs,{className:"h-[200px] border rounded-md p-3",children:u.leagues.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:'Click "Discover Leagues" to find available leagues'}):e.jsx("div",{className:"space-y-2",children:u.leagues.map(E=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ms,{checked:E.is_enabled,onCheckedChange:()=>c(E.league_id)}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:E.league_name}),E.sportapi_tournament_id&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["ID: ",E.sportapi_tournament_id]})]})]}),e.jsxs(B,{variant:"outline",className:"text-xs",children:["Pri
422ority ",E.priority]})]},E.sportapi_tournament_id||E.league_id))})})]})]});case"seasons":return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Q,{children:"Season Status"}),e.jsxs(oe,{value:u.status,onValueChange:E=>x(L=>({...L,status:E})),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsxs(me,{children:[e.jsx(V,{value:"in_season",children:"In Season"}),e.jsx(V,{value:"off_season",children:"Off Season"}),e.jsx(V,{value:"coming_soon",children:"Coming Soon"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Season Start Date"}),e.jsx(pe,{type:"date",value:u.seasonStartDate,onChange:E=>x(L=>({...L,seasonStartDate:E.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Season End Date"}),e.jsx(pe,{type:"date",value:u.seasonEndDate,onChange:E=>x(L=>({...L,seasonEndDate:E.target.value}))})]})]}),e.jsx("div",{className:"p-4 bg-muted/50 rounded-md",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"Tip:"})," Setting the correct season dates helps the system know when to actively sync data and when to reduce API calls during off-season."]})})]});case"syncs":const A=d.filter(E=>E.sport_code!==u.sportCode);return e.jsxs("div",{className:"space-y-4",children:[A.length>0&&e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-md bg-muted/50",children:[e.jsx(vt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Copy from:"}),e.jsxs(oe,{onValueChange:g,children:[e.jsx(de,{className:"w-[180px] h-8",children:e.jsx(ue,{placeholder:"Select a sport..."})}),e.jsx(me,{children:A.map(E=>e.jsxs(V,{value:E.sport_code,children:[Or[E.sport_code]||"🎯"," ",E.sport_name]},E.sport_code))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Copy all sync settings from another sport"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure which data types to sync and timing settings."}),e.jsx(cs,{className:"h-[320px]",children:e.jsx("div",{className:"space-y-4",children:Pa.map(E=>{const L=u.syncs.find(H=>H.type===E.value);return e.jsxs("div",{className:"p-3 border rounded-md space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ms,{checked:(L==null?void 0:L.enabled)||!1,onCheckedChange:()=>p(E.value)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:E.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:E.description})]}),(L==null?void 0:L.enabled)&&e.jsxs(oe,{value:L.source,onValueChange:H=>w(E.value,"source",H),children:[e.jsx(de,{className:"w-[130px] h-8 text-xs",children:e.jsx(ue,{})}),e.jsx(me,{children:so.map(H=>e.jsx(V,{value:H.value,children:H.label},H.value))})]})]}),(L==null?void 0:L.enabled)&&e.jsxs("div",{className:"grid grid-cols-3 gap-2 pl-7",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Start"}),e.jsxs(oe,{value:String(L.startHoursBeforeGame),onValueChange:H=>w(E.value,"startHoursBeforeGame",Number(H)),children:[e.jsx(de,{className:"h-8 text-xs",children:e.jsx(ue,{})}),e.jsx(me,{children:to.map(H=>e.jsx(V,{value:String(H.value),children:H.label},H.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Frequency"}),e.jsxs(oe,{value:String(L.frequencyHours),onValueChange:H=>w(E.value,"frequencyHours",Number(H)),children:[e.jsx(de,{className:"h-8 text-xs",children:e.jsx(ue,{})}),e.jsx(me,{children:Fi.map(H=>e.jsx(V,{value:String(H.value),children:H.label},H.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Q,{className:"text-xs text-muted-foreground",children:"Peak (12p-12a)"}),e.jsxs(oe,{value:String(L.peakHoursFrequency),onValueChange:H=>w(E.value,"peakHoursFrequency",H==="keep_same"?H:Number(H)),children:[e.jsx(de,{className:"h-8 text-xs",children:e.jsx(ue,{})}),e.jsx(me,{children:ao.map(H=>
422e.jsx(V,{value:String(H.value),children:H.label},String(H.value)))})]})]})]})]},E.value)})})})]});case"review":const F=u.syncs.filter(E=>E.enabled),q=u.leagues.filter(E=>E.is_enabled);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 border rounded-md space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-3xl",children:Or[u.sportCode]||"🎯"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:u.sportName}),e.jsx(B,{className:u.status==="in_season"?"bg-green-600":u.status==="coming_soon"?"bg-blue-600":"",variant:u.status==="off_season"?"secondary":"default",children:u.status.replace("_"," ")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Season Start:"}),e.jsx("span",{className:"ml-2",children:u.seasonStartDate||"Not set"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Season End:"}),e.jsx("span",{className:"ml-2",children:u.seasonEndDate||"Not set"})]})]}),u.sportapiCategoryId&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["SportAPI Category ID: ",u.sportapiCategoryId]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"font-medium text-sm",children:["Enabled Leagues (",q.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:q.map(E=>e.jsxs(B,{variant:"outline",children:[E.league_name,E.sportapi_tournament_id&&e.jsxs("span",{className:"ml-1 text-muted-foreground",children:["(",E.sportapi_tournament_id,")"]})]},E.sportapi_tournament_id||E.league_id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"font-medium text-sm",children:["Data Syncs (",F.length,")"]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 text-sm",children:F.map(E=>{var Z;const L=Pa.find(se=>se.value===E.type),H=((Z=Fi.find(se=>se.value===E.frequencyHours))==null?void 0:Z.label)||"Every hour";return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:L==null?void 0:L.label}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",H,")"]})]},E.type)})})]})]})}};return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(ze,{children:[e.jsxs(Ke,{className:"flex items-center gap-2",children:[e.jsx(ft,{className:"h-5 w-5 text-primary"}),"Setup New Sport"]}),e.jsx(Vs,{children:"Configure leagues, seasons, and data syncs for a new sport"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ct,{value:_,className:"h-2"}),e.jsx("div",{className:"flex justify-between",children:Sa.map((A,F)=>e.jsxs("div",{className:`flex items-center gap-1 text-xs ${F<=f?"text-primary":"text-muted-foreground"}`,children:[A.icon,e.jsx("span",{className:"hidden sm:inline",children:A.label})]},A.id))})]}),e.jsx("div",{className:"flex-1 overflow-auto py-4",children:D()}),e.jsxs(lt,{className:"flex-row justify-between sm:justify-between",children:[e.jsxs(R,{variant:"outline",onClick:P,disabled:f===0,children:[e.jsx(na,{className:"h-4 w-4 mr-2"}),"Back"]}),n==="review"?e.jsx(R,{onClick:$,disabled:i,children:i?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}),"Activating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Activate Sport"]})}):e.jsxs(R,{onClick:S,disabled:!C(),children:["Next",e.jsx(aa,{className:"h-4 w-4 ml-2"})]})]})]})})}function vN(){const[s,a]=v.useState(!1),[t,n]=v.useState(new Set(["stale_games","missing_event_ids"])),[r,i]=v.useState(new Set),[l,m]=v.useState(null),{data:o,refetch:h,isLoading:N}=ge({queryKey:["diagnostic-stale-games"],queryFn:async()=>{const{data:D,error:A}=await ms.from("master_games").select("sport, game_status, game_date").lt("game_date",new Date().toISOString().split("T")[0]).in("game_status",["scheduled","live","in_progress"]);if(A)throw A;const F=(D||[]).reduce((q,E)=>{const L=E.sport;return q[L]||(q[L]={sport:L,count:0,oldest:E.game_date}),q[L].count++,E.game_date<q[L].oldest&&(q[L].oldest=E.game_date),q},{});return Object.values(F)},enabled:!1}),{data:d,refetch:y,isLoading:u}=ge({queryKey:["diagnostic-missing-event-ids"],queryFn:async()=>{const D=new Date;D.setDate(D.getDate()-7);const A=new Date;A.setDate(A.getDate()+1);const{data:F,error:q}=await ms.from("master_games").select("sport, game_date").is("sportapi_event_id",null).gte("game_date",D.toISOString().split("T")[0]).lte("game_date",A.toISOString().split("T")[0]);if(q)throw q;const E=(F||[]).reduce((L,H)=>{const Z=H.sport;return L[Z]||(L[Z]={sport:Z,count:0,oldest:H.game_date}),L[Z].count++,H.game_date<L[Z].oldest&&(L[Z].oldest=H.game_date),L},{});return Object.values(E)},enabled:!1}),{data:x,refetch:g,isLoading:f}=ge({queryKey:["diagnostic-missing-box-scores"],queryFn:async()=>{const D=new Date;D.setDate(D.getDate()-30);const{data:A,error:F}=await ms.from("master_games").select("sport, game_date").eq("game_status","completed").is("box_score",null).not("sportapi_event_id","is",null).gte("game_date",D.toISOString().split("T")[0]);if(F)throw F;const q=(A||[]).reduce((E,L)=>{const H=L.sport;return E[H]||(E[H]={sport:H,count:0,oldest:L.game_date}),E[H].count++,L.game_date<E[H].oldest&&(E[H].oldest=L.game_date),E},{});return Object.values(q)},enabled:!1}),{data:_,refetch:k,isLoading:b}=ge({queryKey:["diagnostic-missing-headshots"],queryFn:async()=>{const D=["nba","nfl","nhl","mlb","soccer","mma"],A=[];for(const F of D){const{count:q,error:E}=await ms.from("master_players").select("*",{count:"exact",head:!0}
422).is("headshot_url",null).eq("is_active",!0).not("sportapi_player_id","is",null).eq("sport_code",F),{count:L,error:H}=await ms.from("master_players").select("*",{count:"exact",head:!0}).is("headshot_url",null).eq("is_active",!0).is("sportapi_player_id",null).eq("sport_code",F),Z=(q||0)+(L||0);!E&&!H&&Z>0&&A.push({sport:F,count:q||0,oldest:null,needsIdSync:L||0})}return A},enabled:!1}),j=async()=>{a(!0);try{await Promise.all([h(),y(),g(),k()]),m(new Date),K.success("Diagnostic scan completed")}catch(D){console.error("Scan error:",D),K.error("Failed to complete scan")}finally{a(!1)}},c=async(D,A)=>{const F=`${D}-${A||"all"}`;i(q=>new Set(q).add(F));try{const{data:q,error:E}=await ms.functions.invoke("recover-stale-data",{body:{action:"fix",fixType:D,sport:A,daysBack:7}});if(E)throw E;const L=q;K.success(`Fixed ${L.fixed} items${L.failed>0?` (${L.failed} failed)`:""}`),D==="stale_games"&&h(),D==="missing_event_ids"&&y(),D==="missing_box_scores"&&g(),D==="missing_headshots"&&k()}catch(q){console.error("Fix error:",q),K.error(`Failed to fix ${D}: ${q instanceof Error?q.message:"Unknown error"}`)}finally{i(q=>{const E=new Set(q);return E.delete(F),E})}},p=async D=>{const A=`sync-ids-${D}`;i(F=>new Set(F).add(A));try{const{data:F,error:q}=await ms.functions.invoke("sync-sportapi-data",{body:{syncType:"players",sport:D}});if(q)throw q;K.success(`Player IDs synced for ${D.toUpperCase()}`),k()}catch(F){console.error("Sync player IDs error:",F),K.error(`Failed to sync player IDs: ${F instanceof Error?F.message:"Unknown error"}`)}finally{i(F=>{const q=new Set(F);return q.delete(A),q})}},w=async()=>{i(new Set(["all"]));try{const D=["stale_games","missing_event_ids","missing_box_scores","missing_headshots"];let A=0,F=0;for(const q of D){const{data:E,error:L}=await ms.functions.invoke("recover-stale-data",{body:{action:"fix",fixType:q,daysBack:7}});!L&&E&&(A+=E.fixed||0,F+=E.failed||0)}K.success(`Fixed ${A} items${F>0?` (${F} failed)`:""}`),await j()}catch(D){console.error("Fix all error:",D),K.error("Failed to fix all issues")}finally{i(new Set)}},S=D=>{n(A=>{const F=new Set(A);return F.has(D)?F.delete(D):F.add(D),F})},P=N||u||f||b,C=l!==null,O=((o==null?void 0:o.reduce((D,A)=>D+A.count,0))||0)+((d==null?void 0:d.reduce((D,A)=>D+A.count,0))||0)+((x==null?void 0:x.reduce((D,A)=>D+A.count,0))||0)+((_==null?void 0:_.reduce((D,A)=>D+A.count,0))||0),$=[{id:"stale_games",label:"Stale Games",description:"Games marked scheduled/live but game date has passed",icon:ls,severity:"critical",data:o||[],fixLabel:"Recover Scores"},{id:"missing_event_ids",label:"Missing SportAPI Event IDs",description:"Games without event ID (cannot fetch box scores, lineups)",icon:Mo,severity:"critical",data:d||[],fixLabel:"Match Events"},{id:"missing_box_scores",label:"Missing Box Scores",description:"Completed games with event ID but no box score data",icon:eu,severity:"warning",data:x||[],fixLabel:"Fetch Box Data"},{id:"missing_headshots",label:"Missing Player Headshots",description:"Active players without headshot images",icon:ou,severity:"info",data:_||[],fixLabel:"Sync Players"}],z=(D,A)=>{if(A===0)return e.jsx(B,{variant:"outline",className:"bg-green-500/10 text-green-600 border-green-500/20",children:"✓ Clear"});const F={critical:"bg-red-500/10 text-red-600 border-red-500/20",warning:"bg-yellow-500/10 text-yellow-600 border-yellow-500/20",info:"bg-blue-500/10 text-blue-600 border-blue-500/20"},q={critical:"🔴",warning:"🟡",info:"🟢"};return e.jsxs(B,{variant:"outline",className:F[D],children:[q[D]," ",A," issues"]})};return e.jsxs(G,{children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_t,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(fe,{className:"text-base",children:"Sports Data Health Check"}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Last scan: ",l.toLocaleTimeString()]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&O>0&&e.jsxs(R,{variant:"destructive",size:"sm",onClick:w,disabled:r.has("all"),children:[r.has("all")?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Fix All Issues"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:j,disabled:s||P,children:[s||P?e.jsx(ne,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(He,{className:"h-4 w-4 mr-2"}),"Scan Now"]})]})]})}),e.jsx(J,{className:"space-y-2",children:C?e.jsx(e.Fragment,{children:O===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(rs,{className:"h-8 w-8 mx-auto mb-2 text-green-500"}),e.jsx("p",{className:"text-green-600 font-medium",children:"All data is healthy!"})]}):$.map(D=>{const A=D.data.reduce((E,L)=>E+L.count,0),F=t.has(D.id),q=D.icon;return e.jsxs(vs,{open:F,onOpenChange:()=>S(D.id),children:[e.jsx(ys,{asChild:!0,children:e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[F?e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(st,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(q,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:D.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D.description})]})]}),z(D.severity,A)]})}),e.jsx(_s,{children:A>0&&e.jsx("div",{className:"ml-11 space-y-1 pb-2",children:D.data.sort((E,L)=>L.count+(L.needsIdSync||0)-(E.count+(E.needsIdSync||0))).map(E=>{const L=`${D.id}-${E.sport}`,H=`sync-ids-${E.sport}
422`,Z=r.has(L),se=r.has(H),ie=D.id==="missing_headshots",Y=ie&&(E.needsIdSync||0)>0;return E.count+(E.needsIdSync||0),e.jsxs("div",{className:"flex items-center justify-between py-1.5 px-3 rounded bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium capitalize",children:E.sport.replace(/_/g," ")}),ie?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[E.count>0&&e.jsxs("span",{className:"text-green-600",children:[E.count," fixable"]}),E.count>0&&Y&&" • ",Y&&e.jsxs("span",{className:"text-yellow-600",children:[E.needsIdSync," need ID sync"]})]}):e.jsxs("span",{className:"text-xs text-muted-foreground",children:[E.count," ",E.count===1?"item":"items",E.oldest&&` (oldest: ${E.oldest})`]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Y&&e.jsxs(R,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:I=>{I.stopPropagation(),p(E.sport)},disabled:se||r.has("all"),children:[se?e.jsx(ne,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Sync IDs"]}),E.count>0&&e.jsxs(R,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:I=>{I.stopPropagation(),c(D.id,E.sport)},disabled:Z||r.has("all"),children:[Z?e.jsx(ne,{className:"h-3 w-3 mr-1 animate-spin"}):null,D.fixLabel]})]})]},E.sport)})})})]},D.id)})}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(_t,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:'Click "Scan Now" to check for stale data issues'})]})})]})}function yN(){const[s,a]=v.useState(new Set),[t,n]=v.useState(!1),{data:r,isLoading:i,refetch:l}=ge({queryKey:["sport-statuses-controls"],queryFn:async()=>{const{data:x,error:g}=await ms.from("sport_statuses").select("*").order("sport_name");if(g)throw g;return x}}),{data:m,isLoading:o,refetch:h}=ge({queryKey:["sport-data-sync-configs"],queryFn:async()=>{const{data:x,error:g}=await ms.from("sport_data_sync_config").select("*").order("sport_code, sync_type");if(g)throw g;return x}}),N=i||o,d=()=>{l(),h()},y=x=>{a(g=>{const f=new Set(g);return f.has(x)?f.delete(x):f.add(x),f})},u=x=>(m==null?void 0:m.filter(g=>g.sport_code===x))||[];return N?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(G,{children:e.jsx(je,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Sports Controls"]}),e.jsx(De,{children:"Master control center for all sport data flows, syncs, and configurations"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:d,children:[e.jsx(He,{className:"h-4 w-4 mr-2"}),"Refresh All"]}),e.jsxs(R,{size:"sm",onClick:()=>n(!0),children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Setup Sport"]})]})]})})}),e.jsx(vN,{}),e.jsx("div",{className:"grid gap-4",children:r==null?void 0:r.slice().sort((x,g)=>{const f={in_season:1,off_season:2,coming_soon:3},_=f[x.status]||99,k=f[g.status]||99;return _!==k?_-k:x.sport_name.localeCompare(g.sport_name)}).map(x=>e.jsx(pN,{sport:x,syncConfigs:u(x.sport_code),isExpanded:s.has(x.sport_code),onToggleExpand:()=>y(x.sport_code),onRefresh:d},x.id))}),(!r||r.length===0)&&e.jsx(G,{children:e.jsxs(J,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No sports configured yet."}),e.jsxs(R,{onClick:()=>n(!0),children:[e.jsx(Zs,{className:"h-4 w-4 mr-2"}),"Setup Your First Sport"]})]})}),e.jsx(fN,{open:t,onOpenChange:n,onComplete:d})]})}function NN(s,a=10){return ge({queryKey:["user-search",s],queryFn:async()=>{if(s.length<2)return[];const{data:t,error:n}=await T.from("user_profiles").select("id, display_name, username, full_name, avatar_url").or(`display_name.ilike.%${s}%,username.ilike.%${s}%,full_name.ilike.%${s}%`).is("deleted_at",null).limit(a);if(n)throw n;return t||[]},enabled:s.length>=2})}const _N=["GENERAL","AI","DFS","Betting","Settlement","Subscription","Profile","Props","Bug","KASH","KOMMUNITY","KOMPETE"];function bN({open:s,onOpenChange:a}){const[t,n]=v.useState(null),[r,i]=v.useState(""),[l,m]=v.useState(!1),[o,h]=v.useState("GENERAL"),[N,d]=v.useState(""),[y,u]=v.useState(""),{data:x,isLoading:g}=NN(r),f=qo(),_=j=>j.display_name||j.username||j.full_name||"Unknown User",k=async()=>{!t||!N||!y||(await f.mutateAsync({userId:t.id,category:o,subject:N,description:y}),n(null),i(""),h("GENERAL"),d(""),u(""),a(!1))},b=t&&N.trim()&&y.trim();return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"sm:max-w-[500px]",children:[e.jsxs(ze,{children:[e.jsx(Ke,{children:"Create Support Ticket for User"}),e.jsx(Vs,{children:"Create a support ticket on behalf of a user. They will be notified about this ticket."})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Select User"}),e.jsxs(Ba,{open:l,onOpenChange:m,modal:!1,children:[e.jsx(za,{asChild:!0,children:e.jsxs(R,{variant:"outline",role:"combobox","aria-expanded":l,className:"w-full justify-between",children:[t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ua,{className:"h-5 w-5",children:[e.jsx(ma,{src:t.avatar_url||void 0}
422),e.jsx(xa,{children:e.jsx(oa,{className:"h-3 w-3"})})]}),e.jsx("span",{children:_(t)}),t.username&&e.jsxs("span",{className:"text-muted-foreground",children:["@",t.username]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Search for a user..."}),e.jsx(dc,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ka,{className:"w-[400px] p-0 z-[1200]",align:"start",onOpenAutoFocus:j=>j.preventDefault(),children:e.jsxs(fd,{shouldFilter:!1,children:[e.jsxs("div",{className:"flex items-center border-b px-3",children:[e.jsx(Rs,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(pe,{placeholder:"Search by name or username...",value:r,onChange:j=>i(j.target.value),className:"h-11 border-0 focus-visible:ring-0 focus-visible:ring-offset-0",autoFocus:!0})]}),e.jsxs(vd,{children:[g&&e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ne,{className:"h-4 w-4 animate-spin"})}),!g&&r.length>=2&&(!x||x.length===0)&&e.jsx(gl,{children:"No users found."}),!g&&r.length<2&&e.jsx(gl,{children:"Type at least 2 characters to search..."}),x&&x.length>0&&e.jsx(yd,{children:x.map(j=>e.jsxs(Nd,{value:j.id,onSelect:()=>{n(j),m(!1),i("")},className:"flex items-center gap-2",children:[e.jsxs(ua,{className:"h-6 w-6",children:[e.jsx(ma,{src:j.avatar_url||void 0}),e.jsx(xa,{children:e.jsx(oa,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"font-medium",children:_(j)}),j.username&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["@",j.username]})]}),e.jsx(Ks,{className:Le("h-4 w-4",(t==null?void 0:t.id)===j.id?"opacity-100":"opacity-0")})]},j.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Category"}),e.jsxs(oe,{value:o,onValueChange:j=>h(j),children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select category"})}),e.jsx(me,{children:_N.map(j=>e.jsx(V,{value:j,children:j},j))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Subject"}),e.jsx(pe,{placeholder:"Enter ticket subject...",value:N,onChange:j=>d(j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Description"}),e.jsx(Xs,{placeholder:"Describe the ticket details...",value:y,onChange:j=>u(j.target.value),rows:4})]})]}),e.jsxs(lt,{children:[e.jsx(R,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(R,{onClick:k,disabled:!b||f.isPending,children:[f.isPending&&e.jsx(ne,{className:"mr-2 h-4 w-4 animate-spin"}),"Create Ticket"]})]})]})})}const wN={New:"bg-blue-500/20 text-blue-400 border-blue-500/30",Open:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30","In Progress":"bg-orange-500/20 text-orange-400 border-orange-500/30",Resolved:"bg-green-500/20 text-green-400 border-green-500/30"},SN=["New","Open","In Progress","Resolved","All"],kN=["New","Open","In Progress","Resolved"],ro=s=>{const a=s.user_profiles;return a!=null&&a.display_name?a.display_name:a!=null&&a.username?a.username:a!=null&&a.full_name?a.full_name:s.user_id?`${s.user_id.slice(0,8)}...`:"Unknown"},CN=()=>{const{data:s,isLoading:a,refetch:t}=$o(),n=Oo(),[r,i]=v.useState(""),[l,m]=v.useState("New"),[o,h]=v.useState("all"),[N,d]=v.useState(null),[y,u]=v.useState(!1),x=v.useMemo(()=>s?s.filter(b=>{const j=b.subject.toLowerCase().includes(r.toLowerCase())||b.description.toLowerCase().includes(r.toLowerCase())||b.category.toLowerCase().includes(r.toLowerCase()),c=l==="All"||b.status===l,p=o==="all"||b.category===o;return j&&c&&p}):[],[s,r,l,o]),g=v.useMemo(()=>s?{All:s.length,New:s.filter(b=>b.status==="New").length,Open:s.filter(b=>b.status==="Open").length,"In Progress":s.filter(b=>b.status==="In Progress").length,Resolved:s.filter(b=>b.status==="Resolved").length}:{All:0,New:0,Open:0,"In Progress":0,Resolved:0},[s]),f=v.useMemo(()=>s?[...new Set(s.map(b=>b.category))]:[],[s]);v.useEffect(()=>{x.length>0&&!x.find(b=>b.id===N)?d(x[0].id):x.length===0&&d(null)},[x,N]);const _=v.useMemo(()=>(s==null?void 0:s.find(b=>b.id===N))||null,[s,N]),k=(b,j)=>{n.mutate({ticketId:b,status:j})};return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"w-8 h-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"All Support Tickets"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{size:"sm",onClick:()=>u(!0),children:[e.jsx(Zs,{className:"w-4 h-4 mr-2"}),"Create Ticket"]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>t(),children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Refresh"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search tickets...",value:r,onChange:b=>i(b.target.value),className:"pl-10"})]}),e.jsxs(oe,{value:o,onValueChange:h,children:[e.jsxs(de,{className:"w-[150px]",children:[e.jsx(Qa,{className:"w-4 h-4 mr-2"}),e.jsx(ue,{placeholder:"Category"})]}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Categories"}),f.map(b=>e.jsx(V,{value:b,children:b},b))]})]})]}),e.jsx(js,{value:l,onValueChange:b=>m(b),children:e.jsx(fs,{className:"w-full justify-start",children:SN.map(b=>e.jsxs(Ne,{value:b,className:"flex items-center gap-2",children:[b,e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:g[b]})]},b))})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-4 min-h-[550px]",children:[e.jsx("div",{className:"lg:col-span-5",children:e.jsx(cs,{className:"h-[550
422px] glassmorphism border border-border/50 rounded-lg",children:e.jsx("div",{className:"p-2 space-y-2",children:x.length===0?e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(Kn,{className:"w-12 h-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No Tickets Found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r||l!=="All"||o!=="all"?"Try adjusting your filters":"No support tickets have been submitted yet"})]}):x.map(b=>e.jsx(PN,{ticket:b,isSelected:b.id===N,onClick:()=>d(b.id)},b.id))})})}),e.jsx("div",{className:"lg:col-span-7",children:e.jsx("div",{className:"glassmorphism border border-border/50 rounded-lg h-[550px] overflow-hidden",children:_?e.jsx(FN,{ticket:_,onStatusChange:k,isUpdating:n.isPending}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"Select a ticket to view details"})})})]}),e.jsx(bN,{open:y,onOpenChange:u})]})},PN=({ticket:s,isSelected:a,onClick:t})=>e.jsxs("button",{onClick:t,className:`w-full text-left p-3 rounded-lg transition-all ${a?"bg-primary/10 border-l-4 border-primary":"hover:bg-muted/50 border-l-4 border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(B,{className:`${wN[s.status]} border text-xs`,children:s.status}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ke(new Date(s.created_at),"M/d/yyyy")})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:s.category}),e.jsx("h4",{className:"font-medium text-sm truncate flex-1",children:s.subject})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:s.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["User: ",ro(s)]})]}),FN=({ticket:s,onStatusChange:a,isUpdating:t})=>e.jsx(cs,{className:"h-full",children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:s.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:s.category}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["ID: ",s.id.slice(0,8),"..."]})]})]}),e.jsxs(oe,{value:s.status,onValueChange:n=>a(s.id,n),disabled:t,children:[e.jsx(de,{className:"w-[140px]",children:e.jsx(ue,{})}),e.jsx(me,{children:kN.map(n=>e.jsx(V,{value:n,children:n},n))})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["User: ",ro(s)]}),e.jsxs("span",{children:["Created: ",ke(new Date(s.created_at),"MMM d, yyyy h:mm a")]}),s.resolved_at&&e.jsxs("span",{children:["Resolved: ",ke(new Date(s.resolved_at),"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{children:[e.jsx("h5",{className:"text-sm font-medium text-muted-foreground mb-2",children:"Description"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-3",children:e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:s.description})})]}),s.screenshot_url&&e.jsxs("div",{children:[e.jsxs("h5",{className:"text-sm font-medium text-muted-foreground mb-2 flex items-center gap-1",children:[e.jsx(Ot,{className:"w-4 h-4"}),"Attached Screenshot"]}),e.jsx("a",{href:s.screenshot_url,target:"_blank",rel:"noopener noreferrer",className:"inline-block",children:e.jsx("img",{src:s.screenshot_url,alt:"Ticket attachment",className:"max-w-full max-h-48 rounded-lg border border-border/50 hover:border-primary/50 transition-colors"})})]}),s.admin_response&&e.jsxs("div",{className:"bg-primary/10 border border-primary/20 rounded-lg p-4",children:[e.jsx("h5",{className:"text-sm font-medium text-primary mb-2",children:"Previous Response"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:s.admin_response})]}),e.jsx("div",{className:"border-t border-border/50 pt-4",children:e.jsx(Uo,{ticketId:s.id,isAdmin:!0})})]})});function AN(){return ge({queryKey:["admin-faqs"],queryFn:async()=>{const{data:s,error:a}=await T.rpc("admin_list_support_faqs");if(a)throw a;return s}})}function TN(){const s=Me();return _e({mutationFn:async a=>{const{data:t,error:n}=await T.rpc("admin_upsert_support_faq",{_id:null,_category:a.category,_question:a.question,_answer:a.answer,_display_order:a.display_order,_is_active:a.is_active});if(n)throw n;if(!t)throw new Error("No row returned after create");return t},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-faqs"]}),s.invalidateQueries({queryKey:["support-faqs"]}),K.success("FAQ created successfully")},onError:a=>{K.error(`Failed to create FAQ: ${a.message}`)}})}function LN(){const s=Me();return _e({mutationFn:async({id:a,...t})=>{const{data:n,error:r}=await T.rpc("admin_upsert_support_faq",{_id:a,_category:t.category??"",_question:t.question??"",_answer:t.answer??"",_display_order:t.display_order??1,_is_active:t.is_active??!0});if(r)throw r;if(!n)throw new Error("No row returned after update");return n},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-faqs"]}),s.invalidateQueries({queryKey:["support-faqs"]}),K.success("FAQ updated successfully")},onError:a=>{K.error(`Failed to update FAQ: ${a.message}`)}})}function EN(){const s=Me();return _e({mutationFn:async a=>{const{error:t}=await T.rpc("admin_delete_support_faq",{_id:a});if(t)throw t},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-faqs"]}),s.invalidateQueries({queryKey:["support-faqs"]}),K.success("FAQ deleted successfully")},onError:a=>{K.error(`Failed to delete FAQ: ${a.message}`)}})}const Ti=["AI","ACCOUNT","BETTING","DFS","SUBSCRIPTION","GENERAL"],DN=()=>{const{data:s,isLoading:a,refetch:t}=AN(),n=TN(),r=LN(),i=EN(),[l,m]=v.useState(""),[o,h]=v.useState("all"),[N,d]=v.useState("all"),[y,u]=v.useState(null),[x,g]=v.useState(!1),[f,_]=v.useState(!1),[k,b]=v.useState(""),[j,c]=v.useState(""),[p,w]=v.useState(""),[S,P]=v.useState(1),[C,O]=v.useState(!0),$=v.useMemo(()=>s?s.filter(ie=>{const Y=ie.question.toLowerCase().includes(l.toLowerCase())||ie.answer.toLowerCase().includes(l.toLowerCase())||ie.category.toLowerCase().includes(l.toLowerCase()),I=o==="all"||o==="active"&&ie.is_active||o==="inactive"&&!ie.is_active,ee=N==="all"||ie.category===N;return Y&&I&&ee}):[],[s,l,o,N]),z=v.useMemo(()=>s?{all:s.length,active:s.filter(ie=>ie.is_active).length,inactive:s.filter(ie=>!ie.is_active).length}:{all:0,active:0,inactive:0},[s]),D=v.useMemo(()=>s?[...new Set(s.map(ie=>ie.category))]:[],[s]),A=v.useMemo(()=>[...new Set([...Ti,...D])].sort(),[D]),F=v.useMemo(()=>x?null:(s==null?void 0:s.find(ie=>ie.id===y))||null,[s,y,x]);v.useEffect(()=>{F?(b(F.category),c(F.question),w(F.answer),P(F.display_order),O(F.is_active)):x&&(b(Ti[0]),c(""),w(""),P(1),O(!0))},[F,x]),v.useEffect(()=>{$.length>0&&!x&&!$.find(ie=>ie.id===y)?u($[0].id):$.length===0&&!x&&u(null)},[$,y,x]);const q=()=>{g(!0),u(null)},E=()=>{g(!1),$.length>0&&u($[0].id)},L=async()=>{!k||!j||!p||(x?(await n.mutateAsync({category:k,question:j,answer:p,display_order:S,is_active:C}),g(!1)):y&&await r.mutateAsync({id:y,category:k,question:j,answer:p,display_order:S,is_active:C}))},H=async()=>{y&&(await i.mutateAsync(y),u(null),_(!1))},Z=ie=>{g(!1),u(ie)},se=n.isPending||r.isPending;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"w-8 h-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"FAQs Management"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>t(),children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Refresh"]}),e.jsxs(R,{size:"sm",onClick:q,disabled:x,children:[e.jsx(Zs,{className:"w-4 h-4 mr-2"}),"Add FAQ"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}
422),e.jsx(pe,{placeholder:"Search FAQs...",value:l,onChange:ie=>m(ie.target.value),className:"pl-10"})]}),e.jsxs(oe,{value:N,onValueChange:d,children:[e.jsxs(de,{className:"w-[150px]",children:[e.jsx(Qa,{className:"w-4 h-4 mr-2"}),e.jsx(ue,{placeholder:"Category"})]}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Categories"}),A.map(ie=>e.jsx(V,{value:ie,children:ie},ie))]})]})]}),e.jsx(js,{value:o,onValueChange:ie=>h(ie),children:e.jsxs(fs,{className:"w-full justify-start",children:[e.jsxs(Ne,{value:"all",className:"flex items-center gap-2",children:["All",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:z.all})]}),e.jsxs(Ne,{value:"active",className:"flex items-center gap-2",children:["Active",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:z.active})]}),e.jsxs(Ne,{value:"inactive",className:"flex items-center gap-2",children:["Inactive",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:z.inactive})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-4 min-h-[550px]",children:[e.jsx("div",{className:"lg:col-span-5",children:e.jsx(cs,{className:"h-[550px] glassmorphism border border-border/50 rounded-lg",children:e.jsx("div",{className:"p-2 space-y-2",children:$.length===0?e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(Ui,{className:"w-12 h-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No FAQs Found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l||o!=="all"||N!=="all"?"Try adjusting your filters":"No FAQs have been created yet"})]}):$.map(ie=>e.jsx(MN,{faq:ie,isSelected:ie.id===y&&!x,onClick:()=>Z(ie.id)},ie.id))})})}),e.jsx("div",{className:"lg:col-span-7",children:e.jsx("div",{className:"glassmorphism border border-border/50 rounded-lg h-[550px] overflow-hidden",children:x||F?e.jsx(cs,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-lg font-semibold",children:x?"Add New FAQ":"Edit FAQ"}),x&&e.jsx(R,{variant:"ghost",size:"sm",onClick:E,children:"Cancel"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"category",children:"Category"}),e.jsxs(oe,{value:k,onValueChange:b,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select category"})}),e.jsx(me,{children:A.map(ie=>e.jsx(V,{value:ie,children:ie},ie))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"question",children:"Question"}),e.jsx(pe,{id:"question",value:j,onChange:ie=>c(ie.target.value),placeholder:"Enter the FAQ question..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"answer",children:"Answer"}),e.jsx(Xs,{id:"answer",value:p,onChange:ie=>w(ie.target.value),placeholder:"Enter the FAQ answer...",className:"min-h-[150px]"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"order",children:"Display Order"}),e.jsx(pe,{id:"order",type:"number",min:1,value:S,onChange:ie=>P(parseInt(ie.target.value)||1)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Status"}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(Ge,{id:"active",checked:C,onCheckedChange:O}),e.jsx(Q,{htmlFor:"active",className:"text-sm font-normal",children:C?e.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[e.jsx(us,{className:"w-4 h-4"})," Active"]}):e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ht,{className:"w-4 h-4"})," Inactive"]})})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-border/50",children:[!x&&e.jsxs(R,{variant:"destructive",size:"sm",onClick:()=>_(!0),children:[e.jsx(os,{className:"w-4 h-4 mr-2"}),"Delete FAQ"]}),e.jsx("div",{className:x?"ml-auto":"",children:e.jsxs(R,{onClick:L,disabled:se||!j||!p,children:[se?e.jsx(ne,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(It,{className:"w-4 h-4 mr-2"}),x?"Create FAQ":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"Select a FAQ to edit or add a new one"})})})]}),e.jsx(ws,{open:f,onOpenChange:_,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete FAQ?"}),e.jsx(Ps,{children:"This action cannot be undone. This will permanently delete this FAQ."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:H,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})},MN=({faq:s,isSelected:a,onClick:t})=>e.jsxs("button",{onClick:t,className:`w-full text-left p-3 rounded-lg transition-all ${a?"bg-primary/10 border-l-4 border-primary":"hover:bg-muted/50 border-l-4 border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:s.category}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Order: ",s.display_order]}),s.is_active?e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500",title:"Active"}):e.jsx("span",{className:"w-2 h-2 rounded-full bg-muted-foreground",title:"Inactive"})]})]}),e.jsx("h4",{className:"font-medium text-sm line-clamp-2",children:s.question}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1 mt-1",children:s.answer})]});async function IN(s,a){var m;const t=((m=s.name.split(".").pop())==null?void 0:m.toLowerCase())||"mp4",r=`howtos/${`howto-${a}-${Date.now()}.${t}`}`,{error:i}=await T.storage.from("support-videos").upload(r,s,{cacheControl:"3600",upsert:!1});if(i)throw new Error(`Failed to upload video: ${i.message}`);const{data:l}=T.storage.from("support-videos").getPublicUrl(r);return{url:l.publicUrl,path:r}}async function RN(s){try{const t=new URL(s).pathname.match(/support-videos\/(.+)$/);if(!t)return!1;const n=t[1],{error:r}=await T.storage.from("support-videos").remove([n]);return r?(console.error("Failed to delete video:",r),!1):!0}catch(a){return console.error("Error deleting video:",a),!1}}const qN=500*1024*1024,$N={"video/mp4":[".mp4"],"video/webm":[".webm"],"video/quicktime":[".mov"],"video/x-msvideo":[".avi"],"video/mpeg":[".mpeg",".mpg"]};function ON({value:s,onChange:a,howToId:t}){const[n,r]=v.useState(!1),[i,l]=v.useState(!1),[m,o]=v.useState(""),h=v.useCallback(async f=>{const _=f[0];if(_){if(_.size>qN){K.error("File too large",{description:"Maximum file size is 500MB"});return}r(!0);try{const k=await IN(_,t);a(k.url),K.success("Video uploaded successfully")}catch(k){console.error("Upload error:",k),K.error("Failed to upload video",{description:k instanceof Error?k.message:"Unknown error"})}finally{r(!1)}}},[t,a]),{getRootProps:N,getInputProps:d,isDragActive:y}=sl({onDrop:h,accept:$N,maxFiles:1,disabled:n}),u=async()=>{s&&(s.includes("support-videos")&&await RN(s),a(null),K.success("Video removed"))},x=()=>{m.trim()&&(a(m.trim()),o(""),l(!1),K.success("Video URL added"))},g=!!s;return e.jsx("div",{className:"space-y-3",children:g?e.jsx("div",{className:"relative rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0 p-3 rounded-lg bg-primary/10",children:e.jsx(kr,{className:"w-8 h-8 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:"Video attached"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-1",children:s}),e.jsx("div",{className:"mt-3",children:e.jsx("video",{src:s,controls:!0,className:"max-h-[200px] rounded-md bg-black",preload:"metadata"})})]}),e.jsx(R,{variant:"ghost",size:"icon",className:"flex-shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:u,children:e.jsx(rt,{className:"w-4 h-4"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{...N(),className:`
423              relative border-2 border-dashed rounded-lg p-8 text-center cursor-pointer
424              transition-colors duration-200
425              ${y?"border-primary bg-primary/5":"border-border hover:border-primary/50"}
426              ${n?"pointer-events-none opacity-60":""}
427            `,children:[e.jsx("input",{...d()}),n?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(ne,{className:"w-10 h-10 text-primary animate-spin"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This may take a moment"})]}):e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(fa,{className:"w-10 h-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:y?"Drop the video here":"Drag & drop a video"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"or click to browse"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"MP4, WebM, MOV, AVI, MPEG • Max 500MB"})]})]}),e.jsx("div",{className:"flex items-center justify-center",children:e.jsxs(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l(!i),className:"text-xs text-muted-foreground",children:[e.jsx(Xn,{className:"w-3 h-3 mr-1"}),i?"Hide URL input":"Or enter URL manually"]})}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:m,onChange:f=>o(f.target.value),placeholder:"Enter video URL...",className:"flex-1"}),e.jsx(R,{type:"button",variant:"secondary",onClick:x,disabled:!m.trim(),children:"Add"})]})]})})}function UN(){return ge({queryKey:["admin-how-tos"],queryFn:async()=>{const{data:s,error:a}=await T.from("support_how_tos").select("*").order("display_order",{ascending:!0});if(a)throw a;return s}})}function BN(){const s=Me();return _e({mutationFn:async a=>{const{data:t,error:n}=await T.from("support_how_tos").insert({category:a.category,title:a.title,de
427scription:a.description,video_url:a.video_url,display_order:a.display_order,is_active:a.is_active}).select().single();if(n)throw n;return t},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-how-tos"]}),s.invalidateQueries({queryKey:["support-how-tos"]}),K.success("How To created successfully")},onError:()=>{K.error("Failed to create How To")}})}function zN(){const s=Me();return _e({mutationFn:async({id:a,...t})=>{const{data:n,error:r}=await T.from("support_how_tos").update({...t,updated_at:new Date().toISOString()}).eq("id",a).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-how-tos"]}),s.invalidateQueries({queryKey:["support-how-tos"]}),K.success("How To updated successfully")},onError:()=>{K.error("Failed to update How To")}})}function KN(){const s=Me();return _e({mutationFn:async a=>{const{error:t}=await T.from("support_how_tos").delete().eq("id",a);if(t)throw t},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-how-tos"]}),s.invalidateQueries({queryKey:["support-how-tos"]}),K.success("How To deleted successfully")},onError:()=>{K.error("Failed to delete How To")}})}const Li=["AI","PLATFORM","BETTING","DFS","ACCOUNT","GENERAL"],VN=()=>{const{data:s,isLoading:a,refetch:t}=UN(),n=BN(),r=zN(),i=KN(),[l,m]=v.useState(""),[o,h]=v.useState("all"),[N,d]=v.useState("all"),[y,u]=v.useState(null),[x,g]=v.useState(!1),[f,_]=v.useState(!1),[k,b]=v.useState(""),[j,c]=v.useState(""),[p,w]=v.useState(""),[S,P]=v.useState(""),[C,O]=v.useState(1),[$,z]=v.useState(!0),D=v.useMemo(()=>s?s.filter(I=>{const ee=I.title.toLowerCase().includes(l.toLowerCase())||I.description.toLowerCase().includes(l.toLowerCase())||I.category.toLowerCase().includes(l.toLowerCase()),le=o==="all"||o==="active"&&I.is_active||o==="inactive"&&!I.is_active,ve=N==="all"||I.category===N;return ee&&le&&ve}):[],[s,l,o,N]),A=v.useMemo(()=>s?{all:s.length,active:s.filter(I=>I.is_active).length,inactive:s.filter(I=>!I.is_active).length}:{all:0,active:0,inactive:0},[s]),F=v.useMemo(()=>s?[...new Set(s.map(I=>I.category))]:[],[s]),q=v.useMemo(()=>[...new Set([...Li,...F])].sort(),[F]),E=v.useMemo(()=>x?null:(s==null?void 0:s.find(I=>I.id===y))||null,[s,y,x]);v.useEffect(()=>{E?(b(E.category),c(E.title),w(E.description),P(E.video_url||""),O(E.display_order),z(E.is_active)):x&&(b(Li[0]),c(""),w(""),P(""),O(1),z(!0))},[E,x]),v.useEffect(()=>{D.length>0&&!x&&!D.find(I=>I.id===y)?u(D[0].id):D.length===0&&!x&&u(null)},[D,y,x]);const L=()=>{g(!0),u(null)},H=()=>{g(!1),D.length>0&&u(D[0].id)},Z=async()=>{!k||!j||!p||(x?(await n.mutateAsync({category:k,title:j,description:p,video_url:S||null,display_order:C,is_active:$}),g(!1)):y&&await r.mutateAsync({id:y,category:k,title:j,description:p,video_url:S||null,display_order:C,is_active:$}))},se=async()=>{y&&(await i.mutateAsync(y),u(null),_(!1))},ie=I=>{g(!1),u(I)},Y=n.isPending||r.isPending;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"w-8 h-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"How To Management"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>t(),children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Refresh"]}),e.jsxs(R,{size:"sm",onClick:L,disabled:x,children:[e.jsx(Zs,{className:"w-4 h-4 mr-2"}),"Add How To"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search how-tos...",value:l,onChange:I=>m(I.target.value),className:"pl-10"})]}),e.jsxs(oe,{value:N,onValueChange:d,children:[e.jsxs(de,{className:"w-[150px]",children:[e.jsx(Qa,{className:"w-4 h-4 mr-2"}),e.jsx(ue,{placeholder:"Category"})]}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Categories"}),q.map(I=>e.jsx(V,{value:I,children:I},I))]})]})]}),e.jsx(js,{value:o,onValueChange:I=>h(I),children:e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"all",className:"flex items-center gap-2",children:["All",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:A.all})]}),e.jsxs(Ne,{value:"active",className:"flex items-center gap-2",children:["Active",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:A.active})]}),e.jsxs(Ne,{value:"inactive",className:"flex items-center gap-2",children:["Inactive",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:A.inactive})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-4 min-h-[550px]",children:[e.jsx("div",{className:"lg:col-span-5",children:e.jsx(cs,{className:"h-[550
427px] glassmorphism border border-border/50 rounded-lg",children:e.jsx("div",{className:"p-2 space-y-2",children:D.length===0?e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(rn,{className:"w-12 h-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No How Tos Found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l||o!=="all"||N!=="all"?"Try adjusting your filters":"No how-to videos have been created yet"})]}):D.map(I=>e.jsx(HN,{howTo:I,isSelected:I.id===y&&!x,onClick:()=>ie(I.id)},I.id))})})}),e.jsx("div",{className:"lg:col-span-7",children:e.jsx("div",{className:"glassmorphism border border-border/50 rounded-lg h-[550px] overflow-hidden",children:x||E?e.jsx(cs,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-lg font-semibold",children:x?"Add New How To":"Edit How To"}),x&&e.jsx(R,{variant:"ghost",size:"sm",onClick:H,children:"Cancel"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"category",children:"Category"}),e.jsxs(oe,{value:k,onValueChange:b,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select category"})}),e.jsx(me,{children:q.map(I=>e.jsx(V,{value:I,children:I},I))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",value:j,onChange:I=>c(I.target.value),placeholder:"Enter the how-to title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"description",children:"Description"}),e.jsx(Xs,{id:"description",value:p,onChange:I=>w(I.target.value),placeholder:"Enter the how-to description...",className:"min-h-[100px]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Video"}),e.jsx(ON,{value:S||null,onChange:I=>P(I||""),howToId:y||"new"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"order",children:"Display Order"}),e.jsx(pe,{id:"order",type:"number",min:1,value:C,onChange:I=>O(parseInt(I.target.value)||1)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Status"}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(Ge,{id:"active",checked:$,onCheckedChange:z}),e.jsx(Q,{htmlFor:"active",className:"text-sm font-normal",children:$?e.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[e.jsx(us,{className:"w-4 h-4"})," Active"]}):e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ht,{className:"w-4 h-4"})," Inactive"]})})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-border/50",children:[!x&&e.jsxs(R,{variant:"destructive",size:"sm",onClick:()=>_(!0),children:[e.jsx(os,{className:"w-4 h-4 mr-2"}),"Delete How To"]}),e.jsx("div",{className:x?"ml-auto":"",children:e.jsxs(R,{onClick:Z,disabled:Y||!j||!p,children:[Y?e.jsx(ne,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(It,{className:"w-4 h-4 mr-2"}),x?"Create How To":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"Select a how-to to edit or add a new one"})})})]}),e.jsx(ws,{open:f,onOpenChange:_,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete How To?"}),e.jsx(Ps,{children:"This action cannot be undone. This will permanently delete this how-to video."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:se,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})},HN=({howTo:s,isSelected:a,onClick:t})=>e.jsxs("button",{onClick:t,className:`w-full text-left p-3 rounded-lg transition-all ${a?"bg-primary/10 border-l-4 border-primary":"hover:bg-muted/50 border-l-4 border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:s.category}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(us,{className:"w-3 h-3"})," ",s.view_count]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Order: ",s.display_order]}),s.is_active?e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500",title:"Active"}):e.jsx("span",{className:"w-2 h-2 rounded-full bg-muted-foreground",title:"Inactive"})]})]}),e.jsx("h4",{className:"font-medium text-sm line-clamp-2",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1 mt-1",children:s.description}),s.video_url&&e.jsxs("div",{className:"flex items-center gap-1 mt-1 text-xs text-primary",children:[e.jsx(rn,{className:"w-3 h-3"}),e.jsx("span",{children:"Has video"})]})]});function WN(){return ge({queryKey:["admin-version-logs"],queryFn:async()=>{const{data:s,error:a}=await T.from("support_version_logs").select("*").order("released_at",{ascending:!1});if(a)throw a;return s}})}function GN(){const s=Me();return _e({mutationFn:async a=>{const{data:t,error:n}=await T.from("support_version_logs").insert({category:a.category,version_number:a.version_number,version_name:a.version_name,release_notes:a.release_notes,released_at:a.released_at,is_active:a.is_active}).select().single();if(n)throw n;return t},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-version-logs"]}),s.invalidateQueries({queryKey:["support-version-logs"]}),K.success("Version log created successfully")},onError:()=>{K.error("Failed to create version log")}})}function QN(){const s=Me();return _e({mutationFn:async({id:a,...t})=>{const{data:n,error:r}=await T.from("support_version_logs").update(t).eq("id",a).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-version-logs"]}),s.invalidateQueries({queryKey:["support-version-logs"]}),K.success("Version log updated successfully")},onError:()=>{K.error("Failed to update version log")}})}function YN(){const s=Me();return _e({mutationFn:async a=>{const{error:t}=await T.from("support_version_logs").delete().eq("id",a);if(t)throw t},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-version-logs"]}),s.invalidateQueries({queryKey:["support-version-logs"]}),K.success("Version log deleted successfully")},onError:()=>{K.error("Failed to delete version log")}})}const Ei=["PLATFORM","AI","DFS","PROPS","FEATURES","INTEGRATIONS","BUGFIXES"],JN=()=>{const{data:s,isLoading:a,refetch:t}=WN(),n=GN(),r=QN(),i=YN(),[l,m]=v.useState(""),[o,h]=v.useState("all"),[N,d]=v.useState("all"),[y,u]=v.useState(null),[x,g]=v.useState(!1),[f,_]=v.useState(!1),[k,b]=v.useState(""),[j,c]=v.useState(""),[p,w]=v.useState(""),[S,P]=v.useState(""),[C,O]=v.useState(""),[$,z]=v.useState(!0),D=v.useMemo(()=>s?s.filter(I=>{var te;const ee=I.version_number.toLowerCase().includes(l.toLowerCase())||(((te=I.version_name)==null?void 0:te.toLowerCase().includes(l.toLowerCase()))??!1)||I.release_notes.toLowerCase().includes(l.toLowerCase())||I.category.toLowerCase().includes(l.toLowerCase()),le=o==="all"||o==="active"&&I.is_active||o==="inactive"&&!I.is_active,ve=N==="all"||I.category===N;return ee&&le&&ve}):[],[s,l,o,N]),A=v.useMemo(()=>s?{all:s.length,active:s.filter(I=>I.is_active).length,inactive:s.filter(I=>!I.is_active).length}:{all:0,active:0,inactive:0},[s]),F=v.useMemo(()=>s?[...new Set(s.map(I=>I.category))]:[],[s]),q=v.useMemo(()=>[...new Set([...Ei,...F])].sort(),[F]),E=v.useMemo(()=>x?null:(s==null?void 0:s.find(I=>I.id===y))||null,[s,y,x]);v.useEffect(()=>{E?(b(E.category),c(E.version_number),w(E.version_name||""),P(E.release_notes),O(E.released_at.split("T")[0]),z(E.is_active)):x&&(b(Ei[0]),c(""),w(""),P(""),O(new Date().toISOString().split("T")[0]),z(!0))},[E,x]),v.useEffect(()=>{D.length>0&&!x&&!D.find(I=>I.id===y)?u(D[0].id):D.length===0&&!x&&u(null)},[D,y,x]);const L=()=>{g(!0),u(null)},H=()=>{g(!1),D.length>0&&u(D[0].id)},Z=async()=>{!k||!j||!S||!C||(x?(await n.mutateAsync({category:k,version_number:j,version_name:p||null,release_notes:S,released_at:new Date(C).toISOString(),is_active:$}),g(!1)):y&&await r.mutateAsync({id:y,category:k,version_number:j,version_name:p||null,release_notes:S,released_at:new Date(C).toISOString(),is_active:$}))},se=async()=>{y&&(await i.mutateAsync(y),u(null),_(!1))},ie=I=>{g(!1),u(I)},Y=n.isPending||r.isPending;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"w-8 h-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"Versions Management"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:()=>t(),children:[e.jsx(He,{className:"w-4 h-4 mr-2"}),"Refresh"]}),e.jsxs(R,{size:"sm",onClick:L,disabled:x,children:[e.jsx(Zs,{className:"w-4 h-4 mr-2"}),"Add Version"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}
427),e.jsx(pe,{placeholder:"Search versions...",value:l,onChange:I=>m(I.target.value),className:"pl-10"})]}),e.jsxs(oe,{value:N,onValueChange:d,children:[e.jsxs(de,{className:"w-[150px]",children:[e.jsx(Qa,{className:"w-4 h-4 mr-2"}),e.jsx(ue,{placeholder:"Category"})]}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Categories"}),q.map(I=>e.jsx(V,{value:I,children:I},I))]})]})]}),e.jsx(js,{value:o,onValueChange:I=>h(I),children:e.jsxs(fs,{className:"w-full justify-start",children:[e.jsxs(Ne,{value:"all",className:"flex items-center gap-2",children:["All",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:A.all})]}),e.jsxs(Ne,{value:"active",className:"flex items-center gap-2",children:["Active",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:A.active})]}),e.jsxs(Ne,{value:"inactive",className:"flex items-center gap-2",children:["Inactive",e.jsx(B,{variant:"secondary",className:"text-xs px-1.5 py-0.5 h-5",children:A.inactive})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-4 min-h-[550px]",children:[e.jsx("div",{className:"lg:col-span-5",children:e.jsx(cs,{className:"h-[550px] glassmorphism border border-border/50 rounded-lg",children:e.jsx("div",{className:"p-2 space-y-2",children:D.length===0?e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(Pt,{className:"w-12 h-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No Versions Found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l||o!=="all"||N!=="all"?"Try adjusting your filters":"No version logs have been created yet"})]}):D.map(I=>e.jsx(ZN,{version:I,isSelected:I.id===y&&!x,onClick:()=>ie(I.id)},I.id))})})}),e.jsx("div",{className:"lg:col-span-7",children:e.jsx("div",{className:"glassmorphism border border-border/50 rounded-lg h-[550px] overflow-hidden",children:x||E?e.jsx(cs,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-lg font-semibold",children:x?"Add New Version":"Edit Version"}),x&&e.jsx(R,{variant:"ghost",size:"sm",onClick:H,children:"Cancel"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"category",children:"Category"}),e.jsxs(oe,{value:k,onValueChange:b,children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select category"})}),e.jsx(me,{children:q.map(I=>e.jsx(V,{value:I,children:I},I))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"versionNumber",children:"Version Number *"}),e.jsx(pe,{id:"versionNumber",value:j,onChange:I=>c(I.target.value),placeholder:"e.g., 1.2.0"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"versionName",children:"Version Name (optional)"}),e.jsx(pe,{id:"versionName",value:p,onChange:I=>w(I.target.value),placeholder:"e.g., Spring Update"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"releaseNotes",children:"Release Notes *"}),e.jsx(Xs,{id:"releaseNotes",value:S,onChange:I=>P(I.target.value),placeholder:"Enter the release notes...",className:"min-h-[150px]"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{htmlFor:"releasedAt",children:"Release Date *"}),e.jsx(pe,{id:"releasedAt",type:"date",value:C,onChange:I=>O(I.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Status"}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(Ge,{id:"active",checked:$,onCheckedChange:z}),e.jsx(Q,{htmlFor:"active",className:"text-sm font-normal",children:$?e.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[e.jsx(us,{className:"w-4 h-4"})," Active"]}):e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ht,{className:"w-4 h-4"})," Inactive"]})})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-border/50",children:[!x&&e.jsxs(R,{variant:"destructive",size:"sm",onClick:()=>_(!0),children:[e.jsx(os,{className:"w-4 h-4 mr-2"}),"Delete Version"]}),e.jsx("div",{className:x?"ml-auto":"",children:e.jsxs(R,{onClick:Z,disabled:Y||!j||!S||!C,children:[Y?e.jsx(ne,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(It,{className:"w-4 h-4 mr-2"}),x?"Create Version":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"Select a ver
427sion to edit or add a new one"})})})]}),e.jsx(ws,{open:f,onOpenChange:_,children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Version?"}),e.jsx(Ps,{children:"This action cannot be undone. This will permanently delete this version log."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:se,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})},ZN=({version:s,isSelected:a,onClick:t})=>e.jsxs("button",{onClick:t,className:`w-full text-left p-3 rounded-lg transition-all ${a?"bg-primary/10 border-l-4 border-primary":"hover:bg-muted/50 border-l-4 border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(B,{variant:"outline",className:"text-xs",children:s.category}),e.jsx("div",{className:"flex items-center gap-2",children:s.is_active?e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500",title:"Active"}):e.jsx("span",{className:"w-2 h-2 rounded-full bg-muted-foreground",title:"Inactive"})})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("h4",{className:"font-medium text-sm",children:["v",s.version_number]}),s.version_name&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["- ",s.version_name]})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:s.release_notes}),e.jsxs("div",{className:"flex items-center gap-1 mt-1 text-xs text-muted-foreground",children:[e.jsx(xt,{className:"w-3 h-3"}),e.jsx("span",{children:ke(new Date(s.released_at),"MMM d, yyyy")})]})]}),XN={hours_of_operation:{label:"Hours of Operation",description:"Business hours displayed to users",multiline:!0},response_time:{label:"Response Time",description:"Expected response time message",multiline:!1},contact_email:{label:"Contact Email",description:"Support email address",multiline:!1},contact_phone:{label:"Contact Phone",description:"Support phone number",multiline:!1},live_support_url:{label:"Live Support URL",description:"Link to live chat/support (leave empty to hide)",multiline:!1},before_contacting_steps:{label:"Before Contacting Support",description:"Steps users should take before contacting (one per line)",multiline:!0}},e_=()=>{const{data:s,isLoading:a}=Bo(),t=zo(),[n,r]=v.useState({}),[i,l]=v.useState(!1);v.useEffect(()=>{if(s){const N={};s.forEach(d=>{N[d.key]=d.value}),r(N)}},[s]);const m=(N,d)=>{r(y=>({...y,[N]:d})),l(!0)},o=async N=>{await t.mutateAsync({key:N,value:n[N]}),l(!1)},h=async()=>{var N;for(const[d,y]of Object.entries(n))((N=s==null?void 0:s.find(x=>x.key===d))==null?void 0:N.value)!==y&&await t.mutateAsync({key:d,value:y});l(!1)};return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"w-8 h-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Support Information"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the information displayed on the Contact Support page"})]}),e.jsxs(R,{onClick:h,disabled:!i||t.isPending,children:[t.isPending?e.jsx(ne,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(It,{className:"w-4 h-4 mr-2"}),"Save All Changes"]})]}),e.jsx("div",{className:"grid gap-6",children:Object.entries(XN).map(([N,d])=>{var y;return e.jsxs("div",{className:"glassmorphism border border-border/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Q,{className:"text-base font-medium",children:d.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.description})]}),e.jsxs(R,{size:"sm",variant:"outline",onClick:()=>o(N),disabled:n[N]===((y=s==null?void 0:s.find(u=>u.key===N))==null?void 0:y.value)||t.isPending,children:[e.jsx(It,{className:"w-3 h-3 mr-1"}),"Save"]})]}),d.multiline?e.jsx(Xs,{value:n[N]||"",onChange:u=>m(N,u.target.value),rows:4,placeholder:`Enter ${d.label.toLowerCase()}...`}):e.jsx(pe,{value:n[N]||"",onChange:u=>m(N,u.target.value),placeholder:`Enter ${d.label.toLowerCase()}...`})]},N)})}),e.jsxs("div",{className:"glassmorphism border border-primary/30 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Ys,{className:"w-5 h-5 text-primary"}),e.jsx("h4",{className:"font-semibold",children:"Preview"})]}),!n.hours_of_operation&&!n.response_time&&!n.contact_email&&!n.contact_phone?e.jsx("p",{className:"text-muted-foreground text-sm italic",children:"No support information configured yet."}):e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[n.hours_of_operation&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Hours:"}),e.jsx("p",{className:"whitespace-pre-line",children:n.hours_of_operation})]}),n.response_time&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Response Time:"}),e.jsx("p",{children:n.response_time})]}),n.contact_email&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Email:"}),e.jsx("p",{children:n.contact_email})]}),n.contact_phone&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Phone:"}),e.jsx("p",{children:n.contact_phone})]})]})]})]})},Ir=[{value:"request",label:"Request"},{value:"planned",label:"Planned"},{value:"in_progress",label:"In Progress"},{value:"completed",label:"Completed"}],s_=["AI Assistant","Settings","Flows","Marketing","Tasks","AI Tools","Kontent","Support","Notes","Conversations","Contacts","Calendar","Other"],t_={request:"bg-purple-500/20 text-purple-400 border-purple-500/30",planned:"bg-blue-500/20 text-blue-400 border-blue-500/30",in_progress:"bg-orange-500/20 text-orange-400 border-orange-500/30",completed:"bg-green-500/20 text-green-400 border-green-500/30"},a_=()=>{const{data:s,isLoading:a,refetch:t}=Ko(),[n,r]=v.useState(!1),[i,l]=v.useState(null),[m,o]=v.useState(null),[h,N]=v.useState("all"),[d,y]=v.useState({category:"",stage:"request",title:"",description:"",planned_date:"",goal_date:"",completed_date:""}),u=()=>{y({category:"",stage:"request",title:"",description:"",planned_date:"",goal_date:"",completed_date:""}),l(null)},x=b=>
427{l(b),y({category:b.category,stage:b.stage,title:b.title,description:b.description,planned_date:b.planned_date||"",goal_date:b.goal_date||"",completed_date:b.completed_date||""}),r(!0)},g=async()=>{try{if(i){const{error:b}=await T.from("support_roadmap_items").update({category:d.category,stage:d.stage,title:d.title,description:d.description,planned_date:d.planned_date||null,goal_date:d.goal_date||null,completed_date:d.completed_date||null}).eq("id",i.id);if(b)throw b;K.success("Roadmap item updated")}else{const{error:b}=await T.from("support_roadmap_items").insert({category:d.category,stage:d.stage,title:d.title,description:d.description,planned_date:d.planned_date||null,goal_date:d.goal_date||null,completed_date:d.completed_date||null});if(b)throw b;K.success("Roadmap item created")}r(!1),u(),t()}catch(b){console.error(b),K.error("Failed to save roadmap item")}},f=async b=>{if(confirm("Are you sure you want to delete this item?"))try{const{error:j}=await T.from("support_roadmap_items").delete().eq("id",b);if(j)throw j;K.success("Item deleted"),t()}catch{K.error("Failed to delete item")}},_=async(b,j)=>{try{const c={stage:j};j==="completed"&&(c.completed_date=new Date().toISOString().split("T")[0]);const{error:p}=await T.from("support_roadmap_items").update(c).eq("id",b);if(p)throw p;K.success("Stage updated"),t()}catch{K.error("Failed to update stage")}},k=s==null?void 0:s.filter(b=>h==="all"||b.stage===h);return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"w-8 h-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(oe,{value:h,onValueChange:N,children:[e.jsx(de,{className:"w-[180px]",children:e.jsx(ue,{placeholder:"Filter by stage"})}),e.jsxs(me,{children:[e.jsx(V,{value:"all",children:"All Stages"}),Ir.map(b=>e.jsx(V,{value:b.value,children:b.label},b.value))]})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[(k==null?void 0:k.length)||0," items"]})]}),e.jsxs(Ue,{open:n,onOpenChange:b=>{r(b),b||u()},children:[e.jsx(Ao,{asChild:!0,children:e.jsxs(R,{children:[e.jsx(Zs,{className:"w-4 h-4 mr-2"}),"Add Item"]})}),e.jsxs(Be,{className:"max-w-lg",children:[e.jsx(ze,{children:e.jsxs(Ke,{children:[i?"Edit":"Add"," Roadmap Item"]})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Category"}),e.jsxs(oe,{value:d.category,onValueChange:b=>y(j=>({...j,category:b})),children:[e.jsx(de,{children:e.jsx(ue,{placeholder:"Select category"})}),e.jsx(me,{children:s_.map(b=>e.jsx(V,{value:b,children:b},b))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Stage"}),e.jsxs(oe,{value:d.stage,onValueChange:b=>y(j=>({...j,stage:b})),children:[e.jsx(de,{children:e.jsx(ue,{})}),e.jsx(me,{children:Ir.map(b=>e.jsx(V,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Title"}),e.jsx(pe,{value:d.title,onChange:b=>y(j=>({...j,title:b.target.value})),placeholder:"Feature title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Description"}),e.jsx(Xs,{value:d.description,onChange:b=>y(j=>({...j,description:b.target.value})),placeholder:"Describe the feature...",rows:4})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Planned Date"}),e.jsx(pe,{type:"date",value:d.planned_date,onChange:b=>y(j=>({...j,planned_date:b.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Goal Date"}),e.jsx(pe,{type:"date",value:d.goal_date,onChange:b=>y(j=>({...j,goal_date:b.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Q,{children:"Completed Date"}),e.jsx(pe,{type:"date",value:d.completed_date,onChange:b=>y(j=>({...j,completed_date:b.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(R,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(R,{onClick:g,disabled:!d.title||!d.category,children:i?"Update":"Create"})]})]})]})]})]}),e.jsx("div",{className:"space-y-3",children:(k==null?void 0:k.length)===0?e.jsxs("div",{className:"glassmorphism border border-border/50 rounded-lg p-8 text-center",children:[e.jsx(Ki,{className:"w-12 h-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Roadmap Items"}),e.jsx("p",{className:"text-muted-foreground",children:"Add items to populate the roadmap."})]}):k==null?void 0:k.map(b=>{var c;const j=m===b.id;return e.jsxs("div",{className:"glassmorphism border border-border/50 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"p-4 flex items-center justify-between cursor-pointer hover:bg-muted/30",onClick:()=>o(j?null:b.id),children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"outline",children:b.category}),e.jsx("span",{className:"font-medium",children:b.title})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{className:`${t_[b.stage]} border`,children:(c=Ir.find(p=>p.value===b.stage))==null?void 0:c.label}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["↑",b.upvote_count," ↓",b.downvote_count]}),j?e.jsx(Ua,{className:"w-4 h-4"}):e.jsx(Ns,{className:"w-4 h-4"})]})]}),j&&e.jsxs("div",{className:"px-4 pb-4 border-t border-border/50 pt-4 space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:b.description}),e.jsxs("div",{className:"flex items-center gap-6 text-xs",children:[b.planned_date&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xt,{className:"w-3 h-3"}),"Planned: ",ke(new Date(b.planned_date),"MMM d, yyyy")]}),b.goal_date&&e.jsxs("span",{className:"flex items-center gap-1",children:["Goal: ",ke(new Date(b.goal_date),"MMM d, yyyy")]}),b.completed_date&&e.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:["Completed: ",ke(new Date(b.completed_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-border/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Move to:"}),Ir.filter(p=>p.value!==b.stage).map(p=>e.jsxs(R,{size:"sm",variant:"outline",onClick:w=>{w.stopPropagation(),_(b.id,p.value)},children:[e.jsx(aa,{className:"w-3 h-3 mr-1"}),p.label]},p.value))]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(R,{size:"sm",variant:"outline",onClick:p=>{p.stopPropagation(),x(b)},children:[e.jsx(Bt,{className:"w-3 h-3 mr-1"}),"Edit"]}),e.jsxs(R,{size:"sm",variant:"destructive",onClick:p=>{p.stopPropagation(),f(b.id)},children:[e.jsx(os,{className:"w-3 h-3 mr-1"}),"Delete"]})]})]})]})]},b.id)})})]})}
427,Di=[{key:"tab_help_faqs_visible",label:"Help & FAQs",description:"FAQ section with searchable questions and answers"},{key:"tab_how_to_visible",label:"How To",description:"Tutorial videos and guides"},{key:"tab_versions_log_visible",label:"Versions Log",description:"Release notes and version history"},{key:"tab_roadmap_visible",label:"Roadmap",description:"Feature roadmap with user voting"},{key:"tab_contact_support_visible",label:"Contact Support",description:"Support ticket submission form"},{key:"tab_my_tickets_visible",label:"My Tickets",description:"User ticket history and tracking"},{key:"tab_live_support_visible",label:"Live Support",description:"Upcoming live support sessions and event reminders"}];function r_(){const{data:s,isLoading:a}=Vo(),t=Ho(),n=l=>{const m=s==null?void 0:s.find(o=>o.key===l);return(m==null?void 0:m.value)==="true"},r=Di.filter(l=>n(l.key)).length,i=(l,m)=>{if(m&&r<=1){K.error("At least one tab must remain visible");return}t.mutate({key:l,visible:!m})};return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ne,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"glassmorphism border border-border/50 rounded-lg p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx(ya,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Tab Visibility Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Control which tabs are visible to users on the Support page"})]})]}),e.jsx("div",{className:"space-y-4",children:Di.map(l=>{const m=n(l.key);return e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border border-border/50 bg-background/50",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:`p-2 rounded-full ${m?"bg-primary/20 text-primary":"bg-muted text-muted-foreground"}`,children:m?e.jsx(us,{className:"h-4 w-4"}):e.jsx(Ht,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(Q,{htmlFor:l.key,className:"text-base font-medium cursor-pointer",children:l.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.description})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`text-sm font-medium ${m?"text-primary":"text-muted-foreground"}`,children:m?"Visible":"Hidden"}),e.jsx(Ge,{id:l.key,checked:m,onCheckedChange:()=>i(l.key,m),disabled:t.isPending})]})]},l.key)})}),e.jsx("div",{className:"mt-6 p-4 rounded-lg bg-muted/50 border border-border/30",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"Note:"})," At least one tab must remain visible. Hidden tabs will not appear in the Support page navigation for users."]})})]})})}const n_=[{value:"0",label:"Sunday"},{value:"1",label:"Monday"},{value:"2",label:"Tuesday"},{value:"3",label:"Wednesday"},{value:"4",label:"Thursday"},{value:"5",label:"Friday"},{value:"6",label:"Saturday"}],l_=[{value:"America/New_York",label:"Eastern (ET)"},{value:"America/Chicago",label:"Central (CT)"},{value:"America/Denver",label:"Mountain (MT)"},{value:"America/Los_Angeles",label:"Pacific (PT)"},{value:"America/Phoenix",label:"Arizona (MST)"},{value:"UTC",label:"UTC"}],i_=el({title:ot().min(1,"Title is required"),description:ot().optional(),event_type:Gr(["one_time","recurring"]),day_of_week:ot().optional(),one_time_date:ot().optional(),event_time:ot().min(1,"Time is required"),timezone:ot().min(1,"Timezone is required"),event_link:ot().url("Must be a valid URL")}).refine(s=>!(s.event_type==="recurring"&&!s.day_of_week||s.event_type==="one_time"&&!s.one_time_date),{message:"Please select a day for recurring events or a date for one-time events",path:["day_of_week"]});function Mi({open:s,onOpenChange:a,event:t}){const n=Wo(),r=Go(),i=!!t,l=Wa({resolver:Ga(i_),defaultValues:{title:"",description:"",event_type:"recurring",day_of_week:"",one_time_date:"",event_time:"14:00",timezone:"America/Chicago",event_link:""}}),m=l.watch("event_type");v.useEffect(()=>{var h;
427t?l.reset({title:t.title,description:t.description||"",event_type:t.event_type,day_of_week:((h=t.day_of_week)==null?void 0:h.toString())||"",one_time_date:t.one_time_date||"",event_time:t.event_time,timezone:t.timezone,event_link:t.event_link}):l.reset({title:"",description:"",event_type:"recurring",day_of_week:"",one_time_date:"",event_time:"14:00",timezone:"America/Chicago",event_link:""})},[t,l]);const o=async h=>{const N={title:h.title,description:h.description||void 0,event_type:h.event_type,day_of_week:h.event_type==="recurring"?parseInt(h.day_of_week):void 0,one_time_date:h.event_type==="one_time"?h.one_time_date:void 0,event_time:h.event_time,timezone:h.timezone,event_link:h.event_link};i?await r.mutateAsync({id:t.id,...N}):await n.mutateAsync(N),a(!1)};return e.jsx(Ue,{open:s,onOpenChange:a,children:e.jsxs(Be,{className:"sm:max-w-[500px]",children:[e.jsx(ze,{children:e.jsx(Ke,{children:i?"Edit Live Event":"Add Live Support Event"})}),e.jsx(Cr,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(Ye,{control:l.control,name:"title",render:({field:h})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Title"}),e.jsx(es,{children:e.jsx(pe,{placeholder:"Weekly Office Hours",...h})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"description",render:({field:h})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Description"}),e.jsx(es,{children:e.jsx(Xs,{placeholder:"Join us for live Q&A and support assistance...",className:"resize-none",rows:3,...h})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"event_type",render:({field:h})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Event Type"}),e.jsx(es,{children:e.jsxs(Ut,{onValueChange:h.onChange,value:h.value,className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"recurring",id:"recurring"}),e.jsx("label",{htmlFor:"recurring",className:"cursor-pointer",children:"Recurring"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(nt,{value:"one_time",id:"one_time"}),e.jsx("label",{htmlFor:"one_time",className:"cursor-pointer",children:"One-time"})]})]})}),e.jsx(Xe,{})]})}),m==="recurring"?e.jsx(Ye,{control:l.control,name:"day_of_week",render:({field:h})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Day of Week"}),e.jsxs(oe,{onValueChange:h.onChange,value:h.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select a day"})})}),e.jsx(me,{children:n_.map(N=>e.jsx(V,{value:N.value,children:N.label},N.value))})]}),e.jsx(Xe,{})]})}):e.jsx(Ye,{control:l.control,name:"one_time_date",render:({field:h})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Event Date"}),e.jsx(es,{children:e.jsx(pe,{type:"date",...h})}),e.jsx(Xe,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ye,{control:l.control,name:"event_time",render:({field:h})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Time"}),e.jsx(es,{children:e.jsx(pe,{type:"time",...h})}),e.jsx(Xe,{})]})}),e.jsx(Ye,{control:l.control,name:"timezone",render:({field:h})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Timezone"}),e.jsxs(oe,{onValueChange:h.onChange,value:h.value,children:[e.jsx(es,{children:e.jsx(de,{children:e.jsx(ue,{placeholder:"Select timezone"})})}),e.jsx(me,{children:l_.map(N=>e.jsx(V,{value:N.value,children:N.label},N.value))})]}),e.jsx(Xe,{})]})})]}),e.jsx(Ye,{control:l.control,name:"event_link",render:({field:h})=>e.jsxs(Je,{children:[e.jsx(Ze,{children:"Event Link"}),e.jsx(es,{children:e.jsx(pe,{placeholder:"https://zoom.us/j/123456789",...h})}),e.jsx(Xe,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(R,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(R,{type:"submit",disabled:n.isPending||r.isPending,children:i?"Save Changes":"Create Event"})]})]})})]})})}function c_(){const{data:s=[],isLoading:a}=Qo(),t=Yo(),[n,r]=v.useState(!1),[i,l]=v.useState(null),[m,o]=v.useState(null),h=()=>{m&&(t.mutate(m),o(null))};return e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between",children:[e.jsxs(fe,{className:"flex items-center gap-2",children:[e.jsx(kr,{className:"h-5 w-5"}),"Live Support Events"]}),e.jsxs(R,{onClick:()=>r(!0),className:"gap-2",children:[e.jsx(Zs,{className:"h-4 w-4"}),"Add Event"]})]}),e.jsxs(J,{children:[a?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):s.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No live events created yet. Click "Add Event" to create one.'}):e.jsxs(Re,{children:[e.jsx(qe,{children:e.jsxs(he,{children:[e.jsx(U,{children:"Title"}),e.jsx(U,{children:"Day/Date"}),e.jsx(U,{children:"Time"}),e.jsx(U,{children:"Type"}),e.jsx(U,{children:"Status"}),e.jsx(U,{children:"Link"}),e.jsx(U,{className:"text-right",children:"Actions"})]})}),e.jsx($e,{children:s.map(N=>e.jsxs(he,{children:[e.jsx(M,{className:"font-medium",children:N.title}),e.jsx(M,{children:N.event_type==="recurring"?`Every ${Jo(N.day_of_week)}`:N.one_time_date?ke(new Date(N.one_time_date),"MMM d, yyyy"):"-"}),e.jsxs(M,{children:[Zo(N.event_time,N.timezone)," ",N.timezone]}),e.jsx(M,{children:e.jsx(B,{variant:N.event_type==="recurring"?"default":"secondary",children:N.event_type==="recurring"?"Recurring":"One-time"})}),e.jsx(M,{children:e.jsx(B,{variant:N.is_active?"default":"outline",children:N.is_active?"Active":"Inactive"})}),e.jsx(M,{children:e.jsxs("a",{href:N.event_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(Ma,{className:"h-3 w-3"}),"Open"]})}),e.jsx(M,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>l(N),children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(R,{variant:"ghost",size:"icon",onClick:()=>o(N.id),children:e.jsx(os,{className:"h-4 w-4 text-destructive"})})]})})]},N.id))})]}),e.jsx(Mi,{open:n,onOpenChange:r}),e.jsx(Mi,{open:!!i,onOpenChange:N=>!N&&l(null),event:i||void 0}),e.jsx(ws,{open:!!m,onOpenChange:N=>!N&&o(null),children:e.jsxs(Ss,{children:[e.jsxs(ks,{children:[e.jsx(Cs,{children:"Delete Event"}),e.jsx(Ps,{children:"Are you sure you want to delete this live support event? This will also remove all user reminders for this event."})]}),e.jsxs(Fs,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Ls,{onClick:h,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})]})}function o_(){const[s,a]=v.useState("tickets");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Support Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage all support content and user tickets"})]}),e.jsxs(js,{value:s,onValueChange:a,children:[e.jsxs(fs,{className:"flex flex-wrap gap-2 h-auto p-1 w-full justify-start",children:[e.jsxs(Ne,{value:"tickets",className:"flex items-center gap-2",children:[e.jsx(Kn,{className:"h-4 w-4"}),"Tickets"]}),e.jsxs(Ne,{value:"faqs",className:"flex items-center gap-2",children:[e.jsx(Ui,{className:"h-4 w-4"}),"FAQs"]}),e.jsxs(Ne,{value:"howto",className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4"}),"How To"]}),e.jsxs(Ne,{value:"versions",className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4"}),"Versions"]}),e.jsxs(Ne,{value:"roadmap",className:"flex items-center gap-2",children:[e.jsx(Ki,{className:"h-4 w-4"}),"Roadmap"]}),e.jsxs(Ne,{value:"live-events",className:"flex items-center gap-2",children:[e.jsx(kr,{className:"h-4 w-4"}),"Live Events"]}),e.jsxs(Ne,{value:"info",className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Support Info"]}),e.jsxs(Ne,{value:"tab-settings",className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"Tab Settings"]})]}),e.jsx(we,{value:"tickets",className:"mt-6",children:e.jsx(CN,{})}),e.jsx(we,{value:"faqs",className:"mt-6",children:e.jsx(DN,{})}),e.jsx(we,{value:"howto",className:"mt-6",children:e.jsx(VN,{})}),e.jsx(we,{value:"versions",className:"mt-6",children:e.jsx(JN,{})}),e.jsx(we,{value:"roadmap",className:"mt-6",children:e.jsx(a_,{})}),e.jsx(we,{value:"live-events",className:"mt-6",children:e.jsx(c_,{})}),e.jsx(we,{value:"info",className:"mt-6",children:e.jsx(e_,{})}),e.jsx(we,{value:"tab-settings",className:"mt-6",children:e.jsx(r_,{})})]})]})}function Pb(){const[s,a]=v.useState("dashboard");return e.jsxs("div",{className:"admin-tabs-scope container mx-auto p-2 sm:p-6 space-y-6 overflow-x-hidden max-w-full",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-4xl font-bold text-foreground",children:"Super Admin Panel"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Manage all aspects of the Klever Bet platform"})]})}),e.jsxs(js,{value:s,onValueChange:a,className:"w-full",children:[e.jsxs(fs,{className:"flex flex-wrap justify-start gap-2 h-auto p-2 w-full",children:[e.jsxs(Ne,{value:"dashboard",className:"flex items-center gap-2",children:[e.jsx(Rd,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Dashboard"})]}),e.jsxs(Ne,{value:"trading",className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Trading"})]}),e.jsxs(Ne,{value:"policy-lab",className:"flex items-center gap-2",children:[e.jsx(it,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"KLUTCH AI"})]}),e.jsxs(Ne,{value:"marketing",className:"flex items-center gap-2",children:[e.jsx(_r,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Marketing"})]}),e.jsxs(Ne,{value:"support",className:"flex items-center gap-2",children:[e.jsx(lu,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Support"})]}),e.jsxs(Ne,{value:"users",className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Ne,{value:"kontests",className:"flex items-center gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Kontests"})]}),e.jsxs(Ne,{value:"kommunity",className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Kommunity"})]}),e.jsxs(Ne,{value:"blog",className:"flex items-center gap-2",children:[e.jsx(ic,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Blog"})]}),e.jsxs(Ne,{value:"sports-controls",className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Sports"})]}),e.jsxs(Ne,{value:"imports",className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Imports"})]}),e.jsxs(Ne,{value:"utilities",className:"flex items-center gap-2",children:[e.jsx(ga,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Utilities"})]})]}),e.jsx(we,{value:"dashboard",className:"mt-6",children:e.jsx(Uu,{})}),e.jsx(we,{value:"trading",className:"mt-6",children:e.jsx(Io,{})}),e.jsx(we,{value:"policy-lab",className:"mt-6",children:e.jsx(dg,{})}),e.jsx(we,{value:"marketing",className:"mt-6",children:e.jsx(rN,{})}),e.jsx(we,{value:"support",className:"mt-6",children:e.jsx(o_,{})}),e.jsx(we,{value:"users",className:"mt-6",children:e.jsx(cj,{})}),e.jsx(we,{value:"kontests",className:"mt-6",children:e.jsx(qj,{})}),e.jsx(we,{value:"kommunity",className:"mt-6",children:e.jsx(Gj,{})}),e.jsx(we,{value:"blog",className:"mt-6",children:e.jsx(of,{})}),e.jsx(we,{value:"sports-controls",className:"mt-6",children:e.jsx(yN,{})}),e.jsx(we,{value:"imports",className:"mt-6",children:e.jsx(rv,{})}),e.jsx(we,{value:"utilities",className:"mt-6",children:e.jsx(py,{})})]})]})}export{Pb as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.