react-semaphor 0.1.70 → 0.1.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-plus-CiNHCwjp.js → dashboard-plus-Be9hzz-4.js} +4702 -4714
- package/dist/chunks/dashboard-plus-CnioyOtP.js +245 -0
- package/dist/chunks/{index-hGETKdkr.js → index-37vbFan0.js} +130 -130
- package/dist/chunks/{index-CgdWdS75.js → index-B6tXS6wT.js} +5261 -5217
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/dashboard-plus-zZ_g-UD1.js +0 -245
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-37vbFan0.js"),D=require("react"),gt=require("react-dom");function jt(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const Je=jt(D);/**
|
|
2
|
+
* @license lucide-react v0.453.0 - ISC
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the ISC license.
|
|
5
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/const bt=s.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
|
|
7
|
+
* @license lucide-react v0.453.0 - ISC
|
|
8
|
+
*
|
|
9
|
+
* This source code is licensed under the ISC license.
|
|
10
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
+
*/const vt=s.createLucideIcon("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/**
|
|
12
|
+
* @license lucide-react v0.453.0 - ISC
|
|
13
|
+
*
|
|
14
|
+
* This source code is licensed under the ISC license.
|
|
15
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
+
*/const yt=s.createLucideIcon("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
|
|
17
|
+
* @license lucide-react v0.453.0 - ISC
|
|
18
|
+
*
|
|
19
|
+
* This source code is licensed under the ISC license.
|
|
20
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
+
*/const Nt=s.createLucideIcon("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/**
|
|
22
|
+
* @license lucide-react v0.453.0 - ISC
|
|
23
|
+
*
|
|
24
|
+
* This source code is licensed under the ISC license.
|
|
25
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
+
*/const Is=s.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
|
|
27
|
+
* @license lucide-react v0.453.0 - ISC
|
|
28
|
+
*
|
|
29
|
+
* This source code is licensed under the ISC license.
|
|
30
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
+
*/const Ct=s.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
32
|
+
* @license lucide-react v0.453.0 - ISC
|
|
33
|
+
*
|
|
34
|
+
* This source code is licensed under the ISC license.
|
|
35
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
+
*/const St=s.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
|
|
37
|
+
* @license lucide-react v0.453.0 - ISC
|
|
38
|
+
*
|
|
39
|
+
* This source code is licensed under the ISC license.
|
|
40
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
+
*/const wt=s.createLucideIcon("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/**
|
|
42
|
+
* @license lucide-react v0.453.0 - ISC
|
|
43
|
+
*
|
|
44
|
+
* This source code is licensed under the ISC license.
|
|
45
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
+
*/const Dt=s.createLucideIcon("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"}]]);/**
|
|
47
|
+
* @license lucide-react v0.453.0 - ISC
|
|
48
|
+
*
|
|
49
|
+
* This source code is licensed under the ISC license.
|
|
50
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
+
*/const kt=s.createLucideIcon("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/**
|
|
52
|
+
* @license lucide-react v0.453.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 As=s.createLucideIcon("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
|
|
57
|
+
* @license lucide-react v0.453.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 Tt=s.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
|
|
62
|
+
* @license lucide-react v0.453.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 Et=s.createLucideIcon("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"}]]);/**
|
|
67
|
+
* @license lucide-react v0.453.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 It=s.createLucideIcon("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]);/**
|
|
72
|
+
* @license lucide-react v0.453.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 At=s.createLucideIcon("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"}]]);/**
|
|
77
|
+
* @license lucide-react v0.453.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 Mt=s.createLucideIcon("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/**
|
|
82
|
+
* @license lucide-react v0.453.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 ze=s.createLucideIcon("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
87
|
+
* @license lucide-react v0.453.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 Lt=s.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
|
|
92
|
+
* @license lucide-react v0.453.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 Ft=s.createLucideIcon("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/**
|
|
97
|
+
* @license lucide-react v0.453.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 Pt=s.createLucideIcon("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/**
|
|
102
|
+
* @license lucide-react v0.453.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 Ot=s.createLucideIcon("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"}]]);/**
|
|
107
|
+
* @license lucide-react v0.453.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 Bt=s.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
|
|
112
|
+
* @license lucide-react v0.453.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 Vt=s.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
|
|
117
|
+
* @license lucide-react v0.453.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 Rt=s.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
|
|
122
|
+
* @license lucide-react v0.453.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 zt=s.createLucideIcon("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
|
|
127
|
+
* @license lucide-react v0.453.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 qt=s.createLucideIcon("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
|
|
132
|
+
* @license lucide-react v0.453.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 $e=s.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
137
|
+
* @license lucide-react v0.453.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 Ue=s.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
|
|
142
|
+
* @license lucide-react v0.453.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 Gt=s.createLucideIcon("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
|
|
147
|
+
* @license lucide-react v0.453.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 $t=s.createLucideIcon("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
|
|
152
|
+
* @license lucide-react v0.453.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 xs=s.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
|
|
157
|
+
* @license lucide-react v0.453.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 Ut=s.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
|
|
162
|
+
* @license lucide-react v0.453.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 Ie=s.createLucideIcon("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
|
|
167
|
+
* @license lucide-react v0.453.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 Ae=s.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
|
|
172
|
+
* @license lucide-react v0.453.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 Kt=s.createLucideIcon("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/**
|
|
177
|
+
* @license lucide-react v0.453.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 Ms=s.createLucideIcon("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/**
|
|
182
|
+
* @license lucide-react v0.453.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 _t=s.createLucideIcon("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/**
|
|
187
|
+
* @license lucide-react v0.453.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 Ht=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
192
|
+
* @license lucide-react v0.453.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 Jt=s.createLucideIcon("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
|
|
197
|
+
* @license lucide-react v0.453.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 Ls=s.createLucideIcon("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.453.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 Qt=s.createLucideIcon("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
|
|
207
|
+
* @license lucide-react v0.453.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 Wt=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
|
|
212
|
+
* @license lucide-react v0.453.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 Yt=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/**
|
|
217
|
+
* @license lucide-react v0.453.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 Xt=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Fs(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,l=D.useRef(null);return D.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,n,r]),l}function Zt(){const{setTheme:t}=s.useTheme(),a=s.useDashboardStore(n=>n.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(Jt,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(qt,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),a("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),a("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),a("system")},children:"System"})]})]})}function Re(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>Ps(c))}})}})}}function Ps(t){return{...t,customCfg:ea(t.customCfg),data:[]}}function ea(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function sa(t,a,n,r,l){if(!l)return null;const o=JSON.stringify(n),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:a,template:o,filterValues:r,operation:"create"})}async function Qe(t,a,n){if(!n)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=a,d=`${t}/v1/lens`;return await s.postRequest(d,n,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,operation:"update"})}async function ta(t,a,n){if(!n)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,n,{operation:"delete",lensId:a})}function aa(){const[t,a]=D.useState(""),[n,r]=D.useState(!1),l=s.useDashboardStore(v=>v.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=D.useState(!1),[u,m]=D.useState(!1),h=s.useDashboardStore(v=>v.dashboard),x=s.useDashboardStore(v=>v.filterValues),{authToken:p,tokenProps:b}=s.useSemaphorContext();async function j(){d(!0);const v=Re(h),w=await sa(b.apiServiceUrl,t,v,x,p==null?void 0:p.accessToken);w&&(o([...l||[],w]),c(w.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:v=>{a(v.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function na(){const[t,a]=D.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await ta(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const p=n==null?void 0:n.filter(b=>b.id!==h);l(p||[]),o("original")}}async function m(h){const x=n==null?void 0:n.map(j=>j.id===h.id?{...j,isDefault:!h.isDefault}:{...j,isDefault:!1});l(x||[]);const p={...h,isDefault:!h.isDefault};await Qe(i.apiServiceUrl,p,c==null?void 0:c.accessToken);const b=n==null?void 0:n.find(j=>j.isDefault);if(b&&b.id!==h.id){const j={...b,isDefault:!1};await Qe(i.apiServiceUrl,j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Mt,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function ra({iconClassName:t}){const[a,n]=D.useState(!1),[r,l]=D.useState(""),[o,c]=D.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;n(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>n(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:a,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function Os({triggerButtonClassName:t}){const[a,n]=D.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>n(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:a,onOpenChange:n,dashboardId:r,dashboardName:l})]}):null}const la=async(t,a,n)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,a,n)},oa=async(t,a,n)=>{const r=`${t}/management/v1/groups/${n}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}});if(!l.ok){const o=await l.text();throw new Error(o||"Failed to delete group")}},ia=async(t,a,n,r)=>{const l=`${t}/management/v1/groups/${n}/members`;return await s.postRequestRegular(l,a,r)},ca=async(t,a,n,r)=>{const l=`${t}/management/v1/groups/${n}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function da(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:r=>la(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function ua(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:r=>oa(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["groups"]}),n.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function ma(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>ia(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["group",l.groupId]}),n.invalidateQueries({queryKey:["group-members",l.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function ha(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>ca(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["group",l.groupId]}),n.invalidateQueries({queryKey:["group-members",l.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function xa({onSuccess:t,tenantId:a,isTenantUser:n}){const[r,l]=D.useState(""),[o,c]=D.useState(""),[i,d]=D.useState({}),u=da(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",o&&o.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const p={name:r.trim(),description:o.trim()||void 0,type:n?"TENANT_GROUP":"ORG_GROUP",...n&&a?{tenantId:a}:{}};try{await u.mutateAsync(p),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:x=>{l(x.target.value),i.name&&d(p=>({...p,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:o,onChange:x=>{c(x.target.value),i.description&&d(p=>({...p,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),c(""),d({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function pa({open:t,onOpenChange:a,group:n,onUpdate:r}){const[l,o]=D.useState("members"),[c,i]=D.useState(""),[d,u]=D.useState([]),[m,h]=D.useState([]),{data:x,isLoading:p,refetch:b}=s.useGroupMembers(n.id),j=n.type==="TENANT_GROUP"?"tenant":"organization",{users:v,isLoading:w}=s.useUnifiedUsers({type:j,tenantId:n.tenantId||void 0,active:!0,limit:100}),T=ma(),O=ha(),L=(x==null?void 0:x.members)||[],E=D.useMemo(()=>new Set(L.map(I=>I.userId)),[L]),C=D.useMemo(()=>v.filter(I=>!E.has(I.id)),[v,E]),f=D.useMemo(()=>{if(!c)return C;const I=c.toLowerCase();return C.filter(k=>{var y,M;return((y=k.name)==null?void 0:y.toLowerCase().includes(I))||((M=k.email)==null?void 0:M.toLowerCase().includes(I))})},[C,c]),g=D.useMemo(()=>{if(!c)return L;const I=c.toLowerCase();return L.filter(k=>{var y,M,F,G;return((M=(y=k.user)==null?void 0:y.name)==null?void 0:M.toLowerCase().includes(I))||((G=(F=k.user)==null?void 0:F.email)==null?void 0:G.toLowerCase().includes(I))})},[L,c]),N=async()=>{if(d.length!==0)try{await T.mutateAsync({groupId:n.id,data:{userIds:d,userType:j==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},A=async()=>{if(m.length!==0)try{await O.mutateAsync({groupId:n.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},S=I=>{u(k=>k.includes(I)?k.filter(y=>y!==I):[...k,I])},P=I=>{h(k=>k.includes(I)?k.filter(y=>y!==I):[...k,I])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:n.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[L.length," ",L.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",n.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:I=>{o(I),i(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:c,onChange:I=>i(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:p?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):g.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:g.map(I=>e.jsx(fa,{member:I,selected:m.includes(I.userId),onToggle:()=>P(I.userId)},I.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:A,disabled:O.isPending,children:O.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:c,onChange:I=>i(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:w?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):f.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:f.map(I=>e.jsx(ga,{user:I,selected:d.includes(I.id),onToggle:()=>S(I.id)},I.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:N,disabled:T.isPending,children:T.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.UserPlus,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function fa({member:t,selected:a,onToggle:n}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:n,children:[e.jsx(s.Checkbox,{checked:a}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function ga({user:t,selected:a,onToggle:n}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:n,children:[e.jsx(s.Checkbox,{checked:a}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function ja({open:t,onOpenChange:a}){const[n,r]=D.useState("groups"),[l,o]=D.useState(""),[c,i]=D.useState(null),[d,u]=D.useState(!1),[m,h]=D.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:p}=s.useCurrentUserInfo(),b=ua(),j=(p==null?void 0:p.type)==="tenant",v=x==null?void 0:x.tenantId,{groups:w,isLoading:T,refetch:O}=s.useGroups({type:j?"TENANT_GROUP":"all",tenantId:j?v:void 0,includeMembers:!1}),L=w.filter(g=>{var N;return g.name.toLowerCase().includes(l.toLowerCase())||((N=g.description)==null?void 0:N.toLowerCase().includes(l.toLowerCase()))}),E=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),O()}catch(g){console.error("Failed to delete group:",g)}},C=g=>{i(g),u(!0)},f=()=>{r("groups"),O()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:n,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:g=>o(g.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:T?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(g=>e.jsx(s.Skeleton,{className:"h-24 w-full"},g))}):L.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:l?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:L.map(g=>e.jsx(ba,{group:g,onManageMembers:()=>C(g),onDelete:()=>h(g),currentUserId:p==null?void 0:p.id},g.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(xa,{onSuccess:f,tenantId:v,isTenantUser:j})})]})]})}),c&&e.jsx(pa,{open:d,onOpenChange:u,group:c,onUpdate:()=>O()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:E,disabled:b.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function ba({group:t,onManageMembers:a,onDelete:n,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function Ze(t){const[a,n]=D.useState(null),[r,l]=D.useState(null);return D.useEffect(()=>{if(!t||t.trim()===""){n(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),n(null)}})()},[t]),a}function va(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function ya(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return a}}return t[0].id}async function ps(t,a,n,r){if(!a||!n)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",n],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",n),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",n);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${a}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function Bs(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function Na(t,a){var o,c;const n=(t==null?void 0:t.frameObject)??((o=t==null?void 0:t.visual)==null?void 0:o.frameObject);if(!n)return!1;const r=Bs(n);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.find(i=>i.id===r.activeCardId);return l?(s.setupEditorWithCard({...a,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function Ca(){var x;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(p=>p.frame),n=s.useEditorStore(p=>p.card),r=Ze(((x=n.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatamodelId),c=s.useEditorStore(p=>p.selectedDatabaseName),i=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=n.sql;return{getUpdatedFrame:D.useCallback(()=>{var w;let p=m;m&&!m.includes("{{")&&(p=va(m),t(p));const b=(w=r==null?void 0:r.getState())==null?void 0:w.settings,j={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:p,customCfg:u?n.customCfg:null,preferences:n.preferences,...b&&{customCardPreferences:{...n.customCardPreferences,settings:b}}},v=a.cards.map(T=>T.id===n.id?j:T);return{...a,cards:v,activeCardId:ya(v,a.activeCardId)}},[n,a,u,l,o,c,i,d,t,r,m])}}function ke(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:j,setFilterValues:v,setApplyFilters:w}=s.useEditorActions(),{setIsDashboardEditing:T,setIsVisualEditing:O,setSelectedFrameId:L,clearSelectedFrameId:E,addFrame:C,setIsDashboardPanelOpen:f}=s.useDashboardActions(),g=s.useDashboardStore(y=>y.selectedSheetId),N=s.useDashboardStore(y=>y.selectedFrameId),A=s.useDashboardStore(y=>y.dashboard),S=s.useDashboardStore(y=>y.filterValues),P=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=D.useCallback(async y=>{try{l(y),E();const{data:M,fromCache:F}=await ps(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",y.id,n);if(!Na(M,{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:j,setFilterValues:v,setApplyFilters:w,setIsDashboardEditing:T,setIsVisualEditing:O,dashboard:A,selectedSheetId:g,selectedFrameId:N,filterValues:S}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:F}}catch(M){return console.error("Error editing visual:",M),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a.apiServiceUrl,n,l,o,c,T,O,i,d,u,m,h,x,p,b,j,v,w,E,A,g,N,S]),k=D.useCallback(async y=>{var M;try{if(l(y),!g)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:F,fromCache:G}=await ps(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",y.id,n),V=(F==null?void 0:F.frameObject)??((M=F==null?void 0:F.visual)==null?void 0:M.frameObject);if(!V)return{success:!1,error:"Visual has no frame data"};const B=Bs(V);if(!(B!=null&&B.cards)||B.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const q={...B,id:s.v4(),visualId:y.id};return C(g,q,"end"),T(!0),L(q.id),f(!1),{success:!0,fromCache:G}}catch(F){return console.error("Error adding visual:",F),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a.apiServiceUrl,n,l,g,C,T,L,f]);return{visual:P.data,isLoading:P.isLoading,isError:P.isError,error:P.error,handleEditLibraryVisual:I,handleAddLibraryVisual:k,getUpdatedFrame:Ca().getUpdatedFrame,refetch:P.refetch}}function Sa({open:t,onOpenChange:a,isLibraryVisual:n,currentVisualName:r,isSaving:l=!1,onConfirm:o}){const[c,i]=D.useState(n&&r?`Copy of ${r}`:r||""),[d,u]=D.useState(""),[m,h]=D.useState(!n),[x,p]=D.useState(!0);D.useEffect(()=>{t&&(i(n&&r?`Copy of ${r}`:r||""),u(""),h(!n),p(!0))},[t,n,r]);const b=()=>{c.trim()&&(!m&&!x||o({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},j=c.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:n?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:v=>i(v.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:v=>u(v.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:x,onCheckedChange:v=>p(!!v),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:n?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:v=>h(!!v),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:n?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!j||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function wa({className:t,variant:a="outline"}){var i;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);Ze(((i=r.customCardPreferences)==null?void 0:i.url)||""),s.useEditorStore(d=>d.selectedSchemaName),s.useEditorStore(d=>d.selectedDatamodelId),s.useEditorStore(d=>d.selectedDatabaseName),s.useEditorStore(d=>d.selectedTableName),s.useEditorStore(d=>d.selectedConnectionId),s.useEditorStore(d=>d.isShowingVisual),r.sql;const l=s.useEditorStore(d=>d.onSave),{getUpdatedFrame:o}=ke();function c(){const d=o();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:a,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Da({className:t,variant:a="default"}){const n=s.useQueryClient(),[r,l]=D.useState(!1),o=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:i}=ke(),d=s.useSelectedVisual(),u=s.useEditorStore(x=>x.frame),m=s.useUpdateVisualMutation(),h=()=>{const x=i(),p=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!p){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:p,data:{frameObject:x}},{onSuccess:()=>{l(!1),o(!0),s.ue.success("Visual updated successfully"),n.invalidateQueries({queryKey:["resource-by-id","visual",p],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:a,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function ka({className:t}){const a=s.useQueryClient(),[n,r]=D.useState(!1),l=s.useSelectedVisual(),o=s.useEditorStore(x=>x.frame),c=s.useDashboardStore(x=>x.selectedSheetId),{updateFrame:i,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=ke(),m=s.useUpdateVisualMutation(),h=async()=>{if(!c){s.ue.error("No sheet selected");return}const x=(o==null?void 0:o.visualId)||(l==null?void 0:l.id);if(!x){s.ue.error("No visual to update");return}r(!0);try{const p=u();await m.mutateAsync({visualId:x,data:{frameObject:p}});const b={...p,visualId:x};i(c,b),a.invalidateQueries({queryKey:["visuals"]}),a.invalidateQueries({queryKey:["visual",x]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(p){console.error("Failed to save and apply:",p),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function Ta({className:t}){const{getUpdatedFrame:a}=ke();s.useEditorStore(d=>d.frame);const n=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[o,c]=D.useState(!1),i=()=>{if(!n){s.ue.error("No sheet selected");return}c(!0);const u={...a(),visualId:void 0};r(n,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function Ea({className:t}){const{setTempQueryData:a,setSqlGen:n}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),o=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:i}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}n({}),o==null||o()}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function es(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient();s.useEditorStore(j=>j.isDevMode);const n=s.useEditorStore(j=>j.tempQueryData),r=s.useEditorStore(j=>j.card),{queryKey:l}=s.useDashboardCardQuery(r),{setCardSql:o,setSqlGen:c,setCardPython:i,setCardCustomCfg:d,setCardPreferences:u,updateDataSource:m,clearQueryConfig:h,setCardConfig:x,setCardType:p}=s.useEditorActions();function b(){const j=a.getQueryData(l);n!=null&&n.queryData||t({queryKey:l,queryData:j}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),o(""),c({}),h(),x(void 0),i(""),d(""),u({}),p("bar")}return e.jsxs(s.Button,{onClick:b,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(Dt,{className:"mr-2 size-4"}),"Clear"]})}function Ia(){const[t,a]=D.useState(!1),[n,r]=D.useState(!1),[l,o]=D.useState(null),c=s.useEditorStore(L=>L.frame),i=s.useEditorStore(L=>L.card),d=s.useSelectedVisual(),u=s.useDashboardStore(L=>L.selectedSheetId),m=s.useDashboardStore(L=>L.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=ke(),{selectVisual:x}=s.useManagementActions(),{addFrame:p,setSelectedFrameId:b,setIsVisualEditing:j}=s.useDashboardActions(),v=!!(c!=null&&c.visualId),w=(d==null?void 0:d.title)||(i==null?void 0:i.title)||"Untitled Visual",T=s.useCreateVisualWithFrame(L=>{if(L!=null&&L.id){if(x(L),n&&l&&u){const E={...l,id:s.v4(),visualId:L.id};p(u,E,"end"),b(E.id),r(!1),o(null),j(!1)}m(!0),a(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:a,handleSaveAs:async L=>{if(!u){s.ue.error("No sheet selected");return}const E=h();if(L.saveToLibrary){r(L.saveToCurrentDashboard),o(E);const C={title:L.name,description:L.description,frameObject:E,isPrivate:!1};T.mutate(C)}else if(L.saveToCurrentDashboard){const C={...E,id:s.v4(),visualId:void 0,cards:E.cards.map(f=>({...f,title:f.id===i.id?L.name:f.title}))};p(u,C,"end"),b(C.id),s.ue.success("Visual saved to dashboard"),a(!1),j(!1)}},isLibraryVisual:v,currentVisualName:w,isSaving:T.isPending}}function Vs({className:t}){const a=s.useEditorStore(T=>T.frame),n=s.useEditorStore(T=>T.card),r=s.useManagementStore(T=>T.selectedVisual),l=s.useDashboardStore(T=>T.selectedFrameId),o=s.useDashboardStore(T=>T.selectedSheetId),{setIsVisualEditing:c}=s.useDashboardActions(),i=!!(a!=null&&a.visualId||r!=null&&r.id),d=!!(a!=null&&a.visualId&&l),u=i&&!d,{saveAsDialogOpen:m,setSaveAsDialogOpen:h,handleSaveAs:x,isLibraryVisual:p,currentVisualName:b,isSaving:j}=Ia(),{handleAddLibraryVisual:v}=ke(),w=async()=>{if(!o){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const T=await v(r);T.success?(s.ue.success("Visual added to dashboard"),c(!1)):s.ue.error(T.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!i&&e.jsx(wa,{className:t,variant:"default"}),i&&e.jsxs(e.Fragment,{children:[d&&e.jsx(Ta,{className:t}),u&&o&&n&&(n.sql||s.hasValidCardConfig(n.config))&&e.jsxs(s.Button,{onClick:w,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(Nt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(Da,{className:t,variant:"default"}),d&&e.jsx(ka,{className:t}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:T=>{T.stopPropagation(),h(!0)},children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!i&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(Ea,{className:t}),e.jsx(Sa,{open:m,onOpenChange:T=>{j||h(T)},isLibraryVisual:p,currentVisualName:b,isSaving:j,onConfirm:x})]})}function Rs({className:t,switchClassName:a}){const n=s.useEditorStore(i=>i.isDevMode),r=s.useDashboardStore(i=>i.isVisualEditing),{setIsDevMode:l}=s.useEditorActions(),{config:o}=D.useContext(s.SemaphorContext).tokenProps,c=(o==null?void 0:o.showAdvancedMode)!==!1;return!r||!c?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.DevModeSwitch,{className:s.cn("",a),checked:n,onCheckedChange:()=>l(!n),id:"advanced-mode",icon:e.jsx(s.CodeXml,{className:"h-4 w-4"}),tooltip:n?"Standard Mode":"Advanced Mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"sr-only",children:"Advanced Mode"})]})}function Aa(){var xe,fe,ie;const{authToken:t,tokenProps:a,id:n}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId(),{isLoading:i}=s.useDashboardQuery();s.useDashboardStore(R=>R.theme);const d=s.useDashboardStore(R=>R.lenses),u=s.useDashboardStore(R=>R.selectedLensId),m=d==null?void 0:d.find(R=>R.id===u),h=s.useDashboardStore(R=>R.dashboard);s.useDashboardStore(R=>R.selectedSheetId);const x=s.useDashboardStore(R=>R.isDashboardEditing),{setDashboardTitle:p}=s.useDashboardStore(R=>R.actions),[b,j]=D.useState(!1),[v,w]=D.useState(!1),[T,O]=D.useState(!1),L=s.useDashboardStore(R=>R.isDashboardPanelOpen),E=s.useDashboardStore(R=>R.actions.setIsDashboardPanelOpen),C=s.useDashboardStore(R=>R.filterValues),f=s.useDashboardStore(R=>R.isVisualEditing);s.useEditorStore(R=>R.card);const g=s.useManagementStore(R=>R.selectedDashboard),N=s.useManagementStore(R=>R.initialDashboard);s.useManagementStore(R=>R.selectedVisual),s.useDashboardStore(R=>R.selectedFrameId),s.useEditorStore(R=>R.frame);const A=g?(fe=g==null?void 0:g.permissions)==null?void 0:fe.canEdit:(xe=N==null?void 0:N.permissions)==null?void 0:xe.canEdit,S=s.useDashboardStore(R=>R.showFilters),P=s.useDashboardStore(R=>R.showDashboardJSON),I=s.useDashboardStore(R=>R.onSaveFunction),k=s.useDashboardStore(R=>R.actions.setShowFilters),{setIsDashboardEditing:y,setShowDashboardJSON:M}=s.useDashboardStore(R=>R.actions),{setInitialDashboard:F,clearSelectedDashboard:G}=s.useManagementStore(R=>R.actions),{resources:V}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:B}=s.useCurrentUserInfo(),q=s.canUserManageGroups(B),z=g||N,_=z?{id:z.id,title:(h==null?void 0:h.title)||z.title||"Dashboard"}:null,{handleAddNewFrame:W}=s.useAddNewFrame(),[ee,te]=D.useState(!1),ae=s.useUpdateResource(s.ResourceType.DASHBOARD),Y=async(R,se)=>{if(!(h!=null&&h.id)){console.log("No dashboard ID found");return}console.log("Updating dashboard title:",{dashboardId:h.id,newTitle:R,previousTitle:se}),ae.mutate({resourceId:h.id,data:{title:R}},{onSuccess:()=>{console.log("Dashboard title updated successfully"),s.ue.success("Dashboard title updated")},onError:Z=>{console.error("Failed to update dashboard title:",Z),s.ue.error("Failed to update dashboard title"),p(se)}})};D.useEffect(()=>{if(V&&V.length>0){const R=h==null?void 0:h.id;if(R){const se=V.find(Z=>Z.id===R);se&&F(se)}}},[V,h==null?void 0:h.id,F]);const U=a.orgUserId||a.tenantId,H=x&&!f&&U&&A,X=()=>{y(!0)};async function ce(){const R=Re(h);te(!0);const se={template:R};ae.mutate({resourceId:R.id,data:se},{onSuccess:()=>{te(!1),s.ue.success("Dashboard saved!")},onError:()=>{te(!1),s.ue.error("Failed to save dashboard")}})}async function pe(){if(j(!0),!u||!m)return;const R=Re(h),se=JSON.stringify(R),Z={...m,template:se,filterValues:C};await Qe(a.apiServiceUrl,Z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(R),j(!1)}const ue=(m==null?void 0:m.name)||h.title;ae.isPending&&console.log("Title during update:",{title:ue,dashboardStateTitle:h.title,dashboardId:h==null?void 0:h.id,currentLensName:m==null?void 0:m.name});const Q=V&&V.length>0&&(a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail),de=g&&!(a!=null&&a.dashboard_id)&&!n;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Q&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{E(!L)},className:"h-7 p-2",children:e.jsx(zt,{className:"h-4 w-4"})}),de&&!f&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>G(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!f&&c&&(i?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):e.jsx(s.EditableText,{value:ue||"Untitled Dashboard",onSave:R=>{console.log("EditableText onSave called:",{newTitle:R,canEditDashboard:A,dashboardId:h==null?void 0:h.id});const se=(h==null?void 0:h.title)||"";p(R),Y(R,se)},isEditable:A&&!m,displayClassName:"text-sm font-medium",inputClassName:"text-sm font-medium",placeholder:"Dashboard Title",isPending:ae.isPending}))]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f&&e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"mr-2"}),e.jsx(Vs,{className:"h-7"})]}),r&&!f&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(a.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Kt,{className:"h-4 w-4"})}),!f&&c&&e.jsx(ra,{}),!f&&c&&e.jsx(Os,{}),!f&&c&&q&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>O(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!f&&c&&((ie=z==null?void 0:z.permissions)==null?void 0:ie.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>w(!0),className:"h-7 p-2",children:e.jsx(s.Share2,{className:"h-4 w-4"})}),!S&&!f&&x&&o.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>k(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),x&&!f&&U&&r&&c&&e.jsx(aa,{}),!f&&U&&r&&c&&e.jsx(na,{}),x&&!f&&U&&m&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:b,onClick:pe,size:"sm",children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),x&&!f&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!x,onClick:()=>W(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!f&&!x&&o.canEdit&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:X,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),H&&c&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:ee,onClick:ce,size:"sm",children:[ee?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),ee?"Saving...":"Save"]}),!f&&x&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>M(!P),size:"sm",variant:"ghost",children:e.jsx(s.Code,{className:"h-4 w-4"})})}),!f&&r&&e.jsx(Zt,{}),x&&!f&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{y(!1),M(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),v&&_&&e.jsx(s.ShareDialog,{resource:_,resourceType:s.ResourceType.DASHBOARD,onClose:()=>w(!1)}),e.jsx(ja,{open:T,onOpenChange:O})]})]})}function ss(t){const{tokenProps:a,authToken:n}=s.useSemaphorContext(),r=a==null?void 0:a.apiServiceUrl;return s.useQuery({queryKey:["joinability-map",t],queryFn:async()=>{if(!t||!(n!=null&&n.accessToken))return null;const l=`${r}/v1/domains/${t}/joinability`;return s.getRequest(l,n.accessToken)},enabled:!!t&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function Fe(t,a,n){if(a==="source")return{isValid:!0};const r=s.getDataType(t.dataType);if(n==="kpi"){if(a==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(a==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function We(t,a,n,r,l){if(t!=="kpi"||l.length<3)return;const o=(a==null?void 0:a.groupByColumns)&&a.groupByColumns.length>0,c=(a==null?void 0:a.comparisonType)==="none";!o&&c||n(r,{groupByColumns:[],comparisonType:"none"})}const ts=t=>{var I;const a=(I=t==null?void 0:t.dataSource)==null?void 0:I.semanticDomainId,{data:n}=ss(a),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:o,updatePivotByColumn:c,updateSortByColumn:i,removeGroupByColumn:d,removeMetricColumn:u,removePivotByColumn:m,removeSortByColumn:h}=s.useEditorActions(),x=s.useEditorStore(k=>k.card.type),p=t==null?void 0:t.id,b=D.useCallback(k=>{if(!(t!=null&&t.config))return[];switch(k){case"groupBy":return(t.config.groupByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType,dateFormat:y.dateFormat,customFormat:y.customFormat,granularity:y.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(y=>({id:y.id,name:y.name,dataType:y.dataType,label:y.label!==void 0?y.label:y.name,qualifiedEntityName:y.qualifiedEntityName,entityId:y.entityId,entityName:y.entityName,entityType:y.entityType,direction:y.direction}));case"source":return[];default:return[]}},[t]),j=D.useCallback((k,y)=>{if(p)switch(k){case"groupBy":{r(p,{groupByColumns:y});break}case"metrics":{r(p,{metricColumns:y});break}case"pivotBy":{r(p,{pivotByColumns:y});break}case"sortBy":{r(p,{sortByColumns:y});break}}},[p,r]),v=D.useCallback((k,y,M)=>{if(!p)return;const G=b(k)[y];if(G)switch(k){case"groupBy":l(p,G.id,{label:M});break;case"metrics":o(p,G.id,{label:M});break;case"pivotBy":c(p,G.id,{label:M});break;case"sortBy":i(p,G.id,{label:M});break}},[p,b,l,o,c,i]),w=D.useCallback((k,y)=>{if(!p)return;const F=b("metrics")[k];F&&o(p,F.id,{aggregate:y,label:s.getAggregationLabel(F.name,y)})},[p,b,o]),T=D.useCallback((k,y,M)=>{if(!p)return;const G=b("groupBy")[k];if(!G)return;const V={dateFormat:y};y==="custom"&&M?V.customFormat=M:V.customFormat=void 0,l(p,G.id,V)},[p,b,l]),O=D.useCallback((k,y)=>{if(!p)return;const F=b("groupBy")[k];F&&l(p,F.id,{granularity:y})},[p,b,l]),L=D.useCallback((k,y)=>{if(!p)return;const F=b("metrics")[k];F&&o(p,F.id,{aliasTemplate:y})},[p,b,o]),E=D.useCallback((k,y)=>{if(console.log("handleValueAliasesChange",k,y),!p)return;console.log("handleValueAliasesChange",k,y);const F=b("metrics")[k];F&&(console.log("handleValueAliasesChange",y),o(p,F.id,{valueAliases:y}))},[p,b,o]),C=D.useCallback(k=>{if(!p)return;if(b("metrics").length===0){s.ue.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:k})},[p,r,b]),f=D.useCallback(k=>{p&&r(p,{showTrendline:k})},[p,r]),g=D.useCallback(k=>{p&&r(p,{trendlineWindow:k})},[p,r]),N=D.useCallback(k=>{p&&r(p,{trendlineGranularity:k})},[p,r]),A=D.useCallback(k=>{p&&r(p,{targetValue:k})},[p,r]),S=D.useCallback(k=>{var q;if(!p)return;const y=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy")],M=s.validateEntityConsistency(k,y,{joinPlan:(q=t==null?void 0:t.config)==null?void 0:q.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:a});if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const F=s.getSmartContainerForField(k,y,x);if(!F){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const G=Fe(k,F,x);if(!G.isValid){s.ue.error("Invalid Field Type",{description:G.reason,position:"top-center",duration:3e3});return}const V=b(F);if(s.fieldAlreadyExists(k,V))return;const B=s.getNewField(k,F,V);if(B){const z=[...V,B];j(F,z),F==="metrics"&&We(x,t==null?void 0:t.config,r,p,z)}},[p,t==null?void 0:t.config,b,j,a,n,x,r]),P=D.useCallback((k,y)=>{if(!p)return;const F=b(k)[y];if(F){if(k!=="sortBy"){const G=b("sortBy"),V=G.filter(B=>!(B.name===F.name&&B.qualifiedEntityName===F.qualifiedEntityName));V.length!==G.length&&r(p,{sortByColumns:V})}switch(k){case"groupBy":d(p,F.id);break;case"metrics":u(p,F.id);break;case"pivotBy":m(p,F.id);break;case"sortBy":h(p,F.id);break}}},[p,b,d,u,m,h,r]);return{getFieldsForContainer:b,setFieldsForContainer:j,updateLabel:v,handleAggregationChange:w,handleDateFormatChange:T,handleGranularityChange:O,handleAliasTemplateChange:L,handleValueAliasesChange:E,removeField:P,handleFieldClick:S,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:f,handleKpiTrendlineWindowChange:g,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:A,cardType:x}};function Pe(t){return`${t}-${s.v4()}`}function fs(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ma(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function as(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:t==null?void 0:t.connectionId,connectionType:t==null?void 0:t.connectionType};const a=t.selectedEntities[0];return{tableName:a==null?void 0:a.name,schemaName:a==null?void 0:a.schema,databaseName:a==null?void 0:a.database,connectionId:t.connectionId,connectionType:t.connectionType}}function zs(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const a=t.selectedEntities[0];return!!(a!=null&&a.name)}function qs(){const t=s.useEditorStore(C=>C.sqlGen),a=s.useEditorStore(C=>C.isDevMode),n=s.useEditorStore(C=>C.card.dataSource),r=s.useEditorStore(C=>{var f,g;return(g=(f=C.card)==null?void 0:f.queryConfig)==null?void 0:g.metricColumns}),{tableName:l,schemaName:o,databaseName:c}=as(n),i=zs(n),d=s.useEditorStore(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:m,setCardSql:h,setRunSql:x,setSqlGen:p,setIsShowingVisual:b}=s.useEditorActions(),{connectionType:j,modelItems:v,selectedDatamodelName:w}=s.useEditorAside(),T=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var g;if(!a)return;const f=T(C);if(a&&i&&l){const N=s.createSqlGenConfig(f,t);p(N);const A=(g=v==null?void 0:v.find(P=>P.id===d))==null?void 0:g.name,S=s.getSql(N,s.fmt(o||""),s.fmt(l),A||"",j,c||"");S&&(h(S),x(!0))}else if(!a){if(s.isTextDataType(f.data_type))if(r&&r.length>0){const N={...f,role:"groupby",id:Pe(f.column_name),name:f.column_name,type:f.data_type};m(N)}else{const N={...f,role:"metric",id:Pe(f.column_name),name:f.column_name,label:fs(f.column_name,"COUNT"),type:f.data_type,aggregate:"COUNT"};u(N)}if(s.isDateDataType(f.data_type)){const N={...f,role:"groupby",id:Pe(f.column_name),name:f.column_name,type:f.data_type,label:Ma(f.column_name,"month"),granularity:"month"};m(N)}if(s.isNumberDataType(f.data_type)){const N={...f,role:"metric",id:Pe(f.column_name),name:f.column_name,label:fs(f.column_name,"SUM"),type:f.data_type,aggregate:"SUM"};u(N)}}},handleShowSample:()=>{if(!i||!l){console.warn("Cannot generate SQL: missing table metadata");return}const C=s.getFormattedTableNameForQuery({schemaName:o||"",tableName:l,modelName:w,connectionType:j,databaseName:c||""});b(!1);const f=j==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;h(f),x(!0)},handleShowCount:()=>{if(!i||!l){console.warn("Cannot generate SQL: missing table metadata");return}const C=s.getFormattedTableNameForQuery({schemaName:o||"",tableName:l,modelName:w,connectionType:j,databaseName:c||""});h(`SELECT COUNT(*) as count FROM ${C}`),x(!0)},isNumberField:C=>s.isNumberDataType(C.dataType)}}function Gs(){const t=s.useEditorStore(b=>b.selectedConnectionId),a=s.useEditorStore(b=>b.selectedDatamodelId),n=s.useEditorStore(b=>b.selectedDatabaseName),r=s.useEditorStore(b=>b.selectedSchemaName),l=s.useEditorStore(b=>b.selectedTableName),o=s.useDashboardStore(b=>b.dashboard.filters)||[],c=s.useDashboardStore(b=>b.selectedSheetId),i=s.useDashboardStore(b=>b.actions.addFilter),d=s.useDashboardStore(b=>b.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{modelItems:m,tableName:h,connectionType:x}=s.useEditorAside();function p(b,j="sheet",v){var N;const w=s.fmt(b.column_name),T=s.fmt(n||""),O=s.fmt(r||""),L=s.fmt(h);let E=s.getQualifiedTableName({schemaName:O,tableName:L,connectionType:x,databaseName:T}),C=`${E}.${w}`;const f=(N=m==null?void 0:m.find(A=>A.id===a))==null?void 0:N.name;a&&a!=="none"&&(C=`${s.DATAMODEL_NAMESPCACE}.${f}.${w}`,E=`${s.DATAMODEL_NAMESPCACE}.${f}`),v!=null&&v.qualifiedFieldName&&(C=v.qualifiedFieldName),v!=null&&v.entityName&&(E=v.entityName);let g;if(j==="sheet"&&c?g=s.filterExistsInSheet(o,C,L,n||"",T,c):g=o==null?void 0:o.find(A=>A.column===C&&A.table===L&&(A.database===T||A.database===n)),g)u(g.id),d(g.id);else{const A=s.v4(),S=j==="sheet"&&c?[c]:void 0;return h==="api"&&t?(i({location:j,id:A,column:C,title:b.label||b.column_name,dataType:b.data_type,table:"api",database:"",connectionId:t,operation:"in",applyToSheetIds:S,sql:s.getDefaultFilterSql(b.data_type,E,w)}),A):(i({id:A,location:j,column:C,title:b.label||b.column_name,dataType:b.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",applyToSheetIds:S,sql:s.getDefaultFilterSql(b.data_type,E,w)}),A)}}return{assignFilter:p}}function La({column:t}){const[a,n]=D.useState(!1),r=s.useEditorStore(w=>w.card.dataSource),{tableName:l,schemaName:o,databaseName:c}=as(r),i=s.useEditorStore(w=>w.selectedDatamodelId),d=s.useEditorStore(w=>w.sqlGen),{modelItems:u,connectionType:m}=s.useEditorAside(),h=s.useEditorStore(w=>w.actions.setSqlGen),x=s.useEditorStore(w=>w.actions.setCardSql),p=s.useEditorStore(w=>w.actions.setRunSql),b=zs(r);function j(w,T){var C;if(!b||!l){console.warn("Cannot generate SQL: missing table metadata");return}const O=s.createSqlGenConfig(w,d,T),L=(C=u==null?void 0:u.find(f=>f.id===i))==null?void 0:C.name;h(O);const E=s.getSql(O,s.fmt(o||""),s.fmt(l),L||"",m,c||"");E&&(x(E),p(!0)),n(!1)}function v(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>j(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>j(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>j(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>j(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>j(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return b?e.jsxs(s.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:v()})]}):null}function Fa({field:t,fieldState:a}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),a&&a.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:a.tooltip})}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function Pa({field:t,context:a="editor",fieldState:n}){const r=s.useEditorStore(z=>z.isDevMode),l=a==="filter",o=r||l||(n==null?void 0:n.state)==="unreachable"&&!l,c=s.useDashboardStore(z=>z.dashboard.filters),i=s.useDashboardStore(z=>z.selectedSheetId),d=s.useDashboardStore(z=>z.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{assignFilter:m}=Gs(),h=l?s.getSheetScopedFilters(c,i):c,x=l?h==null?void 0:h.find(z=>{var _;return z.title===t.name||((_=z.column)==null?void 0:_.includes(t.name))}):void 0,p=!!x,b=x&&l?c==null?void 0:c.find(z=>z.id===x.id):void 0,j=b&&(b.applyToSheetIds&&b.applyToSheetIds.length>1||b.excludeSheetIds&&b.excludeSheetIds.length>0||!b.applyToSheetIds&&!b.excludeSheetIds&&!b.sheetId);l&&p&&console.log("[SourceField Debug]",{fieldName:t.name,hasActiveFilter:p,activeFilterOnSheet:x?{id:x.id,title:x.title,column:x.column,applyToSheetIds:x.applyToSheetIds,excludeSheetIds:x.excludeSheetIds}:null,activeFilterForField:b?{id:b.id,title:b.title,column:b.column,applyToSheetIds:b.applyToSheetIds,excludeSheetIds:b.excludeSheetIds}:null,isMultiSheetFilter:j,selectedSheetId:i});const[v,w]=D.useState(!1),[T,O]=D.useState(null),{attributes:L,listeners:E,setNodeRef:C,transform:f,transition:g,isDragging:N}=s.useSortable({id:t.id,disabled:o}),[A,S]=D.useState(!1),P=s.useEditorStore(z=>z.card),{handleFieldClick:I}=ts(P),{handleDevModeFieldClick:k,isNumberField:y}=qs(),M=()=>{b&&(console.log("[SourceField] Removing multi-sheet filter:",b.id),u(b.id),d(b.id)),O(null),w(!1)},F=()=>{if(l){const z={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};console.log("[SourceField Click]",{fieldName:t.name,hasActiveFilter:p,isMultiSheetFilter:j,willShowWarning:p&&j}),p&&j?(console.log("[SourceField] Showing warning dialog for multi-sheet filter"),O({column:z,field:t}),w(!0)):(console.log("[SourceField] Calling assignFilter directly (single-sheet or new filter)"),m(z,"sheet",t))}else r?k(t):I(t)},G={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},V={transform:s.CSS.Transform.toString(f),transition:g},q=(()=>{if(!n||l)return{};const _={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",..._},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",..._},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",..._}}[n.state]||_})();return e.jsxs("div",{ref:C,style:V,...o?{}:L,...o?{}:E,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",N&&"scale-95 opacity-50",!N&&"border",q.borderColor||"border-transparent",q.bgColor||"",q.hoverBorderColor,q.hoverBgColor||"hover:bg-muted",q.opacity,q.cursor,p&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!o&&!r&&!l}),title:n==null?void 0:n.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:F,children:[s.getFieldIconComponent(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${A?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(Fa,{field:t,fieldState:n})})]})}),r&&!l&&y(t)&&e.jsx("div",{onClick:z=>z.stopPropagation(),children:e.jsx(La,{column:G})})]}),A&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ls,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})}),e.jsx(s.AlertDialog,{open:v,onOpenChange:w,children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Remove Filter from Multiple Sheets?"}),e.jsx(s.AlertDialogDescription,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:M,children:"Remove Filter"})]})]})})]})}function Oa({context:t="editor"}={}){var A,S,P,I;const[a,n]=D.useState(""),[r,l]=D.useState("all");s.useEditorStore(k=>k.isDevMode);const o=s.useEditorStore(k=>k.card.dataSource),c=s.useEditorStore(k=>k.card.config),i=s.useEditorStore(k=>k.card),{autoJoinMetadata:d}=s.useDashboardCardQuery(i),{columns:u=[],columnGroups:m=[],isLoading:h,error:x}=s.useColumns(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:b}=ss(p),j=[...(c==null?void 0:c.groupByColumns)||[],...(c==null?void 0:c.metricColumns)||[]];(S=(A=c==null?void 0:c.joinPlan)==null?void 0:A.baseEntity)==null||S.name,(I=(P=d==null?void 0:d.resolvedJoinPlan)==null?void 0:P.baseEntity)==null||I.name,qs();const v=u.filter(k=>k.name.toLowerCase().includes(a.toLowerCase())||k.dataType.toLowerCase().includes(a.toLowerCase())||k.label&&k.label.toLowerCase().includes(a.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(a.toLowerCase())),w=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const y=s.getDataType(k.dataType);return["date","string","boolean"].includes(y)?"dimensions":y==="number"?"metrics":"dimensions"},O=(r==="all"?v:v.filter(k=>w(k)===r)).reduce((k,y)=>{const M=y.qualifiedEntityName||"Other Fields";return k[M]||(k[M]={label:s.toLabel(y.entityName),fields:[]}),k[M].fields.push(y),k},{}),E=Object.keys(O),C=v.filter(k=>w(k)==="dimensions").length,f=v.filter(k=>w(k)==="metrics").length,g=v.filter(k=>w(k)==="calculated").length,N=v.length>0;return h?e.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):x?e.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:x.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:a,onChange:k=>n(k.target.value)}),a&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:k=>l(k),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(s.Calculator,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:E,className:"space-y-2",children:Object.entries(O).map(([k,y])=>{const M=m.find(F=>F.entityName===k)||{entityName:k,label:y.label};return e.jsxs(s.AccordionItem,{value:k,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:M.label||M.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:M.label||M.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:y.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:y.fields.map(F=>{const G=s.calculateFieldState(F,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:j,cardConfig:c,autoJoinMetadata:d});return e.jsx(Pa,{field:F,context:t,fieldState:G},F.id)})})})]},k)})}),Object.keys(O).length===0&&u.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(O).length===0&&u.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function $s({context:t="editor"}={}){return e.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",e.jsx(Oa,{context:t})," "]})}function Ba({initialJoinPlan:t,availableDataSources:a}){const[n,r]=D.useState(t),[l,o]=D.useState(new Set),c=()=>{const C=n.joins.length>0?Math.max(...n.joins.map(g=>g.sequence))+1:1,f={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:C,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,f]}),o(new Set([...l,f.id]))},i=C=>{r({...n,joins:n.joins.filter(f=>f.id!==C)}),o(new Set([...l].filter(f=>f!==C)))},d=(C,f)=>{var P,I,k,y,M;const g=n.joins.find(F=>F.id===C);if(!g)return;const N={...g,...f};if((P=N.source)!=null&&P.name&&((I=N.target)!=null&&I.name)&&N.source.name===N.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${N.source.name} to itself is not currently supported. Please select a different target table.`});return}const A=n.joins.filter(F=>{var G;return F.id!==C&&F.target.name===((G=N.target)==null?void 0:G.name)});if((k=N.target)!=null&&k.name&&A.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${N.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const S=n.joins.map(F=>F.id===C?N:F);if((y=N.source)!=null&&y.name&&((M=N.target)!=null&&M.name)&&N.joinKeyGroups[0].keys.length===0){const F=a.find(q=>{var z;return q.name===((z=N.source)==null?void 0:z.name)}),G=a.find(q=>{var z;return q.name===((z=N.target)==null?void 0:z.name)}),V={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(G==null?void 0:G.name)||"",entityName:(G==null?void 0:G.name)||"",entityType:(G==null?void 0:G.type)||"table"},operator:"="},B=[...N.joinKeyGroups];B[0]={...B[0],keys:[V]},N.joinKeyGroups=B,S[S.findIndex(q=>q.id===C)]=N}r({...n,joins:S})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:C=>{const f=n.joins.findIndex(g=>g.id===C);if(f>0){const g=[...n.joins],N={...g[f]},A={...g[f-1]};g[f]=A,g[f-1]=N,g.forEach((P,I)=>{P.sequence=I+1});const S={...n,joins:g};r(S)}},moveJoinDown:C=>{const f=n.joins.findIndex(g=>g.id===C);if(f<n.joins.length-1){const g=[...n.joins],N={...g[f]},A={...g[f+1]};g[f]=A,g[f+1]=N,g.forEach((P,I)=>{P.sequence=I+1});const S={...n,joins:g};r(S)}},toggleJoinExpansion:C=>{const f=new Set(l);f.has(C)?f.delete(C):f.add(C),o(f)},getAvailableSourceEntities:C=>{if(n.joins.length===0)return a;const f=n.joins.findIndex(N=>N.id===C);if(f===0)return a.filter(N=>N.name===n.baseEntity.name);const g=new Set;return n.baseEntity.name&&g.add(n.baseEntity.name),n.joins.slice(0,f).forEach(N=>{g.add(N.source.name),g.add(N.target.name)}),a.filter(N=>g.has(N.name))},getAvailableTargetEntities:C=>a.filter(f=>f.name!==C),addJoinKeyGroup:C=>{const f=n.joins.find(N=>N.id===C);if(!f)return;const g=[...f.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(C,{joinKeyGroups:g})},updateGroupOperator:(C,f,g)=>{const N=n.joins.find(S=>S.id===C);if(!N)return;const A=[...N.joinKeyGroups];A[f]={...A[f],operator:g},d(C,{joinKeyGroups:A})},removeJoinKeyGroup:(C,f)=>{const g=n.joins.find(A=>A.id===C);if(!g)return;const N=[...g.joinKeyGroups];N.splice(f,1),d(C,{joinKeyGroups:N})},addJoinKey:(C,f)=>{const g=n.joins.find(I=>I.id===C);if(!g)return;const N=a.find(I=>I.name===g.source.name),A=a.find(I=>I.name===g.target.name),S=[...g.joinKeyGroups],P={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(N==null?void 0:N.name)||"",entityName:(N==null?void 0:N.name)||"",entityType:(N==null?void 0:N.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},operator:"="};S[f]={...S[f],keys:[...S[f].keys,P]},d(C,{joinKeyGroups:S})},updateJoinKey:(C,f,g,N,A)=>{const S=n.joins.find(M=>M.id===C);if(!S)return;const P=a.find(M=>M.name===S.source.name),I=a.find(M=>M.name===S.target.name),k=[...S.joinKeyGroups],y=k[f].keys[g];N==="sourceColumnName"&&P?k[f].keys[g]={...y,source:{...y.source,name:A}}:N==="targetColumnName"&&I?k[f].keys[g]={...y,target:{...y.target,name:A}}:N==="operator"&&(k[f].keys[g]={...y,operator:A}),d(C,{joinKeyGroups:k})},removeJoinKey:(C,f,g)=>{const N=n.joins.find(S=>S.id===C);if(!N)return;const A=[...N.joinKeyGroups];A[f].keys.splice(g,1),d(C,{joinKeyGroups:A})},generateSQLPreview:()=>{const C=[...n.joins].sort((N,A)=>N.sequence-A.sequence),f=n.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
|
|
222
|
+
FROM ${f.name}`;return C.forEach(N=>{const A=a.find(I=>I.name===N.target.name);if(!A)return;const S=N.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const k=I.keys.filter(y=>{var M,F,G,V;return((M=y.source)==null?void 0:M.name)&&((F=y.target)==null?void 0:F.name)&&((G=y.source)==null?void 0:G.entityName)&&((V=y.target)==null?void 0:V.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return k.length>1?`(${k.join(` ${I.operator} `)})`:k[0]}).filter(Boolean),P=S.length>1?S.join(" OR "):S[0]||"condition_here";g+=`
|
|
223
|
+
${N.joinType} JOIN ${A.name}
|
|
224
|
+
ON ${P}`}),g},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(N=>!N.source.name||!N.target.name)||n.joins.some(N=>N.joinKeyGroups.some(A=>A.keys.length===0))||n.joins.some(N=>N.joinKeyGroups.some(A=>A.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function Va({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:o}=s.useEditorActions();s.useEditorStore(S=>S.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:x,moveJoinUp:p,moveJoinDown:b,toggleJoinExpansion:j,getAvailableSourceEntities:v,getAvailableTargetEntities:w,addJoinKeyGroup:T,updateGroupOperator:O,removeJoinKeyGroup:L,addJoinKey:E,updateJoinKey:C,removeJoinKey:f,generateSQLPreview:g,isValidConfiguration:N}=Ba({initialJoinPlan:t,availableDataSources:a}),A=S=>{const P=c.find(I=>I.entityName===S);return(P==null?void 0:P.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:S=>{const P=a.find(I=>I.name===S);u({...i,baseEntity:{connectionId:(P==null?void 0:P.connectionId)||"",connectionType:(P==null?void 0:P.connectionType)||"none",type:(P==null?void 0:P.type)||"table",name:S,database:P==null?void 0:P.database,schema:P==null?void 0:P.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:g()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(S=>{const P=a.find(y=>y.name===S.source.name),I=a.find(y=>y.name===S.target.name),k=d.has(S.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{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(s.Badge,{children:S.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",S.sequence,P&&I&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",P.name," → ",I.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(S.id),disabled:S.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(S.id),disabled:S.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(S.id),children:k?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(S.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),k&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:S.source.name,onValueChange:y=>{const M=a.find(F=>F.name===y);x(S.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:y,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(S.id).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name]})},y.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:S.joinType,onValueChange:y=>x(S.id,{joinType:y}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:S.target.name,onValueChange:y=>{const M=a.find(F=>F.name===y);x(S.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:y,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!S.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:S.source.name?w(S.source.name).map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,y.name===S.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},y.name)):[]})]})]})]}),S.source.name&&S.target.name&&P&&I&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>T(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:S.joinKeyGroups.map((y,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:y.operator,onValueChange:F=>O(S.id,M,F),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>L(S.id,M),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:y.keys.map((F,G)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[G>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:y.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.source.name,onValueChange:V=>C(S.id,M,G,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:A(S.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:F.operator,onValueChange:V=>C(S.id,M,G,"operator",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:F.target.name,onValueChange:V=>C(S.id,M,G,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:A(S.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>f(S.id,M,G),children:e.jsx(s.X,{className:"size-3.5"})})]},F.id||G))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(S.id,M),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},y.id))})]})]})]},S.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(i),disabled:!N(),children:"Save"})]})]})}function Ye({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:o,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Va,{joinPlan:r,availableDataSources:l,onSave:c,onCancel:i,onRemove:o})]}),t]})}function Ra({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((c,i)=>c.sequence-i.sequence),o=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(c=>{const i=n.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,o)=>l.sequence-o.sequence).map((l,o)=>{const c=n.find(d=>d.name===l.source.name),i=n.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:o+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function za(){var h,x;const t=s.useEditorStore(p=>p.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(t),n=s.useEditorStore(p=>p.actions.updateCardConfig),r=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[l,o]=D.useState(!1),c=((x=t==null?void 0:t.dataSource)==null?void 0:x.selectedEntities)||[],i=p=>{n(t.id,{...t==null?void 0:t.config,joinPlan:p}),o(!1)},d=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{o(!1)},m=()=>{const p=[...r.joins].sort((v,w)=>v.sequence-w.sequence),b=r.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
|
|
225
|
+
FROM ${b.name}`;return p.forEach(v=>{const w=c.find(L=>L.name===v.target.name);if(!w)return;const T=v.joinKeyGroups.filter(L=>L.keys&&L.keys.length>0).map(L=>{const E=L.keys.filter(C=>{var f,g,N,A;return((f=C.source)==null?void 0:f.name)&&((g=C.target)==null?void 0:g.name)&&((N=C.source)==null?void 0:N.entityName)&&((A=C.target)==null?void 0:A.entityName)}).map(C=>`${C.source.entityName}.${C.source.name} ${C.operator} ${C.target.entityName}.${C.target.name}`);return E.length>1?`(${E.join(` ${L.operator} `)})`:E[0]}).filter(Boolean),O=T.length>1?T.join(" OR "):T[0]||"condition_here";j+=`
|
|
226
|
+
${v.joinType} JOIN ${w.name}
|
|
227
|
+
ON ${O}`}),j};return c.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[r.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(s.Link,{className:s.cn("mr-1 h-3 w-3",{"text-blue-500":r.joins.length>0,"text-gray-500":r.joins.length===0})}),"Join",r.joins.length>1?"s":""," (",r.joins.length,")"]})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Ra,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:c,generateSQLPreview:m})})]})}),(a==null?void 0:a.autoResolved)&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-6 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})}),e.jsx(s.TooltipContent,{side:"right",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium",children:"Auto-resolved using relationships:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:a.relationshipsUsed.map((p,b)=>e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p},b))})]})})]})}),e.jsx(Ye,{open:l,onOpenChange:o,joinPlan:r,availableDataSources:c,onSave:i,onCancel:u,onRemove:d,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(Ye,{open:l,onOpenChange:o,joinPlan:r,availableDataSources:c,onSave:i,onCancel:u,onRemove:d,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function qa({open:t,onOpenChange:a}){const[n,r]=D.useState([]),{updateDataSource:l}=s.useEditorActions(),o=s.useDashboardStore(j=>j.dashboard.aiContext),c=(o==null?void 0:o.selectedEntities)||[];D.useEffect(()=>{t&&r([])},[t]);const i=j=>{r(v=>v.some(T=>T.name===j.name&&T.type===j.type)?v.filter(T=>!(T.name===j.name&&T.type===j.type)):[...v,j])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(n.length===0)return;const j=n[0],v=j.connectionId||"",w=j.connectionType||"",O=n.some(E=>E.type==="dataset")?"semanticDomain":"database";l({connectionId:v,connectionType:w,mode:O,selectedEntities:n}),a(!1)},h=j=>{switch(j.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Yt,{className:"h-4 w-4"});case"model":return e.jsx(wt,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},x=j=>"label"in j&&j.label?j.label:j.name,p=j=>{if("description"in j&&j.description)return j.description;const v=[];return j.database&&v.push(j.database),j.schema&&v.push(j.schema),j.name&&v.push(j.name),v.join(".")},b=j=>n.some(v=>v.name===j.name&&v.type===j.type);return c.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 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(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===c.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",c.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:c.map((j,v)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(j)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(j),onCheckedChange:()=>i(j)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(j)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(j)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(j)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:j.type})]},`${j.type}-${j.name}-${v}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function Ga({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),o=l.find(i=>i.label==="Description"),c=l.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:a||s.getDisplayName(t)}),o&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function $a({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),l=r.find(c=>c.label==="Description"),o=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(a)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),o.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:o.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function Us(){const t=s.useEditorStore(c=>c.card.dataSource),{setSelectedConnectionId:a,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:l,setSelectedDatamodelId:o}=s.useEditorActions();D.useEffect(()=>{var p;if(!t)return;const{tableName:c,schemaName:i,databaseName:d,connectionId:u}=as(t),m=(p=t.selectedEntities)==null?void 0:p[0],x=(m==null?void 0:m.type)==="model"&&"id"in m?m.id:"";a(u||""),n(d||""),r(i||""),l(c||""),o(x)},[t,a,n,r,l,o])}function Ks({isVisible:t}){const a=s.useEditorStore(x=>x.isDevMode);Us();const[n,r]=D.useState(!1),[l,o]=D.useState(!1),[c,i]=D.useState(!0),d=s.useEditorStore(x=>x.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:"p-4 px-6 pb-2",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}),e.jsxs("div",{className:"relative px-6",children:[e.jsx("div",{className:"absolute inset-0 flex items-center px-6",children:e.jsx("div",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!c),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:c?e.jsx(s.ChevronUp,{className:"h-3.5 w-3.5"}):e.jsx(s.ChevronDown,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:`overflow-hidden px-6 ${c?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((x,p)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(x),e.jsx("button",{onClick:b=>{b.stopPropagation();const j=h.selectedEntities.filter(v=>!(v.name===x.name&&v.type===x.type));u({...m,...d,selectedEntities:j})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(Ga,{entity:x})]},`${x.type}-${x.name}-${p}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx($a,{entities:h.selectedEntities.slice(3)})]})]})}),!a&&e.jsx(za,{})]})]}),e.jsx($s,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:h}),e.jsx(qa,{open:l,onOpenChange:o})]})}function ns({error:t,errorSql:a,onSendFeedback:n,onOpenInEditor:r,className:l,showFeedbackButton:o=!0,errorTitle:c="Query Error"}){const[i,d]=D.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",l),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:c}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(s.Collapsible,{open:i,onOpenChange:d,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:i?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(As,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),o&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),e.jsx(s.Collapsible,{open:i,onOpenChange:d,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:a?"Error SQL Query":"SQL Query"}),a&&e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),a?e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})}):e.jsx("div",{className:"rounded-md bg-background/60 p-3",children:e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"SQL query not available for this error"})})]})})})]})]})})}function _s({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(j=>j.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions(),[d,u]=D.useState(!1),m=s.useEditorStore(j=>j.card),h=s.useEditorStore(j=>j.frame),x=s.useDashboardStore(j=>j.selectedSheetId),p=s.useDashboardStore(j=>{var v;return(v=j.dashboard)==null?void 0:v.id});function b(j){o(!0),c(j||t),setTimeout(()=>{i(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!a&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>b(),variant:"secondary",size:"sm",children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>u(!d),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),d&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>u(!1),children:e.jsx(Is,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:m.id||"N/A"})]}),e.jsx(s.CopyButton,{text:m.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:h.id||"N/A"})]}),e.jsx(s.CopyButton,{text:h.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:x||"N/A"})]}),e.jsx(s.CopyButton,{text:x||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:p||"N/A"})]}),e.jsx(s.CopyButton,{text:p||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(ns,{error:a,errorSql:n,showFeedbackButton:!1,onOpenInEditor:()=>b(n)}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),a&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Lt,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Ua({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Is,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(_s,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Ka(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Hs(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(j=>j.theme),r=s.useEditorStore(j=>j.frame),l=s.useEditorStore(j=>j.card),o=s.useEditorStore(j=>j.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=D.useRef(),h=D.useRef({}),x=r.cards.find(j=>j.id===o),p=D.useCallback(()=>{let j="";return t==="python"&&(j=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(j=(x==null?void 0:x.sql)||""),j},[t,x]);D.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const j=m.current.getModel();j&&(h.current[l.id]=j);let v=h.current[o];if(!v){const w=p();v=c.editor.createModel(w,t),h.current[o]=v}m.current.setModel(v)}d(o,l),u(!0)}},[o,l,d,c,u,t,p]),D.useEffect(()=>{if(!c)return;const j=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?j:n;c.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),D.useEffect(()=>{const j=m.current;j&&c&&l&&j.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(j,v){if(m.current=j,!h.current[l.id]){const w=j.getModel(),T=p();h.current[l.id]=w||(v==null?void 0:v.editor.createModel(T,t))||j.getModel()}j.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function _a(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Hs("sql");function o(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ha(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=Hs("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Ja({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Qa(){const t=s.useQueryClient(),{isConsoleMode:a}=s.useDashboardPreferences(),[n,r]=D.useState(!1),[l,o]=D.useState(!1);s.useEditorStore(z=>z.frame);const c=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const i=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const d=s.useEditorStore(z=>{var _;return(_=z==null?void 0:z.card)==null?void 0:_.sql}),u=s.useEditorStore(z=>{var _;return(_=z==null?void 0:z.card)==null?void 0:_.python}),{cardFilterValues:m}=s.useCardFilterValues((c==null?void 0:c.id)??""),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:p,setTempQueryData:b,setPythonStdOut:j,setCardPreferences:v,setCardType:w,setCardPython:T,runAssistant:O,setShowAIDialog:L}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const E=s.useEditorStore(z=>z.runSql),C=s.useEditorStore(z=>z.actions.setRunSql),f=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:g,isLoading:N,isFetching:A,isSuccess:S,isError:P,error:I,errorSql:k,queryKey:y,refetch:M,errorMessage:F}=s.useDashboardCardQuery(c);D.useEffect(()=>{if(g&&(g.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((g==null?void 0:g.output)||""),g.records.length>0)){const{dimensionKeys:z}=s.getKeys(g.records);x(z)}},[g,x,j]),D.useEffect(()=>{(N||A)&&f(!0),(P||S)&&f(!1),P&&(x([]),j(""))},[N,A,g,j,P,S,f,x,I]),D.useEffect(()=>{E&&(t.getQueryData(y)||M(),C(!1))},[E,M,C,y,t]);async function G(){const z=`Can you help me debug this query?
|
|
228
|
+
|
|
229
|
+
Error:
|
|
230
|
+
|
|
231
|
+
${F}
|
|
232
|
+
|
|
233
|
+
Error SQL:
|
|
234
|
+
|
|
235
|
+
${k}
|
|
236
|
+
|
|
237
|
+
Query:
|
|
238
|
+
|
|
239
|
+
${d}
|
|
240
|
+
|
|
241
|
+
${u?`Python:
|
|
242
|
+
${u}`:""}
|
|
243
|
+
`;O(z)}function V(){return e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Ja,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!l),className:"absolute bottom-0 right-6 size-7 p-1",children:l?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function B(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(_a,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Ha,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){return e.jsx("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:N||A,onClick:()=>{M()},className:"h-8 shrink-0",size:"sm",children:[N||A?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Ua,{errorSql:k,sql:g==null?void 0:g.sql,error:F,onDebugWithAssistant:G}),e.jsx(es,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:z=>r(z),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Ka,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!i&&e.jsxs("button",{disabled:i,onClick:()=>{L(!0)},className:"flex h-9 w-full cursor-text items-center justify-start px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[B(),V()]}),q()]})}const Wa=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:ze}];function Ya({className:t}){const a=s.useEditorStore(d=>d.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),o=["table","aggregateTable","pivotTable"].includes(a.type),c=s.hasValidCardConfig(a.config);if(!o||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=a.config)!=null&&m.pivotByColumns)&&a.config.pivotByColumns.length>0){const h={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(h),l(h)}else{n(u);const h={...a,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Wa.map(d=>{const u=d.icon,m=a.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function Xa({card:t}){var O,L,E,C,f,g,N,A,S,P,I;const[a,n]=D.useState(!1),[r,l]=D.useState([]),{authToken:o}=s.useSemaphorContext(),{theme:c}=s.useTheme(),i=s.getTokenParams(o==null?void 0:o.accessToken),d=s.useDashboardStore(k=>k.themeStyle),u={mode:c||"system",colors:((L=(O=d==null?void 0:d.chart)==null?void 0:O.dataset)==null?void 0:L.backgroundColor)||[]};(E=t.customCardPreferences)!=null&&E.inputData;const{getCard:m}=s.useCustomVisual(((C=t.customCardPreferences)==null?void 0:C.url)||""),h=((f=t.customCardPreferences)==null?void 0:f.visualType)||"single",x=s.useEditorStore(k=>k.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),j=D.useCallback((k,y)=>{l(M=>({...M,[k]:y}))},[]);if(!((g=t.customCardPreferences)!=null&&g.componentName))return null;const v=m((N=t.customCardPreferences)==null?void 0:N.componentName);function w(k){n(k)}const T=Object.keys(((A=t.customCardPreferences)==null?void 0:A.dataInputCardIds)||{}).map(k=>{var F,G,V;const y=(G=(F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)==null?void 0:G[k].cardId,M=(V=x==null?void 0:x.cards)==null?void 0:V.find(B=>B.id===y);return M||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(D.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[v&&h==="single"&&e.jsx(v,{editing:!0,params:i,theme:u,settings:(S=t.customCardPreferences)==null?void 0:S.settings,onDataChange:j,data:(b==null?void 0:b.records)||[]}),v&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((P=t.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(k=>{var F,G,V;const y=(G=(F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)==null?void 0:G[k].cardId,M=(V=x==null?void 0:x.cards)==null?void 0:V.find(B=>B.id===y);if(M)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:w,onDataChange:j,dataInputIndex:k,card:M},M.id+k)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(v,{theme:u,onDataChange:j,settings:T.map(k=>{var y;return(y=k==null?void 0:k.customCardPreferences)==null?void 0:y.settings}),data:T.map(k=>k!=null&&k.id?r==null?void 0:r[k.id]:[])})})]})]},(I=t.customCardPreferences)==null?void 0:I.componentName)})}function Za({type:t,isLinked:a,className:n}){const r=s.useDashboardStore(x=>x.selectedFrameId),l=s.useManagementStore(x=>x.selectedVisual),o=s.useEditorStore(x=>x.frame);let c;if(t)c=t;else if(a!==void 0)c=a?"linked":"library";else if(!!!(o!=null&&o.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(o!=null&&o.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;if(c==="local")return null;const i={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},d={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},m={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(Ot,{className:"h-3.5 w-3.5"}),library:e.jsx(Pt,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",i[c],n),children:h[c]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[c]),children:[e.jsx(s.TooltipArrow,{className:m[c]}),e.jsx("p",{children:d[c]})]})]})})}function Js({className:t,...a}){var G;const n=s.useEditorStore(V=>V.card),r=((G=n.customCardPreferences)==null?void 0:G.showCardHeader)??!0,l=s.useEditorStore(V=>V.frame),o=s.useDashboardStore(V=>V.dashboard.filters),[c,i]=D.useState(!1),{currentUser:d}=s.useCurrentUserInfo(),{tokenProps:u}=D.useContext(s.SemaphorContext),m=s.useEditorStore(V=>V.actions.setRunSql),{updateFilter:h}=s.useDashboardActions(),x=o==null?void 0:o.find(V=>V.id===l.filterId),{data:p,isLoading:b,isFetching:j,errorMessage:v,errorSql:w,pagination:T}=s.useDashboardCardQuery(n),{setCard:O,updateCardInFrame:L,setIsDevMode:E,setCardSql:C}=s.useEditorActions(),{data:f}=s.useTopoJson(n),g=D.useMemo(()=>{var V;return n.type!=="pivotTable"||!((V=p==null?void 0:p.records)!=null&&V.length)?null:{records:p.records,columnSubtotalMeta:p.columnSubtotalMeta,subtotalColumns:p.subtotalColumns||[],pivotSchema:p.pivotSchema||[],groupByColumns:p.groupByColumns}},[n.type,p==null?void 0:p.records,p==null?void 0:p.columnSubtotalMeta,p==null?void 0:p.subtotalColumns,p==null?void 0:p.pivotSchema,p==null?void 0:p.groupByColumns]),N=s.usePivotTableConfig(n,g),A=V=>{E(!0),C(V||w||n.sql||n.python||""),setTimeout(()=>{m(!0)},100)},S=()=>{i(!0)},P=D.useMemo(()=>{const V=typeof window<"u"?window.location.href:"",B=typeof navigator<"u"?navigator.userAgent:"",q=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:d,tokenContext:u,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:o,errorMessage:v||void 0,errorSql:w||n.sql||n.python,generatedSql:w||n.sql},metadata:{url:V,userAgent:B,timestamp:new Date().toISOString(),viewport:q}}},[d,u,n,o,v,w]),I=(V,B)=>{var z,_;const q={...n,paginationConfig:{page:V+1,pageSize:B}};O(q),L(q),n.sql&&((_=(z=n.preferences)==null?void 0:z.tablePrefs)!=null&&_.enableDevModePagination)&&m(!0)},k=V=>{var z,_,W,ee;const B=s.sortStateToSortByColumns(V,(z=n.config)==null?void 0:z.metricColumns,(_=n.config)==null?void 0:_.groupByColumns),q={...n,config:{...n.config||{},sortByColumns:B}};O(q),L(q),n.sql&&((ee=(W=n.preferences)==null?void 0:W.tablePrefs)!=null&&ee.enableDevModePagination)&&m(!0)},y=D.useMemo(()=>!n.id||!(p!=null&&p.records)?null:s.createChartConfig({card:n,data:p==null?void 0:p.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:f}),[n.id,p==null?void 0:p.records,n.type,n.customCfg,n.preferences,f]);function M(V){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Xa,{card:V})})}function F(){if(p!=null&&p.records&&(p==null?void 0:p.records.length)===0&&!b&&!j)return v?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ns,{error:v,errorSql:w||n.sql||n.python,onOpenInEditor:A,onSendFeedback:S,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((b||j)&&n.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return M(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&y)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:b||j?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:y})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:(p==null?void 0:p.records)||[],paginationMetadata:T,onPaginationChange:I,onSortChange:k,isLoading:b||j})});if(n.type==="pivotTable"&&N)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:n,data:N.data,options:N.options,onAggregationChange:V=>{const B=s.handleAggregationChange(V,n.config),q={...n,config:B};O(q),L(q)},onAggregationLabelChange:V=>{const B=s.handleAggregationLabelChange(V,n.config),q={...n,config:B};O(q),L(q)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(p==null?void 0:p.records)||[],groupByColumns:p==null?void 0:p.groupByColumns,pivotSchema:p==null?void 0:p.pivotSchema,paginationMetadata:T,onPaginationChange:I,onAggregationChange:V=>{const B=s.handleAggregationChange(V,n.config),q={...n,config:B};O(q),L(q)},isLoading:b||j})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:V=>O({...n,title:V}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Za,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Ya,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:V=>O({...n,description:V}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),x&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:x.title||x.column,onSave:V=>h({...x,title:V}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:x})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:F()}),e.jsx(s.FeedbackDialog,{open:c,onOpenChange:i,feedbackData:P,showDebugInfo:!0})]})}const Ke=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),en=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),sn=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"javascript",value:t,onChange:l})})]}),tn=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function an(){const[t,a]=D.useState(!1),[n,r]=D.useState(""),[l,o]=D.useState(""),[c,i]=D.useState(""),[d,u]=D.useState(""),m=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),x=h?JSON.stringify(h,null,2):"",{data:p}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:j,setCustomVisualCode:v}=s.useEditorActions(),w=E=>{var C,f;return JSON.stringify({...E,data:{...E.data,datasets:(f=(C=E.data)==null?void 0:C.datasets)==null?void 0:f.map(g=>({...g,data:[]}))}},null,2)},T=()=>{var C,f;if(!((C=p==null?void 0:p.records)!=null&&C.length))return;const E=s.createChartConfig({card:m,data:p.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(E){r(w(E)),i(((f=m.preferences)==null?void 0:f.customVisualCode)||"");const g=s.merge(E,h);o(w(g))}},O=()=>{try{if(c&&v(c),l){const E=JSON.parse(l),C=s.getObjectDiff(JSON.parse(n),E);j(C),u("")}}catch{u("Invalid JSON configuration")}},L=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:T,className:L?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(en,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Js,{className:"w-1/2 rounded shadow-none"})}),e.jsx(sn,{customCode:c,cardCustomCfgString:x,mergedConfig:l,onConfigChange:E=>o(E??""),onCodeChange:E=>i(E??"")})]}),e.jsx(tn,{error:d,hasCardCustomConfig:!!h,onReset:()=>{o(n),j(null)},onApply:O,onClose:()=>a(!1)})]})]})}function qe(t){const[a,n]=D.useState(null);return a}function Qs(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),{data:n,isLoading:r,isFetching:l,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(a.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:n,isLoading:r,isFetching:l,isError:o}}function Ws(){const{data:t,isLoading:a,isError:n}=Qs(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let o=a,c=n;return r.forEach((i,d)=>{var u;if(i.isLoading&&(o=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(x=>({name:x.name,pluginName:m.label,componentType:x.componentType,pluginType:m.type,icon:x.icon,chartType:x.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:o,isError:c}}function nn({onChartTypeChange:t}){const{setCardCustomCfg:a,setCardPreferences:n,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:o,isLoading:c,isError:i}=Ws(),d=D.useCallback((u,m)=>{a(null),n({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[a,n,r,l,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom visuals..."})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-destructive",children:"Failed to load custom visuals"})]}):!o||o.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Custom Charts"})}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:o.map((u,m)=>e.jsx(rn,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const rn=({text:t,icon:a,onClick:n})=>{const r=qe();return e.jsxs("button",{onClick:n,className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[r?e.jsx(r,{className:"h-6 w-6"}):e.jsx(Ae,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{title:t,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:t})]})};function ln({onChartTypeChange:t,iconClassName:a,searchQuery:n=""}){const{setCardType:r,setCardPreferences:l,setIsDevMode:o}=s.useEditorStore(x=>x.actions),{setCardCustomCfg:c,setCustomCardPreferences:i,setQueryConfig:d}=s.useEditorActions();function u(x,p){c(null),l({}),r(x),["custom","text","map"].includes(x)&&(o(!0),d(void 0)),t==null||t()}const h=[{type:"table",name:"Table",icon:s.Table2},{type:"bar",name:"Bar Chart",icon:s.ChartColumnIncreasing},{type:"line",name:"Line Chart",icon:s.ChartLine},{type:"stackedBar",name:"Stacked Bar",icon:s.ChartColumnStacked},{type:"stackedLine",name:"Stacked Line",icon:s.MdStackedLineChart},{type:"scatter",name:"Scatter",icon:s.ChartScatter},{type:"bubble",name:"Bubble",icon:s.TbChartBubble},{type:"pie",name:"Pie Chart",icon:s.ChartPie},{type:"doughnut",name:"Doughnut",icon:s.Donut},{type:"funnel",name:"Funnel",icon:s.TbChartFunnel},{type:"radar",name:"Radar",icon:s.Radar},{type:"polarArea",name:"Polar Area",icon:s.PiChartPolar},{type:"tornado",name:"Tornado",icon:s.Tornado},{type:"range",name:"Range",icon:s.ChartNoAxesGantt},{type:"bullet",name:"Bullet Chart",icon:s.BulletChartIcon},{type:"treemap",name:"Treemap",icon:s.TbChartTreemap},{type:"kpi",name:"KPI",icon:s.TiSortNumerically},{type:"text",name:"Text",icon:s.BookType},{type:"map",name:"Map",icon:s.Map},{type:"custom",name:"Custom",icon:Ae}].filter(x=>x.name.toLowerCase().includes(n.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:h.map(x=>{const p=x.icon;return e.jsxs("button",{onClick:()=>u(x.type),className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[e.jsx(p,{className:s.cn("h-6 w-6",a),strokeWidth:x.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:x.name})]},x.type)})})}function on({chartType:t,className:a,customIcon:n,componentName:r}){const l=qe();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:a});case"line":return e.jsx(s.ChartLine,{className:a});case"pie":return e.jsx(s.ChartPie,{className:a});case"radar":return e.jsx(s.Radar,{className:a});case"scatter":return e.jsx(s.ChartScatter,{className:a});case"bubble":return e.jsx(s.TbChartBubble,{className:a});case"doughnut":return e.jsx(s.Donut,{className:a});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:a});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:a});case"polarArea":return e.jsx(s.PiChartPolar,{className:a});case"treemap":return e.jsx(s.TbChartTreemap,{className:a});case"bullet":return e.jsx(s.BulletChartIcon,{className:a});case"funnel":return e.jsx(s.TbChartFunnel,{className:a});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:a});case"range":return e.jsx(s.ChartNoAxesGantt,{className:a});case"kpi":return e.jsx(s.TiSortNumerically,{className:a});case"text":return e.jsx(s.Type,{className:a});case"map":return e.jsx(s.Map,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:a});default:return e.jsx(s.Table2,{className:a})}}function Ys({variant:t="ghost"}){var i,d;const[a,n]=D.useState(!1),[r,l]=D.useState(""),o=s.useEditorStore(u=>u.card),c=o.type;return e.jsxs(s.Popover,{open:a,onOpenChange:u=>{n(u),u||l("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(on,{className:"size-4",chartType:c,customIcon:(i=o.customCardPreferences)==null?void 0:i.icon,componentName:(d=o.customCardPreferences)==null?void 0:d.componentName})})}),e.jsxs(s.PopoverContent,{onOpenAutoFocus:u=>u.preventDefault(),className:"z-[70] w-[360px] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search charts...",value:r,onChange:u=>l(u.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[e.jsx(ln,{onChartTypeChange:()=>n(!1),searchQuery:r}),e.jsx(nn,{onChartTypeChange:()=>n(!1)})]})]})]})}function cn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,o]=D.useState(!1),c=D.useRef(null),i=D.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(x){(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d())}function m(){const x=window.getSelection();if(x&&x.toString().trim()!==""){const p=x.toString();navigator.clipboard.writeText(p),o(!0),i.current=!0,setTimeout(()=>{o(!1),i.current=!1},1e3)}else i.current=!1}function h(){o(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function dn(){const t=s.useEditorStore(d=>{var u,m;return(m=(u=d.card.preferences)==null?void 0:u.chartOptions)==null?void 0:m.indexAxis}),a=s.useEditorStore(d=>d.card.type),{setChartOrientation:n,setCardPreferences:r}=s.useEditorStore(d=>d.actions),l=d=>{if(n(d),a!=="bullet")return;const u=d==="y"?"horizontal":"vertical",m=s.useEditorStore.getState().card.preferences,h={...m||{},bulletConfig:{...(m==null?void 0:m.bulletConfig)||{},orientation:u}};r(h)};function o(){const d=t??"x",u=()=>{l(d==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:d==="x"?e.jsx(Ue,{className:"size-4"}):e.jsx($e,{className:"size-4"})})}function c(){const d=()=>{l(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:d,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Ue,{className:"size-4"}):e.jsx($e,{className:"size-4"})})}function i(){const d=t??"y",u=()=>{l(d==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:d==="y"?e.jsx($e,{className:"size-4"}):e.jsx(Ue,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?c():a==="bullet"?i():o()})}function un({className:t}){var x,p,b,j,v,w,T,O;const a=s.useEditorStore(L=>L.card),{setCardPreferences:n,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[o,c]=D.useState(!1),i=((p=(x=a.preferences)==null?void 0:x.displayOptions)==null?void 0:p.showFilterInfo)??!0,d=((j=(b=a.preferences)==null?void 0:b.displayOptions)==null?void 0:j.showCardToolbar)??!0,u=((w=(v=a.preferences)==null?void 0:v.displayOptions)==null?void 0:w.showChrome)??!0,m=((O=(T=a.preferences)==null?void 0:T.displayOptions)==null?void 0:O.allowScroll)??!0,h=(L,E)=>{var g;const C={...a.preferences,displayOptions:{...(g=a.preferences)==null?void 0:g.displayOptions,[L]:E}};n(C);const f={...a,preferences:C};l(f),r(f)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:o,onOpenChange:c,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(Ms,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:L=>{h("showFilterInfo",L)},onSelect:L=>L.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:L=>{h("showCardToolbar",L)},onSelect:L=>L.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:L=>{h("showChrome",L)},onSelect:L=>L.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:L=>{h("allowScroll",L)},onSelect:L=>L.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]})]})]})})}function Xs(){const t=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>{var c,i;return(i=(c=o.card)==null?void 0:c.preferences)==null?void 0:i.chartOptions}),n=s.getChartGridStyle(a),{setChartGrid:r}=s.useEditorActions();function l(){const o=["xy","none","x","y"],i=(o.indexOf(n)+1)%o.length;r(o[i])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(dn,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(n==="xy"||!n)&&e.jsx(ze,{className:"size-4"}),n==="x"&&e.jsx(Ct,{className:"size-4"}),n==="y"&&e.jsx(Ut,{className:"size-4"}),n==="none"&&e.jsx(Ht,{className:"size-4"})]}),e.jsx(un,{})]})}function mn(){const t=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:o}=s.useEditorActions(),c=(b,j)=>{b.dataTransfer.setData("tabIndex",j.toString())},i=b=>{b.preventDefault()},d=(b,j)=>{const v=b.dataTransfer.getData("tabIndex");if(v===j.toString())return;const w=Array.from(t.cards),[T]=w.splice(parseInt(v),1);w.splice(j,0,T),n({...t,cards:w})};function u(b){const j=t.cards.filter(T=>T.id!==b),v=j[0],w={...t,cards:j,activeCardId:v.id};n(w),r(v.id),l(v)}function m(b,j){const v={...t,cards:[...t.cards,j],activeCardId:b.id};n(v),r(j.id)}function h(){const b={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,b)}function x(b){const j={dataSource:b.dataSource,connectionId:b.connectionId,lastSelectedDatabase:b.lastSelectedDatabase,lastSelectedSchema:b.lastSelectedSchema,lastSelectedTable:b.lastSelectedTable,lastSelectedDatamodelId:b.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(b,j)}function p(b,j){return b.cards.length===1&&(j.displayTab===!0||j.displayTab===void 0)||b.activeCardId!==j.id&&(j.displayTab===!0||j.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=j.displayTab===void 0?!1:!j.displayTab;l({...j,displayTab:v}),o({...j,displayTab:v})},children:j.displayTab===!0||j.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(kt,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((b,j)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,j),onDragOver:i,onDrop:v=>d(v,j),className:"",value:b.id,children:[p(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:v=>{l({...a,tabTitle:v}),o({...a,tabTitle:v})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:v=>{v.stopPropagation(),h()}}),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>x(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Xe(){const t=s.useEditorStore(v=>v.frame),a=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:l,setActiveTabCardId:o,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h,isError:x}=s.useDashboardCardQuery(a);function p(v){const w=t.cards.find(T=>T.id===v);if(w!=null&&w.sql){r||i(!0),o(v);return}if(w!=null&&w.queryConfig){r&&i(!1),b(v),o(v);return}r||b(v),o(v)}function b(v){const w={...t,cards:t.cards.map(O=>O.id===a.id?a:O),activeCardId:v};l(w);const T=w.cards.find(O=>O.id===v);T.sql&&d(!0),c(T)}function j(){return a.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:m||h,isError:x})})}):a.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Js,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(v=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:v.id,children:j()},v.id)),e.jsx(mn,{})]})}function gs({children:t}){var C,f;s.useEditorStore(g=>g.frame);const a=s.useEditorStore(g=>g.card),n=s.useEditorStore(g=>g.isDevMode),r=s.useEditorStore(g=>g.isShowingVisual),l=s.useDashboardStore(g=>g.isVisualEditing),o=s.useEditorStore(g=>g.pythonStdOut);s.useEditorStore(g=>g.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:x,isLoading:p,isFetching:b,errorMessage:j,refetch:v}=s.useDashboardCardQuery(a),[w,T]=D.useState(!1);D.useEffect(()=>{b||T(!1)},[b]);function O(){const g=JSON.stringify(x==null?void 0:x.records,null,2),N=new Blob([g],{type:"application/json"}),A=URL.createObjectURL(N),S=document.createElement("a");S.href=A,S.download=`${a.title}.json`,S.click()}function L(){const N=[Object.keys(x==null?void 0:x.records.reduce((I,k)=>({...I,...k}),{})).join(","),...((x==null?void 0:x.records)||[]).map(I=>Object.values(I).join(","))].join(`
|
|
244
|
+
`),A=new Blob([N],{type:"text/csv"}),S=URL.createObjectURL(A),P=document.createElement("a");P.href=S,P.download=`${a.title}.csv`,P.click()}function E(){const g=`Can you get the documentation for ${a.type} chart?`;u(g)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ys,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:E,children:e.jsx(vt,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(an,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:L,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:O,children:e.jsx(Tt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(x==null?void 0:x.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:p||b,onClick:()=>{T(!0),v()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":w})})}),e.jsx(Xs,{})]}),a.type==="table"&&a.sql&&n&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((f=(C=a.preferences)==null?void 0:C.tablePrefs)==null?void 0:f.enableDevModePagination)??!1,onCheckedChange:g=>{var N;h({...a.preferences,tablePrefs:{...(N=a.preferences)==null?void 0:N.tablePrefs,enableDevModePagination:g}}),v()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(xn,{})]}),r?e.jsx(Xe,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:o&&e.jsx(hn,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":o}),children:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:(x==null?void 0:x.records)||[]}),j&&e.jsx(cn,{error:j})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function hn(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function xn(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ye({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:o,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",o),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function pn(){var j,v;const t=s.useEditorStore(w=>w.card.customCardPreferences),{data:a}=Qs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(w=>w.card),l=s.useEditorStore(w=>w.frame),o=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(j=d==null?void 0:d.visuals)==null?void 0:j.find(w=>w.name===(t==null?void 0:t.componentName));function m(w,T){if(!t)return;const L={...(t==null?void 0:t.dataInputCardIds)||{},[w]:{cardId:T,hookRef:null}};c({...t,dataInputCardIds:L})}function h(w){var O,L;const T=(O=l==null?void 0:l.cards)==null?void 0:O.filter(E=>{var C;return((C=E==null?void 0:E.customCardPreferences)==null?void 0:C.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(L=w==null?void 0:w.dataInputs)==null?void 0:L.map((E,C)=>{var f,g;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(ye,{className:"col-span-6 h-8 w-full justify-between",label:"",options:T||[],value:((g=(f=t==null?void 0:t.dataInputCardIds)==null?void 0:f[C])==null?void 0:g.cardId)||"",onValueChange:N=>m(C,N)})]},C+Math.random())})})}function x(w,T,O=[],L=""){var E,C;return t?w==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[T])||L,onChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[T]:f.target.value}})}},T):w==="select"?e.jsx(ye,{className:"h-8 w-full",label:"",options:O,value:((C=t==null?void 0:t.settings)==null?void 0:C[T])||L,onValueChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[T]:f}})}}):null:null}function p(w){const T=Object.entries((w==null?void 0:w.settings)||{});return e.jsx("div",{className:"space-y-3",children:T.map(([O,L])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:L.title}),x(L.ui,O,L.options,L.defaultValue)]},O))})}function b(w){t&&c({...t,visualType:w,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(ye,{icon:e.jsx(bt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:w=>c({...t||{url:"",componentName:""},url:w})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:o,onValueChange:b,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(ye,{icon:e.jsx(St,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(w=>w.type===o).map(w=>({value:w.name,label:w.name})))||[],value:t.componentName,onValueChange:w=>{console.log("changing value",w),c({...t,componentName:w})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function Te(){const[t,a]=D.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),o=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),D.useEffect(()=>{o&&a(new Array(o.length).fill(!1))},[o]);function c(u,m){var h,x;m?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(x=n==null?void 0:n.onClickFilter)==null?void 0:x.filter(p=>p.columnIndex!==u)}),a(p=>{const b=[...p];return b[u]=!1,b}))}function i(u,m){var x;const h=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);l({...n,onClickFilter:h})}function d(u){var m,h,x,p;if(t!=null&&t[u]||(h=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(p=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(b=>b.columnIndex===u))==null?void 0:p.expression,onChange:b=>i(u,b),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:o==null?void 0:o.map((u,m)=>{var h,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(p=>{const b=[...p];return b[m]=!p[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function fn({idx:t}){var i;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(i=a==null?void 0:a.chartOptions)==null?void 0:i.indexAxis,o=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!o)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const h={...o};h.datalabels=m;const x=n==null?void 0:n.map(p=>p.idx===u?h:p);r({...a,datasetOptions:x})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Ls,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Bt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Rt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function gn(){const t=s.useEditorStore(o=>o.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(o=>!s.METADATA_KEYS.includes(o));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const o=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(o);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function rs({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Zs(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:o,transformedMetricKeys:c,keys:i}=gn();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:o.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:et(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(st,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function et(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function st({col:t,idx:a,className:n,iconClassName:r,children:l}){const o=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,x;return(x=(h=m.card)==null?void 0:h.preferences)==null?void 0:x.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...o,datasetOptions:[...c||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const x=c==null?void 0:c.map(p=>p.idx===a?h:p);d({...o,datasetOptions:x})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(rs,{className:"max-w-[100px]",title:t,children:et(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(fn,{idx:a})]})]})}function Me(){const t=s.useDashboardStore(i=>i.dashboard.filters),a=s.useEditorStore(i=>i.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Gs();function o(i){const d=l(i,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(jn,{onSelect:o,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function jn({columns:t,onSelect:a}){var c;const[n,r]=Je.useState(!1),[l,o]=Je.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(i=>i.column_name===l))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===l?"":d;o(u),r(!1),u&&a(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function bn({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Zs,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Te,{}),e.jsx(Me,{})]})]})]})})}function vn({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Te,{}),e.jsx(Me,{})]})]})]})})}function tt(){const t=s.useEditorStore(i=>i.card.type),a=s.useEditorStore(i=>i.isDevMode),n=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function l(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function o(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=n==null?void 0:n.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?o():c()})}const yn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Nn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Cn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Sn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(tt,{}),e.jsx(Te,{}),e.jsx(Me,{})]})]})}function Sn(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(yn,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Nn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function wn({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},a(u)}function l(c){const i=[...t];i.splice(c,1),a(i)}function o(){a([...t,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:o,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Dn(){var m,h,x,p,b;const t=s.useEditorStore(j=>j.card.preferences),a=s.useEditorStore(j=>j.actions.setCardPreferences),n=s.useEditorStore(j=>j.card),r=s.hasValidCardConfig(n.config),l=s.useEditorStore(j=>j.actions.setNumberFormat);s.useEditorStore(j=>{var v,w;return(w=(v=j.card.preferences)==null?void 0:v.formatNumber)==null?void 0:w.decimalPlaces});const o=s.useEditorStore(j=>{var v,w;return(w=(v=j.card.preferences)==null?void 0:v.formatNumber)==null?void 0:w.locale}),c=s.useEditorStore(j=>{var v,w;return(w=(v=j.card.preferences)==null?void 0:v.formatNumber)==null?void 0:w.currency});s.useEditorStore(j=>j.actions.setFilterOnClickField);const i=s.useEditorStore(j=>{var v,w;return(w=(v=j.card.preferences)==null?void 0:v.formatNumber)==null?void 0:w.colorRanges})||[],d=s.useEditorStore(j=>j.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(j=>j.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:j=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:j}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:o||"none",onValueChange:j=>{var v,w,T;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((w=t==null?void 0:t.formatNumber)==null?void 0:w.currency)||"",j,((T=t==null?void 0:t.formatNumber)==null?void 0:T.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(j=>e.jsx(s.SelectItem,{value:j.locale,children:j.locale},j.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:j=>{var v,w,T;console.log("currency",j),l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,j==="none"?"":j,((w=t==null?void 0:t.formatNumber)==null?void 0:w.locale)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(j=>e.jsx(s.SelectItem,{value:j,children:j},j))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((p=(x=t==null?void 0:t.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:p.toString())||"0",onValueChange:j=>{var v,w,T;return l(Number(j),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((w=t==null?void 0:t.formatNumber)==null?void 0:w.locale)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(j=>e.jsx(s.SelectItem,{value:j,children:j},j))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:j=>{var v,w,T;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((w=t==null?void 0:t.formatNumber)==null?void 0:w.currency)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",j.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(wn,{colorRanges:i,setColorRanges:d})]})]})}function kn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Dn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function _e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Tn=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],En=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],In=En.map(t=>({label:t,value:t}));function An(){var d,u,m,h,x,p,b,j,v,w,T,O,L,E,C,f,g,N;const t=s.useEditorStore(A=>A.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=D.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:o}=s.useTopoJson(t),c=Object.keys((o==null?void 0:o.objects)||{}).map(A=>({label:A,value:A}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(_e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ye,{className:"h-9",options:i,onValueChange:A=>{console.log("value",A),l({...t.preferences,mapVisualOptions:{topoJsonUrl:A}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:A=>{r(A.target.value)},onBlur:()=>{var A;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(A=t.preferences)==null?void 0:A.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ye,{className:"h-9",options:c,value:((p=(x=t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:A=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,objectKey:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ye,{className:"h-9",options:Tn,value:((j=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:j.projection)||"",label:"Projection",onValueChange:A=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projection:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ye,{className:"h-9",options:In,value:((w=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:w.colorScale)||"",label:"Select Color Scale",onValueChange:A=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,colorScale:A}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((O=(T=t.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:A=>{var S;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionScale:Number(A.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(E=(L=t.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:C[0])||0,onChange:A=>{var S,P,I,k;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[Number(A.target.value),((k=(I=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:k[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(g=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.projectionOffset)==null?void 0:N[1])||0,onChange:A=>{var S,P,I,k;l({...t.preferences,mapVisualOptions:{...(S=t.preferences)==null?void 0:S.mapVisualOptions,projectionOffset:[((k=(I=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:k[0])||0,Number(A.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Te,{})]})}function Mn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Mn,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Te,{}),e.jsx(Me,{})]})]})]})})}function Ln(){const t=s.useEditorStore(r=>{var l,o;return(o=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:o.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(ye,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Zs,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Te,{}),e.jsx(Me,{})]})]})]})})}function Fn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var o;return(o=l.card)==null?void 0:o.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Te,{}),e.jsx(Me,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function at({color:t,onColorChange:a,onClose:n}){const[r,l]=D.useState(0),[o,c]=D.useState(100),[i,d]=D.useState(50),[u,m]=D.useState(t);D.useEffect(()=>{const v=js(t);if(v){const w=bs(v.r,v.g,v.b);l(w.h),c(w.s),d(w.l),m(t)}},[t]);const h=v=>{l(v),p(v,o,i)},x=v=>{const w=v.currentTarget.getBoundingClientRect(),T=Math.max(0,Math.min(1,(v.clientX-w.left)/w.width)),O=Math.max(0,Math.min(1,(v.clientY-w.top)/w.height)),L=T*100,E=(1-O)*100;c(L),d(E),p(r,L,E)},p=(v,w,T)=>{const O=On(v,w,T),L=Pn(O.r,O.g,O.b);m(L)},b=v=>{if(m(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const w=js(v);if(w){const T=bs(w.r,w.g,w.b);l(T.h),c(T.s),d(T.l)}}},j=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:v=>{v.buttons===1&&x(v)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${o}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>h(Number(v.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:v=>b(v.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:j,children:"OK"})]})]})}function js(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Pn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function bs(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let o=0,c=0;const i=(r+l)/2;if(r!==l){const d=r-l;switch(c=i>.5?d/(2-r-l):d/(r+l),r){case t:o=((a-n)/d+(a<n?6:0))/6;break;case a:o=((n-t)/d+2)/6;break;case n:o=((t-a)/d+4)/6;break}}return{h:Math.round(o*360),s:Math.round(c*100),l:Math.round(i*100)}}function On(t,a,n){t/=360,a/=100,n/=100;let r,l,o;if(a===0)r=l=o=n;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=n<.5?n*(1+a):n+a-n*a,d=2*n-i;r=c(d,i,t+1/3),l=c(d,i,t),o=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(o*255)}}const Bn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function nt(){var O,L,E,C,f,g,N,A,S,P;const t=s.useEditorStore(I=>I.card),a=s.useEditorStore(I=>{var k;return(k=I.card)==null?void 0:k.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[o,c]=D.useState({}),[i,d]=D.useState(null),[u,m]=D.useState(null),h=D.useMemo(()=>{var M,F,G,V,B,q,z;if(!(l!=null&&l.records)||l.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",k=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",y=((M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)&&t.config.pivotByColumns.length>0;if((I||k)&&y){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const _=new Set;return l.pivotSchema.forEach(W=>{W.alias&&_.add(W.alias)}),Array.from(_)}if(l.records.length>0){const _=l.records[0],W=Object.keys(_),ee=new Set;(F=t==null?void 0:t.config)!=null&&F.groupByColumns&&t.config.groupByColumns.forEach(Y=>{ee.add(Y.label||Y.name),ee.add(Y.alias||Y.name)});const te=new Set;return(G=t==null?void 0:t.config)!=null&&G.metricColumns&&t.config.metricColumns.forEach(Y=>{const U=Y.alias||Y.name;te.add(U),te.add(`${U}_count`),te.add(`${U}_sum`),te.add(`${U}_avg`),te.add(`${U}_min`),te.add(`${U}_max`);const H=Y.entityName||Y.qualifiedEntityName;H&&(te.add(`${H}_${U}`),te.add(`${H}_${U}_count`))}),W.filter(Y=>!ee.has(Y)&&!te.has(Y))}}if((k||I)&&!y&&((B=(V=t==null?void 0:t.config)==null?void 0:V.metricColumns)!=null&&B.length))return t.config.metricColumns.map(_=>_.alias||_.label||_.name);if((z=(q=t==null?void 0:t.config)==null?void 0:q.groupByColumns)!=null&&z.length){const _=t.config.groupByColumns[0],W=_.label||_.name,ee=new Set;return l.records.forEach(te=>{const ae=te[W];ae!=null&&ee.add(String(ae))}),Array.from(ee)}return[]},[l,(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns,(L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns,(E=t==null?void 0:t.config)==null?void 0:E.metricColumns,t==null?void 0:t.type]),x=D.useMemo(()=>s.getDefaultChartColors(),[]);D.useEffect(()=>{const I={};h.forEach((k,y)=>{I[k]=s.getColorForValue(k,y,a==null?void 0:a.colorConfig)}),c(I)},[h,a==null?void 0:a.colorConfig,x]);const p=(I,k)=>{const y={...o,[I]:k};c(y);const M={...a||{},colorConfig:{segments:y}};n(M);const F={...t,preferences:M};r(F)},b=(I,k)=>{var B;const y=x[k%x.length],{[I]:M,...F}=((B=a==null?void 0:a.colorConfig)==null?void 0:B.segments)||{},G={...a||{},colorConfig:{segments:F}};n(G);const V={...t,preferences:G};r(V),c(q=>({...q,[I]:y}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(C=t==null?void 0:t.config)==null?void 0:C.groupByColumns)==null?void 0:f.length)||((N=(g=t==null?void 0:t.config)==null?void 0:g.pivotByColumns)==null?void 0:N.length):(S=(A=t==null?void 0:t.config)==null?void 0:A.groupByColumns)==null?void 0:S.length)||["table","kpi","text","custom"].includes(t.type))return null;const w=()=>{const I={...a||{},colorConfig:{segments:{}}};n(I);const k={...t,preferences:I};r(k);const y={};h.forEach((M,F)=>{y[M]=s.getColorForValue(M,F,void 0)}),c(y)},T=Object.keys(((P=a==null?void 0:a.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:T&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:w,children:[e.jsx(xs,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((I,k)=>{const y=s.isDefaultColor(o[I],k),M=!y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===I,onOpenChange:F=>d(F?I:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:o[I]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:x.slice(0,10).map((F,G)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",o[I]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{p(I,F),d(null)},children:[G===k%x.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:F})]},`default-${G}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Bn.map((F,G)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",o[I]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{p(I,F),d(null)},children:e.jsx("span",{className:"sr-only",children:F})},`preset-${G}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:I,color:o[I]}),d(null)},children:"Custom color"}),!y&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(I,k),d(null)},children:[e.jsx(xs,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),M&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(at,{color:u.color,onColorChange:I=>{p(u.value,I),m(null)},onClose:()=>m(null)})})]})]})})]})}function Ne({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[o,c]=D.useState(t??""),[i,d]=D.useState(!1);D.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(o),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:i?o:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&o!==t?u():h.key==="Escape"&&m()},"aria-label":n||"Edit field"}),i&&o!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Vn=["auto","number","currency","percent","scientific","date"],Rn=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],zn=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],qn=t=>t.charAt(0).toUpperCase()+t.slice(1);function ls({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",o=(i,d)=>{a({...t,[i]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:i=>o("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Vn.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":qn(i)},i))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>o("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>o("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rn.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>o("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>o("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:zn.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>o("prefix",i.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>o("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>o("negativeInParentheses",i)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>o("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>o("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function vs({axis:t,label:a,type:n,config:r,onChange:l}){var h,x,p,b,j,v,w,T,O,L,E,C;const o=(f,g)=>{l({...r,[f]:g})},c=(f,g)=>{var N,A;l({...r,name:{enabled:f==="enabled"?g:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,text:f==="text"?g:(A=r==null?void 0:r.name)==null?void 0:A.text}})},i=(f,g)=>{var N,A;l({...r,labels:{enabled:f==="enabled"?g:((N=r==null?void 0:r.labels)==null?void 0:N.enabled)??!0,rotation:f==="rotation"?g:(A=r==null?void 0:r.labels)==null?void 0:A.rotation}})},d=(f,g)=>{l({...r,scale:{...r==null?void 0:r.scale,[f]:g===""?"auto":Number(g)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>o("enabled",f),onClick:f=>f.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:f=>c("enabled",f)})]}),((x=r==null?void 0:r.name)==null?void 0:x.enabled)&&e.jsx(Ne,{placeholder:`${a} title`,value:((p=r==null?void 0:r.name)==null?void 0:p.text)||"",onSave:f=>c("text",f),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:f=>o("position",f),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":s.titleCase(f)},f))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((b=r==null?void 0:r.labels)==null?void 0:b.enabled)!==!1,onCheckedChange:f=>i("enabled",f)})]}),((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((v=r==null?void 0:r.labels)==null?void 0:v.rotation)||"auto"),onValueChange:f=>i("rotation",f==="auto"?"auto":Number(f)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),n==="value"&&e.jsx(ls,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>l({...r,formatOptions:f}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((w=r==null?void 0:r.scale)==null?void 0:w.min)==="auto"||((T=r==null?void 0:r.scale)==null?void 0:T.min)===void 0?"":String(r.scale.min),onSave:f=>d("min",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((O=r==null?void 0:r.scale)==null?void 0:O.max)==="auto"||((L=r==null?void 0:r.scale)==null?void 0:L.max)===void 0?"":String(r.scale.max),onSave:f=>d("max",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.stepSize)==="auto"||((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>d("stepSize",f),className:""})})]})]})]})]})]})}function rt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const o=(c,i)=>{const u={...a||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};n(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(vs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:a==null?void 0:a.xAxisConfig,onChange:c=>o("x",c)}),l.hasYAxis&&e.jsx(vs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:a==null?void 0:a.yAxisConfig,onChange:c=>o("y",c)})]})})]})}function lt(){const t=s.useEditorStore(u=>u.card),a=s.useEditorStore(u=>{var m,h,x,p;return(p=(x=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:x.plugins)==null?void 0:p.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",o=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...a,[u]:m};n(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??o,onCheckedChange:u=>c("display",u)})]}),((a==null?void 0:a.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||l,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function ot(){var S,P,I,k,y,M,F,G,V;const t=s.useEditorStore(B=>B.card),a=s.useEditorStore(B=>{var q,z;return(z=(q=B.card)==null?void 0:q.preferences)==null?void 0:z.dataLabelsConfig}),n=s.useEditorStore(B=>{var q;return(q=B.card)==null?void 0:q.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const o=((S=n==null?void 0:n.chartOptions)==null?void 0:S.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(I=(P=n==null?void 0:n.chartOptions)==null?void 0:P.plugins)==null?void 0:I.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=t.type==="treemap"?!0:m,x=(a==null?void 0:a.enabled)!==void 0?a.enabled:h,p=(B,q)=>{const z={...a,[B]:q},_={...t.preferences||{},dataLabelsConfig:z};r(_);const W={...t,preferences:_};l(W)},b=(B,q)=>{const z={...a,font:{...a==null?void 0:a.font,[B]:q}},_={...t.preferences||{},dataLabelsConfig:z};r(_);const W={...t,preferences:_};l(W)},j=(B,q)=>{const z={...a,formatOptions:{...a==null?void 0:a.formatOptions,[B]:q}},_={...t.preferences||{},dataLabelsConfig:z};r(_);const W={...t,preferences:_};l(W)},v=()=>{const B=t.type;return B==="stackedBar"||B==="stackedLine"||B==="pie"||B==="doughnut"?"center":o?"right":"top"},w=t.type!=="treemap",T=t.type!=="treemap",O=v();let L=[];w&&(c||i?L=["center"]:L=["auto",...(o?["center","left","right"]:["center","top","bottom"]).filter(q=>q!==O),"custom"]);const E=()=>s.titleCase(O),C=["center","start","end"],f=["center","start","end","top","bottom"],g=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],N=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],A=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:x,onCheckedChange:B=>p("enabled",B)})]}),x&&e.jsxs(e.Fragment,{children:[w&&!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||"auto",onValueChange:B=>p("position",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:B==="auto"?E():B==="custom"?"Custom (Advanced)":s.titleCase(B)},B))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:B=>p("showTotal",B)})]}),(a==null?void 0:a.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(a==null?void 0:a.anchor)||"center",onValueChange:B=>p("anchor",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:s.titleCase(B)},B))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((a==null?void 0:a.align)||"center"),onValueChange:B=>p("align",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:s.titleCase(B)},B))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(a==null?void 0:a.format)||(d?"auto":"none"),onValueChange:B=>p("format",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:g.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:B==="auto"&&d?"Auto (Use Axis)":B==="none"?"None (Raw Value)":s.titleCase(B)},B))})]})]}),(a==null?void 0:a.format)&&!["auto","none"].includes(a.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(a.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String(((k=a==null?void 0:a.formatOptions)==null?void 0:k.decimalPlaces)??(a.format==="currency"?2:a.format==="percent"?1:0)),onSave:B=>j("decimalPlaces",Number(B)),className:""})})]}),a.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((y=a==null?void 0:a.formatOptions)==null?void 0:y.currency)||"USD",onValueChange:B=>j("currency",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(B=>e.jsx(s.SelectItem,{value:B.value,className:"text-xs",children:B.label},B.value))})]})]}),["number","currency"].includes(a.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((M=a==null?void 0:a.formatOptions)==null?void 0:M.useSuffix)??!1,onCheckedChange:B=>j("useSuffix",B)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((F=a==null?void 0:a.formatOptions)==null?void 0:F.locale)||"en-US",onValueChange:B=>j("locale",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(B=>e.jsx(s.SelectItem,{value:B.value,className:"text-xs",children:B.label},B.value))})]})]})]}),T&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"12",value:String(((G=a==null?void 0:a.font)==null?void 0:G.size)||12),onSave:B=>b("size",Number(B)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((V=a==null?void 0:a.font)==null?void 0:V.weight)||"normal",onValueChange:B=>b("weight",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(a==null?void 0:a.color)==="auto"||!(a!=null&&a.color)?"auto":"custom",onValueChange:B=>{B==="auto"&&p("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String((a==null?void 0:a.rotation)||0),onSave:B=>p("rotation",Number(B)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Be({value:t,onCommit:a,type:n="text",placeholder:r,className:l}){const[o,c]=D.useState(t),i=D.useRef(!1);D.useEffect(()=>{c(t)},[t]);const d=()=>{if(i.current){i.current=!1;return}o!==t&&a(o)},u=m=>{if(m.key==="Enter"){m.currentTarget.blur();return}m.key==="Escape"&&(i.current=!0,c(t),m.currentTarget.blur())};return e.jsx(s.Input,{type:n,placeholder:r,value:o,onChange:m=>c(m.target.value),onBlur:d,onKeyDown:u,className:l})}const ys=["poor","satisfactory","good"];function Ns(t){if(!t)return;const a={...t};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function it(){var I,k;const t=s.useEditorStore(y=>y.card.preferences),a=s.useEditorStore(y=>y.card),n=s.useEditorStore(y=>y.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),o=D.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),i=s.hasValidCardConfig(a==null?void 0:a.config)&&!n,[d,u]=D.useState(o.showRanges??!1),[m,h]=D.useState(o.rangesArePercentages??!1),x=o.disableAutoComparative?!1:o.comparativeMetricKey!==void 0||!i,[p,b]=D.useState(x);D.useEffect(()=>{u(o.showRanges??!1)},[o.showRanges]),D.useEffect(()=>{h(o.rangesArePercentages??!1)},[o.rangesArePercentages]);const j=o.targetValue===void 0?"":String(o.targetValue);D.useEffect(()=>{const y=o.disableAutoComparative?!1:o.comparativeMetricKey!==void 0||!i;b(y)},[o.disableAutoComparative,o.comparativeMetricKey,i]);const v=D.useMemo(()=>{var y,M;return((M=(y=a==null?void 0:a.config)==null?void 0:y.metricColumns)==null?void 0:M.map(F=>{const G=F.label||F.name||F.alias||"";return{value:G,label:G}}))||[]},[(I=a==null?void 0:a.config)==null?void 0:I.metricColumns]);D.useEffect(()=>{var z,_;if(!t||v.length===0)return;const y={};let M=!1;const F=(z=v[1])==null?void 0:z.value;!o.targetMetricKey&&F&&(y.targetMetricKey=F,M=!0);const G=(_=v[2])==null?void 0:_.value;!o.comparativeMetricKey&&!o.disableAutoComparative&&G&&(y.comparativeMetricKey=G,M=!0);const V=v.slice(3),B={...o.rangeKeys||{}};let q=!1;if(ys.forEach((W,ee)=>{!B[W]&&V[ee]&&(B[W]=V[ee].value,q=!0)}),q&&(y.rangeKeys=B,M=!0,o.showRanges===void 0&&(y.showRanges=!0)),M){const W=Ns({...o,...y});r({...t,bulletConfig:W})}},[v,o,t,r]);const w=y=>{const M=Ns({...o,...y});r({...t,bulletConfig:M})},T=(y,M)=>{const F={...o.rangeKeys||{},[y]:M.trim()};M.trim()||delete F[y],w({rangeKeys:Object.keys(F).length>0?F:void 0})},O=(y,M)=>{const F=M===""?void 0:Number(M),G={...o.ranges||{}};F===void 0||Number.isNaN(F)?delete G[y]:G[y]=F,w({ranges:Object.keys(G).length?G:void 0})},L=y=>{if(y===""){w({targetValue:void 0});return}const M=Number(y);w({targetValue:Number.isNaN(M)?void 0:M})},E=(y,M)=>{const F=M.trim(),G={...o.rangeLabels||{}};F?G[y]=F:delete G[y],w({rangeLabels:Object.keys(G).length>0?G:void 0})},C=y=>{u(y),w({showRanges:y})},f=y=>{h(y),w({rangesArePercentages:y})},g=o.orientation||(((k=t==null?void 0:t.chartOptions)==null?void 0:k.indexAxis)==="y"?"horizontal":"vertical"),N=y=>{w({orientation:y}),l(y==="horizontal"?"y":"x")},A=[{value:"__none",label:"None"},...v.map(y=>({value:y.value,label:y.label}))],S=A,P=y=>{if(b(y),!y){w({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!i){w({disableAutoComparative:!1});return}if(o.comparativeMetricKey)w({disableAutoComparative:!1});else{const M=v.find(F=>F.value!==o.targetMetricKey);w({comparativeMetricKey:M==null?void 0:M.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:g,onValueChange:y=>N(y),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),i&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:o.targetMetricKey||"__none",onValueChange:y=>w({targetMetricKey:y==="__none"?void 0:y}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),v.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),i?e.jsxs(s.Select,{value:o.comparativeMetricKey||"__none",onValueChange:y=>w({comparativeMetricKey:y==="__none"?void 0:y,disableAutoComparative:y==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:A.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:y=>P(y)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(Be,{type:"number",className:"h-8 text-xs",value:j,onCommit:L,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(s.SmallSwitch,{checked:d,onCheckedChange:C})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:m,disabled:!d,onChange:y=>f(y.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),d&&e.jsx("div",{className:"space-y-3",children:ys.map(y=>{var M,F,G,V,B;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," LABEL"]}),e.jsx(Be,{placeholder:`Display label (${y})`,value:((M=o.rangeLabels)==null?void 0:M[y])||"",onCommit:q=>E(y,q),className:"h-8 text-xs"})]}),i?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN"]}),e.jsxs(s.Select,{value:((F=o.rangeKeys)==null?void 0:F[y])||"__none",onValueChange:q=>{q==="__none"?T(y,""):T(y,q)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:S.map(q=>e.jsx(s.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN KEY"]}),e.jsx(Be,{placeholder:"Column key",value:((G=o.rangeKeys)==null?void 0:G[y])||"",onCommit:q=>T(y,q),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," VALUE"]}),e.jsx(Be,{type:"number",placeholder:m?"0.80":"Static value",value:((V=o.ranges)==null?void 0:V[y])===void 0?"":String((B=o.ranges)==null?void 0:B[y]),onCommit:q=>O(y,q),className:"h-8 text-xs"})]})]},y)})})]})]})]})}function Gn(){const t=s.useEditorStore(a=>a.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="bullet"&&e.jsx(it,{}),e.jsx(nt,{}),e.jsx(rt,{}),e.jsx(lt,{}),e.jsx(ot,{})]})]})}const $n=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Un=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Kn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function _n(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=o=>r.includes(n)?o:e.jsxs(e.Fragment,{children:[o,e.jsx(Gn,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(Ln,{}));case"tornado":case"pyramid":return l(e.jsx(Oe,{docContent:$n,cardType:n}));case"kpi":return e.jsx(kn,{});case"line":case"bar":return l(e.jsx(bn,{cardType:n}));case"range":return l(e.jsx(Oe,{docContent:Un,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Oe,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(vn,{cardType:n}));case"table":return e.jsx(Fn,{cardType:n});case"text":return e.jsx(Oe,{docContent:Kn,cardType:n,suffix:"Visual"});case"map":return e.jsx(An,{});case"custom":return e.jsx(pn,{});default:return l(e.jsx(Cn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Hn(){const t=D.useRef(null),a=D.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return D.useEffect(()=>{var l,o,c,i;r?((l=t.current)==null||l.resize(0),(o=a.current)==null||o.resize(0)):((c=t.current)==null||c.resize(25),(i=a.current)==null||i.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Qa,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(_n,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(gs,{})})]}):e.jsx(gs,{})})]})}function Jn(t){var ue;s.useAIInteractionStore($=>$.currentAIContext);const[a,n]=D.useState(""),[r,l]=D.useState(null),{authToken:o,tokenProps:c}=s.useSemaphorContext(),i=s.useEditorStore($=>{var Q;return(Q=$==null?void 0:$.card)==null?void 0:Q.sql}),d=s.useEditorStore($=>$.isDevMode),u=s.useEditorStore($=>{var Q;return(Q=$==null?void 0:$.card)==null?void 0:Q.python}),{setCardPython:m,setCardSql:h,setRunSql:x,switchCardType:p,setQueryConfig:b}=s.useEditorActions(),j=s.useEditorStore($=>$.currentAssitantScope)||[],v=s.useEditorStore($=>$.userInputForAI),w=s.useEditorStore($=>$.triggerAIRun),T=s.useEditorStore($=>$.card),O=s.useEditorStore($=>$.selectedDatabaseName),L=s.useEditorStore($=>$.selectedTableName),E=s.useEditorStore($=>$.selectedConnectionId),C=s.useEditorStore($=>$.selectedSchemaName),f=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:g,refetch:N,data:A}=s.useDashboardCardQuery(T),{setTriggerAIRun:S,setCurrentAssitantScope:P,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:k,connectionType:y,selectedDatamodelId:M}=s.useEditorAside(),F=(ue=s.useDashboardQuery().data)==null?void 0:ue.assistantProfileId,{messages:G,setMessages:V,regenerate:B,error:q,sendMessage:z,status:_,addToolResult:W,stop:ee,clearError:te}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const $=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:F,isDevMode:d,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:Q})=>({body:{...Q,messages:s.cleanupIncompleteMessages($)}})}),onError:$=>{var Q;if($.name==="AbortError"||(Q=$.message)!=null&&Q.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",$)},onToolCall:ae,onFinish({isAbort:$,isDisconnect:Q,isError:de}){n(""),console.log($?"[Editor Assistant] Stream aborted by user":Q?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});D.useEffect(()=>{w&&v&&(z({role:"user",parts:[{type:"text",text:v}]}),S(!1))},[w,v,z,S]);async function ae({toolCall:$}){var Q,de,xe,fe,ie,R,se,Z,je,ge,be,ve,me,Ee,Se,we;if(["createChartFromSql","createForecast"].includes($.toolName)){const J=((Q=$.input)==null?void 0:Q.sql)??((de=$.args)==null?void 0:de.sql),ne=((xe=$.input)==null?void 0:xe.python)??((fe=$.args)==null?void 0:fe.python),re=((ie=$.input)==null?void 0:ie.chartType)??((R=$.args)==null?void 0:R.chartType);p(re),h(J),m(ne),x(!0),W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!i){W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:i,python:u||""}})}else if($.toolName==="generateQueryConfig"){n("Generating query config...");const J=((se=$.input)==null?void 0:se.chartType)??((Z=$.args)==null?void 0:Z.chartType),ne=((je=$.input)==null?void 0:je.queryConfig)??((ge=$.args)==null?void 0:ge.queryConfig);((be=$.input)==null?void 0:be.cardConfig)??((ve=$.args)==null||ve.cardConfig),p(J),I(ne),h(void 0),m(void 0);const re=await N();if((me=re==null?void 0:re.data)!=null&&me.error){W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:ne,message:(Ee=re==null?void 0:re.data)==null?void 0:Ee.error.message}});return}if((Se=re==null?void 0:re.data)!=null&&Se.records){W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized"}});return}W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized",records:(we=re==null?void 0:re.data)==null?void 0:we.records}})}else n("Analyzing...")}function Y($){const Q=s.removeFromScopeArray(j,$);U(Q)}function U($){const Q=s.sanitizeAIScope($);P(Q),V(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}]}])}function H(){const $={databaseName:O||"",schemaName:C||"",tableName:L||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(k),connectionId:E||"",connectionType:y||""},Q=s.dedup([...j,$]);U(Q)}function X(){const $={databaseName:O||"",schemaName:C||"",tableName:L||"",datamodelName:s.resolveDatamodelName(k),connectionId:E||"",connectionType:y||"",datamodelId:M||""};if(!s.isInAiScopeArray([...f||[],...j],$)||j.length===0){const de=s.dedup([...f||[],...j,$]).filter(xe=>xe.connectionId===$.connectionId);U(de)}}const ce=!["ready","error"].includes(_),pe=s.getErrorMessage(q);return{messages:G,setMessages:V,sendMessage:z,regenerate:B,isLoading:ce,handleSetAIScope:X,handleAddCurrentTableToScope:H,removeFromCurrentSelections:Y,currentAssitantScope:j,setCurrentAssitantScope:P,stop:ee,status:_,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:pe,clearError:te}}const Qn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Cs({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=D.useRef(null),[l,o]=D.useState(!1),[c,i]=D.useState(s.isDevEnv),[d,u]=D.useState(!1),[m,h]=D.useState(!1),[x,p]=D.useState(!1),b=t??x,j=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:w}=s.useQueueActions(),{clearFileAttachments:T}=s.useFileActions(),O=s.useFileAttachments("editor"),L=s.useDashboardStore(J=>J.dashboard.aiContext),E=s.useEditorStore(J=>J.card.dataSource),C=s.useEditorStore(J=>J.actions.setCardSql),f=s.useEditorStore(J=>J.actions.setRunSql),g=s.useEditorStore(J=>J.showAIDialog),N=s.useDashboardStore(J=>J.handleOpenAssistantProfile),{setShowAIDialog:A,setCardPython:S}=s.useEditorActions(),{setDataSource:P}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:k,setMessages:y,sendMessage:M,isLoading:F,stop:G,status:V,llmUsage:B,errorMessage:q,clearError:z}=Jn(),[_,W]=D.useState(""),ee=J=>{W(J.target.value)},te=J=>{J.preventDefault();const ne=_.trim();if(!ne&&O.length===0)return;const re=[];ne&&re.push({type:"text",text:ne}),O.forEach(De=>{De.data&&re.push({type:"file",mediaType:De.type,filename:De.name,url:`data:${De.type};base64,${De.data}`})}),M({role:"user",parts:re}),W(""),T("editor"),Q({force:!0})},{visibleMessages:ae,hasMoreMessages:Y,totalMessageCount:U,loadMoreMessages:H,resetMessageWindow:X}=s.useMessageWindow(k,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ce,isAtBottom:pe,hasNewMessages:ue,newMessageCount:$,scrollToBottom:Q,handleScroll:de,resetNewMessageCount:xe}=s.useAutoScroll(ae,{threshold:50,behavior:"smooth",isStreaming:F});D.useEffect(()=>{var J;g&&((J=r.current)==null||J.focus(),v({selectedEntities:(E==null?void 0:E.selectedEntities)||[]}))},[g,E,v]),s.useAutoSubmitQueue({assistantType:"editor",status:V,isLoading:F,sendMessage:M});const{hasActiveTools:fe}=s.useActiveToolStatus(k),ie=D.useCallback(J=>{a==null||a(J),t===void 0&&p(J)},[t,a]);D.useEffect(()=>{if(!b)return;function J(ne){ne.key==="Escape"&&ie(!1)}return window.addEventListener("keydown",J),()=>{window.removeEventListener("keydown",J)}},[b,ie]);const R=D.useCallback(J=>{M({role:"user",parts:[{type:"text",text:J}]}),Q({force:!0})},[M,Q]),se=D.useCallback(async()=>{const J=JSON.stringify(k??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(J),s.ue.success("Conversation copied")}catch(ne){console.error("Failed to copy conversation",ne),s.ue.error("Unable to copy conversation")}},[k]),Z=D.useCallback(()=>{ie(!b)},[b,ie]);function je(J,ne){ne==="sql"?(C(J),f(!0)):ne==="python"&&(S(J),f(!0))}function ge(){j.selectedEntities.length===0&&v({selectedEntities:(L==null?void 0:L.selectedEntities)||[]})}function be(J){ge();const ne={role:"user",parts:[{type:"text",text:J.title+" "+J.subtitle}]};M(ne)}function ve(J){ge(),M({role:"user",parts:[{type:"text",text:J}]})}function me(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:o,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:u,children:"System Message"})]})]})}function Ee(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Se=(_==null?void 0:_.length)===0&&(k==null?void 0:k.filter(J=>J.role==="user").length)===0,we=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ee(),N&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:N,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[me(),c&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:se,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Z,children:b?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{y([]),w("editor"),z(),X()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{A(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:ce,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:H,className:"text-xs",children:["Load ",Math.min(5,U-ae.length)," ","more messages (",U-ae.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:ae,showTools:c,handleRun:je,showSystemMessage:d,onQuickReply:R,disableQuickReplies:F}),!fe&&e.jsx(s.AssistantStatus,{status:V,errorMessage:q})]})}),g&&!pe&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{Q({force:!0}),xe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ue&&$>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:$>9?"9+":$})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Se&&!I&&e.jsx(s.Placeholders,{onClick:be,placeholders:Qn}),e.jsx("div",{children:Se&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:W,stop:G,input:_,handleInputChange:ee,handleSubmit:J=>{ge(),te(J),Q({force:!0})},isLoading:F,status:V,assistantType:"editor",onFocus:()=>{}})]}),B&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",B.inputTokens," prompt tokens, ",B.outputTokens," ","completion tokens, ",B.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(E==null?void 0:E.selectedEntities)||[],open:m,onOpenChange:h,dataSource:E||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&n?gt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:we})}),n):we}function Ge(t,a){const[n,r]=D.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return D.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}const Wn="chart-selector-standard-first";function Yn(){const[t,a]=Ge(Wn,!0);return{standardFirst:t,updatePreference:a}}const Ss=({pluginVisual:t,index:a,onSelect:n})=>{const r=qe(t.icon||""),l=t.name.charAt(0).toUpperCase(),o=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):o||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},ws=["default","standardPlugin","customPlugin"];function Xn({selectedChart:t,onChartChange:a}){var E;const[n,r]=D.useState(!1),{data:l}=Ws();Yn();const c=((E=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:E.url)||"";Ze(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:x}=s.useEditorActions(),[p,b]=Ge("chart-section-active",null),j=D.useMemo(()=>p?[p,...ws.filter(C=>C!==p)]:ws,[p]);function v(C){m(null),d({}),i(C),["custom","map"].includes(C)&&(u(!0),x(void 0)),a(C),r(!1)}function w(C){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),x(void 0),a("custom"),r(!1)}const T=D.useMemo(()=>s.chartTypes.some(f=>f.id==="bullet")?s.chartTypes:[...s.chartTypes,{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"}],[]),O=()=>{var f;if(t==="custom"){const g=s.useEditorStore.getState().card;return((f=g==null?void 0:g.customCardPreferences)==null?void 0:f.componentName)||"Custom Visual"}const C=T.find(g=>g.id===t);return(C==null?void 0:C.label)||"Select chart type"},L=()=>{var f,g;if(t==="custom"){const N=s.useEditorStore.getState().card,A=(f=N==null?void 0:N.customCardPreferences)==null?void 0:f.icon,S=(g=N==null?void 0:N.customCardPreferences)==null?void 0:g.componentName;if(A&&S)return e.jsx(Zn,{icon:A,componentName:S});if(S){const P=s.getAutoDetectedChartIcon(S);if(P)return P}return e.jsx(Ae,{className:"h-4 w-4"})}const C=T.find(N=>N.id===t);if(C){const N=C.icon;return e.jsx(N,{className:"h-4 w-4"})}return e.jsx(Ae,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[L(),e.jsx("span",{children:O()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),j.map(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="default",onCheckedChange:f=>b(f?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:T.map(f=>{const g=f.icon;return e.jsx(s.CommandItem,{value:`${f.label} ${f.id} chart graph visualization`,onSelect:()=>v(f.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(g,{className:"h-4 w-4"}),e.jsx("span",{children:f.label})]})},f.id)})},"default");if(C==="standardPlugin"){const f=l.filter(g=>g.pluginType==="standard");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="standardPlugin",onCheckedChange:g=>b(g?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.filter(g=>g.componentType==="chart").map((g,N)=>e.jsx(Ss,{pluginVisual:g,index:N,onSelect:()=>w(g)},`${g.url}-${g.name}-${N}`))},"standardPlugin"):null}if(C==="customPlugin"){const f=l.filter(g=>g.pluginType==="custom");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="customPlugin",onCheckedChange:g=>b(g?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.map((g,N)=>e.jsx(Ss,{pluginVisual:g,index:N,onSelect:()=>w(g)},`${g.url}-${g.name}-${N}`))},"customPlugin"):null}return null})]})]})})]})})}const Zn=({icon:t,componentName:a})=>{const n=qe(),r=s.getAutoDetectedChartIcon(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},er=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"},{id:"treemap",icon:s.TbChartTreemap,label:"Treemap"},{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"}];function sr({selectedChart:t,onChartChange:a}){var l;const n=s.useEditorStore(o=>o.card),r=((l=n==null?void 0:n.config)==null?void 0:l.pivotByColumns)&&n.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-0.5",children:er.map(o=>{if(o.requiresPivot&&!r)return null;const c=o.icon,i=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>a(o.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:o.label})})]},o.id)})})}const os=({dataType:t})=>s.getFieldIconComponent(t);function tr({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=D.useState(t),[l,o]=D.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:l?n:t,onChange:u=>{r(u.target.value),o(!0)},onFocus:()=>o(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),o(!1)):u.key==="Escape"&&(r(t),o(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),o(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),o(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function ar({valueAliases:t,onValueAliasesChange:a}){const[n,r]=D.useState(null),[l,o]=D.useState(""),[c,i]=D.useState(""),d=()=>{a({...t,"":""})},u=h=>{const x={...t};delete x[h],a(x)},m=h=>{const x={...t};delete x[h],x[l]=c,a(x),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,x],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:b=>i(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),o(h),i(x)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function nr({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),o=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(st,{idx:o,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(tt,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&i()]})}function rr({field:t,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),o=s.useEditorStore(u=>u.card),c=o==null?void 0:o.dataSource,i=["attribute-values",t.entityName,t.name,a,n],d=s.useQuery({queryKey:i,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const j=b[x]||b[t.alias||x]||b[t.label];return{id:j||"",value:j||"",label:String(j||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function lr({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:o}){var O,L;const c=!!l,[i,d]=D.useState(c?"values":"fields"),[u,m]=D.useState(""),[h,x]=D.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),p=n.filter(E=>{var f;return c?!1:!((f=r==null?void 0:r.conditions)==null?void 0:f.some(g=>g.field.id===E.id))&&E.label.toLowerCase().includes(u.toLowerCase())}),b=E=>{x({...h,field:E}),d("values")},j=()=>{if(h.field&&h.selectedValues.length>0){const E={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let C;if(c){const f=((r==null?void 0:r.conditions)||[]).map(g=>g.id===l.id?E:g);C={...r,conditions:f}}else{const f=(r==null?void 0:r.conditions)||[];C={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...f,E],groups:[]}}o(C),a(!1)}},v=()=>{if(!c||!l)return;const E=((r==null?void 0:r.conditions)||[]).filter(C=>C.id!==l.id);if(E.length>0){const C={...r,conditions:E};o(C)}else o(void 0);a(!1)},w=E=>{x({...h,selectedValues:E})},T=()=>{c&&l?(x({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(x({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return D.useEffect(()=>{t&&T()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(O=h.field)==null?void 0:O.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(L=h.field)==null?void 0:L.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(E=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),i==="fields"&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:u,onChange:E=>m(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:p.map(E=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(E),children:[e.jsx(os,{dataType:s.getDataType(E.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:E.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),p.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),p.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(or,{field:h.field,selectedValues:h.selectedValues,onValuesChange:w,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:T,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:j,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function or({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,o]=D.useState(""),{values:c,isLoading:i,isFetching:d}=rr({field:t,searchQuery:l,limit:500}),u=l?c.filter(x=>String(x.value).toLowerCase().includes(l.toLowerCase())):c,m=x=>{const p=a.includes(x);n(p?a.filter(b=>b!==x):[...a,x])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:x=>o(x.target.value),className:"pl-10"})]}),i||d?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(x.value),children:[e.jsx(s.Checkbox,{checked:a.includes(x.value),onCheckedChange:()=>m(x.value)}),e.jsx(rs,{className:"text-sm",children:x.label})]},x.id))})]})]})}function ir({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:o=!1,cardType:c}){var cs,ds,us,ms;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id}),p=s.useEditorStore(K=>K.card),{updateLabel:b,handleAggregationChange:j,handleDateFormatChange:v,handleGranularityChange:w,handleAliasTemplateChange:T,handleValueAliasesChange:O,removeField:L,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:g,handleKpiTargetValueChange:N}=ts(p),[A,S]=D.useState(!1),[P,I]=D.useState(!1),[k,y]=D.useState(null),[M,F]=D.useState(t.dateFormat||"YYYY-MM-DD"),[G,V]=D.useState(t.customFormat||""),[B,q]=D.useState(!!t.customFormat),[z,_]=D.useState(t.granularity||"day"),[W,ee]=D.useState(t.aliasTemplate||""),[te,ae]=D.useState(t.valueAliases||{}),[Y,U]=D.useState((cs=t.parameters)==null?void 0:cs.filters),H=K=>{K==="custom"?q(!0):(q(!1),F(K),a==="groupBy"&&v(n,K,""))},X=K=>{V(K),a==="groupBy"&&v(n,"custom",K)},ce=K=>{var he;_(K);const oe=(he=s.getDateFormatOptionsForGranularity(K)[0])==null?void 0:he.value;oe&&!B&&(F(oe),a==="groupBy"&&v(n,oe,"")),a==="groupBy"&&w(n,K)},pe=K=>{ee(K),a==="metrics"&&T(n,K)},ue=K=>{ae(K),a==="metrics"&&O(n,K)},$=K=>{b(a,n,K)},Q=K=>{var le;if(U(K),a==="metrics"){const oe={...t,parameters:{...t.parameters,filters:K}},he=[...((le=p.config)==null?void 0:le.metricColumns)||[]];he[n]=oe,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:he})}I(!1)},de=()=>{L(a,n)},xe={transform:s.CSS.Transform.toString(m),transition:h},fe=s.getDataType(t.dataType),ie=fe==="date",R=c==="kpi",se=s.getDateFormatOptionsForGranularity(z),Z=a!=="pivotBy",je=ie&&a==="groupBy"&&(!R||((ds=p.config)==null?void 0:ds.comparisonType)==="start_vs_end"),ge=!R&&ie&&a==="groupBy",be=c&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(c)&&ie&&a==="groupBy",ve=c==="kpi"&&ie&&a==="groupBy",me=c&&c!=="pivotTable"&&a==="metrics"&&((us=p.config)==null?void 0:us.comparisonType)==="target",Ee=a==="metrics",Se=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:K=>{K.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),we=()=>Z?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ne,{value:t.label??"",onSave:$,placeholder:"Display label...",type:"text"})]}):null,J=()=>je?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:ce,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K,children:s.toTitleCase(K)},K))})]})]}):null,ne=()=>ge?e.jsxs(e.Fragment,{children:[J(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:B?"custom":M,onValueChange:H,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:se.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),B&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:G,onChange:K=>{K.stopPropagation(),X(K.target.value)},onClick:K=>K.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,re=()=>{var oe,he,Ce,Le,hs;const K=be,le=ve;return!K&&!le?null:e.jsxs(e.Fragment,{children:[K&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((oe=p.config)==null?void 0:oe.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),le&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((he=p.config)==null?void 0:he.showTrendline)||!1,onCheckedChange:C})]})}),((Ce=p.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((Le=p.config)==null?void 0:Le.trendlineWindow)||30,onChange:pt=>{const ft=parseInt(pt.target.value)||30;f(ft)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((hs=p.config)==null?void 0:hs.trendlineGranularity)||"day",onValueChange:g,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},De=()=>{var K,le;return me?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(Ne,{value:((K=p.config)==null?void 0:K.targetValue)!==void 0&&((le=p.config)==null?void 0:le.targetValue)!==null?String(p.config.targetValue):"",onSave:oe=>{!isNaN(Number(oe))&&oe!==null?N(Number(oe)):N(0)},placeholder:"Enter target value...",type:"text"})]}):null},mt=()=>Ee?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:K=>{j(n,K)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Y==null?void 0:Y.conditions)&&Y.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Y.conditions.map(K=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{y(K),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[K.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(K.value)?K.value.length===1?String(K.value[0]):K.value.length<=2?K.value.join(", "):`${K.value.slice(0,2).join(", ")} +${K.value.length-2}`:String(K.value)})}),Array.isArray(K.value)&&K.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",K.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:K.value.map((le,oe)=>e.jsx("div",{children:String(le)},oe))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:le=>{var he;le.stopPropagation();const oe=Y.conditions.filter(Ce=>Ce.id!==K.id);if(oe.length>0){const Ce={...Y,conditions:oe};Q(Ce)}else if(U(void 0),a==="metrics"){const Ce={...t,parameters:{...t.parameters,filters:void 0}},Le=[...((he=p.config)==null?void 0:he.metricColumns)||[]];Le[n]=Ce,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Le})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},K.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{y(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(nr,{column:t}),o&&e.jsxs(e.Fragment,{children:[e.jsx(tr,{aliasTemplate:W,onAliasTemplateChange:pe}),e.jsx(ar,{valueAliases:te,onValueAliasesChange:ue})]})]}):null,{columns:ht=[]}=s.useColumns(),xt=(Y==null?void 0:Y.conditions)&&Y.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:xe,...i,...d,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${x?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(os,{dataType:fe}),e.jsx(rs,{className:s.cn("w-[140px] flex-1 text-sm",xt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((ms=Y==null?void 0:Y.conditions)==null?void 0:ms.length)&&!A&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:Y.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Y.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),S(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const le=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",le),l(le)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),de()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[Se(),we(),c==="kpi"&&J(),ne(),re(),De(),mt()]})]}),P&&e.jsx(lr,{open:P,onOpenChange:K=>{I(K),K||y(null)},availableFields:ht,existingFilters:Y,editingCondition:k,onSave:K=>{var le;if(K)Q(K);else if(U(void 0),a==="metrics"){const oe={...t,parameters:{...t.parameters,filters:void 0}},he=[...((le=p.config)==null?void 0:le.metricColumns)||[]];he[n]=oe,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:he})}y(null)}})]})}function cr({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Ve({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:o=!1,activeField:c=null}){const{isOver:i,setNodeRef:d}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.card.type),x=a.length>0,p=D.useMemo(()=>!c||!i?!0:Fe(c,t,h).isValid,[c,i,t,h]),b=(v,w)=>{var O;!((O=m.config)!=null&&O.sortByColumns)||m.config.sortByColumns.findIndex(L=>L.id===v)===-1||u(m.id,v,{direction:w})};if(t==="sortBy"&&l===!1)return null;const j=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),j&&e.jsx(cr,{concept:t})]}),e.jsx("div",{ref:d,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":i&&p,"border-red-500 bg-red-50 dark:bg-red-950":i&&!p,"border-muted-foreground/30 bg-muted/40":!i&&x,"min-h-[60px] border-muted-foreground/20 bg-background":!i&&!x}),children:a.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:a.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((v,w)=>{const O=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(ir,{field:v,zone:t,index:w,sortDirection:O,onSortDirectionChange:L=>b(v.id,L),hasPivotColumns:o,cardType:h})})},v.id)})})})})]})}const Ds=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],dr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function He({value:t,onChange:a,label:n}){const[r,l]=D.useState(!1),[o,c]=D.useState(!1),i=()=>{const d=Ds.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Ds[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${n}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:dr.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{a(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),o&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(at,{color:i(),onColorChange:d=>{a(d),c(!1)},onClose:()=>c(!1)})})]})]})}const ks={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
245
|
+
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function ur(){var x,p,b,j,v,w,T,O,L,E,C;const t=s.useEditorStore(f=>f.card),{setCardPreferences:a}=s.useEditorActions(),n=((x=t.config)==null?void 0:x.metricColumns)||[],r=((p=t.config)==null?void 0:p.groupByColumns)||[],l=n.length===2&&r.length===0,o=n.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||o)))return null;const i=((j=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:j.metricComparison)||{},d=f=>{var N;const g={...t.preferences,kpiVisualOptions:{...(N=t.preferences)==null?void 0:N.kpiVisualOptions,metricComparison:{...i,...f}}};a(g)},u=o||i.enabled,m=((v=t.config)==null?void 0:v.comparisonType)||"none",h=m==="previous_period"||m==="same_period_last_year"||m==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:i.enabled||!1,onCheckedChange:f=>d({enabled:f,...f&&!i.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const f=i.calculationType||"difference",g=ks[f];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:g==null?void 0:g.label}),e.jsx("p",{children:g==null?void 0:g.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:g==null?void 0:g.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",g==null?void 0:g.example]})]})})()})]})]}),e.jsxs(s.Select,{value:i.calculationType||"difference",onValueChange:f=>d({calculationType:f}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(ks).map(([f,g])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:g.label},f))})]})]}),e.jsx(ls,{formatOptions:i.formatOptions||{},onFormatOptionsChange:f=>d({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||l)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:i.position||"right",onValueChange:f=>d({position:f}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:i.showArrow!==!1,onCheckedChange:f=>d({showArrow:f})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:i.showColor!==!1,onCheckedChange:f=>d({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),i.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(He,{value:((w=i.colorConfig)==null?void 0:w.increase)||"green",onChange:f=>d({colorConfig:{...i.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(He,{value:((T=i.colorConfig)==null?void 0:T.decrease)||"red",onChange:f=>d({colorConfig:{...i.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(He,{value:((O=i.colorConfig)==null?void 0:O.noChange)||"neutral",onChange:f=>d({colorConfig:{...i.colorConfig,noChange:f}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:i.conditionalLabel||!1,onCheckedChange:f=>d({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),i.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((L=i.conditionalLabels)==null?void 0:L.increase)??"Increase",onChange:f=>d({conditionalLabels:{...i.conditionalLabels,increase:f.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((E=i.conditionalLabels)==null?void 0:E.decrease)??"Decrease",onChange:f=>d({conditionalLabels:{...i.conditionalLabels,decrease:f.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((C=i.conditionalLabels)==null?void 0:C.noChange)??"No change",onChange:f=>d({conditionalLabels:{...i.conditionalLabels,noChange:f.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input,{id:"label-name",type:"text",value:i.labelName??"",onChange:f=>d({labelName:f.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function mr(){var l,o;const t=s.useEditorStore(c=>c.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((o=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:o.formatOptions)||{},r=c=>{var d;const i={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};a(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(ls,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function hr(){var o;const t=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.type}),a=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:n}=s.useEditorActions();if(t!=="treemap")return null;const r=((o=a==null?void 0:a.chartOptions)==null?void 0:o.treemapColorMode)??"branch",l=c=>{const i={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:c}};n(i)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:c=>l(c??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}function xr({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const o=s.useEditorStore(v=>{var w;return((w=v.card.customCardPreferences)==null?void 0:w.url)&&v.card.type==="custom"}),c=s.useEditorStore(v=>v.card),i=c==null?void 0:c.type,d=t.length>0||n.length>0,u=i!=="kpi"||n.length<=2,m=i!=="kpi",h=i!=="kpi"&&d,x=["pie","doughnut","polar","funnel","aggregateTable"].includes(i),p=m&&!x,b=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},j=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[u&&e.jsx(Ve,{zone:"groupBy",fields:t,label:b().label,placeholder:b().placeholder,activeField:l}),p&&e.jsx(Ve,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Ve,{zone:"metrics",fields:n,label:j().label,placeholder:j().placeholder,hasPivotColumns:a.length>0,activeField:l}),h&&e.jsx(Ve,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!o&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(mr,{}),e.jsx(ur,{}),e.jsx(nt,{}),e.jsx(hr,{}),i==="bullet"&&e.jsx(it,{}),e.jsx(rt,{}),e.jsx(lt,{}),e.jsx(ot,{})]})})]})]})}function pr({onEditJoins:t}){const a=s.useEditorStore(i=>i.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const o=i=>!i||i.length===0?"No conditions":i.map(d=>{var x,p,b,j;const u=`${(x=d.source)==null?void 0:x.entityName}.${(p=d.source)==null?void 0:p.name}`,m=`${(b=d.target)==null?void 0:b.entityName}.${(j=d.target)==null?void 0:j.name}`,h=d.operator||"=";return`${u} ${h} ${m}`}).join(" AND "),c=i=>!i.joinKeyGroups||i.joinKeyGroups.length===0?"No conditions defined":i.joinKeyGroups.length===1?o(i.joinKeyGroups[0].keys):i.joinKeyGroups.map((d,u)=>({id:u,operator:d.operator,condition:o(d.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((i,d)=>{const u=c(i),m=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:i.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:i.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:i.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:m?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},i.id||d)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const Ts={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function fr({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o,activeField:c}){var f,g;const[i,d]=D.useState(()=>Ts.getItem("chart-selector-expanded")==="true"),[u,m]=D.useState(!1),h=s.useEditorStore(N=>N.card),x=s.useEditorStore(N=>N.actions.updateCardConfig),p=n.length>0||r.length>0||l.length>0,{data:b,autoJoinMetadata:j}=s.useDashboardCardQuery(h),v=((f=h==null?void 0:h.config)==null?void 0:f.joinPlan)||(j!=null&&j.autoResolved?j.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),w=((g=h==null?void 0:h.dataSource)==null?void 0:g.selectedEntities)||[],T=N=>{x(h.id,{...h==null?void 0:h.config,joinPlan:N}),m(!1)},O=()=>{x(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),m(!1)},L=()=>{m(!1)},E=()=>{m(!0)};D.useEffect(()=>{Ts.setItem("chart-selector-expanded",String(i))},[i]);const C=()=>{d(N=>!N)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":i}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",i?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:i&&e.jsx(Xn,{selectedChart:t,onChartChange:a})}),e.jsxs("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center gap-0.5",children:[e.jsx(sr,{selectedChart:t,onChartChange:a}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:C,className:"h-8 w-8 p-0","aria-label":i?"Hide all charts":"Show all charts",children:i?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:i?"Hide dropdown":"Show all charts"})})]})]})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:p||b}),children:e.jsx(es,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(pr,{onEditJoins:E}),e.jsx(xr,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:o,activeField:c})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Ye,{open:u,onOpenChange:m,joinPlan:v,availableDataSources:w,onSave:T,onCancel:L,onRemove:O,children:e.jsx("div",{})})]})}function gr({initialFilters:t,availableFields:a}={}){const[n,r]=D.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:l,isLoading:o}=s.useColumns(),i=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const C=f=>{if(f.id===E){const g=i[0]||d,N=s.getDataType(g.dataType)==="date";return{...f,conditions:[...f.conditions,{id:`condition-${Date.now()}`,field:g,operator:N?"between":"=",value:N?[]:""}]}}return{...f,groups:f.groups.map(C)}};r(C(n))},m=E=>{const C=f=>{if(f.id===E){const g=i[0]||d,N=s.getDataType(g.dataType)==="date";return{...f,groups:[...f.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:g,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...f,groups:f.groups.map(C)}};r(C(n))},h=(E,C)=>{const f=g=>g.id===E?{...g,conditions:g.conditions.filter(N=>N.id!==C)}:{...g,groups:g.groups.map(f)};r(f(n))},x=(E,C)=>{const f=g=>g.id===E?{...g,groups:g.groups.filter(N=>N.id!==C)}:{...g,groups:g.groups.map(f)};r(f(n))},p=(E,C,f,g)=>{if(f==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=A=>A.id===E?{...A,conditions:A.conditions.map(S=>S.id===C?{...S,[f]:g}:S)}:{...A,groups:A.groups.map(N)};r(N(n))},b=(E,C,f)=>{const g=N=>N.id===E?{...N,conditions:N.conditions.map(A=>A.id===C?{...A,...f}:A)}:{...N,groups:N.groups.map(g)};r(g(n))},j=(E,C)=>{const f=g=>g.id===E?{...g,logicalOperator:C}:{...g,groups:g.groups.map(f)};r(f(n))},v=(E,C)=>{const f=g=>g.id===E?{...g,negate:C}:{...g,groups:g.groups.map(f)};r(f(n))},w=(E,C,f)=>{const g=N=>N.id===E?{...N,conditions:s.arrayMove(N.conditions,C,f)}:{...N,groups:N.groups.map(g)};r(g(n))},T=(E,C,f)=>{const g=N=>N.id===E?{...N,groups:s.arrayMove(N.groups,C,f)}:{...N,groups:N.groups.map(g)};r(g(n))},O=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const C=g=>{let N="";typeof g.field=="object"?N=g.field.entityName?`${g.field.entityName}.${g.field.name}`:g.field.name:N=String(g.field);const A=g.operator;let S=g.value;if(g.field.dataType==="string"&&!["in","not in"].includes(g.operator))typeof S=="string"?S=`'${S}'`:Array.isArray(S)&&(S=`'${S.join(", ")}'`);else if(g.field.dataType==="date"||g.field.dataType==="datetime"||g.field.dataType==="timestamp")if(g.operator==="between"&&Array.isArray(S)&&S.length===2){const P=S[0]?`'${S[0]}'`:"NULL",I=S[1]?`'${S[1]}'`:"NULL";return`${N} BETWEEN ${P} AND ${I}`}else if((g.operator==="in"||g.operator==="not in")&&Array.isArray(S)){const P=S.map(I=>I?`'${I}'`:"NULL").join(", ");return`${N} ${A} (${P})`}else typeof S=="string"||S instanceof Date?S=`'${S}'`:Array.isArray(S)&&S.length>0&&(S=`'${S[0]}'`);else if(["in","not in"].includes(g.operator)){let P=[];Array.isArray(S)?P=S.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof S=="string"?P=S.split(",").map(I=>{const k=I.trim();return g.field.dataType==="string"?`'${k}'`:k}):typeof S=="number"&&(P=[String(S)]),S=`(${P.join(", ")})`}switch(A){case"contains":return typeof S=="string"?`${N} LIKE '%${S.replace(/'/g,"")}'`:`${N} LIKE '%${String(S)}'`;case"startsWith":return typeof S=="string"?`${N} LIKE '${S.replace(/'/g,"")}%'`:`${N} LIKE '${String(S)}%'`;case"endsWith":return typeof S=="string"?`${N} LIKE '%${S.replace(/'/g,"")}'`:`${N} LIKE '%${String(S)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${A} ${S}`}},f=g=>{const N=g.conditions.map(C),A=g.groups.map(k=>f(k)),S=[...N,...A].filter(Boolean);if(S.length===0)return"";const P=S.join(` ${g.logicalOperator} `),I=S.length>1?`(${P})`:P;return g.negate?`NOT ${I}`:I};return f(E)},L=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:i,isLoading:o,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:p,updateConditionFields:b,updateGroupOperator:j,updateGroupNegate:v,reorderConditions:w,reorderGroups:T,generateSQLPreview:O,hasAnyFilters:L}}function jr({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const br=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},vr=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function yr({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[o,c]=D.useState(!1),i=D.useMemo(()=>{const d={};return n.forEach(u=>{const m=vr(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:o,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(jr,{children:[t.entityName,".",t.name]})}):r,e.jsx(yt,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[br(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,p)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{a(x),c(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+p))]},`${d}-${m}`))},d))})]})})]})}function is(t){var j;const a=s.useEditorStore(v=>v.card),{authToken:n,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(v=>v.card.config),o=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:o,groupByColumns:[c],metricColumns:[i],sortByColumns:[d]},m=((j=a.dataSource)==null?void 0:j.connectionId)||a.connectionId,{data:h,isPending:x,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:a.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:x,error:p}}function Nr({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[o,c]=Je.useState(!1),{filterValues:i}=is(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:o,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const h=i.find(x=>x.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function Cr({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:o,isPending:c,error:i}=is(t);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:o.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function Sr({value:t,operator:a,onChange:n,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),o=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=D.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,a]),i=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),n([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),n([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:i,timezone:o,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const wr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Dr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],kr=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Tr=["=","!=","isNull","isNotNull"],Er=["between","isNull","isNotNull"],Ir={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function Es(t){return Ir[t]||s.titleCase(t)}function Ar(t){switch(t){case"string":return Dr;case"number":return kr;case"boolean":return Tr;case"date":return Er;default:return wr}}function ct({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:o,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:p,isDragging:b}=s.useSortable({id:t.id}),{isPending:j,error:v}=is(t.field),w={transform:s.CSS.Transform.toString(x),transition:p};return e.jsxs("div",{ref:h,style:w,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:T=>c(n,T),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(yr,{value:t.field,onValueChange:T=>{const O=T,L=s.getDataType(O.dataType)==="date";d(n,t.id,{field:O,value:"",operator:L?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:T=>{T==="in"||T==="not in"?d(n,t.id,{operator:T,value:[]}):T==="isNull"||T==="isNotNull"?d(n,t.id,{operator:T,value:null}):d(n,t.id,{operator:T,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Es(t.operator):""})}),e.jsx(s.SelectContent,{children:Ar(s.getDataType(t.field.dataType)).map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T,children:Es(T)},T))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?j?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Nr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(T=>typeof T=="string")?t.value:[],onChange:T=>d(n,t.id,{value:T}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:T=>d(n,t.id,{value:T.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Cr,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:T=>d(n,t.id,{value:T}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:T=>d(n,t.id,{value:T==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Sr,{value:t.value,operator:t.operator,onChange:T=>d(n,t.id,{value:T}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:T=>l(n,t.id,"value",T.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>o(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Mr({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:o,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:p,renderFilterGroup:b,updateConditionFields:j}){const{attributes:v,listeners:w,setNodeRef:T,transform:O,transition:L,isDragging:E}=s.useSortable({id:t.id}),C={transform:s.CSS.Transform.toString(O),transition:L},f=N=>{const{active:A,over:S}=N;if(S&&A.id!==S.id){const P=t.conditions.findIndex(k=>k.id===A.id),I=t.conditions.findIndex(k=>k.id===S.id);P!==-1&&I!==-1&&u(t.id,P,I)}},g=N=>{const{active:A,over:S}=N;if(S&&A.id!==S.id&&n){const P=t.groups.findIndex(k=>k.id===A.id),I=t.groups.findIndex(k=>k.id===S.id);P!==-1&&I!==-1&&m(n,P,I)}};return e.jsxs("div",{ref:T,style:C,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...w,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:N=>r(t.id,N),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&o(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:f,children:e.jsx(s.SortableContext,{items:t.conditions.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((N,A)=>e.jsx(ct,{condition:N,index:A,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:j},N.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:g,children:e.jsx(s.SortableContext,{items:t.groups.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(N=>b(N,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Lr({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:o,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:p,updateGroupOperator:b,updateGroupNegate:j,reorderConditions:v,reorderGroups:w,generateSQLPreview:T,hasAnyFilters:O,setCurrentFilters:L}=gr({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[C,f]=D.useState(!1),g=(S,P,I)=>{const k=y=>y.id===S?{...y,conditions:y.conditions.map(M=>M.id===P?{...M,field:I,dataType:I.dataType}:M)}:{...y,groups:y.groups.map(k)};L(k(o))},N=(S,P=0,I)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:k=>{const{active:y,over:M}=k;if(M&&y.id!==M.id){const F=S.conditions.findIndex(V=>V.id===y.id),G=S.conditions.findIndex(V=>V.id===M.id);F!==-1&&G!==-1&&v(S.id,F,G)}},children:e.jsx(s.SortableContext,{items:S.conditions.map(k=>k.id),strategy:s.verticalListSortingStrategy,children:S.conditions.map((k,y)=>e.jsx(ct,{condition:k,index:y,groupId:S.id,groupLogicalOperator:S.logicalOperator,onUpdateCondition:x,onUpdateField:g,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:c,updateConditionFields:p},k.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:k=>{const{active:y,over:M}=k;if(M&&y.id!==M.id){const F=S.groups.findIndex(V=>V.id===y.id),G=S.groups.findIndex(V=>V.id===M.id);F!==-1&&G!==-1&&w(S.id,F,G)}},children:e.jsx(s.SortableContext,{items:S.groups.map(k=>k.id),strategy:s.verticalListSortingStrategy,children:S.groups.map(k=>N(k,P+1,S.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>d(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),C&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},S.id):e.jsx(Mr,{group:S,depth:P,parentGroupId:I,onUpdateGroupOperator:b,onUpdateGroupNegate:j,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:g,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:w,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:N,updateConditionFields:p},S.id),A=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):N(o),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:C,onCheckedChange:S=>f(S)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),O&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:T(o)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),A>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(O?o:null),children:"Apply Filters"})]})]})}function Fr({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:o,onOpenChange:c}){const i=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:o,onOpenChange:c,children:[o&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Lr,{filters:a,availableFields:l,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function Pr({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var v,w;const[l,o]=D.useState(null),c=s.useEditorStore(T=>T.card),i=s.useEditorStore(T=>T.actions.updateCardConfig),d=(v=c==null?void 0:c.config)==null?void 0:v.joinPlan,u=(w=c==null?void 0:c.dataSource)==null?void 0:w.semanticDomainId,{data:m}=ss(u),h=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],x=D.useCallback(T=>T.startsWith("card-")?null:T.startsWith("source-")||a.find(O=>O.id===T)?"source":n("groupBy").find(O=>O.id===T)?"groupBy":n("metrics").find(O=>O.id===T)?"metrics":n("pivotBy").find(O=>O.id===T)?"pivotBy":n("sortBy").find(O=>O.id===T)?"sortBy":null,[a,n]),p=D.useCallback(T=>{o(T.active.id)},[]),b=D.useCallback(T=>{var N;const{active:O,over:L}=T;if(!L||!t){o(null);return}const E=O.id,C=L.id,f=x(E),g=x(C)||C;if(g==="sortBy"){if(f==="source"){const A=a.find(P=>P.id===E);if(!A){o(null);return}if(!(n("groupBy").some(P=>P.name===A.name&&P.qualifiedEntityName===A.qualifiedEntityName)||n("metrics").some(P=>P.name===A.name&&P.qualifiedEntityName===A.qualifiedEntityName))){o(null);return}}else if(f==="pivotBy"){o(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"){o(null);return}}if(f==="source"&&g==="sortBy"){const A=[...a].find(k=>k.id===E);if(!A){o(null);return}const S=n("sortBy");if(s.fieldAlreadyExists(A,S)){o(null);return}const P=Fe(A,"sortBy",c.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),o(null);return}const I=s.getNewField(A,"sortBy",S);o(null),r("sortBy",[...S,I]);return}if(f==="source"&&g!=="source"&&g!=="sortBy"){const A=[...a].find(M=>M.id===E);if(!A){o(null);return}const S=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(S.length>0){const M=S[0].qualifiedEntityName;if(!M){o(null);return}if(M!==A.qualifiedEntityName&&A.qualifiedEntityName)if(u&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(A,{joinabilityMap:m.joinabilityMap,selectedFields:S,baseEntityName:(N=d==null?void 0:d.baseEntity)==null?void 0:N.name}).state==="unreachable"){s.showJoinRequiredNotification(),o(null);return}}else{if(!d){s.showJoinRequiredNotification(),o(null);return}if(!s.areEntitiesJoined(M,A.qualifiedEntityName,d)){s.showJoinRequiredNotification(),o(null);return}}}const P=n(g);if(s.fieldAlreadyExists(A,P)){o(null);return}const I=Fe(A,g,c.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),o(null);return}const k=s.getNewField(A,g,P),y=[...P,k];o(null),r(g,y),g==="metrics"&&t&&We(c.type,c.config,i,t,y);return}if(f&&g&&f!=="source"&&g!=="source"&&f!==g){const A=n(f),S=n(g),P=A.find(F=>F.id===E);if(!P){o(null);return}const I=Fe(P,g,c.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),o(null);return}const k=s.getNewField(P,g,S);if(o(null),g==="sortBy"){s.fieldAlreadyExists(P,S)||r(g,[...S,k]);return}const y=A.filter(F=>F.id!==E),M=[...S,k];r(f,y),r(g,M),g==="metrics"&&t&&We(c.type,c.config,i,t,M);return}if(f&&g&&f===g&&f!=="source"){const A=n(f),S=A.findIndex(I=>I.id===E),P=A.findIndex(I=>I.id===C);if(S!==P){const I=s.arrayMove(A,S,P);r(f,I)}}o(null)},[t,a,n,r,x,d,u,m,c.type,i,c.config]),j=l?h.find(T=>T.id===l):null;return{activeId:l,activeField:j,handleDragStart:p,handleDragEnd:b}}function Or({activeView:t,onViewChange:a,splitViewEnabled:n}){const r=s.useEditorStore(d=>d.card),{config:l}=D.useContext(s.SemaphorContext).tokenProps,o=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(r),i=()=>!n&&r.type!=="table";return e.jsx(s.Tabs,{value:t,onValueChange:d=>a(d),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),i()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&o&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",c&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:c?"Error":"Info"})]})})}const Br=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Vr(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=D.useState(!1),[l,o]=D.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},i=m=>{const h=m.target.value;o(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:Br.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Rr({card:t,queryData:a,isLoading:n,isFetching:r,pagination:l,onPaginationChange:o,onSortChange:c,sortState:i,splitViewEnabled:d}){return!d||t.type==="table"?e.jsx(Xe,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(Xe,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(a==null?void 0:a.records)&&e.jsx(s.TableVisual,{card:t,data:(a==null?void 0:a.records)||[],paginationMetadata:l,onPaginationChange:o,isLoading:n||r,onSortChange:c,sortState:i})})})]})}const zr="semaphor-split-view-enabled";function qr(){return Ge(zr,!0)}function Gr({isOpen:t,onClose:a}){const n=Fs(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),o=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=D.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(D.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:o,settings:c})})})]})})}function $r({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:o,columns:c,columnsLoading:i,columnsError:d}){var ae,Y,U;const u=s.useEditorStore(H=>H.card),m=s.useDashboardStore(H=>H.filterValues),{updateCardConfig:h,setCard:x,updateCardInFrame:p,setShowAIDialog:b}=s.useEditorActions(),j=s.useEditorStore(H=>H.showAIDialog),v=s.useDashboardStore(H=>H.isVisualEditing),[w,T]=D.useState(!1),[O,L]=D.useState(!1),[E,C]=D.useState(null),{config:f}=D.useContext(s.SemaphorContext).tokenProps,g=(f==null?void 0:f.showInfoTab)!==!1,[N,A]=qr(),S=s.useEditorStore(H=>{var X;return((X=H.card.customCardPreferences)==null?void 0:X.url)&&H.card.type==="custom"}),{data:P,errorMessage:I,isLoading:k,isFetching:y,errorSql:M,pagination:F,refetch:G,comparisonMetadata:V}=s.useDashboardCardQuery(o),[B,q]=D.useState(!1);D.useEffect(()=>{y||q(!1)},[y]);const z=()=>{const H=!N;H&&t==="table"&&a("chart"),A(H)},_=(H,X)=>{const ce={...o,paginationConfig:{page:H+1,pageSize:X}};x(ce),p(ce)};function W(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(o.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",c.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:i?"Loading...":d?"Error loading columns":JSON.stringify(c.slice(0,5),null,2)})]})]})]})}const ee=H=>{if(!u.config)return;const X=s.sortStateToSortByColumns(H,u.config.metricColumns,u.config.groupByColumns);h(u.id,{...u.config,sortByColumns:X})},te=D.useMemo(()=>{var H;return s.sortByColumnsToSortState((H=u.config)==null?void 0:H.sortByColumns)},[(ae=u.config)==null?void 0:ae.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":j&&v}),children:[n&&W(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&j&&e.jsx(Ys,{variant:"outline"}),e.jsx(Or,{activeView:t,onViewChange:a,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:o.id,cardFilters:(Y=o.config)==null?void 0:Y.filters,cardFilterCount:s.getFilterCount(((U=o.config)==null?void 0:U.filters)||null),onFiltersClick:l}),V&&e.jsx(s.ComparisonMetadataBadge,{metadata:V,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Vr,{})}),j&&e.jsx(es,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:k||y,onClick:()=>{q(!0),G()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":B})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:z,children:N?e.jsx(It,{className:"size-4"}):e.jsx(_t,{className:"size-4"})}),t==="chart"&&e.jsx(Xs,{}),!j&&e.jsx(s.IconButton,{onClick:()=>b(!j),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!w&&S&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>T(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-6",{"pb-0":N&&o.type!=="table"}),children:e.jsx(Rr,{card:o,queryData:P,isLoading:k,isFetching:y,pagination:F,onPaginationChange:_,onSortChange:ee,sortState:te,splitViewEnabled:N})}),t==="table"&&(P==null?void 0:P.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:o,data:(P==null?void 0:P.records)||[],paginationMetadata:F,onPaginationChange:_,isLoading:k||y,onSortChange:ee,sortState:te})}),t==="info"&&g&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:I?e.jsx(ns,{error:I,errorSql:M,onSendFeedback:()=>{const H=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:o.dataSource,dashboardFilters:m,errorMessage:I,errorSql:M,generatedSql:P==null?void 0:P.sql});C(H),L(!0)},onOpenInEditor:()=>{b(!0),setTimeout(()=>{const H=s.useEditorStore.getState().actions;H.setIsDevMode(!0),H.setCardSql(M||""),setTimeout(()=>{H.setRunSql(!0)},100)},100)}}):e.jsx(_s,{sql:P==null?void 0:P.sql,error:I,errorSql:M})})})]}),e.jsx(Gr,{isOpen:w,onClose:()=>T(!1)}),E&&e.jsx(s.FeedbackDialog,{open:O,onOpenChange:L,feedbackData:E})]})]})}function Ur({activeField:t}){const[a,n]=D.useState(!0);return D.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(os,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Kr=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function _r(){var V,B;const[t,a]=D.useState("chart"),[n,r]=D.useState(!1),[l,o]=D.useState(!1),[c,i]=D.useState(!0),d=s.useEditorStore(q=>q.showAIDialog),u=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(q=>q.card.type);D.useEffect(()=>Kr(),[]);const x=q=>{m(q)},p=s.useEditorStore(q=>q.frame),b=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:j,removeCard:v,updateCard:w,setActiveCard:T,updateFilters:O}=s.useEditorActions(),{columns:L=[],isLoading:E,error:C}=s.useColumns(),f=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),g=b,{getFieldsForContainer:N,setFieldsForContainer:A}=ts(g),{activeField:S,handleDragStart:P,handleDragEnd:I}=Pr({activeCardId:p.activeCardId,sourceFields:L,getFieldsForContainer:N,setFieldsForContainer:A}),k=(q,z)=>{z&&O(q,z)},y=q=>{var z;w(q,{config:{...(z=p.cards.find(_=>_.id===q))==null?void 0:z.config,filters:void 0}})},M=L,F=q=>{if(!q)return 0;let z=q.conditions.length;return q.groups.forEach(_=>{z+=F(_)}),z},G=F(((V=g==null?void 0:g.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:f,collisionDetection:s.closestCenter,onDragStart:P,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ks,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(fr,{selectedChart:h,onChartChange:x,groupByFields:N("groupBy"),pivotByFields:N("pivotBy"),metricsFields:N("metrics"),sortByFields:N("sortBy"),activeField:S}),e.jsx($r,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>o(!0),filterCount:G,activeCard:g,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:L,columnsLoading:E,columnsError:C,getFieldsForContainer:N,cards:p.cards,activeCardId:p.activeCardId,addCard:j,setActiveCard:T})]}),!c&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),g&&e.jsx(Fr,{cardId:g.id,filters:((B=g.config)==null?void 0:B.filters)||null,onFiltersChange:k,onClearFilters:y,availableFields:M,isOpen:l,onOpenChange:o}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ur,{activeField:S||null})})]})}function Hr({authToken:t,onSave:a,onClose:n}){const r=D.useRef(null),l=s.useEditorStore(C=>C.showAIDialog),o=s.useEditorStore(C=>C.isDevMode),c=s.useAssistantLayoutStore(C=>C.setFullscreen),i=s.useAssistantLayoutStore(C=>C.setPanelOpen),d=s.useAssistantLayoutStore(C=>C.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),x=m==="editor",p=D.useCallback(C=>{d("editor",C)},[d]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:j,setOnSave:v,setOnClose:w}=s.useEditorActions(),{setActiveAssistantType:T}=s.useAIActions();D.useEffect(()=>{a&&v(a),n&&w(n)},[a,v,n,w]),D.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),D.useEffect(()=>{var C,f;l?((C=r.current)==null||C.resize(40),i("editor",!0),T("editor")):((f=r.current)==null||f.resize(0),i("editor",!1),m==="editor"&&c(null),T(null))},[l,i,T,c,m]);function O(C){C<1?(j(!1),i("editor",!1),m==="editor"&&c(null),T(null)):(l||(j(!0),T("editor")),u.isOpen||i("editor",!0))}function L(){return e.jsxs(e.Fragment,{children:[e.jsx(Ks,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Hn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Cs,{isFullscreen:x,onFullscreenChange:C=>c(C?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!x&&"pointer-events-none")})]})]})}function E(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(_r,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Cs,{isFullscreen:x,onFullscreenChange:C=>c(C?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!x&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:o?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:L()}):E()})}function Jr(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function o(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Hr,{onSave:l,onClose:o})})}function Qr(){Us();const t=s.useDashboardStore(d=>d.selectedSheetId),a=s.useDashboardStore(d=>d.selectedFrameId),n=s.useDashboardStore(d=>d.dashboard),r=s.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:o}=s.useEditorActions(),c=s.useEditorStore(d=>d.card.dataSource);return D.useEffect(()=>{var u,m;let d=r();if(!d){const h=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===t),x=(m=h==null?void 0:h.frames)==null?void 0:m[0];x&&(l(x.id),d=x)}if(d){const h=d.cards.find(x=>x.id===d.activeCardId);h&&o(h)}},[r,t,a,n,l,o]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function Wr(){const t=s.useDashboardStore(n=>n.actions.setShowFilters),{hasEntities:a}=Qr();return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[e.jsx(s.Label,{className:"px-2 text-base",children:"Dashboard Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),!a&&e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),a&&e.jsx("div",{className:"flex grow",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx($s,{context:"filter"})})})})]})}function Yr(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Xr(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Yr,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Wr,{})})]})}function Zr(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function dt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4 py-2",children:[e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"space-y-3 pt-2",children:[...Array(3)].map((t,a)=>e.jsxs("div",{className:"flex gap-3 animate-pulse",children:[e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex-shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 w-2/3 rounded bg-muted"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted"})]})]},a))})]})})}const el=t=>{const a=s.useDashboardStore(l=>l.isVisualEditing),n=s.useDashboardStore(l=>l.selectedFrameId),r=s.useEditorStore(l=>l.frame);return!!(a&&n&&(r==null?void 0:r.visualId)===t)};function sl({visual:t,isDeleting:a,isDuplicating:n,onAddVisual:r,onOpenVisual:l,onEditDetails:o,onDeleteClick:c,onDuplicateVisual:i,onShareVisual:d,formatDate:u}){var E,C,f,g;const{selectVisual:m}=s.useManagementActions(),h=s.useIsVisualSelected(t.id),x=el(t.id),{isConsoleMode:p}=s.useDashboardPreferences(),b=D.useRef(null),[j,v]=D.useState(!1),[w,T]=D.useState(!1);D.useEffect(()=>{n?(v(!0),T(!0)):w&&(v(!1),T(!1))},[n,w]),D.useEffect(()=>{x&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[x]);const O=()=>e.jsx(ze,{className:"h-4 w-4"}),L=()=>{m(t),l==null||l(t)};return e.jsx(s.Card,{ref:b,className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",x?"border-purple-500":h&&"border-primary"),onClick:L,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:O()}),e.jsxs("div",{className:"min-w-0 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",title:t.description||"No description",children:(E=t.description)!=null&&E.trim()?t.description:"No description"}),e.jsxs("div",{className:s.cn("invisible flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",h&&"visible"),onClick:N=>N.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),r(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),t.ownership.isOwner&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),o==null||o(t)},title:"Edit details",children:e.jsx(s.PenLine,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:j,onOpenChange:v,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),l==null||l(t)},children:[e.jsx(Et,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),i(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),o==null||o(t)},children:[e.jsx(s.PenLine,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),d(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),c(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((f=t.ownership.createdBy)==null?void 0:f.type)==="organization"&&p)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((g=t.ownership.createdBy)==null?void 0:g.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:u(t.lastModified)})]})]})]})]})]})]})]})]})},t.id)}function tl({open:t,onOpenChange:a,onSubmit:n,isCreating:r}){const[l,o]=D.useState(""),[c,i]=D.useState("");D.useEffect(()=>{t||(o(""),i(""))},[t]);const d=()=>{l.trim()&&n({title:l,description:c})},u=m=>{a(m)};return e.jsx(s.Dialog,{open:t,onOpenChange:u,children:e.jsxs(s.DialogContent,{children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create New Visual"}),e.jsx(s.DialogDescription,{children:"Add a new visual to your library. You can configure it after creation."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",children:"Visual Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:m=>o(m.target.value),disabled:r,onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),d())}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:m=>i(m.target.value),disabled:r})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>u(!1),disabled:r,children:"Cancel"}),e.jsx(s.Button,{onClick:d,disabled:!l.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Visual"})]})]})})}function al(){const[t,a]=D.useState(""),[n,r]=D.useState(!1),[l,o]=D.useState(!1),[c,i]=D.useState(null),[d,u]=D.useState(!1),[m,h]=D.useState(null),[x,p]=D.useState(null),[b,j]=D.useState(null),{selectVisual:v}=s.useManagementActions(),{handleEditLibraryVisual:w,handleAddLibraryVisual:T}=ke(),{resources:O,isLoading:L,isError:E,createResource:C,updateResource:f,deleteResource:g,duplicateResource:N,isCreating:A,isDeleting:S}=s.useVisualManagement(()=>{u(!1),h(null)},U=>{r(!1),U&&(v(U),w(U))});s.useCurrentUserInfo();const P=O.filter(U=>{var H,X;return((H=U==null?void 0:U.title)==null?void 0:H.toLowerCase().includes(t.toLowerCase()))||((X=U==null?void 0:U.description)==null?void 0:X.toLowerCase().includes(t.toLowerCase()))}),I=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),k=U=>{C({title:U.title,description:U.description,isPrivate:!1})},y=U=>{h(U),u(!0)},M=()=>{m&&g(m.id)},{startUpdating:F,stopUpdating:G,isUpdating:V}=s.useResourceUpdateState(),B=(U,H,X)=>{var $;const ce=Object.fromEntries(Object.entries(H).filter(([,Q])=>Q!==void 0));if(Object.keys(ce).length===0){($=X==null?void 0:X.onSuccess)==null||$.call(X);return}const pe=Object.keys(ce),ue=pe.length===1?pe[0]:void 0;F(U,ue),f({resourceId:U,data:ce},{onSuccess:()=>{var Q;G(U,ue),(Q=X==null?void 0:X.onSuccess)==null||Q.call(X)},onError:()=>{var Q;G(U,ue),(Q=X==null?void 0:X.onError)==null||Q.call(X)}})},q=U=>{p(U),N(U,{onSettled:()=>p(null)})},z=U=>{w(U)},_=U=>{T(U)},W=U=>{const H=O.find(X=>X.id===U);H&&f({resourceId:U,data:{isPrivate:!H.isPrivate}})},ee=U=>{i(U),o(!0)},te=U=>{j(U)},ae=()=>{j(null)},Y=({title:U,description:H})=>{if(!b)return;const X={};U!==b.title&&(X.title=U),(b.description||"")!==H&&(X.description=H),B(b.id,X,{onSuccess:()=>{j(null)}})};return L?e.jsx(dt,{}):E?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[O&&O.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>a(U.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:P.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(ze,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Visual"]})]}):P.map(U=>e.jsx(sl,{visual:U,onAddVisual:_,onOpenVisual:z,onEditDetails:te,onDeleteClick:y,onDuplicateVisual:q,onTogglePrivacy:W,onShareVisual:ee,isDeleting:S,isDuplicating:x===U.id,formatDate:I},U.id))})}),l&&c&&e.jsx(s.ShareDialog,{resource:c,resourceType:s.ResourceType.VISUAL,onClose:()=>{o(!1),i(null)}}),b&&e.jsx(s.ResourceEditDialog,{open:!!b,resourceLabel:"Visual",initialTitle:b.title||"",initialDescription:b.description||"",onClose:ae,onSave:Y,isSaving:V(b.id)}),e.jsx(s.AlertDialog,{open:d,onOpenChange:U=>{!U&&S||(u(U),U||h(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:S,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:U=>{U.preventDefault(),U.stopPropagation(),M()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:S,children:[S?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),S?"Deleting...":"Delete"]})]})]})}),e.jsx(tl,{open:n,onOpenChange:r,onSubmit:k,isCreating:A}),e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>r(!0),"aria-label":"Create visual",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function nl({dashboard:t,isDeleting:a,isDuplicating:n,onLoadDashboard:r,onEditDetails:l,onDeleteClick:o,onDuplicateDashboard:c,onShareDashboard:i,formatDate:d,onDashboardItemClick:u}){var T,O;const{selectDashboard:m}=s.useManagementActions(),h=s.useIsDashboardSelected(t.id),{userContext:x,isLoading:p}=s.useCurrentUserInfo(),b=((T=x==null?void 0:x.permissions)==null?void 0:T.canEdit)??!1,j=p||!b,v=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4"}),w=()=>{m(t),r(t.id),u==null||u(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",h&&"border-primary"),onClick:w,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:v()}),e.jsxs("div",{className:"min-w-0 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Dashboard",children:t.title||"Untitled Dashboard"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",title:t.description||"No description",children:(O=t.description)!=null&&O.trim()?t.description:"No description"}),e.jsx(s.DashboardActionsMenu,{dashboard:t,isDeleting:a,isDuplicating:n,shouldHideActions:j,onEditDetails:l,onDeleteClick:o,onDuplicateDashboard:c,onShareDashboard:i,formatDate:d})]})]})]})},t.id)}function rl({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function ll(t){var ie;const{onLoadDashboard:a,onEditDashboard:n,onDashboardItemClick:r}=t,[l,o]=D.useState(""),[c,i]=D.useState(!1),[d,u]=D.useState(!1),[m,h]=D.useState(null),[x,p]=D.useState(!1),[b,j]=D.useState(null),[v,w]=D.useState(null),[T,O]=D.useState(null),L=s.useManagementStore(R=>R.lastSelectedDashboard),E=s.useManagementStore(R=>R.selectedDashboard),C=s.useManagementStore(R=>R.actions.selectDashboard),f=s.useManagementStore(R=>R.actions.clearSelectedDashboard),{tokenProps:g,id:N}=s.useSemaphorContext();s.useRoleAwareDisplayPreferences();const{onCreateSuccess:A}=s.useDashboardCreation({onDashboardSelect:r}),{resources:S,isLoading:P,isError:I,createResource:k,updateResource:y,deleteResource:M,duplicateResource:F,isCreating:G,isDeleting:V,refetch:B}=s.useDashboardManagement(()=>{p(!1);const R=b==null?void 0:b.id;j(null),(E==null?void 0:E.id)===R&&(!(g!=null&&g.dashboard_id)&&!N?f():L&&L.id!==R&&C(L))},R=>{i(!1),A(R,B)}),{currentUser:q,userContext:z}=s.useCurrentUserInfo(),_=((ie=z==null?void 0:z.permissions)==null?void 0:ie.canCreateDashboard)??!1,W=S.filter(R=>{var se,Z;return((se=R==null?void 0:R.title)==null?void 0:se.toLowerCase().includes(l.toLowerCase()))||((Z=R==null?void 0:R.description)==null?void 0:Z.toLowerCase().includes(l.toLowerCase()))}),ee=R=>new Date(R).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),te=R=>{k({title:R.title,description:R.description,isPrivate:!1})},ae=R=>{a==null||a(R)},Y=R=>{j(R),p(!0)},U=()=>{b&&M(b.id)},H=R=>{w(R),F(R,{onSettled:()=>w(null)})},{startUpdating:X,stopUpdating:ce,isUpdating:pe}=s.useResourceUpdateState(),ue=(R,se,Z)=>{var ve;const je=Object.fromEntries(Object.entries(se).filter(([,me])=>me!==void 0));if(Object.keys(je).length===0){(ve=Z==null?void 0:Z.onSuccess)==null||ve.call(Z);return}const ge=Object.keys(je),be=ge.length===1?ge[0]:void 0;X(R,be),y({resourceId:R,data:je},{onSuccess:()=>{var me;ce(R,be),(me=Z==null?void 0:Z.onSuccess)==null||me.call(Z)},onError:()=>{var me;ce(R,be),(me=Z==null?void 0:Z.onError)==null||me.call(Z)}})},$=R=>{const se=S.find(Z=>Z.id===R);se&&y({resourceId:R,data:{isPrivate:!se.isPrivate}})},Q=R=>{h(R),q==null||q.type,u(!0)},de=R=>{n==null||n(R.id),O(R)},xe=()=>{O(null)},fe=({title:R,description:se})=>{if(!T)return;const Z={};R!==T.title&&(Z.title=R),(T.description||"")!==se&&(Z.description=se),ue(T.id,Z,{onSuccess:()=>{O(null)}})};return P?e.jsx(dt,{}):I?e.jsx(rl,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[S&&S.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:l,onChange:R=>o(R.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:W.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:l?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:l?"Try adjusting your search":_?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),_&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>i(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):W.map(R=>e.jsx(nl,{dashboard:R,isDeleting:V,isDuplicating:v===R.id,onLoadDashboard:ae,onEditDetails:de,onDeleteClick:Y,onDuplicateDashboard:H,onTogglePrivacy:$,onShareDashboard:Q,formatDate:ee,onDashboardItemClick:r},R.id))})}),d&&m&&e.jsx(s.ShareDialog,{resource:m,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:x,onOpenChange:R=>{!R&&V||(p(R),R||j(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',b==null?void 0:b.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:V,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:R=>{R.preventDefault(),R.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:V,children:[V?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),V?"Deleting...":"Delete"]})]})]})}),T&&e.jsx(s.ResourceEditDialog,{open:!!T,resourceLabel:"Dashboard",initialTitle:T.title||"",initialDescription:T.description||"",onClose:xe,onSave:fe,isSaving:pe(T.id)}),e.jsx(s.CreateDashboardDialog,{open:c,onOpenChange:i,onSubmit:te,isCreating:G}),_&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>i(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function ut({isOpen:t,onClose:a,className:n,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(C=>C.dashboard);const o=s.useDashboardStore(C=>C.isDashboardEditing),{setDashboard:c,addSheet:i}=s.useDashboardStore(C=>C.actions),{currentUser:d}=s.useCurrentUserInfo(),u=d,{permissions:m}=s.useRoleAwareDisplayPreferences(),x=s.useSelectedDashboard()&&m.canAccessVisuals&&o,p="dashboards",[b,j]=Ge("resource-management-active-tab",p),v=x?b:"dashboards",w=l==="overlay",T=Fs(a,{enabled:t&&w}),O=s.cn("flex h-full flex-col border-r bg-background",w?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",n),L=C=>{},E=C=>{console.log("Editing dashboard:",C)};return e.jsx(s.TooltipProvider,{children:(!w||t)&&e.jsxs("div",{ref:T,className:O,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:u&&e.jsxs(e.Fragment,{children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"flex h-8 w-8 cursor-default items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:u.name.charAt(0).toUpperCase()})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:u.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email}),u.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(u.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",u.id]})]})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-foreground",children:u.name})})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Close Sidebar",children:e.jsx($t,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:v,onValueChange:x?j:void 0,className:"flex h-9 grow flex-col",children:[x&&e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(ll,{onLoadDashboard:L,onEditDashboard:E,onDashboardItemClick:r})}),x&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(al,{})})]})})]})})}function ol({showControls:t=!1,showFooter:a=!0,...n}){const r=s.useDashboardStore(x=>x.isDashboardPanelOpen);s.useDashboardStore(x=>x.isVisualEditing);const l=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),o=20,c=20,i=30,d=r,u=D.useRef(null),m=D.useRef(null);D.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(o),m.current.resize(100-o)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:h}=n;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:h,children:[e.jsx(Zr,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Aa,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?o:0,minSize:d?c:0,maxSize:d?i:0,children:e.jsx(ut,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{className:s.cn("",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-o:100,minSize:d?40:100,children:e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(Jr,{}),e.jsx(Xr,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Rs;exports.DashboardPlus=ol;exports.ResourceManagementPanel=ut;exports.ScheduleDashboard=Os;exports.VisualEditingControls=Vs;exports.cleanCard=Ps;exports.getDashbaordStateWithoutData=Re;
|