react-semaphor 0.1.64 → 0.1.65
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-BuCiUxZH.js → dashboard-plus-C7pYT2XM.js} +47 -37
- package/dist/chunks/{dashboard-plus-Dr_jkDZA.js → dashboard-plus-DeKpPZdL.js} +2334 -2213
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),s=require("./index-DHzLB6Yx.js"),w=require("react"),ht=require("react-dom");function xt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-DHzLB6Yx.js"),w=require("react"),ht=require("react-dom");function xt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const Ke=xt(w);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the ISC license.
|
|
25
25
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const
|
|
26
|
+
*/const ks=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
27
|
* @license lucide-react v0.453.0 - ISC
|
|
28
28
|
*
|
|
29
29
|
* This source code is licensed under the ISC license.
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
*
|
|
54
54
|
* This source code is licensed under the ISC license.
|
|
55
55
|
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const
|
|
56
|
+
*/const Ts=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
57
|
* @license lucide-react v0.453.0 - ISC
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
@@ -68,12 +68,17 @@
|
|
|
68
68
|
*
|
|
69
69
|
* This source code is licensed under the ISC license.
|
|
70
70
|
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const Dt=s.createLucideIcon("
|
|
71
|
+
*/const Dt=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
72
|
* @license lucide-react v0.453.0 - ISC
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const kt=s.createLucideIcon("
|
|
76
|
+
*/const kt=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 Tt=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"}]]);/**
|
|
77
82
|
* @license lucide-react v0.453.0 - ISC
|
|
78
83
|
*
|
|
79
84
|
* This source code is licensed under the ISC license.
|
|
@@ -83,77 +88,77 @@
|
|
|
83
88
|
*
|
|
84
89
|
* This source code is licensed under the ISC license.
|
|
85
90
|
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const
|
|
91
|
+
*/const Et=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"}]]);/**
|
|
87
92
|
* @license lucide-react v0.453.0 - ISC
|
|
88
93
|
*
|
|
89
94
|
* This source code is licensed under the ISC license.
|
|
90
95
|
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const
|
|
96
|
+
*/const It=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"}]]);/**
|
|
92
97
|
* @license lucide-react v0.453.0 - ISC
|
|
93
98
|
*
|
|
94
99
|
* This source code is licensed under the ISC license.
|
|
95
100
|
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
-
*/const
|
|
101
|
+
*/const At=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"}]]);/**
|
|
97
102
|
* @license lucide-react v0.453.0 - ISC
|
|
98
103
|
*
|
|
99
104
|
* This source code is licensed under the ISC license.
|
|
100
105
|
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
-
*/const
|
|
106
|
+
*/const Ft=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"}]]);/**
|
|
102
107
|
* @license lucide-react v0.453.0 - ISC
|
|
103
108
|
*
|
|
104
109
|
* This source code is licensed under the ISC license.
|
|
105
110
|
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
-
*/const
|
|
111
|
+
*/const Mt=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"}]]);/**
|
|
107
112
|
* @license lucide-react v0.453.0 - ISC
|
|
108
113
|
*
|
|
109
114
|
* This source code is licensed under the ISC license.
|
|
110
115
|
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const
|
|
116
|
+
*/const Lt=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"}]]);/**
|
|
112
117
|
* @license lucide-react v0.453.0 - ISC
|
|
113
118
|
*
|
|
114
119
|
* This source code is licensed under the ISC license.
|
|
115
120
|
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const
|
|
121
|
+
*/const Pt=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"}]]);/**
|
|
117
122
|
* @license lucide-react v0.453.0 - ISC
|
|
118
123
|
*
|
|
119
124
|
* This source code is licensed under the ISC license.
|
|
120
125
|
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
-
*/const
|
|
126
|
+
*/const Ot=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"}]]);/**
|
|
122
127
|
* @license lucide-react v0.453.0 - ISC
|
|
123
128
|
*
|
|
124
129
|
* This source code is licensed under the ISC license.
|
|
125
130
|
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const
|
|
131
|
+
*/const Bt=s.createLucideIcon("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
|
|
127
132
|
* @license lucide-react v0.453.0 - ISC
|
|
128
133
|
*
|
|
129
134
|
* This source code is licensed under the ISC license.
|
|
130
135
|
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
-
*/const
|
|
136
|
+
*/const us=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"}]]);/**
|
|
132
137
|
* @license lucide-react v0.453.0 - ISC
|
|
133
138
|
*
|
|
134
139
|
* This source code is licensed under the ISC license.
|
|
135
140
|
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
-
*/const
|
|
141
|
+
*/const ms=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"}]]);/**
|
|
137
142
|
* @license lucide-react v0.453.0 - ISC
|
|
138
143
|
*
|
|
139
144
|
* This source code is licensed under the ISC license.
|
|
140
145
|
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
-
*/const
|
|
146
|
+
*/const Vt=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"}]]);/**
|
|
142
147
|
* @license lucide-react v0.453.0 - ISC
|
|
143
148
|
*
|
|
144
149
|
* This source code is licensed under the ISC license.
|
|
145
150
|
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
-
*/const
|
|
151
|
+
*/const Rt=s.createLucideIcon("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
|
|
147
152
|
* @license lucide-react v0.453.0 - ISC
|
|
148
153
|
*
|
|
149
154
|
* This source code is licensed under the ISC license.
|
|
150
155
|
* See the LICENSE file in the root directory of this source tree.
|
|
151
|
-
*/const
|
|
156
|
+
*/const hs=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"}]]);/**
|
|
152
157
|
* @license lucide-react v0.453.0 - ISC
|
|
153
158
|
*
|
|
154
159
|
* This source code is licensed under the ISC license.
|
|
155
160
|
* See the LICENSE file in the root directory of this source tree.
|
|
156
|
-
*/const
|
|
161
|
+
*/const zt=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"}]]);/**
|
|
157
162
|
* @license lucide-react v0.453.0 - ISC
|
|
158
163
|
*
|
|
159
164
|
* This source code is licensed under the ISC license.
|
|
@@ -168,53 +173,58 @@
|
|
|
168
173
|
*
|
|
169
174
|
* This source code is licensed under the ISC license.
|
|
170
175
|
* See the LICENSE file in the root directory of this source tree.
|
|
171
|
-
*/const
|
|
176
|
+
*/const qt=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 Es=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"}]]);/**
|
|
172
182
|
* @license lucide-react v0.453.0 - ISC
|
|
173
183
|
*
|
|
174
184
|
* This source code is licensed under the ISC license.
|
|
175
185
|
* See the LICENSE file in the root directory of this source tree.
|
|
176
|
-
*/const
|
|
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"}]]);/**
|
|
177
187
|
* @license lucide-react v0.453.0 - ISC
|
|
178
188
|
*
|
|
179
189
|
* This source code is licensed under the ISC license.
|
|
180
190
|
* See the LICENSE file in the root directory of this source tree.
|
|
181
|
-
*/const
|
|
191
|
+
*/const Gt=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
182
192
|
* @license lucide-react v0.453.0 - ISC
|
|
183
193
|
*
|
|
184
194
|
* This source code is licensed under the ISC license.
|
|
185
195
|
* See the LICENSE file in the root directory of this source tree.
|
|
186
|
-
*/const
|
|
196
|
+
*/const Ut=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"}]]);/**
|
|
187
197
|
* @license lucide-react v0.453.0 - ISC
|
|
188
198
|
*
|
|
189
199
|
* This source code is licensed under the ISC license.
|
|
190
200
|
* See the LICENSE file in the root directory of this source tree.
|
|
191
|
-
*/const
|
|
201
|
+
*/const Is=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"}]]);/**
|
|
192
202
|
* @license lucide-react v0.453.0 - ISC
|
|
193
203
|
*
|
|
194
204
|
* This source code is licensed under the ISC license.
|
|
195
205
|
* See the LICENSE file in the root directory of this source tree.
|
|
196
|
-
*/const
|
|
206
|
+
*/const Kt=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"}]]);/**
|
|
197
207
|
* @license lucide-react v0.453.0 - ISC
|
|
198
208
|
*
|
|
199
209
|
* This source code is licensed under the ISC license.
|
|
200
210
|
* See the LICENSE file in the root directory of this source tree.
|
|
201
|
-
*/const
|
|
211
|
+
*/const _t=s.createLucideIcon("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/**
|
|
202
212
|
* @license lucide-react v0.453.0 - ISC
|
|
203
213
|
*
|
|
204
214
|
* This source code is licensed under the ISC license.
|
|
205
215
|
* See the LICENSE file in the root directory of this source tree.
|
|
206
|
-
*/const
|
|
216
|
+
*/const Ht=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"}]]);/**
|
|
207
217
|
* @license lucide-react v0.453.0 - ISC
|
|
208
218
|
*
|
|
209
219
|
* This source code is licensed under the ISC license.
|
|
210
220
|
* See the LICENSE file in the root directory of this source tree.
|
|
211
|
-
*/const _t=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 Is(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=w.useRef(null);return w.useEffect(()=>{const c=i=>{const o=i.target;l.current&&l.current.contains(o)||o instanceof Element&&(o.closest("[data-radix-popper-content-wrapper]")||o.closest("[data-radix-select-content]")||o.closest("[data-radix-popover-content]")||o.closest("[data-radix-dropdown-menu-content]")||o.closest("[data-radix-tooltip-content]")||o.closest('[role="listbox"]')||o.closest('[role="option"]')||o.closest('[role="combobox"]'))||o instanceof Element&&o.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,c),()=>{document.removeEventListener(r,c)}},[t,a,r]),l}function Ht(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.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($t,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Ot,{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"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function Ve(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var c;return{...l,cards:(c=l.cards)==null?void 0:c.map(i=>As(i))}})}})}}function As(t){return{...t,customCfg:Jt(t.customCfg),data:[]}}function Jt(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Qt(t,n,a,r,l){if(!l)return null;const c=JSON.stringify(a),i=`${t}/v1/lens`;return await s.postRequest(i,l,{name:n,template:c,filterValues:r,operation:"create"})}async function Ke(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:c,isDefault:i,shared:o}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:c,isDefault:i,shared:o,operation:"update"})}async function Wt(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Yt(){const[t,n]=w.useState(""),[a,r]=w.useState(!1),l=s.useDashboardStore(v=>v.lenses),{setLenses:c,setSelectedLensId:i}=s.useDashboardActions(),[o,d]=w.useState(!1),[u,x]=w.useState(!1),m=s.useDashboardStore(v=>v.dashboard),h=s.useDashboardStore(v=>v.filterValues),{authToken:p,tokenProps:b}=s.useSemaphorContext();async function g(){d(!0);const v=Ve(m),S=await Qt(b.apiServiceUrl,t,v,h,p==null?void 0:p.accessToken);S&&(c([...l||[],S]),i(S.id),x(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:x,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=>{n(v.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&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:g,disabled:o,children:o?"Creating...":"Add"})})]})]})}function Xt(){const[t,n]=w.useState(!1),a=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),{authToken:i,tokenProps:o}=s.useSemaphorContext();async function d(m){c(m)}async function u(m){if(await Wt(o.apiServiceUrl,m,i==null?void 0:i.accessToken)){const p=a==null?void 0:a.filter(b=>b.id!==m);l(p||[]),c("original")}}async function x(m){const h=a==null?void 0:a.map(g=>g.id===m.id?{...g,isDefault:!m.isDefault}:{...g,isDefault:!1});l(h||[]);const p={...m,isDefault:!m.isDefault};await Ke(o.apiServiceUrl,p,i==null?void 0:i.accessToken);const b=a==null?void 0:a.find(g=>g.isDefault);if(b&&b.id!==m.id){const g={...b,isDefault:!1};await Ke(o.apiServiceUrl,g,i==null?void 0:i.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(kt,{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"}),a==null?void 0:a.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),x(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function Zt({iconClassName:t}){const[n,a]=w.useState(!1),[r,l]=w.useState(""),[c,i]=w.useState(!1),o=s.useDashboardStore(m=>m.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function x(){if(!r)return;a(!1),l(""),i(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}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:o,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:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,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:c?"text":"password",value:r,onChange:m=>l(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&x()}}),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:()=>i(!c),children:c?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:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:!r,children:"Download"})]})]})})]})}function Fs({triggerButtonClassName:t}){const[n,a]=w.useState(!1),r=s.useDashboardStore(o=>{var d;return(d=o.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(o=>{var d;return(d=o.dashboard)==null?void 0:d.title}),c=s.useDashboardStore(o=>{var d;return(d=o.dashboard)==null?void 0:d.sheets}),i=s.useDashboardStore(o=>o.selectedSheetId);return c==null||c.find(o=>o.id===i),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}const ea=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},sa=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const c=await l.text();throw new Error(c||"Failed to delete group")}},ta=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},aa=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,c=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!c.ok){const i=await c.text();throw new Error(i||"Failed to remove group members")}};function na(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>ea(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.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 ra(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>sa(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.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 la(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>ta(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.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 oa(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>aa(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.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 ia({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=w.useState(""),[c,i]=w.useState(""),[o,d]=w.useState({}),u=na(),x=()=>{const h={};return r.trim()?r.length<3?h.name="Group name must be at least 3 characters":r.length>50&&(h.name="Group name must be less than 50 characters"):h.name="Group name is required",c&&c.length>200&&(h.description="Description must be less than 200 characters"),d(h),Object.keys(h).length===0},m=async h=>{if(h.preventDefault(),!x())return;const p={name:r.trim(),description:c.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(p),l(""),i(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:m,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:h=>{l(h.target.value),o.name&&d(p=>({...p,name:""}))},className:o.name?"border-destructive":"",disabled:u.isPending}),o.name&&e.jsx("p",{className:"text-sm text-destructive",children:o.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:c,onChange:h=>{i(h.target.value),o.description&&d(p=>({...p,description:""}))},className:o.description?"border-destructive":"",disabled:u.isPending,rows:3}),o.description&&e.jsx("p",{className:"text-sm text-destructive",children:o.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.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(""),i(""),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 ca({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,c]=w.useState("members"),[i,o]=w.useState(""),[d,u]=w.useState([]),[x,m]=w.useState([]),{data:h,isLoading:p,refetch:b}=s.useGroupMembers(a.id),g=a.type==="TENANT_GROUP"?"tenant":"organization",{users:v,isLoading:S}=s.useUnifiedUsers({type:g,tenantId:a.tenantId||void 0,active:!0,limit:100}),k=la(),P=oa(),M=(h==null?void 0:h.members)||[],T=w.useMemo(()=>new Set(M.map(F=>F.userId)),[M]),y=w.useMemo(()=>v.filter(F=>!T.has(F.id)),[v,T]),f=w.useMemo(()=>{if(!i)return y;const F=i.toLowerCase();return y.filter(D=>{var E,L;return((E=D.name)==null?void 0:E.toLowerCase().includes(F))||((L=D.email)==null?void 0:L.toLowerCase().includes(F))})},[y,i]),j=w.useMemo(()=>{if(!i)return M;const F=i.toLowerCase();return M.filter(D=>{var E,L,I,B;return((L=(E=D.user)==null?void 0:E.name)==null?void 0:L.toLowerCase().includes(F))||((B=(I=D.user)==null?void 0:I.email)==null?void 0:B.toLowerCase().includes(F))})},[M,i]),N=async()=>{if(d.length!==0)try{await k.mutateAsync({groupId:a.id,data:{userIds:d,userType:g==="tenant"?"tenant":"org"}}),u([]),c("members"),b(),r==null||r()}catch(F){console.error("Failed to add members:",F)}},A=async()=>{if(x.length!==0)try{await P.mutateAsync({groupId:a.id,data:{userIds:x}}),m([]),b(),r==null||r()}catch(F){console.error("Failed to remove members:",F)}},C=F=>{u(D=>D.includes(F)?D.filter(E=>E!==F):[...D,F])},O=F=>{m(D=>D.includes(F)?D.filter(E=>E!==F):[...D,F])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[M.length," ",M.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:F=>{c(F),o(""),m([])},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:i,onChange:F=>o(F.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:x.length>0?"h-[300px]":"h-[350px]",children:p?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(F=>e.jsx(s.Skeleton,{className:"h-16 w-full"},F))}):j.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:i?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:i?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:j.map(F=>e.jsx(da,{member:F,selected:x.includes(F.userId),onToggle:()=>O(F.userId)},F.id))})}),x.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:[x.length," member",x.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:A,disabled:P.isPending,children:P.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:i,onChange:F=>o(F.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:S?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(F=>e.jsx(s.Skeleton,{className:"h-16 w-full"},F))}):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:i?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:f.map(F=>e.jsx(ua,{user:F,selected:d.includes(F.id),onToggle:()=>C(F.id)},F.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:k.isPending,children:k.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 da({member:t,selected:n,onToggle:a}){var l,c,i,o;const r=((c=(l=t.user)==null?void 0:l.name)==null?void 0:c.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:a,children:[e.jsx(s.Checkbox,{checked:n}),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:((i=t.user)==null?void 0:i.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(o=t.user)==null?void 0:o.email})]})]})}function ua({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(c=>c[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:a,children:[e.jsx(s.Checkbox,{checked:n}),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 ma({open:t,onOpenChange:n}){const[a,r]=w.useState("groups"),[l,c]=w.useState(""),[i,o]=w.useState(null),[d,u]=w.useState(!1),[x,m]=w.useState(null),{tokenProps:h}=s.useSemaphorContext(),{currentUser:p}=s.useCurrentUserInfo(),b=ra(),g=(p==null?void 0:p.type)==="tenant",v=h==null?void 0:h.tenantId,{groups:S,isLoading:k,refetch:P}=s.useGroups({type:g?"TENANT_GROUP":"all",tenantId:g?v:void 0,includeMembers:!1}),M=S.filter(j=>{var N;return j.name.toLowerCase().includes(l.toLowerCase())||((N=j.description)==null?void 0:N.toLowerCase().includes(l.toLowerCase()))}),T=async()=>{if(x)try{await b.mutateAsync(x.id),m(null),P()}catch(j){console.error("Failed to delete group:",j)}},y=j=>{o(j),u(!0)},f=()=>{r("groups"),P()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a,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:j=>c(j.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:k?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(j=>e.jsx(s.Skeleton,{className:"h-24 w-full"},j))}):M.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:M.map(j=>e.jsx(ha,{group:j,onManageMembers:()=>y(j),onDelete:()=>m(j),currentUserId:p==null?void 0:p.id},j.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(ia,{onSuccess:f,tenantId:v,isTenantUser:g})})]})]})}),i&&e.jsx(ca,{open:d,onOpenChange:u,group:i,onUpdate:()=>P()}),e.jsx(s.AlertDialog,{open:!!x,onOpenChange:()=>m(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 "',x==null?void 0:x.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:T,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 ha({group:t,onManageMembers:n,onDelete:a,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:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function Je(t){const[n,a]=w.useState(null),[r,l]=w.useState(null);return w.useEffect(()=>{if(!t||t.trim()===""){a(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 o=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(o,{method:"HEAD"})).ok)throw new Error(`Module not found at ${o}`)}catch{}const d=await import(o);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(i){const o=i instanceof Error?i.message:"Unknown error";console.error("Failed to load remote chart store:",o),l(o),a(null)}})()},[t]),n}function xa(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let c=t.length;if(l!==-1&&(c=l),r!==-1&&r<c&&(c=r),n!==-1){const i=t.substring(0,n),o=t.substring(n);return`${i} {{ filters | where }} AND ${o.substring(6)}`}else if(a!==-1){const i=t.substring(0,a),o=t.substring(a);return`${i} {{ filters | where }} ${o}`}else{const i=t.substring(0,c),o=t.substring(c);return console.log("beforeClause",i),console.log("afterClause",o),o?`${i} {{ filters | where }} ${o}`:`${i.replace(/;$/,"")} {{ filters | where }}`}}function pa(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const c=r.split("__")[0],i=t.find(o=>o.tabTitle===c);return i?i.id:t[0].id}return n}}return t[0].id}async function hs(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],c=r.getQueryData(l);if(c)return console.log("Using cached visual data for:",a),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",a);const i=s.ue.loading("Loading visual...",{position:"top-center"});try{const o=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!o.ok)throw new Error("Failed to load visual");const d=await o.json();return r.setQueryData(l,d),s.ue.dismiss(i),{data:d,fromCache:!1}}catch(o){throw s.ue.dismiss(i),o}}function Ms(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function fa(t,n){var c,i;const a=(t==null?void 0:t.frameObject)??((c=t==null?void 0:t.visual)==null?void 0:c.frameObject);if(!a)return!1;const r=Ms(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(i=r.cards)==null?void 0:i.find(o=>o.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function ga(){var h;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),r=Je(((h=a.customCardPreferences)==null?void 0:h.url)||""),l=s.useEditorStore(p=>p.selectedSchemaName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.selectedDatabaseName),o=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),x=a.sql;return{getUpdatedFrame:w.useCallback(()=>{var S;let p=x;x&&!x.includes("{{")&&(p=xa(x),t(p));const b=(S=r==null?void 0:r.getState())==null?void 0:S.settings,g={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:c,lastSelectedDatabase:i,lastSelectedTable:o,connectionId:d,sql:p,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},v=n.cards.map(k=>k.id===a.id?g:k);return{...n,cards:v,activeCardId:pa(v,n.activeCardId)}},[a,n,u,l,c,i,o,d,t,r,x])}}function ke(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:c,setCard:i,setIsDevMode:o,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:x,setSelectedConnectionId:m,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:g,setFilterValues:v,setApplyFilters:S}=s.useEditorActions(),{setIsDashboardEditing:k,setIsVisualEditing:P,setSelectedFrameId:M,clearSelectedFrameId:T,addFrame:y,setIsDashboardPanelOpen:f}=s.useDashboardActions(),j=s.useDashboardStore(E=>E.selectedSheetId),N=s.useDashboardStore(E=>E.selectedFrameId),A=s.useDashboardStore(E=>E.dashboard),C=s.useDashboardStore(E=>E.filterValues),O=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),F=w.useCallback(async E=>{try{l(E),T();const{data:L,fromCache:I}=await hs(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",E.id,a);if(!fa(L,{setFrame:c,setCard:i,setIsDevMode:o,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:x,setSelectedConnectionId:m,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:g,setFilterValues:v,setApplyFilters:S,setIsDashboardEditing:k,setIsVisualEditing:P,dashboard:A,selectedSheetId:j,selectedFrameId:N,filterValues:C}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:I}}catch(L){return console.error("Error editing visual:",L),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,c,i,k,P,o,d,u,x,m,h,p,b,g,v,S,T,A,j,N,C]),D=w.useCallback(async E=>{var L;try{if(l(E),!j)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:I,fromCache:B}=await hs(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",E.id,a),z=(I==null?void 0:I.frameObject)??((L=I==null?void 0:I.visual)==null?void 0:L.frameObject);if(!z)return{success:!1,error:"Visual has no frame data"};const K=Ms(z);if(!(K!=null&&K.cards)||K.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const U={...K,id:s.v4(),visualId:E.id};return y(j,U,"end"),k(!0),M(U.id),f(!1),{success:!0,fromCache:B}}catch(I){return console.error("Error adding visual:",I),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,j,y,k,M,f]);return{visual:O.data,isLoading:O.isLoading,isError:O.isError,error:O.error,handleEditLibraryVisual:F,handleAddLibraryVisual:D,getUpdatedFrame:ga().getUpdatedFrame,refetch:O.refetch}}function ja({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:c}){const[i,o]=w.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=w.useState(""),[x,m]=w.useState(!a),[h,p]=w.useState(!0);w.useEffect(()=>{t&&(o(a&&r?`Copy of ${r}`:r||""),u(""),m(!a),p(!0))},[t,a,r]);const b=()=>{i.trim()&&(!x&&!h||c({name:i.trim(),description:d.trim()||void 0,saveToLibrary:x,saveToCurrentDashboard:h}))},g=i.trim()&&(x||h);return e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a?"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:i,onChange:v=>o(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:h,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:a?"(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:x,onCheckedChange:v=>m(!!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:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!x&&!h&&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:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!g||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function ba({className:t,variant:n="outline"}){var o;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);Je(((o=r.customCardPreferences)==null?void 0:o.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:c}=ke();function i(){const d=c();l==null||l(d)}return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function va({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=w.useState(!1),c=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),{setIsVisualEditing:i}=s.useDashboardActions(),{getUpdatedFrame:o}=ke(),d=s.useSelectedVisual(),u=s.useEditorStore(h=>h.frame),x=s.useUpdateVisualMutation(),m=()=>{const h=o(),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),x.mutate({visualId:p,data:{frameObject:h}},{onSuccess:()=>{l(!1),c(!0),s.ue.success("Visual updated successfully"),a.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:m,className:s.cn("h-8",t),size:"sm",variant:n,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 ya({className:t}){const n=s.useQueryClient(),[a,r]=w.useState(!1),l=s.useSelectedVisual(),c=s.useEditorStore(h=>h.frame),i=s.useDashboardStore(h=>h.selectedSheetId),{updateFrame:o,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=ke(),x=s.useUpdateVisualMutation(),m=async()=>{if(!i){s.ue.error("No sheet selected");return}const h=(c==null?void 0:c.visualId)||(l==null?void 0:l.id);if(!h){s.ue.error("No visual to update");return}r(!0);try{const p=u();await x.mutateAsync({visualId:h,data:{frameObject:p}});const b={...p,visualId:h};o(i,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",h]}),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:m,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?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 Na({className:t}){const{getUpdatedFrame:n}=ke();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[c,i]=w.useState(!1),o=()=>{if(!a){s.ue.error("No sheet selected");return}i(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{i(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:o,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[c&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!c&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function Ca({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),c=s.useEditorStore(u=>u.onClose),i=s.useEditorStore(u=>u.card),{queryKey:o}=s.useDashboardCardQuery(i);function d(){if(l){const{queryKey:u,queryData:x}=l;u&&x&&r.setQueryData(u,x)}a({}),c==null||c()}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 Qe(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient();s.useEditorStore(g=>g.isDevMode);const a=s.useEditorStore(g=>g.tempQueryData),r=s.useEditorStore(g=>g.card),{queryKey:l}=s.useDashboardCardQuery(r),{setCardSql:c,setSqlGen:i,setCardPython:o,setCardCustomCfg:d,setCardPreferences:u,updateDataSource:x,clearQueryConfig:m,setCardConfig:h,setCardType:p}=s.useEditorActions();function b(){const g=n.getQueryData(l);a!=null&&a.queryData||t({queryKey:l,queryData:g}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),c(""),i({}),m(),h(void 0),o(""),d(""),u({}),p("bar")}return e.jsxs(s.Button,{onClick:b,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(Nt,{className:"mr-2 size-4"}),"Clear"]})}function Sa(){const[t,n]=w.useState(!1),[a,r]=w.useState(!1),[l,c]=w.useState(null),i=s.useEditorStore(M=>M.frame),o=s.useEditorStore(M=>M.card),d=s.useSelectedVisual(),u=s.useDashboardStore(M=>M.selectedSheetId),x=s.useDashboardStore(M=>M.actions.setIsDashboardPanelOpen),{getUpdatedFrame:m}=ke(),{selectVisual:h}=s.useManagementActions(),{addFrame:p,setSelectedFrameId:b,setIsVisualEditing:g}=s.useDashboardActions(),v=!!(i!=null&&i.visualId),S=(d==null?void 0:d.title)||(o==null?void 0:o.title)||"Untitled Visual",k=s.useCreateVisualWithFrame(M=>{if(M!=null&&M.id){if(h(M),a&&l&&u){const T={...l,id:s.v4(),visualId:M.id};p(u,T,"end"),b(T.id),r(!1),c(null),g(!1)}x(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async M=>{if(!u){s.ue.error("No sheet selected");return}const T=m();if(M.saveToLibrary){r(M.saveToCurrentDashboard),c(T);const y={title:M.name,description:M.description,frameObject:T,isPrivate:!1};k.mutate(y)}else if(M.saveToCurrentDashboard){const y={...T,id:s.v4(),visualId:void 0,cards:T.cards.map(f=>({...f,title:f.id===o.id?M.name:f.title}))};p(u,y,"end"),b(y.id),s.ue.success("Visual saved to dashboard"),n(!1),g(!1)}},isLibraryVisual:v,currentVisualName:S,isSaving:k.isPending}}function Ls({className:t}){const n=s.useEditorStore(k=>k.frame),a=s.useEditorStore(k=>k.card),r=s.useManagementStore(k=>k.selectedVisual),l=s.useDashboardStore(k=>k.selectedFrameId),c=s.useDashboardStore(k=>k.selectedSheetId),{setIsVisualEditing:i}=s.useDashboardActions(),o=!!(n!=null&&n.visualId||r!=null&&r.id),d=!!(n!=null&&n.visualId&&l),u=o&&!d,{saveAsDialogOpen:x,setSaveAsDialogOpen:m,handleSaveAs:h,isLibraryVisual:p,currentVisualName:b,isSaving:g}=Sa(),{handleAddLibraryVisual:v}=ke(),S=async()=>{if(!c){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const k=await v(r);k.success?(s.ue.success("Visual added to dashboard"),i(!1)):s.ue.error(k.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!o&&e.jsx(ba,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[d&&e.jsx(Na,{className:t}),u&&c&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:S,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(jt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(va,{className:t,variant:"default"}),d&&e.jsx(ya,{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:k=>{k.stopPropagation(),m(!0)},children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!o&&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:()=>m(!0),children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(Ca,{className:t}),e.jsx(ja,{open:x,onOpenChange:k=>{g||m(k)},isLibraryVisual:p,currentVisualName:b,isSaving:g,onConfirm:h})]})}function Ps({className:t,switchClassName:n}){const a=s.useEditorStore(o=>o.isDevMode),r=s.useDashboardStore(o=>o.isVisualEditing),{setIsDevMode:l}=s.useEditorActions(),{config:c}=w.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!r||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.DevModeSwitch,{className:s.cn("",n),checked:a,onCheckedChange:()=>l(!a),id:"advanced-mode",icon:e.jsx(s.CodeXml,{className:"h-4 w-4"}),tooltip:a?"Standard Mode":"Advanced Mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"sr-only",children:"Advanced Mode"})]})}function wa(){var pe,fe,de;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:c}=s.useRoleAwareDisplayPreferences(),i=s.useHasDashboardId(),{isLoading:o}=s.useDashboardQuery();s.useDashboardStore(V=>V.theme);const d=s.useDashboardStore(V=>V.lenses),u=s.useDashboardStore(V=>V.selectedLensId),x=d==null?void 0:d.find(V=>V.id===u),m=s.useDashboardStore(V=>V.dashboard);s.useDashboardStore(V=>V.selectedSheetId);const h=s.useDashboardStore(V=>V.isDashboardEditing),{setDashboardTitle:p}=s.useDashboardStore(V=>V.actions),[b,g]=w.useState(!1),[v,S]=w.useState(!1),[k,P]=w.useState(!1),M=s.useDashboardStore(V=>V.isDashboardPanelOpen),T=s.useDashboardStore(V=>V.actions.setIsDashboardPanelOpen),y=s.useDashboardStore(V=>V.filterValues),f=s.useDashboardStore(V=>V.isVisualEditing);s.useEditorStore(V=>V.card);const j=s.useManagementStore(V=>V.selectedDashboard),N=s.useManagementStore(V=>V.initialDashboard);s.useManagementStore(V=>V.selectedVisual),s.useDashboardStore(V=>V.selectedFrameId),s.useEditorStore(V=>V.frame);const A=j?(fe=j==null?void 0:j.permissions)==null?void 0:fe.canEdit:(pe=N==null?void 0:N.permissions)==null?void 0:pe.canEdit,C=s.useDashboardStore(V=>V.showFilters),O=s.useDashboardStore(V=>V.showDashboardJSON),F=s.useDashboardStore(V=>V.onSaveFunction),D=s.useDashboardStore(V=>V.actions.setShowFilters),{setIsDashboardEditing:E,setShowDashboardJSON:L}=s.useDashboardStore(V=>V.actions),{setInitialDashboard:I,clearSelectedDashboard:B}=s.useManagementStore(V=>V.actions),{resources:z}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:K}=s.useCurrentUserInfo(),U=s.canUserManageGroups(K),R=j||N,_=R?{id:R.id,title:(m==null?void 0:m.title)||R.title||"Dashboard"}:null,{handleAddNewFrame:Z}=s.useAddNewFrame(),[ne,te]=w.useState(!1),J=s.useUpdateResource(s.ResourceType.DASHBOARD),H=async(V,se)=>{if(!(m!=null&&m.id)){console.log("No dashboard ID found");return}console.log("Updating dashboard title:",{dashboardId:m.id,newTitle:V,previousTitle:se}),J.mutate({resourceId:m.id,data:{title:V}},{onSuccess:()=>{console.log("Dashboard title updated successfully"),s.ue.success("Dashboard title updated")},onError:Y=>{console.error("Failed to update dashboard title:",Y),s.ue.error("Failed to update dashboard title"),p(se)}})};w.useEffect(()=>{if(z&&z.length>0){const V=m==null?void 0:m.id;if(V){const se=z.find(Y=>Y.id===V);se&&I(se)}}},[z,m==null?void 0:m.id,I]);const $=n.orgUserId||n.tenantId,ee=h&&!f&&$&&A,X=()=>{E(!0)};async function ue(){const V=Ve(m);te(!0);const se={template:V};J.mutate({resourceId:V.id,data:se},{onSuccess:()=>{te(!1),s.ue.success("Dashboard saved!")},onError:()=>{te(!1),s.ue.error("Failed to save dashboard")}})}async function me(){if(g(!0),!u||!x)return;const V=Ve(m),se=JSON.stringify(V),Y={...x,template:se,filterValues:y};await Ke(n.apiServiceUrl,Y,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),F==null||F(V),g(!1)}const ae=(x==null?void 0:x.name)||m.title;J.isPending&&console.log("Title during update:",{title:ae,dashboardStateTitle:m.title,dashboardId:m==null?void 0:m.id,currentLensName:x==null?void 0:x.name});const Q=z&&z.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),le=j&&!(n!=null&&n.dashboard_id)&&!a;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:()=>{T(!M)},className:"h-7 p-2",children:e.jsx(Pt,{className:"h-4 w-4"})}),le&&!f&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>B(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!f&&i&&(o?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:ae||"Untitled Dashboard",onSave:V=>{console.log("EditableText onSave called:",{newTitle:V,canEditDashboard:A,dashboardId:m==null?void 0:m.id});const se=(m==null?void 0:m.title)||"";p(V),H(V,se)},isEditable:A&&!x,displayClassName:"text-sm font-medium",inputClassName:"text-sm font-medium",placeholder:"Dashboard Title",isPending:J.isPending}))]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f&&e.jsxs(e.Fragment,{children:[e.jsx(Ps,{className:"mr-2"}),e.jsx(Ls,{className:"h-7"})]}),r&&!f&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(zt,{className:"h-4 w-4"})}),!f&&i&&e.jsx(Zt,{}),!f&&i&&e.jsx(Fs,{}),!f&&i&&U&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>P(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!f&&i&&((de=R==null?void 0:R.permissions)==null?void 0:de.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>S(!0),className:"h-7 p-2",children:e.jsx(s.Share2,{className:"h-4 w-4"})}),!C&&!f&&h&&c.canUseFilters&&i&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>D(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),h&&!f&&$&&r&&i&&e.jsx(Yt,{}),!f&&$&&r&&i&&e.jsx(Xt,{}),h&&!f&&$&&x&&r&&i&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:b,onClick:me,size:"sm",children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!f&&i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>Z(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!f&&!h&&c.canEdit&&i&&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"]}),ee&&i&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:ne,onClick:ue,size:"sm",children:[ne?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),ne?"Saving...":"Save"]}),!f&&h&&r&&i&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>L(!O),size:"sm",variant:"ghost",children:e.jsx(s.Code,{className:"h-4 w-4"})})}),!f&&r&&e.jsx(Ht,{}),h&&!f&&i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{E(!1),L(!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:()=>S(!1)}),e.jsx(ma,{open:k,onOpenChange:P})]})]})}function We(t){const{tokenProps:n,authToken:a}=s.useSemaphorContext(),r=n==null?void 0:n.apiServiceUrl;return s.useQuery({queryKey:["joinability-map",t],queryFn:async()=>{if(!t||!(a!=null&&a.accessToken))return null;const l=`${r}/v1/domains/${t}/joinability`;return s.getRequest(l,a.accessToken)},enabled:!!t&&!!(a!=null&&a.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function Le(t,n,a){if(n==="source")return{isValid:!0};const r=s.getDataType(t.dataType);if(a==="kpi"){if(n==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(n==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function _e(t,n,a,r,l){if(t!=="kpi"||l.length<3)return;const c=(n==null?void 0:n.groupByColumns)&&n.groupByColumns.length>0,i=(n==null?void 0:n.comparisonType)==="none";!c&&i||a(r,{groupByColumns:[],comparisonType:"none"})}const Ye=t=>{var F;const n=(F=t==null?void 0:t.dataSource)==null?void 0:F.semanticDomainId,{data:a}=We(n),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:c,updatePivotByColumn:i,updateSortByColumn:o,removeGroupByColumn:d,removeMetricColumn:u,removePivotByColumn:x,removeSortByColumn:m}=s.useEditorActions(),h=s.useEditorStore(D=>D.card.type),p=t==null?void 0:t.id,b=w.useCallback(D=>{if(!(t!=null&&t.config))return[];switch(D){case"groupBy":return(t.config.groupByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,dateFormat:E.dateFormat,customFormat:E.customFormat,granularity:E.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,direction:E.direction}));case"source":return[];default:return[]}},[t]),g=w.useCallback((D,E)=>{if(p)switch(D){case"groupBy":{r(p,{groupByColumns:E});break}case"metrics":{r(p,{metricColumns:E});break}case"pivotBy":{r(p,{pivotByColumns:E});break}case"sortBy":{r(p,{sortByColumns:E});break}}},[p,r]),v=w.useCallback((D,E,L)=>{if(!p)return;const B=b(D)[E];if(B)switch(D){case"groupBy":l(p,B.id,{label:L});break;case"metrics":c(p,B.id,{label:L});break;case"pivotBy":i(p,B.id,{label:L});break;case"sortBy":o(p,B.id,{label:L});break}},[p,b,l,c,i,o]),S=w.useCallback((D,E)=>{if(!p)return;const I=b("metrics")[D];I&&c(p,I.id,{aggregate:E,label:s.getAggregationLabel(I.name,E)})},[p,b,c]),k=w.useCallback((D,E,L)=>{if(!p)return;const B=b("groupBy")[D];if(!B)return;const z={dateFormat:E};E==="custom"&&L?z.customFormat=L:z.customFormat=void 0,l(p,B.id,z)},[p,b,l]),P=w.useCallback((D,E)=>{if(!p)return;const I=b("groupBy")[D];I&&l(p,I.id,{granularity:E})},[p,b,l]),M=w.useCallback((D,E)=>{if(!p)return;const I=b("metrics")[D];I&&c(p,I.id,{aliasTemplate:E})},[p,b,c]),T=w.useCallback((D,E)=>{if(console.log("handleValueAliasesChange",D,E),!p)return;console.log("handleValueAliasesChange",D,E);const I=b("metrics")[D];I&&(console.log("handleValueAliasesChange",E),c(p,I.id,{valueAliases:E}))},[p,b,c]),y=w.useCallback(D=>{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:D})},[p,r,b]),f=w.useCallback(D=>{p&&r(p,{showTrendline:D})},[p,r]),j=w.useCallback(D=>{p&&r(p,{trendlineWindow:D})},[p,r]),N=w.useCallback(D=>{p&&r(p,{trendlineGranularity:D})},[p,r]),A=w.useCallback(D=>{p&&r(p,{targetValue:D})},[p,r]),C=w.useCallback(D=>{var U;if(!p)return;const E=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy")],L=s.validateEntityConsistency(D,E,{joinPlan:(U=t==null?void 0:t.config)==null?void 0:U.joinPlan,joinabilityMap:a==null?void 0:a.joinabilityMap,semanticDomainId:n});if(!L.isValid){L.showError&&s.showJoinRequiredNotification();return}const I=s.getSmartContainerForField(D,E,h);if(!I){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=Le(D,I,h);if(!B.isValid){s.ue.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const z=b(I);if(s.fieldAlreadyExists(D,z))return;const K=s.getNewField(D,I,z);if(K){const R=[...z,K];g(I,R),I==="metrics"&&_e(h,t==null?void 0:t.config,r,p,R)}},[p,t==null?void 0:t.config,b,g,n,a,h,r]),O=w.useCallback((D,E)=>{if(!p)return;const I=b(D)[E];if(I){if(D!=="sortBy"){const B=b("sortBy"),z=B.filter(K=>!(K.name===I.name&&K.qualifiedEntityName===I.qualifiedEntityName));z.length!==B.length&&r(p,{sortByColumns:z})}switch(D){case"groupBy":d(p,I.id);break;case"metrics":u(p,I.id);break;case"pivotBy":x(p,I.id);break;case"sortBy":m(p,I.id);break}}},[p,b,d,u,x,m,r]);return{getFieldsForContainer:b,setFieldsForContainer:g,updateLabel:v,handleAggregationChange:S,handleDateFormatChange:k,handleGranularityChange:P,handleAliasTemplateChange:M,handleValueAliasesChange:T,removeField:O,handleFieldClick:C,handleKpiComparisonTypeChange:y,handleKpiShowTrendlineChange:f,handleKpiTrendlineWindowChange:j,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:A,cardType:h}};function Pe(t){return`${t}-${s.v4()}`}function xs(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Da(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function Xe(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 n=t.selectedEntities[0];return{tableName:n==null?void 0:n.name,schemaName:n==null?void 0:n.schema,databaseName:n==null?void 0:n.database,connectionId:t.connectionId,connectionType:t.connectionType}}function Os(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const n=t.selectedEntities[0];return!!(n!=null&&n.name)}function Bs(){const t=s.useEditorStore(y=>y.sqlGen),n=s.useEditorStore(y=>y.isDevMode),a=s.useEditorStore(y=>y.card.dataSource),r=s.useEditorStore(y=>{var f,j;return(j=(f=y.card)==null?void 0:f.queryConfig)==null?void 0:j.metricColumns}),{tableName:l,schemaName:c,databaseName:i}=Xe(a),o=Os(a),d=s.useEditorStore(y=>y.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:x,setCardSql:m,setRunSql:h,setSqlGen:p,setIsShowingVisual:b}=s.useEditorActions(),{connectionType:g,modelItems:v,selectedDatamodelName:S}=s.useEditorAside(),k=y=>({column_name:y.name,data_type:y.dataType,label:y.label,description:y.description});return{handleDevModeFieldClick:y=>{var j;if(!n)return;const f=k(y);if(n&&o&&l){const N=s.createSqlGenConfig(f,t);p(N);const A=(j=v==null?void 0:v.find(O=>O.id===d))==null?void 0:j.name,C=s.getSql(N,s.fmt(c||""),s.fmt(l),A||"",g,i||"");C&&(m(C),h(!0))}else if(!n){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};x(N)}else{const N={...f,role:"metric",id:Pe(f.column_name),name:f.column_name,label:xs(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:Da(f.column_name,"month"),granularity:"month"};x(N)}if(s.isNumberDataType(f.data_type)){const N={...f,role:"metric",id:Pe(f.column_name),name:f.column_name,label:xs(f.column_name,"SUM"),type:f.data_type,aggregate:"SUM"};u(N)}}},handleShowSample:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const y=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:S,connectionType:g,databaseName:i||""});b(!1);const f=g==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;m(f),h(!0)},handleShowCount:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const y=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:S,connectionType:g,databaseName:i||""});m(`SELECT COUNT(*) as count FROM ${y}`),h(!0)},isNumberField:y=>s.isNumberDataType(y.dataType)}}function Vs(){const t=s.useEditorStore(b=>b.selectedConnectionId),n=s.useEditorStore(b=>b.selectedDatamodelId),a=s.useEditorStore(b=>b.selectedDatabaseName),r=s.useEditorStore(b=>b.selectedSchemaName),l=s.useEditorStore(b=>b.selectedTableName),c=s.useDashboardStore(b=>b.dashboard.filters)||[],i=s.useDashboardStore(b=>b.selectedSheetId),o=s.useDashboardStore(b=>b.actions.addFilter),d=s.useDashboardStore(b=>b.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{modelItems:x,tableName:m,connectionType:h}=s.useEditorAside();function p(b,g="sheet",v){var N;const S=s.fmt(b.column_name),k=s.fmt(a||""),P=s.fmt(r||""),M=s.fmt(m);let T=s.getQualifiedTableName({schemaName:P,tableName:M,connectionType:h,databaseName:k}),y=`${T}.${S}`;const f=(N=x==null?void 0:x.find(A=>A.id===n))==null?void 0:N.name;n&&n!=="none"&&(y=`${s.DATAMODEL_NAMESPCACE}.${f}.${S}`,T=`${s.DATAMODEL_NAMESPCACE}.${f}`),v!=null&&v.qualifiedFieldName&&(y=v.qualifiedFieldName),v!=null&&v.entityName&&(T=v.entityName);let j;if(g==="sheet"&&i?j=s.filterExistsInSheet(c,y,M,a||"",k,i):j=c==null?void 0:c.find(A=>A.column===y&&A.table===M&&(A.database===k||A.database===a)),j)u(j.id),d(j.id);else{const A=s.v4(),C=g==="sheet"&&i?[i]:void 0;return m==="api"&&t?(o({location:g,id:A,column:y,title:b.label||b.column_name,dataType:b.data_type,table:"api",database:"",connectionId:t,operation:"in",applyToSheetIds:C,sql:s.getDefaultFilterSql(b.data_type,T,S)}),A):(o({id:A,location:g,column:y,title:b.label||b.column_name,dataType:b.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",applyToSheetIds:C,sql:s.getDefaultFilterSql(b.data_type,T,S)}),A)}}return{assignFilter:p}}function ka({column:t}){const[n,a]=w.useState(!1),r=s.useEditorStore(S=>S.card.dataSource),{tableName:l,schemaName:c,databaseName:i}=Xe(r),o=s.useEditorStore(S=>S.selectedDatamodelId),d=s.useEditorStore(S=>S.sqlGen),{modelItems:u,connectionType:x}=s.useEditorAside(),m=s.useEditorStore(S=>S.actions.setSqlGen),h=s.useEditorStore(S=>S.actions.setCardSql),p=s.useEditorStore(S=>S.actions.setRunSql),b=Os(r);function g(S,k){var y;if(!b||!l){console.warn("Cannot generate SQL: missing table metadata");return}const P=s.createSqlGenConfig(S,d,k),M=(y=u==null?void 0:u.find(f=>f.id===o))==null?void 0:y.name;m(P);const T=s.getSql(P,s.fmt(c||""),s.fmt(l),M||"",x,i||"");T&&(h(T),p(!0)),a(!1)}function v(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(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:n,onOpenChange:a,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 Ta({field:t,fieldState:n}){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}),n&&n.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n.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 Ea({field:t,context:n="editor",fieldState:a}){const r=s.useEditorStore(R=>R.isDevMode),l=n==="filter",c=r||l||(a==null?void 0:a.state)==="unreachable"&&!l,i=s.useDashboardStore(R=>R.dashboard.filters),o=s.useDashboardStore(R=>R.selectedSheetId),d=s.useDashboardStore(R=>R.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{assignFilter:x}=Vs(),m=l?s.getSheetScopedFilters(i,o):i,h=l?m==null?void 0:m.find(R=>{var _;return R.title===t.name||((_=R.column)==null?void 0:_.includes(t.name))}):void 0,p=!!h,b=h&&l?i==null?void 0:i.find(R=>R.id===h.id):void 0,g=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:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:b?{id:b.id,title:b.title,column:b.column,applyToSheetIds:b.applyToSheetIds,excludeSheetIds:b.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:o});const[v,S]=w.useState(!1),[k,P]=w.useState(null),{attributes:M,listeners:T,setNodeRef:y,transform:f,transition:j,isDragging:N}=s.useSortable({id:t.id,disabled:c}),[A,C]=w.useState(!1),O=s.useEditorStore(R=>R.card),{handleFieldClick:F}=Ye(O),{handleDevModeFieldClick:D,isNumberField:E}=Bs(),L=()=>{b&&(console.log("[SourceField] Removing multi-sheet filter:",b.id),u(b.id),d(b.id)),P(null),S(!1)},I=()=>{if(l){const R={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};console.log("[SourceField Click]",{fieldName:t.name,hasActiveFilter:p,isMultiSheetFilter:g,willShowWarning:p&&g}),p&&g?(console.log("[SourceField] Showing warning dialog for multi-sheet filter"),P({column:R,field:t}),S(!0)):(console.log("[SourceField] Calling assignFilter directly (single-sheet or new filter)"),x(R,"sheet",t))}else r?D(t):F(t)},B={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},z={transform:s.CSS.Transform.toString(f),transition:j},U=(()=>{if(!a||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"}}[a.state]||{};return a.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",..._}}[a.state]||_})();return e.jsxs("div",{ref:y,style:z,...c?{}:M,...c?{}:T,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",N&&"scale-95 opacity-50",!N&&"border",U.borderColor||"border-transparent",U.bgColor||"",U.hoverBorderColor,U.hoverBgColor||"hover:bg-muted",U.opacity,U.cursor,p&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!c&&!r&&!l}),title:a==null?void 0:a.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:I,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(Ta,{field:t,fieldState:a})})]})}),r&&!l&&E(t)&&e.jsx("div",{onClick:R=>R.stopPropagation(),children:e.jsx(ka,{column:B})})]}),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(Es,{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(Ut,{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:S,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:L,children:"Remove Filter"})]})]})})]})}function Ia({context:t="editor"}={}){var A,C,O,F;const[n,a]=w.useState(""),[r,l]=w.useState("all");s.useEditorStore(D=>D.isDevMode);const c=s.useEditorStore(D=>D.card.dataSource),i=s.useEditorStore(D=>D.card.config),o=s.useEditorStore(D=>D.card),{autoJoinMetadata:d}=s.useDashboardCardQuery(o),{columns:u=[],columnGroups:x=[],isLoading:m,error:h}=s.useColumns(),p=(c==null?void 0:c.mode)==="semanticDomain"?c.semanticDomainId:void 0,{data:b}=We(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(C=(A=i==null?void 0:i.joinPlan)==null?void 0:A.baseEntity)==null||C.name,(F=(O=d==null?void 0:d.resolvedJoinPlan)==null?void 0:O.baseEntity)==null||F.name,Bs();const v=u.filter(D=>D.name.toLowerCase().includes(n.toLowerCase())||D.dataType.toLowerCase().includes(n.toLowerCase())||D.label&&D.label.toLowerCase().includes(n.toLowerCase())||D.qualifiedEntityName&&D.qualifiedEntityName.toLowerCase().includes(n.toLowerCase())),S=D=>{if(D.dataType==="number"||D.dataType==="integer"||D.dataType==="float"||D.dataType==="decimal"||D.dataType==="currency")return"metrics";const E=s.getDataType(D.dataType);return["date","string","boolean"].includes(E)?"dimensions":E==="number"?"metrics":"dimensions"},P=(r==="all"?v:v.filter(D=>S(D)===r)).reduce((D,E)=>{const L=E.qualifiedEntityName||"Other Fields";return D[L]||(D[L]={label:s.toLabel(E.entityName),fields:[]}),D[L].fields.push(E),D},{}),T=Object.keys(P),y=v.filter(D=>S(D)==="dimensions").length,f=v.filter(D=>S(D)==="metrics").length,j=v.filter(D=>S(D)==="calculated").length,N=v.length>0;return m?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"})}):h?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:h.message||"Failed to load column data"})]}):!c||!c.selectedEntities||c.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:n,onChange:D=>a(D.target.value)}),n&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>a(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:D=>l(D),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:y})]}),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:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:T,className:"space-y-2",children:Object.entries(P).map(([D,E])=>{const L=x.find(I=>I.entityName===D)||{entityName:D,label:E.label};return e.jsxs(s.AccordionItem,{value:D,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:L.label||L.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:L.label||L.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:E.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:E.fields.map(I=>{const B=s.calculateFieldState(I,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:d});return e.jsx(Ea,{field:I,context:t,fieldState:B},I.id)})})})]},D)})}),Object.keys(P).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(P).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 Rs({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(Ia,{context:t})," "]})}function Aa({initialJoinPlan:t,availableDataSources:n}){const[a,r]=w.useState(t),[l,c]=w.useState(new Set),i=()=>{const y=a.joins.length>0?Math.max(...a.joins.map(j=>j.sequence))+1:1,f={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:y,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,f]}),c(new Set([...l,f.id]))},o=y=>{r({...a,joins:a.joins.filter(f=>f.id!==y)}),c(new Set([...l].filter(f=>f!==y)))},d=(y,f)=>{var O,F,D,E,L;const j=a.joins.find(I=>I.id===y);if(!j)return;const N={...j,...f};if((O=N.source)!=null&&O.name&&((F=N.target)!=null&&F.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=a.joins.filter(I=>{var B;return I.id!==y&&I.target.name===((B=N.target)==null?void 0:B.name)});if((D=N.target)!=null&&D.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 C=a.joins.map(I=>I.id===y?N:I);if((E=N.source)!=null&&E.name&&((L=N.target)!=null&&L.name)&&N.joinKeyGroups[0].keys.length===0){const I=n.find(U=>{var R;return U.name===((R=N.source)==null?void 0:R.name)}),B=n.find(U=>{var R;return U.name===((R=N.target)==null?void 0:R.name)}),z={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(B==null?void 0:B.name)||"",entityName:(B==null?void 0:B.name)||"",entityType:(B==null?void 0:B.type)||"table"},operator:"="},K=[...N.joinKeyGroups];K[0]={...K[0],keys:[z]},N.joinKeyGroups=K,C[C.findIndex(U=>U.id===y)]=N}r({...a,joins:C})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:i,removeJoin:o,updateJoin:d,moveJoinUp:y=>{const f=a.joins.findIndex(j=>j.id===y);if(f>0){const j=[...a.joins],N={...j[f]},A={...j[f-1]};j[f]=A,j[f-1]=N,j.forEach((O,F)=>{O.sequence=F+1});const C={...a,joins:j};r(C)}},moveJoinDown:y=>{const f=a.joins.findIndex(j=>j.id===y);if(f<a.joins.length-1){const j=[...a.joins],N={...j[f]},A={...j[f+1]};j[f]=A,j[f+1]=N,j.forEach((O,F)=>{O.sequence=F+1});const C={...a,joins:j};r(C)}},toggleJoinExpansion:y=>{const f=new Set(l);f.has(y)?f.delete(y):f.add(y),c(f)},getAvailableSourceEntities:y=>{if(a.joins.length===0)return n;const f=a.joins.findIndex(N=>N.id===y);if(f===0)return n.filter(N=>N.name===a.baseEntity.name);const j=new Set;return a.baseEntity.name&&j.add(a.baseEntity.name),a.joins.slice(0,f).forEach(N=>{j.add(N.source.name),j.add(N.target.name)}),n.filter(N=>j.has(N.name))},getAvailableTargetEntities:y=>n.filter(f=>f.name!==y),addJoinKeyGroup:y=>{const f=a.joins.find(N=>N.id===y);if(!f)return;const j=[...f.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(y,{joinKeyGroups:j})},updateGroupOperator:(y,f,j)=>{const N=a.joins.find(C=>C.id===y);if(!N)return;const A=[...N.joinKeyGroups];A[f]={...A[f],operator:j},d(y,{joinKeyGroups:A})},removeJoinKeyGroup:(y,f)=>{const j=a.joins.find(A=>A.id===y);if(!j)return;const N=[...j.joinKeyGroups];N.splice(f,1),d(y,{joinKeyGroups:N})},addJoinKey:(y,f)=>{const j=a.joins.find(F=>F.id===y);if(!j)return;const N=n.find(F=>F.name===j.source.name),A=n.find(F=>F.name===j.target.name),C=[...j.joinKeyGroups],O={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:"="};C[f]={...C[f],keys:[...C[f].keys,O]},d(y,{joinKeyGroups:C})},updateJoinKey:(y,f,j,N,A)=>{const C=a.joins.find(L=>L.id===y);if(!C)return;const O=n.find(L=>L.name===C.source.name),F=n.find(L=>L.name===C.target.name),D=[...C.joinKeyGroups],E=D[f].keys[j];N==="sourceColumnName"&&O?D[f].keys[j]={...E,source:{...E.source,name:A}}:N==="targetColumnName"&&F?D[f].keys[j]={...E,target:{...E.target,name:A}}:N==="operator"&&(D[f].keys[j]={...E,operator:A}),d(y,{joinKeyGroups:D})},removeJoinKey:(y,f,j)=>{const N=a.joins.find(C=>C.id===y);if(!N)return;const A=[...N.joinKeyGroups];A[f].keys.splice(j,1),d(y,{joinKeyGroups:A})},generateSQLPreview:()=>{const y=[...a.joins].sort((N,A)=>N.sequence-A.sequence),f=a.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
|
|
212
|
-
FROM ${f.name}`;return y.forEach(N=>{const
|
|
213
|
-
${N.joinType} JOIN ${
|
|
214
|
-
ON ${O}`}),j},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(N=>!N.source.name||!N.target.name)||a.joins.some(N=>N.joinKeyGroups.some(A=>A.keys.length===0))||a.joins.some(N=>N.joinKeyGroups.some(A=>A.keys.some(C=>!C.source.name||!C.target.name||!C.operator))))}}function Fa({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:c}=s.useEditorActions();s.useEditorStore(C=>C.card.config);const{columnGroups:i}=s.useColumns(),{joinPlan:o,expandedJoins:d,setJoinPlan:u,addJoin:x,removeJoin:m,updateJoin:h,moveJoinUp:p,moveJoinDown:b,toggleJoinExpansion:g,getAvailableSourceEntities:v,getAvailableTargetEntities:S,addJoinKeyGroup:k,updateGroupOperator:P,removeJoinKeyGroup:M,addJoinKey:T,updateJoinKey:y,removeJoinKey:f,generateSQLPreview:j,isValidConfiguration:N}=Aa({initialJoinPlan:t,availableDataSources:n}),A=C=>{const O=i.find(F=>F.entityName===C);return(O==null?void 0:O.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:o.baseEntity.name,onValueChange:C=>{const O=n.find(F=>F.name===C);u({...o,baseEntity:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:C,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:C.type}),C.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},C.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:j()})]}),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 (",o.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),o.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:o.joins.map(C=>{const O=n.find(E=>E.name===C.source.name),F=n.find(E=>E.name===C.target.name),D=d.has(C.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:C.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",C.sequence,O&&F&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",O.name," → ",F.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(C.id),disabled:C.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(C.id),disabled:C.sequence===o.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(C.id),children:D?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:()=>m(C.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),D&&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:C.source.name,onValueChange:E=>{const L=n.find(I=>I.name===E);h(C.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(C.id).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name]})},E.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:C.joinType,onValueChange:E=>h(C.id,{joinType:E}),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:C.target.name,onValueChange:E=>{const L=n.find(I=>I.name===E);h(C.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!C.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:C.source.name?S(C.source.name).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name,E.name===C.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},E.name)):[]})]})]})]}),C.source.name&&C.target.name&&O&&F&&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:()=>k(C.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),C.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:C.joinKeyGroups.map((E,L)=>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 ",L+1]}),L>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:E.operator,onValueChange:I=>P(C.id,L,I),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:()=>M(C.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[E.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:E.keys.map((I,B)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[B>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:E.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:I.source.name,onValueChange:z=>y(C.id,L,B,"sourceColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:A(C.source.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:I.operator,onValueChange:z=>y(C.id,L,B,"operator",z),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:I.target.name,onValueChange:z=>y(C.id,L,B,"targetColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:A(C.target.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>f(C.id,L,B),children:e.jsx(s.X,{className:"size-3.5"})})]},I.id||B))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>T(C.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},E.id))})]})]})]},C.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:()=>a(o),disabled:!N(),children:"Save"})]})]})}function He({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:c,onSave:i,onCancel:o}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,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(Fa,{joinPlan:r,availableDataSources:l,onSave:i,onCancel:o,onRemove:c})]}),t]})}function Ma({joins:t,baseEntityId:n,availableDataSources:a,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((i,o)=>i.sequence-o.sequence),c=a.find(i=>i.name===n);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:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(i=>{const o=a.find(d=>d.name===i.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:i.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:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name})]})]},i.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,c)=>l.sequence-c.sequence).map((l,c)=>{const i=a.find(d=>d.name===l.source.name),o=a.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:c+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[i==null?void 0:i.name," → ",o==null?void 0:o.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 La(){var m,h;const t=s.useEditorStore(p=>p.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(t),a=s.useEditorStore(p=>p.actions.updateCardConfig),r=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[l,c]=w.useState(!1),i=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],o=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),c(!1)},d=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{c(!1)},x=()=>{const p=[...r.joins].sort((v,S)=>v.sequence-S.sequence),b=r.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
|
|
215
|
-
FROM ${b.name}`;return p.forEach(v=>{const S=i.find(M=>M.name===v.target.name);if(!S)return;const k=v.joinKeyGroups.filter(M=>M.keys&&M.keys.length>0).map(M=>{const T=M.keys.filter(y=>{var f,j,N,
|
|
221
|
+
*/const Jt=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 As(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=w.useRef(null);return w.useEffect(()=>{const c=i=>{const o=i.target;l.current&&l.current.contains(o)||o instanceof Element&&(o.closest("[data-radix-popper-content-wrapper]")||o.closest("[data-radix-select-content]")||o.closest("[data-radix-popover-content]")||o.closest("[data-radix-dropdown-menu-content]")||o.closest("[data-radix-tooltip-content]")||o.closest('[role="listbox"]')||o.closest('[role="option"]')||o.closest('[role="combobox"]'))||o instanceof Element&&o.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,c),()=>{document.removeEventListener(r,c)}},[t,a,r]),l}function Qt(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.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(Ut,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Bt,{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"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function Ve(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var c;return{...l,cards:(c=l.cards)==null?void 0:c.map(i=>Fs(i))}})}})}}function Fs(t){return{...t,customCfg:Wt(t.customCfg),data:[]}}function Wt(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Yt(t,n,a,r,l){if(!l)return null;const c=JSON.stringify(a),i=`${t}/v1/lens`;return await s.postRequest(i,l,{name:n,template:c,filterValues:r,operation:"create"})}async function _e(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:c,isDefault:i,shared:o}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:c,isDefault:i,shared:o,operation:"update"})}async function Xt(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Zt(){const[t,n]=w.useState(""),[a,r]=w.useState(!1),l=s.useDashboardStore(v=>v.lenses),{setLenses:c,setSelectedLensId:i}=s.useDashboardActions(),[o,d]=w.useState(!1),[u,x]=w.useState(!1),m=s.useDashboardStore(v=>v.dashboard),h=s.useDashboardStore(v=>v.filterValues),{authToken:p,tokenProps:b}=s.useSemaphorContext();async function g(){d(!0);const v=Ve(m),S=await Yt(b.apiServiceUrl,t,v,h,p==null?void 0:p.accessToken);S&&(c([...l||[],S]),i(S.id),x(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:x,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=>{n(v.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&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:g,disabled:o,children:o?"Creating...":"Add"})})]})]})}function ea(){const[t,n]=w.useState(!1),a=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),{authToken:i,tokenProps:o}=s.useSemaphorContext();async function d(m){c(m)}async function u(m){if(await Xt(o.apiServiceUrl,m,i==null?void 0:i.accessToken)){const p=a==null?void 0:a.filter(b=>b.id!==m);l(p||[]),c("original")}}async function x(m){const h=a==null?void 0:a.map(g=>g.id===m.id?{...g,isDefault:!m.isDefault}:{...g,isDefault:!1});l(h||[]);const p={...m,isDefault:!m.isDefault};await _e(o.apiServiceUrl,p,i==null?void 0:i.accessToken);const b=a==null?void 0:a.find(g=>g.isDefault);if(b&&b.id!==m.id){const g={...b,isDefault:!1};await _e(o.apiServiceUrl,g,i==null?void 0:i.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Tt,{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"}),a==null?void 0:a.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),x(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function sa({iconClassName:t}){const[n,a]=w.useState(!1),[r,l]=w.useState(""),[c,i]=w.useState(!1),o=s.useDashboardStore(m=>m.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function x(){if(!r)return;a(!1),l(""),i(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}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:o,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:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,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:c?"text":"password",value:r,onChange:m=>l(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&x()}}),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:()=>i(!c),children:c?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:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:x,disabled:!r,children:"Download"})]})]})})]})}function Ms({triggerButtonClassName:t}){const[n,a]=w.useState(!1),r=s.useDashboardStore(o=>{var d;return(d=o.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(o=>{var d;return(d=o.dashboard)==null?void 0:d.title}),c=s.useDashboardStore(o=>{var d;return(d=o.dashboard)==null?void 0:d.sheets}),i=s.useDashboardStore(o=>o.selectedSheetId);return c==null||c.find(o=>o.id===i),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}const ta=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},aa=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const c=await l.text();throw new Error(c||"Failed to delete group")}},na=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},ra=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,c=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!c.ok){const i=await c.text();throw new Error(i||"Failed to remove group members")}};function la(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>ta(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.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 oa(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>aa(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.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 ia(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>na(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.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 ca(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>ra(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.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 da({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=w.useState(""),[c,i]=w.useState(""),[o,d]=w.useState({}),u=la(),x=()=>{const h={};return r.trim()?r.length<3?h.name="Group name must be at least 3 characters":r.length>50&&(h.name="Group name must be less than 50 characters"):h.name="Group name is required",c&&c.length>200&&(h.description="Description must be less than 200 characters"),d(h),Object.keys(h).length===0},m=async h=>{if(h.preventDefault(),!x())return;const p={name:r.trim(),description:c.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(p),l(""),i(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:m,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:h=>{l(h.target.value),o.name&&d(p=>({...p,name:""}))},className:o.name?"border-destructive":"",disabled:u.isPending}),o.name&&e.jsx("p",{className:"text-sm text-destructive",children:o.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:c,onChange:h=>{i(h.target.value),o.description&&d(p=>({...p,description:""}))},className:o.description?"border-destructive":"",disabled:u.isPending,rows:3}),o.description&&e.jsx("p",{className:"text-sm text-destructive",children:o.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.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(""),i(""),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 ua({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,c]=w.useState("members"),[i,o]=w.useState(""),[d,u]=w.useState([]),[x,m]=w.useState([]),{data:h,isLoading:p,refetch:b}=s.useGroupMembers(a.id),g=a.type==="TENANT_GROUP"?"tenant":"organization",{users:v,isLoading:S}=s.useUnifiedUsers({type:g,tenantId:a.tenantId||void 0,active:!0,limit:100}),k=ia(),O=ca(),M=(h==null?void 0:h.members)||[],T=w.useMemo(()=>new Set(M.map(A=>A.userId)),[M]),y=w.useMemo(()=>v.filter(A=>!T.has(A.id)),[v,T]),f=w.useMemo(()=>{if(!i)return y;const A=i.toLowerCase();return y.filter(D=>{var E,L;return((E=D.name)==null?void 0:E.toLowerCase().includes(A))||((L=D.email)==null?void 0:L.toLowerCase().includes(A))})},[y,i]),j=w.useMemo(()=>{if(!i)return M;const A=i.toLowerCase();return M.filter(D=>{var E,L,I,B;return((L=(E=D.user)==null?void 0:E.name)==null?void 0:L.toLowerCase().includes(A))||((B=(I=D.user)==null?void 0:I.email)==null?void 0:B.toLowerCase().includes(A))})},[M,i]),N=async()=>{if(d.length!==0)try{await k.mutateAsync({groupId:a.id,data:{userIds:d,userType:g==="tenant"?"tenant":"org"}}),u([]),c("members"),b(),r==null||r()}catch(A){console.error("Failed to add members:",A)}},F=async()=>{if(x.length!==0)try{await O.mutateAsync({groupId:a.id,data:{userIds:x}}),m([]),b(),r==null||r()}catch(A){console.error("Failed to remove members:",A)}},C=A=>{u(D=>D.includes(A)?D.filter(E=>E!==A):[...D,A])},P=A=>{m(D=>D.includes(A)?D.filter(E=>E!==A):[...D,A])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[M.length," ",M.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:A=>{c(A),o(""),m([])},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:i,onChange:A=>o(A.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:x.length>0?"h-[300px]":"h-[350px]",children:p?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(A=>e.jsx(s.Skeleton,{className:"h-16 w-full"},A))}):j.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:i?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:i?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:j.map(A=>e.jsx(ma,{member:A,selected:x.includes(A.userId),onToggle:()=>P(A.userId)},A.id))})}),x.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:[x.length," member",x.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:F,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:i,onChange:A=>o(A.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:S?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(A=>e.jsx(s.Skeleton,{className:"h-16 w-full"},A))}):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:i?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:f.map(A=>e.jsx(ha,{user:A,selected:d.includes(A.id),onToggle:()=>C(A.id)},A.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:k.isPending,children:k.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 ma({member:t,selected:n,onToggle:a}){var l,c,i,o;const r=((c=(l=t.user)==null?void 0:l.name)==null?void 0:c.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:a,children:[e.jsx(s.Checkbox,{checked:n}),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:((i=t.user)==null?void 0:i.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(o=t.user)==null?void 0:o.email})]})]})}function ha({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(c=>c[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:a,children:[e.jsx(s.Checkbox,{checked:n}),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 xa({open:t,onOpenChange:n}){const[a,r]=w.useState("groups"),[l,c]=w.useState(""),[i,o]=w.useState(null),[d,u]=w.useState(!1),[x,m]=w.useState(null),{tokenProps:h}=s.useSemaphorContext(),{currentUser:p}=s.useCurrentUserInfo(),b=oa(),g=(p==null?void 0:p.type)==="tenant",v=h==null?void 0:h.tenantId,{groups:S,isLoading:k,refetch:O}=s.useGroups({type:g?"TENANT_GROUP":"all",tenantId:g?v:void 0,includeMembers:!1}),M=S.filter(j=>{var N;return j.name.toLowerCase().includes(l.toLowerCase())||((N=j.description)==null?void 0:N.toLowerCase().includes(l.toLowerCase()))}),T=async()=>{if(x)try{await b.mutateAsync(x.id),m(null),O()}catch(j){console.error("Failed to delete group:",j)}},y=j=>{o(j),u(!0)},f=()=>{r("groups"),O()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a,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:j=>c(j.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:k?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(j=>e.jsx(s.Skeleton,{className:"h-24 w-full"},j))}):M.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:M.map(j=>e.jsx(pa,{group:j,onManageMembers:()=>y(j),onDelete:()=>m(j),currentUserId:p==null?void 0:p.id},j.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(da,{onSuccess:f,tenantId:v,isTenantUser:g})})]})]})}),i&&e.jsx(ua,{open:d,onOpenChange:u,group:i,onUpdate:()=>O()}),e.jsx(s.AlertDialog,{open:!!x,onOpenChange:()=>m(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 "',x==null?void 0:x.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:T,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 pa({group:t,onManageMembers:n,onDelete:a,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:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function We(t){const[n,a]=w.useState(null),[r,l]=w.useState(null);return w.useEffect(()=>{if(!t||t.trim()===""){a(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 o=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(o,{method:"HEAD"})).ok)throw new Error(`Module not found at ${o}`)}catch{}const d=await import(o);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(i){const o=i instanceof Error?i.message:"Unknown error";console.error("Failed to load remote chart store:",o),l(o),a(null)}})()},[t]),n}function fa(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let c=t.length;if(l!==-1&&(c=l),r!==-1&&r<c&&(c=r),n!==-1){const i=t.substring(0,n),o=t.substring(n);return`${i} {{ filters | where }} AND ${o.substring(6)}`}else if(a!==-1){const i=t.substring(0,a),o=t.substring(a);return`${i} {{ filters | where }} ${o}`}else{const i=t.substring(0,c),o=t.substring(c);return console.log("beforeClause",i),console.log("afterClause",o),o?`${i} {{ filters | where }} ${o}`:`${i.replace(/;$/,"")} {{ filters | where }}`}}function ga(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const c=r.split("__")[0],i=t.find(o=>o.tabTitle===c);return i?i.id:t[0].id}return n}}return t[0].id}async function xs(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],c=r.getQueryData(l);if(c)return console.log("Using cached visual data for:",a),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",a);const i=s.ue.loading("Loading visual...",{position:"top-center"});try{const o=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!o.ok)throw new Error("Failed to load visual");const d=await o.json();return r.setQueryData(l,d),s.ue.dismiss(i),{data:d,fromCache:!1}}catch(o){throw s.ue.dismiss(i),o}}function Ls(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function ja(t,n){var c,i;const a=(t==null?void 0:t.frameObject)??((c=t==null?void 0:t.visual)==null?void 0:c.frameObject);if(!a)return!1;const r=Ls(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(i=r.cards)==null?void 0:i.find(o=>o.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function ba(){var h;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),r=We(((h=a.customCardPreferences)==null?void 0:h.url)||""),l=s.useEditorStore(p=>p.selectedSchemaName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.selectedDatabaseName),o=s.useEditorStore(p=>p.selectedTableName),d=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),x=a.sql;return{getUpdatedFrame:w.useCallback(()=>{var S;let p=x;x&&!x.includes("{{")&&(p=fa(x),t(p));const b=(S=r==null?void 0:r.getState())==null?void 0:S.settings,g={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:c,lastSelectedDatabase:i,lastSelectedTable:o,connectionId:d,sql:p,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},v=n.cards.map(k=>k.id===a.id?g:k);return{...n,cards:v,activeCardId:ga(v,n.activeCardId)}},[a,n,u,l,c,i,o,d,t,r,x])}}function ke(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:c,setCard:i,setIsDevMode:o,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:x,setSelectedConnectionId:m,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:g,setFilterValues:v,setApplyFilters:S}=s.useEditorActions(),{setIsDashboardEditing:k,setIsVisualEditing:O,setSelectedFrameId:M,clearSelectedFrameId:T,addFrame:y,setIsDashboardPanelOpen:f}=s.useDashboardActions(),j=s.useDashboardStore(E=>E.selectedSheetId),N=s.useDashboardStore(E=>E.selectedFrameId),F=s.useDashboardStore(E=>E.dashboard),C=s.useDashboardStore(E=>E.filterValues),P=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),A=w.useCallback(async E=>{try{l(E),T();const{data:L,fromCache:I}=await xs(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",E.id,a);if(!ja(L,{setFrame:c,setCard:i,setIsDevMode:o,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:x,setSelectedConnectionId:m,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:g,setFilterValues:v,setApplyFilters:S,setIsDashboardEditing:k,setIsVisualEditing:O,dashboard:F,selectedSheetId:j,selectedFrameId:N,filterValues:C}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:I}}catch(L){return console.error("Error editing visual:",L),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,c,i,k,O,o,d,u,x,m,h,p,b,g,v,S,T,F,j,N,C]),D=w.useCallback(async E=>{var L;try{if(l(E),!j)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:I,fromCache:B}=await xs(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",E.id,a),z=(I==null?void 0:I.frameObject)??((L=I==null?void 0:I.visual)==null?void 0:L.frameObject);if(!z)return{success:!1,error:"Visual has no frame data"};const K=Ls(z);if(!(K!=null&&K.cards)||K.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const U={...K,id:s.v4(),visualId:E.id};return y(j,U,"end"),k(!0),M(U.id),f(!1),{success:!0,fromCache:B}}catch(I){return console.error("Error adding visual:",I),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,j,y,k,M,f]);return{visual:P.data,isLoading:P.isLoading,isError:P.isError,error:P.error,handleEditLibraryVisual:A,handleAddLibraryVisual:D,getUpdatedFrame:ba().getUpdatedFrame,refetch:P.refetch}}function va({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:c}){const[i,o]=w.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=w.useState(""),[x,m]=w.useState(!a),[h,p]=w.useState(!0);w.useEffect(()=>{t&&(o(a&&r?`Copy of ${r}`:r||""),u(""),m(!a),p(!0))},[t,a,r]);const b=()=>{i.trim()&&(!x&&!h||c({name:i.trim(),description:d.trim()||void 0,saveToLibrary:x,saveToCurrentDashboard:h}))},g=i.trim()&&(x||h);return e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a?"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:i,onChange:v=>o(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:h,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:a?"(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:x,onCheckedChange:v=>m(!!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:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!x&&!h&&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:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!g||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function ya({className:t,variant:n="outline"}){var o;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);We(((o=r.customCardPreferences)==null?void 0:o.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:c}=ke();function i(){const d=c();l==null||l(d)}return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Na({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=w.useState(!1),c=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),{setIsVisualEditing:i}=s.useDashboardActions(),{getUpdatedFrame:o}=ke(),d=s.useSelectedVisual(),u=s.useEditorStore(h=>h.frame),x=s.useUpdateVisualMutation(),m=()=>{const h=o(),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),x.mutate({visualId:p,data:{frameObject:h}},{onSuccess:()=>{l(!1),c(!0),s.ue.success("Visual updated successfully"),a.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:m,className:s.cn("h-8",t),size:"sm",variant:n,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 Ca({className:t}){const n=s.useQueryClient(),[a,r]=w.useState(!1),l=s.useSelectedVisual(),c=s.useEditorStore(h=>h.frame),i=s.useDashboardStore(h=>h.selectedSheetId),{updateFrame:o,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=ke(),x=s.useUpdateVisualMutation(),m=async()=>{if(!i){s.ue.error("No sheet selected");return}const h=(c==null?void 0:c.visualId)||(l==null?void 0:l.id);if(!h){s.ue.error("No visual to update");return}r(!0);try{const p=u();await x.mutateAsync({visualId:h,data:{frameObject:p}});const b={...p,visualId:h};o(i,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",h]}),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:m,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?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 Sa({className:t}){const{getUpdatedFrame:n}=ke();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[c,i]=w.useState(!1),o=()=>{if(!a){s.ue.error("No sheet selected");return}i(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{i(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:o,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[c&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!c&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function wa({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),c=s.useEditorStore(u=>u.onClose),i=s.useEditorStore(u=>u.card),{queryKey:o}=s.useDashboardCardQuery(i);function d(){if(l){const{queryKey:u,queryData:x}=l;u&&x&&r.setQueryData(u,x)}a({}),c==null||c()}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 Ye(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient();s.useEditorStore(g=>g.isDevMode);const a=s.useEditorStore(g=>g.tempQueryData),r=s.useEditorStore(g=>g.card),{queryKey:l}=s.useDashboardCardQuery(r),{setCardSql:c,setSqlGen:i,setCardPython:o,setCardCustomCfg:d,setCardPreferences:u,updateDataSource:x,clearQueryConfig:m,setCardConfig:h,setCardType:p}=s.useEditorActions();function b(){const g=n.getQueryData(l);a!=null&&a.queryData||t({queryKey:l,queryData:g}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),c(""),i({}),m(),h(void 0),o(""),d(""),u({}),p("bar")}return e.jsxs(s.Button,{onClick:b,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(Nt,{className:"mr-2 size-4"}),"Clear"]})}function Da(){const[t,n]=w.useState(!1),[a,r]=w.useState(!1),[l,c]=w.useState(null),i=s.useEditorStore(M=>M.frame),o=s.useEditorStore(M=>M.card),d=s.useSelectedVisual(),u=s.useDashboardStore(M=>M.selectedSheetId),x=s.useDashboardStore(M=>M.actions.setIsDashboardPanelOpen),{getUpdatedFrame:m}=ke(),{selectVisual:h}=s.useManagementActions(),{addFrame:p,setSelectedFrameId:b,setIsVisualEditing:g}=s.useDashboardActions(),v=!!(i!=null&&i.visualId),S=(d==null?void 0:d.title)||(o==null?void 0:o.title)||"Untitled Visual",k=s.useCreateVisualWithFrame(M=>{if(M!=null&&M.id){if(h(M),a&&l&&u){const T={...l,id:s.v4(),visualId:M.id};p(u,T,"end"),b(T.id),r(!1),c(null),g(!1)}x(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async M=>{if(!u){s.ue.error("No sheet selected");return}const T=m();if(M.saveToLibrary){r(M.saveToCurrentDashboard),c(T);const y={title:M.name,description:M.description,frameObject:T,isPrivate:!1};k.mutate(y)}else if(M.saveToCurrentDashboard){const y={...T,id:s.v4(),visualId:void 0,cards:T.cards.map(f=>({...f,title:f.id===o.id?M.name:f.title}))};p(u,y,"end"),b(y.id),s.ue.success("Visual saved to dashboard"),n(!1),g(!1)}},isLibraryVisual:v,currentVisualName:S,isSaving:k.isPending}}function Ps({className:t}){const n=s.useEditorStore(k=>k.frame),a=s.useEditorStore(k=>k.card),r=s.useManagementStore(k=>k.selectedVisual),l=s.useDashboardStore(k=>k.selectedFrameId),c=s.useDashboardStore(k=>k.selectedSheetId),{setIsVisualEditing:i}=s.useDashboardActions(),o=!!(n!=null&&n.visualId||r!=null&&r.id),d=!!(n!=null&&n.visualId&&l),u=o&&!d,{saveAsDialogOpen:x,setSaveAsDialogOpen:m,handleSaveAs:h,isLibraryVisual:p,currentVisualName:b,isSaving:g}=Da(),{handleAddLibraryVisual:v}=ke(),S=async()=>{if(!c){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const k=await v(r);k.success?(s.ue.success("Visual added to dashboard"),i(!1)):s.ue.error(k.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!o&&e.jsx(ya,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[d&&e.jsx(Sa,{className:t}),u&&c&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:S,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(jt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(Na,{className:t,variant:"default"}),d&&e.jsx(Ca,{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:k=>{k.stopPropagation(),m(!0)},children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!o&&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:()=>m(!0),children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(wa,{className:t}),e.jsx(va,{open:x,onOpenChange:k=>{g||m(k)},isLibraryVisual:p,currentVisualName:b,isSaving:g,onConfirm:h})]})}function Os({className:t,switchClassName:n}){const a=s.useEditorStore(o=>o.isDevMode),r=s.useDashboardStore(o=>o.isVisualEditing),{setIsDevMode:l}=s.useEditorActions(),{config:c}=w.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!r||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.DevModeSwitch,{className:s.cn("",n),checked:a,onCheckedChange:()=>l(!a),id:"advanced-mode",icon:e.jsx(s.CodeXml,{className:"h-4 w-4"}),tooltip:a?"Standard Mode":"Advanced Mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:"sr-only",children:"Advanced Mode"})]})}function ka(){var he,xe,le;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:c}=s.useRoleAwareDisplayPreferences(),i=s.useHasDashboardId(),{isLoading:o}=s.useDashboardQuery();s.useDashboardStore(V=>V.theme);const d=s.useDashboardStore(V=>V.lenses),u=s.useDashboardStore(V=>V.selectedLensId),x=d==null?void 0:d.find(V=>V.id===u),m=s.useDashboardStore(V=>V.dashboard);s.useDashboardStore(V=>V.selectedSheetId);const h=s.useDashboardStore(V=>V.isDashboardEditing),{setDashboardTitle:p}=s.useDashboardStore(V=>V.actions),[b,g]=w.useState(!1),[v,S]=w.useState(!1),[k,O]=w.useState(!1),M=s.useDashboardStore(V=>V.isDashboardPanelOpen),T=s.useDashboardStore(V=>V.actions.setIsDashboardPanelOpen),y=s.useDashboardStore(V=>V.filterValues),f=s.useDashboardStore(V=>V.isVisualEditing);s.useEditorStore(V=>V.card);const j=s.useManagementStore(V=>V.selectedDashboard),N=s.useManagementStore(V=>V.initialDashboard);s.useManagementStore(V=>V.selectedVisual),s.useDashboardStore(V=>V.selectedFrameId),s.useEditorStore(V=>V.frame);const F=j?(xe=j==null?void 0:j.permissions)==null?void 0:xe.canEdit:(he=N==null?void 0:N.permissions)==null?void 0:he.canEdit,C=s.useDashboardStore(V=>V.showFilters),P=s.useDashboardStore(V=>V.showDashboardJSON),A=s.useDashboardStore(V=>V.onSaveFunction),D=s.useDashboardStore(V=>V.actions.setShowFilters),{setIsDashboardEditing:E,setShowDashboardJSON:L}=s.useDashboardStore(V=>V.actions),{setInitialDashboard:I,clearSelectedDashboard:B}=s.useManagementStore(V=>V.actions),{resources:z}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:K}=s.useCurrentUserInfo(),U=s.canUserManageGroups(K),R=j||N,_=R?{id:R.id,title:(m==null?void 0:m.title)||R.title||"Dashboard"}:null,{handleAddNewFrame:Z}=s.useAddNewFrame(),[ne,se]=w.useState(!1),ae=s.useUpdateResource(s.ResourceType.DASHBOARD),Y=async(V,ee)=>{if(!(m!=null&&m.id)){console.log("No dashboard ID found");return}console.log("Updating dashboard title:",{dashboardId:m.id,newTitle:V,previousTitle:ee}),ae.mutate({resourceId:m.id,data:{title:V}},{onSuccess:()=>{console.log("Dashboard title updated successfully"),s.ue.success("Dashboard title updated")},onError:X=>{console.error("Failed to update dashboard title:",X),s.ue.error("Failed to update dashboard title"),p(ee)}})};w.useEffect(()=>{if(z&&z.length>0){const V=m==null?void 0:m.id;if(V){const ee=z.find(X=>X.id===V);ee&&I(ee)}}},[z,m==null?void 0:m.id,I]);const $=n.orgUserId||n.tenantId,H=h&&!f&&$&&F,Q=()=>{E(!0)};async function re(){const V=Ve(m);se(!0);const ee={template:V};ae.mutate({resourceId:V.id,data:ee},{onSuccess:()=>{se(!1),s.ue.success("Dashboard saved!")},onError:()=>{se(!1),s.ue.error("Failed to save dashboard")}})}async function ue(){if(g(!0),!u||!x)return;const V=Ve(m),ee=JSON.stringify(V),X={...x,template:ee,filterValues:y};await _e(n.apiServiceUrl,X,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),A==null||A(V),g(!1)}const me=(x==null?void 0:x.name)||m.title;ae.isPending&&console.log("Title during update:",{title:me,dashboardStateTitle:m.title,dashboardId:m==null?void 0:m.id,currentLensName:x==null?void 0:x.name});const W=z&&z.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),te=j&&!(n!=null&&n.dashboard_id)&&!a;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:[W&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{T(!M)},className:"h-7 p-2",children:e.jsx(Ot,{className:"h-4 w-4"})}),te&&!f&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>B(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!f&&i&&(o?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:me||"Untitled Dashboard",onSave:V=>{console.log("EditableText onSave called:",{newTitle:V,canEditDashboard:F,dashboardId:m==null?void 0:m.id});const ee=(m==null?void 0:m.title)||"";p(V),Y(V,ee)},isEditable:F&&!x,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(Os,{className:"mr-2"}),e.jsx(Ps,{className:"h-7"})]}),r&&!f&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(qt,{className:"h-4 w-4"})}),!f&&i&&e.jsx(sa,{}),!f&&i&&e.jsx(Ms,{}),!f&&i&&U&&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&&i&&((le=R==null?void 0:R.permissions)==null?void 0:le.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>S(!0),className:"h-7 p-2",children:e.jsx(s.Share2,{className:"h-4 w-4"})}),!C&&!f&&h&&c.canUseFilters&&i&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>D(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),h&&!f&&$&&r&&i&&e.jsx(Zt,{}),!f&&$&&r&&i&&e.jsx(ea,{}),h&&!f&&$&&x&&r&&i&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:b,onClick:ue,size:"sm",children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!f&&i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>Z(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!f&&!h&&c.canEdit&&i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:Q,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),H&&i&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:ne,onClick:re,size:"sm",children:[ne?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),ne?"Saving...":"Save"]}),!f&&h&&r&&i&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>L(!P),size:"sm",variant:"ghost",children:e.jsx(s.Code,{className:"h-4 w-4"})})}),!f&&r&&e.jsx(Qt,{}),h&&!f&&i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{E(!1),L(!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:()=>S(!1)}),e.jsx(xa,{open:k,onOpenChange:O})]})]})}function Xe(t){const{tokenProps:n,authToken:a}=s.useSemaphorContext(),r=n==null?void 0:n.apiServiceUrl;return s.useQuery({queryKey:["joinability-map",t],queryFn:async()=>{if(!t||!(a!=null&&a.accessToken))return null;const l=`${r}/v1/domains/${t}/joinability`;return s.getRequest(l,a.accessToken)},enabled:!!t&&!!(a!=null&&a.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function Le(t,n,a){if(n==="source")return{isValid:!0};const r=s.getDataType(t.dataType);if(a==="kpi"){if(n==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(n==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function He(t,n,a,r,l){if(t!=="kpi"||l.length<3)return;const c=(n==null?void 0:n.groupByColumns)&&n.groupByColumns.length>0,i=(n==null?void 0:n.comparisonType)==="none";!c&&i||a(r,{groupByColumns:[],comparisonType:"none"})}const Ze=t=>{var A;const n=(A=t==null?void 0:t.dataSource)==null?void 0:A.semanticDomainId,{data:a}=Xe(n),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:c,updatePivotByColumn:i,updateSortByColumn:o,removeGroupByColumn:d,removeMetricColumn:u,removePivotByColumn:x,removeSortByColumn:m}=s.useEditorActions(),h=s.useEditorStore(D=>D.card.type),p=t==null?void 0:t.id,b=w.useCallback(D=>{if(!(t!=null&&t.config))return[];switch(D){case"groupBy":return(t.config.groupByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,dateFormat:E.dateFormat,customFormat:E.customFormat,granularity:E.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(E=>({id:E.id,name:E.name,dataType:E.dataType,label:E.label!==void 0?E.label:E.name,qualifiedEntityName:E.qualifiedEntityName,entityId:E.entityId,entityName:E.entityName,entityType:E.entityType,direction:E.direction}));case"source":return[];default:return[]}},[t]),g=w.useCallback((D,E)=>{if(p)switch(D){case"groupBy":{r(p,{groupByColumns:E});break}case"metrics":{r(p,{metricColumns:E});break}case"pivotBy":{r(p,{pivotByColumns:E});break}case"sortBy":{r(p,{sortByColumns:E});break}}},[p,r]),v=w.useCallback((D,E,L)=>{if(!p)return;const B=b(D)[E];if(B)switch(D){case"groupBy":l(p,B.id,{label:L});break;case"metrics":c(p,B.id,{label:L});break;case"pivotBy":i(p,B.id,{label:L});break;case"sortBy":o(p,B.id,{label:L});break}},[p,b,l,c,i,o]),S=w.useCallback((D,E)=>{if(!p)return;const I=b("metrics")[D];I&&c(p,I.id,{aggregate:E,label:s.getAggregationLabel(I.name,E)})},[p,b,c]),k=w.useCallback((D,E,L)=>{if(!p)return;const B=b("groupBy")[D];if(!B)return;const z={dateFormat:E};E==="custom"&&L?z.customFormat=L:z.customFormat=void 0,l(p,B.id,z)},[p,b,l]),O=w.useCallback((D,E)=>{if(!p)return;const I=b("groupBy")[D];I&&l(p,I.id,{granularity:E})},[p,b,l]),M=w.useCallback((D,E)=>{if(!p)return;const I=b("metrics")[D];I&&c(p,I.id,{aliasTemplate:E})},[p,b,c]),T=w.useCallback((D,E)=>{if(console.log("handleValueAliasesChange",D,E),!p)return;console.log("handleValueAliasesChange",D,E);const I=b("metrics")[D];I&&(console.log("handleValueAliasesChange",E),c(p,I.id,{valueAliases:E}))},[p,b,c]),y=w.useCallback(D=>{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:D})},[p,r,b]),f=w.useCallback(D=>{p&&r(p,{showTrendline:D})},[p,r]),j=w.useCallback(D=>{p&&r(p,{trendlineWindow:D})},[p,r]),N=w.useCallback(D=>{p&&r(p,{trendlineGranularity:D})},[p,r]),F=w.useCallback(D=>{p&&r(p,{targetValue:D})},[p,r]),C=w.useCallback(D=>{var U;if(!p)return;const E=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy")],L=s.validateEntityConsistency(D,E,{joinPlan:(U=t==null?void 0:t.config)==null?void 0:U.joinPlan,joinabilityMap:a==null?void 0:a.joinabilityMap,semanticDomainId:n});if(!L.isValid){L.showError&&s.showJoinRequiredNotification();return}const I=s.getSmartContainerForField(D,E,h);if(!I){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=Le(D,I,h);if(!B.isValid){s.ue.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const z=b(I);if(s.fieldAlreadyExists(D,z))return;const K=s.getNewField(D,I,z);if(K){const R=[...z,K];g(I,R),I==="metrics"&&He(h,t==null?void 0:t.config,r,p,R)}},[p,t==null?void 0:t.config,b,g,n,a,h,r]),P=w.useCallback((D,E)=>{if(!p)return;const I=b(D)[E];if(I){if(D!=="sortBy"){const B=b("sortBy"),z=B.filter(K=>!(K.name===I.name&&K.qualifiedEntityName===I.qualifiedEntityName));z.length!==B.length&&r(p,{sortByColumns:z})}switch(D){case"groupBy":d(p,I.id);break;case"metrics":u(p,I.id);break;case"pivotBy":x(p,I.id);break;case"sortBy":m(p,I.id);break}}},[p,b,d,u,x,m,r]);return{getFieldsForContainer:b,setFieldsForContainer:g,updateLabel:v,handleAggregationChange:S,handleDateFormatChange:k,handleGranularityChange:O,handleAliasTemplateChange:M,handleValueAliasesChange:T,removeField:P,handleFieldClick:C,handleKpiComparisonTypeChange:y,handleKpiShowTrendlineChange:f,handleKpiTrendlineWindowChange:j,handleKpiTrendlineGranularityChange:N,handleKpiTargetValueChange:F,cardType:h}};function Pe(t){return`${t}-${s.v4()}`}function ps(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function Ta(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function es(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 n=t.selectedEntities[0];return{tableName:n==null?void 0:n.name,schemaName:n==null?void 0:n.schema,databaseName:n==null?void 0:n.database,connectionId:t.connectionId,connectionType:t.connectionType}}function Bs(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const n=t.selectedEntities[0];return!!(n!=null&&n.name)}function Vs(){const t=s.useEditorStore(y=>y.sqlGen),n=s.useEditorStore(y=>y.isDevMode),a=s.useEditorStore(y=>y.card.dataSource),r=s.useEditorStore(y=>{var f,j;return(j=(f=y.card)==null?void 0:f.queryConfig)==null?void 0:j.metricColumns}),{tableName:l,schemaName:c,databaseName:i}=es(a),o=Bs(a),d=s.useEditorStore(y=>y.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:x,setCardSql:m,setRunSql:h,setSqlGen:p,setIsShowingVisual:b}=s.useEditorActions(),{connectionType:g,modelItems:v,selectedDatamodelName:S}=s.useEditorAside(),k=y=>({column_name:y.name,data_type:y.dataType,label:y.label,description:y.description});return{handleDevModeFieldClick:y=>{var j;if(!n)return;const f=k(y);if(n&&o&&l){const N=s.createSqlGenConfig(f,t);p(N);const F=(j=v==null?void 0:v.find(P=>P.id===d))==null?void 0:j.name,C=s.getSql(N,s.fmt(c||""),s.fmt(l),F||"",g,i||"");C&&(m(C),h(!0))}else if(!n){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};x(N)}else{const N={...f,role:"metric",id:Pe(f.column_name),name:f.column_name,label:ps(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:Ta(f.column_name,"month"),granularity:"month"};x(N)}if(s.isNumberDataType(f.data_type)){const N={...f,role:"metric",id:Pe(f.column_name),name:f.column_name,label:ps(f.column_name,"SUM"),type:f.data_type,aggregate:"SUM"};u(N)}}},handleShowSample:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const y=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:S,connectionType:g,databaseName:i||""});b(!1);const f=g==="MSSQL"?`SELECT top 10 * FROM ${y}`:`SELECT * FROM ${y} LIMIT 10`;m(f),h(!0)},handleShowCount:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const y=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:S,connectionType:g,databaseName:i||""});m(`SELECT COUNT(*) as count FROM ${y}`),h(!0)},isNumberField:y=>s.isNumberDataType(y.dataType)}}function Rs(){const t=s.useEditorStore(b=>b.selectedConnectionId),n=s.useEditorStore(b=>b.selectedDatamodelId),a=s.useEditorStore(b=>b.selectedDatabaseName),r=s.useEditorStore(b=>b.selectedSchemaName),l=s.useEditorStore(b=>b.selectedTableName),c=s.useDashboardStore(b=>b.dashboard.filters)||[],i=s.useDashboardStore(b=>b.selectedSheetId),o=s.useDashboardStore(b=>b.actions.addFilter),d=s.useDashboardStore(b=>b.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{modelItems:x,tableName:m,connectionType:h}=s.useEditorAside();function p(b,g="sheet",v){var N;const S=s.fmt(b.column_name),k=s.fmt(a||""),O=s.fmt(r||""),M=s.fmt(m);let T=s.getQualifiedTableName({schemaName:O,tableName:M,connectionType:h,databaseName:k}),y=`${T}.${S}`;const f=(N=x==null?void 0:x.find(F=>F.id===n))==null?void 0:N.name;n&&n!=="none"&&(y=`${s.DATAMODEL_NAMESPCACE}.${f}.${S}`,T=`${s.DATAMODEL_NAMESPCACE}.${f}`),v!=null&&v.qualifiedFieldName&&(y=v.qualifiedFieldName),v!=null&&v.entityName&&(T=v.entityName);let j;if(g==="sheet"&&i?j=s.filterExistsInSheet(c,y,M,a||"",k,i):j=c==null?void 0:c.find(F=>F.column===y&&F.table===M&&(F.database===k||F.database===a)),j)u(j.id),d(j.id);else{const F=s.v4(),C=g==="sheet"&&i?[i]:void 0;return m==="api"&&t?(o({location:g,id:F,column:y,title:b.label||b.column_name,dataType:b.data_type,table:"api",database:"",connectionId:t,operation:"in",applyToSheetIds:C,sql:s.getDefaultFilterSql(b.data_type,T,S)}),F):(o({id:F,location:g,column:y,title:b.label||b.column_name,dataType:b.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",applyToSheetIds:C,sql:s.getDefaultFilterSql(b.data_type,T,S)}),F)}}return{assignFilter:p}}function Ea({column:t}){const[n,a]=w.useState(!1),r=s.useEditorStore(S=>S.card.dataSource),{tableName:l,schemaName:c,databaseName:i}=es(r),o=s.useEditorStore(S=>S.selectedDatamodelId),d=s.useEditorStore(S=>S.sqlGen),{modelItems:u,connectionType:x}=s.useEditorAside(),m=s.useEditorStore(S=>S.actions.setSqlGen),h=s.useEditorStore(S=>S.actions.setCardSql),p=s.useEditorStore(S=>S.actions.setRunSql),b=Bs(r);function g(S,k){var y;if(!b||!l){console.warn("Cannot generate SQL: missing table metadata");return}const O=s.createSqlGenConfig(S,d,k),M=(y=u==null?void 0:u.find(f=>f.id===o))==null?void 0:y.name;m(O);const T=s.getSql(O,s.fmt(c||""),s.fmt(l),M||"",x,i||"");T&&(h(T),p(!0)),a(!1)}function v(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(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:n,onOpenChange:a,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 Ia({field:t,fieldState:n}){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}),n&&n.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n.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 Aa({field:t,context:n="editor",fieldState:a}){const r=s.useEditorStore(R=>R.isDevMode),l=n==="filter",c=r||l||(a==null?void 0:a.state)==="unreachable"&&!l,i=s.useDashboardStore(R=>R.dashboard.filters),o=s.useDashboardStore(R=>R.selectedSheetId),d=s.useDashboardStore(R=>R.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{assignFilter:x}=Rs(),m=l?s.getSheetScopedFilters(i,o):i,h=l?m==null?void 0:m.find(R=>{var _;return R.title===t.name||((_=R.column)==null?void 0:_.includes(t.name))}):void 0,p=!!h,b=h&&l?i==null?void 0:i.find(R=>R.id===h.id):void 0,g=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:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:b?{id:b.id,title:b.title,column:b.column,applyToSheetIds:b.applyToSheetIds,excludeSheetIds:b.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:o});const[v,S]=w.useState(!1),[k,O]=w.useState(null),{attributes:M,listeners:T,setNodeRef:y,transform:f,transition:j,isDragging:N}=s.useSortable({id:t.id,disabled:c}),[F,C]=w.useState(!1),P=s.useEditorStore(R=>R.card),{handleFieldClick:A}=Ze(P),{handleDevModeFieldClick:D,isNumberField:E}=Vs(),L=()=>{b&&(console.log("[SourceField] Removing multi-sheet filter:",b.id),u(b.id),d(b.id)),O(null),S(!1)},I=()=>{if(l){const R={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};console.log("[SourceField Click]",{fieldName:t.name,hasActiveFilter:p,isMultiSheetFilter:g,willShowWarning:p&&g}),p&&g?(console.log("[SourceField] Showing warning dialog for multi-sheet filter"),O({column:R,field:t}),S(!0)):(console.log("[SourceField] Calling assignFilter directly (single-sheet or new filter)"),x(R,"sheet",t))}else r?D(t):A(t)},B={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},z={transform:s.CSS.Transform.toString(f),transition:j},U=(()=>{if(!a||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"}}[a.state]||{};return a.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",..._}}[a.state]||_})();return e.jsxs("div",{ref:y,style:z,...c?{}:M,...c?{}:T,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",N&&"scale-95 opacity-50",!N&&"border",U.borderColor||"border-transparent",U.bgColor||"",U.hoverBorderColor,U.hoverBgColor||"hover:bg-muted",U.opacity,U.cursor,p&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!c&&!r&&!l}),title:a==null?void 0:a.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:I,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 ${F?"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(Ia,{field:t,fieldState:a})})]})}),r&&!l&&E(t)&&e.jsx("div",{onClick:R=>R.stopPropagation(),children:e.jsx(Ea,{column:B})})]}),F&&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(Is,{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(_t,{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:S,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:L,children:"Remove Filter"})]})]})})]})}function Fa({context:t="editor"}={}){var F,C,P,A;const[n,a]=w.useState(""),[r,l]=w.useState("all");s.useEditorStore(D=>D.isDevMode);const c=s.useEditorStore(D=>D.card.dataSource),i=s.useEditorStore(D=>D.card.config),o=s.useEditorStore(D=>D.card),{autoJoinMetadata:d}=s.useDashboardCardQuery(o),{columns:u=[],columnGroups:x=[],isLoading:m,error:h}=s.useColumns(),p=(c==null?void 0:c.mode)==="semanticDomain"?c.semanticDomainId:void 0,{data:b}=Xe(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(C=(F=i==null?void 0:i.joinPlan)==null?void 0:F.baseEntity)==null||C.name,(A=(P=d==null?void 0:d.resolvedJoinPlan)==null?void 0:P.baseEntity)==null||A.name,Vs();const v=u.filter(D=>D.name.toLowerCase().includes(n.toLowerCase())||D.dataType.toLowerCase().includes(n.toLowerCase())||D.label&&D.label.toLowerCase().includes(n.toLowerCase())||D.qualifiedEntityName&&D.qualifiedEntityName.toLowerCase().includes(n.toLowerCase())),S=D=>{if(D.dataType==="number"||D.dataType==="integer"||D.dataType==="float"||D.dataType==="decimal"||D.dataType==="currency")return"metrics";const E=s.getDataType(D.dataType);return["date","string","boolean"].includes(E)?"dimensions":E==="number"?"metrics":"dimensions"},O=(r==="all"?v:v.filter(D=>S(D)===r)).reduce((D,E)=>{const L=E.qualifiedEntityName||"Other Fields";return D[L]||(D[L]={label:s.toLabel(E.entityName),fields:[]}),D[L].fields.push(E),D},{}),T=Object.keys(O),y=v.filter(D=>S(D)==="dimensions").length,f=v.filter(D=>S(D)==="metrics").length,j=v.filter(D=>S(D)==="calculated").length,N=v.length>0;return m?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"})}):h?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:h.message||"Failed to load column data"})]}):!c||!c.selectedEntities||c.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:n,onChange:D=>a(D.target.value)}),n&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>a(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:D=>l(D),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:y})]}),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:j})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:T,className:"space-y-2",children:Object.entries(O).map(([D,E])=>{const L=x.find(I=>I.entityName===D)||{entityName:D,label:E.label};return e.jsxs(s.AccordionItem,{value:D,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:L.label||L.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:L.label||L.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:E.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:E.fields.map(I=>{const B=s.calculateFieldState(I,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:d});return e.jsx(Aa,{field:I,context:t,fieldState:B},I.id)})})})]},D)})}),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 zs({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(Fa,{context:t})," "]})}function Ma({initialJoinPlan:t,availableDataSources:n}){const[a,r]=w.useState(t),[l,c]=w.useState(new Set),i=()=>{const y=a.joins.length>0?Math.max(...a.joins.map(j=>j.sequence))+1:1,f={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:y,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,f]}),c(new Set([...l,f.id]))},o=y=>{r({...a,joins:a.joins.filter(f=>f.id!==y)}),c(new Set([...l].filter(f=>f!==y)))},d=(y,f)=>{var P,A,D,E,L;const j=a.joins.find(I=>I.id===y);if(!j)return;const N={...j,...f};if((P=N.source)!=null&&P.name&&((A=N.target)!=null&&A.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 F=a.joins.filter(I=>{var B;return I.id!==y&&I.target.name===((B=N.target)==null?void 0:B.name)});if((D=N.target)!=null&&D.name&&F.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 C=a.joins.map(I=>I.id===y?N:I);if((E=N.source)!=null&&E.name&&((L=N.target)!=null&&L.name)&&N.joinKeyGroups[0].keys.length===0){const I=n.find(U=>{var R;return U.name===((R=N.source)==null?void 0:R.name)}),B=n.find(U=>{var R;return U.name===((R=N.target)==null?void 0:R.name)}),z={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(B==null?void 0:B.name)||"",entityName:(B==null?void 0:B.name)||"",entityType:(B==null?void 0:B.type)||"table"},operator:"="},K=[...N.joinKeyGroups];K[0]={...K[0],keys:[z]},N.joinKeyGroups=K,C[C.findIndex(U=>U.id===y)]=N}r({...a,joins:C})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:i,removeJoin:o,updateJoin:d,moveJoinUp:y=>{const f=a.joins.findIndex(j=>j.id===y);if(f>0){const j=[...a.joins],N={...j[f]},F={...j[f-1]};j[f]=F,j[f-1]=N,j.forEach((P,A)=>{P.sequence=A+1});const C={...a,joins:j};r(C)}},moveJoinDown:y=>{const f=a.joins.findIndex(j=>j.id===y);if(f<a.joins.length-1){const j=[...a.joins],N={...j[f]},F={...j[f+1]};j[f]=F,j[f+1]=N,j.forEach((P,A)=>{P.sequence=A+1});const C={...a,joins:j};r(C)}},toggleJoinExpansion:y=>{const f=new Set(l);f.has(y)?f.delete(y):f.add(y),c(f)},getAvailableSourceEntities:y=>{if(a.joins.length===0)return n;const f=a.joins.findIndex(N=>N.id===y);if(f===0)return n.filter(N=>N.name===a.baseEntity.name);const j=new Set;return a.baseEntity.name&&j.add(a.baseEntity.name),a.joins.slice(0,f).forEach(N=>{j.add(N.source.name),j.add(N.target.name)}),n.filter(N=>j.has(N.name))},getAvailableTargetEntities:y=>n.filter(f=>f.name!==y),addJoinKeyGroup:y=>{const f=a.joins.find(N=>N.id===y);if(!f)return;const j=[...f.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(y,{joinKeyGroups:j})},updateGroupOperator:(y,f,j)=>{const N=a.joins.find(C=>C.id===y);if(!N)return;const F=[...N.joinKeyGroups];F[f]={...F[f],operator:j},d(y,{joinKeyGroups:F})},removeJoinKeyGroup:(y,f)=>{const j=a.joins.find(F=>F.id===y);if(!j)return;const N=[...j.joinKeyGroups];N.splice(f,1),d(y,{joinKeyGroups:N})},addJoinKey:(y,f)=>{const j=a.joins.find(A=>A.id===y);if(!j)return;const N=n.find(A=>A.name===j.source.name),F=n.find(A=>A.name===j.target.name),C=[...j.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:(F==null?void 0:F.name)||"",entityName:(F==null?void 0:F.name)||"",entityType:(F==null?void 0:F.type)||"table"},operator:"="};C[f]={...C[f],keys:[...C[f].keys,P]},d(y,{joinKeyGroups:C})},updateJoinKey:(y,f,j,N,F)=>{const C=a.joins.find(L=>L.id===y);if(!C)return;const P=n.find(L=>L.name===C.source.name),A=n.find(L=>L.name===C.target.name),D=[...C.joinKeyGroups],E=D[f].keys[j];N==="sourceColumnName"&&P?D[f].keys[j]={...E,source:{...E.source,name:F}}:N==="targetColumnName"&&A?D[f].keys[j]={...E,target:{...E.target,name:F}}:N==="operator"&&(D[f].keys[j]={...E,operator:F}),d(y,{joinKeyGroups:D})},removeJoinKey:(y,f,j)=>{const N=a.joins.find(C=>C.id===y);if(!N)return;const F=[...N.joinKeyGroups];F[f].keys.splice(j,1),d(y,{joinKeyGroups:F})},generateSQLPreview:()=>{const y=[...a.joins].sort((N,F)=>N.sequence-F.sequence),f=a.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
|
|
222
|
+
FROM ${f.name}`;return y.forEach(N=>{const F=n.find(A=>A.name===N.target.name);if(!F)return;const C=N.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const D=A.keys.filter(E=>{var L,I,B,z;return((L=E.source)==null?void 0:L.name)&&((I=E.target)==null?void 0:I.name)&&((B=E.source)==null?void 0:B.entityName)&&((z=E.target)==null?void 0:z.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return D.length>1?`(${D.join(` ${A.operator} `)})`:D[0]}).filter(Boolean),P=C.length>1?C.join(" OR "):C[0]||"condition_here";j+=`
|
|
223
|
+
${N.joinType} JOIN ${F.name}
|
|
224
|
+
ON ${P}`}),j},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(N=>!N.source.name||!N.target.name)||a.joins.some(N=>N.joinKeyGroups.some(F=>F.keys.length===0))||a.joins.some(N=>N.joinKeyGroups.some(F=>F.keys.some(C=>!C.source.name||!C.target.name||!C.operator))))}}function La({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:c}=s.useEditorActions();s.useEditorStore(C=>C.card.config);const{columnGroups:i}=s.useColumns(),{joinPlan:o,expandedJoins:d,setJoinPlan:u,addJoin:x,removeJoin:m,updateJoin:h,moveJoinUp:p,moveJoinDown:b,toggleJoinExpansion:g,getAvailableSourceEntities:v,getAvailableTargetEntities:S,addJoinKeyGroup:k,updateGroupOperator:O,removeJoinKeyGroup:M,addJoinKey:T,updateJoinKey:y,removeJoinKey:f,generateSQLPreview:j,isValidConfiguration:N}=Ma({initialJoinPlan:t,availableDataSources:n}),F=C=>{const P=i.find(A=>A.entityName===C);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:o.baseEntity.name,onValueChange:C=>{const P=n.find(A=>A.name===C);u({...o,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:C,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:n.map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:C.type}),C.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},C.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:j()})]}),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 (",o.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),o.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:o.joins.map(C=>{const P=n.find(E=>E.name===C.source.name),A=n.find(E=>E.name===C.target.name),D=d.has(C.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:C.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",C.sequence,P&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",P.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(C.id),disabled:C.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(C.id),disabled:C.sequence===o.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(C.id),children:D?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:()=>m(C.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),D&&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:C.source.name,onValueChange:E=>{const L=n.find(I=>I.name===E);h(C.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(C.id).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name]})},E.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:C.joinType,onValueChange:E=>h(C.id,{joinType:E}),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:C.target.name,onValueChange:E=>{const L=n.find(I=>I.name===E);h(C.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!C.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:C.source.name?S(C.source.name).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name,E.name===C.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},E.name)):[]})]})]})]}),C.source.name&&C.target.name&&P&&A&&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:()=>k(C.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),C.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:C.joinKeyGroups.map((E,L)=>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 ",L+1]}),L>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:E.operator,onValueChange:I=>O(C.id,L,I),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:()=>M(C.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[E.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:E.keys.map((I,B)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[B>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:E.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:I.source.name,onValueChange:z=>y(C.id,L,B,"sourceColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:F(C.source.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:I.operator,onValueChange:z=>y(C.id,L,B,"operator",z),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:I.target.name,onValueChange:z=>y(C.id,L,B,"targetColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:F(C.target.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>f(C.id,L,B),children:e.jsx(s.X,{className:"size-3.5"})})]},I.id||B))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>T(C.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},E.id))})]})]})]},C.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:()=>a(o),disabled:!N(),children:"Save"})]})]})}function Je({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:c,onSave:i,onCancel:o}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,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(La,{joinPlan:r,availableDataSources:l,onSave:i,onCancel:o,onRemove:c})]}),t]})}function Pa({joins:t,baseEntityId:n,availableDataSources:a,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((i,o)=>i.sequence-o.sequence),c=a.find(i=>i.name===n);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:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(i=>{const o=a.find(d=>d.name===i.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:i.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:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name})]})]},i.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,c)=>l.sequence-c.sequence).map((l,c)=>{const i=a.find(d=>d.name===l.source.name),o=a.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:c+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[i==null?void 0:i.name," → ",o==null?void 0:o.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 Oa(){var m,h;const t=s.useEditorStore(p=>p.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(t),a=s.useEditorStore(p=>p.actions.updateCardConfig),r=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[l,c]=w.useState(!1),i=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],o=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),c(!1)},d=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{c(!1)},x=()=>{const p=[...r.joins].sort((v,S)=>v.sequence-S.sequence),b=r.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
|
|
225
|
+
FROM ${b.name}`;return p.forEach(v=>{const S=i.find(M=>M.name===v.target.name);if(!S)return;const k=v.joinKeyGroups.filter(M=>M.keys&&M.keys.length>0).map(M=>{const T=M.keys.filter(y=>{var f,j,N,F;return((f=y.source)==null?void 0:f.name)&&((j=y.target)==null?void 0:j.name)&&((N=y.source)==null?void 0:N.entityName)&&((F=y.target)==null?void 0:F.entityName)}).map(y=>`${y.source.entityName}.${y.source.name} ${y.operator} ${y.target.entityName}.${y.target.name}`);return T.length>1?`(${T.join(` ${M.operator} `)})`:T[0]}).filter(Boolean),O=k.length>1?k.join(" OR "):k[0]||"condition_here";g+=`
|
|
216
226
|
${v.joinType} JOIN ${S.name}
|
|
217
|
-
ON ${P}`}),g};return i.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:()=>c(!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(Ma,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:i,generateSQLPreview:x})})]})}),(n==null?void 0:n.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:n.relationshipsUsed.map((p,b)=>e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p},b))})]})})]})}),e.jsx(He,{open:l,onOpenChange:c,joinPlan:r,availableDataSources:i,onSave:o,onCancel:u,onRemove:d,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(He,{open:l,onOpenChange:c,joinPlan:r,availableDataSources:i,onSave:o,onCancel:u,onRemove:d,children:e.jsxs(s.Button,{onClick:()=>c(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Pa({open:t,onOpenChange:n}){const[a,r]=w.useState([]),{updateDataSource:l}=s.useEditorActions(),c=s.useDashboardStore(g=>g.dashboard.aiContext),i=(c==null?void 0:c.selectedEntities)||[];w.useEffect(()=>{t&&r([])},[t]);const o=g=>{r(v=>v.some(k=>k.name===g.name&&k.type===g.type)?v.filter(k=>!(k.name===g.name&&k.type===g.type)):[...v,g])},d=()=>{r([...i])},u=()=>{r([])},x=()=>{if(a.length===0)return;const g=a[0],v=g.connectionId||"",S=g.connectionType||"",P=a.some(T=>T.type==="dataset")?"semanticDomain":"database";l({connectionId:v,connectionType:S,mode:P,selectedEntities:a}),n(!1)},m=g=>{switch(g.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Kt,{className:"h-4 w-4"});case"model":return e.jsx(yt,{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"})}},h=g=>"label"in g&&g.label?g.label:g.name,p=g=>{if("description"in g&&g.description)return g.description;const v=[];return g.database&&v.push(g.database),g.schema&&v.push(g.schema),g.name&&v.push(g.name),v.join(".")},b=g=>a.some(v=>v.name===g.name&&v.type===g.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,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:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",i.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((g,v)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(g)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(g),onCheckedChange:()=>o(g)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:m(g)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(g)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(g)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:g.type})]},`${g.type}-${g.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:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:x,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function Oa({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),c=l.find(o=>o.label==="Description"),i=l.filter(o=>o.label==="Description"?!1:!["Connection","Database","Schema"].includes(o.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:n||s.getDisplayName(t)}),c&&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:c.value})]}),i.length>0&&e.jsx("div",{className:"space-y-0.5",children:i.map((o,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},d))})]})})}function Ba({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((n,a)=>{const r=s.getEntityDetails(n),l=r.find(i=>i.label==="Description"),c=r.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.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(n)}),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})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((i,o)=>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})]},o))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function zs(){const t=s.useEditorStore(i=>i.card.dataSource),{setSelectedConnectionId:n,setSelectedDatabaseName:a,setSelectedSchemaName:r,setSelectedTableName:l,setSelectedDatamodelId:c}=s.useEditorActions();w.useEffect(()=>{var p;if(!t)return;const{tableName:i,schemaName:o,databaseName:d,connectionId:u}=Xe(t),x=(p=t.selectedEntities)==null?void 0:p[0],h=(x==null?void 0:x.type)==="model"&&"id"in x?x.id:"";n(u||""),a(d||""),r(o||""),l(i||""),c(h)},[t,n,a,r,l,c])}function qs({isVisible:t}){const n=s.useEditorStore(h=>h.isDevMode);zs();const[a,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(!0),d=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),x={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...x,...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:()=>o(!i),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:i?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 ${i?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,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(h),e.jsx("button",{onClick:b=>{b.stopPropagation();const g=m.selectedEntities.filter(v=>!(v.name===h.name&&v.type===h.type));u({...x,...d,selectedEntities:g})},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(Oa,{entity:h})]},`${h.type}-${h.name}-${p}`)),m.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:["+",m.selectedEntities.length-3," more"]})}),e.jsx(Ba,{entities:m.selectedEntities.slice(3)})]})]})}),!n&&e.jsx(La,{})]})]}),e.jsx(Rs,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:m}),e.jsx(Pa,{open:l,onOpenChange:c})]})}function Ze({error:t,errorSql:n,onSendFeedback:a,onOpenInEditor:r,className:l,showFeedbackButton:c=!0,errorTitle:i="Query Error"}){const[o,d]=w.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:i}),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:o,onOpenChange:d,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?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&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(ks,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),c&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),e.jsx(s.Collapsible,{open:o,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:n?"Error SQL Query":"SQL Query"}),n&&e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),n?e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,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:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(g=>g.isDevMode),{setIsDevMode:c,setCardSql:i,setRunSql:o}=s.useEditorActions(),[d,u]=w.useState(!1),x=s.useEditorStore(g=>g.card),m=s.useEditorStore(g=>g.frame),h=s.useDashboardStore(g=>g.selectedSheetId),p=s.useDashboardStore(g=>{var v;return(v=g.dashboard)==null?void 0:v.id});function b(g){c(!0),i(g||t),setTimeout(()=>{o(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!n&&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(ks,{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(Ds,{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:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.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: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:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:h||"N/A"})]}),e.jsx(s.CopyButton,{text:h||"",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:[n&&e.jsx(Ze,{error:n,errorSql:a,showFeedbackButton:!1,onOpenInEditor:()=>b(a)}),!n&&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"})]})})]}),n&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Tt,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Va({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(Ds,{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:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Ra(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 Gs(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(g=>g.theme),r=s.useEditorStore(g=>g.frame),l=s.useEditorStore(g=>g.card),c=s.useEditorStore(g=>g.activeTabCardId),i=s.Le(),{refetch:o}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),x=w.useRef(),m=w.useRef({}),h=r.cards.find(g=>g.id===c),p=w.useCallback(()=>{let g="";return t==="python"&&(g=(h==null?void 0:h.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(g=(h==null?void 0:h.sql)||""),g},[t,h]);w.useEffect(()=>{if(c&&l.id&&l.id!==c){if(x.current&&i){const g=x.current.getModel();g&&(m.current[l.id]=g);let v=m.current[c];if(!v){const S=p();v=i.editor.createModel(S,t),m.current[c]=v}x.current.setModel(v)}d(c,l),u(!0)}},[c,l,d,i,u,t,p]),w.useEffect(()=>{if(!i)return;const g=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=a==="system"?g:a;i.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),i.editor.setTheme("default")},[n,a,i]),w.useEffect(()=>{const g=x.current;g&&i&&l&&g.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return o(),!1})},[i,o,l]);function b(g,v){if(x.current=g,!m.current[l.id]){const S=g.getModel(),k=p();m.current[l.id]=S||(v==null?void 0:v.editor.createModel(k,t))||g.getModel()}g.setModel(m.current[l.id])}return{handleEditorDidMount:b}}function za(){const t=s.useEditorStore(i=>i.card.sql),n=s.useEditorStore(i=>i.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Gs("sql");function c(i){a(i),s.isObjectEmpty(n)||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:c,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function qa(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Gs("python");function r(l){n(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:a})}function $a({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 Ga(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=w.useState(!1),[l,c]=w.useState(!1);s.useEditorStore(R=>R.frame);const i=s.useEditorStore(R=>R.card);s.useEditorStore(R=>R.isShowingVisual),s.useEditorStore(R=>R.selectedConnectionId),s.useEditorStore(R=>R.tempQueryData),s.useEditorStore(R=>R.selectedDatabaseName),s.useEditorStore(R=>R.selectedDatamodelId),s.useEditorStore(R=>R.selectedSchemaName);const o=s.useEditorStore(R=>R.showAIDialog);s.useEditorStore(R=>R.selectedTableName);const d=s.useEditorStore(R=>{var _;return(_=R==null?void 0:R.card)==null?void 0:_.sql}),u=s.useEditorStore(R=>{var _;return(_=R==null?void 0:R.card)==null?void 0:_.python}),{cardFilterValues:x}=s.useCardFilterValues((i==null?void 0:i.id)??""),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:p,setTempQueryData:b,setPythonStdOut:g,setCardPreferences:v,setCardType:S,setCardPython:k,runAssistant:P,setShowAIDialog:M}=s.useEditorActions();s.useEditorStore(R=>R.onSave),s.useEditorStore(R=>R.onClose),s.useEditorStore(R=>R.actions.setSqlGen);const T=s.useEditorStore(R=>R.runSql),y=s.useEditorStore(R=>R.actions.setRunSql),f=s.useEditorStore(R=>R.actions.setIsSqlRunning),{data:j,isLoading:N,isFetching:A,isSuccess:C,isError:O,error:F,errorSql:D,queryKey:E,refetch:L,errorMessage:I}=s.useDashboardCardQuery(i);w.useEffect(()=>{if(j&&(j.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((j==null?void 0:j.output)||""),j.records.length>0)){const{dimensionKeys:R}=s.getKeys(j.records);h(R)}},[j,h,g]),w.useEffect(()=>{(N||A)&&f(!0),(O||C)&&f(!1),O&&(h([]),g(""))},[N,A,j,g,O,C,f,h,F]),w.useEffect(()=>{T&&(t.getQueryData(E)||L(),y(!1))},[T,L,y,E,t]);async function B(){const R=`Can you help me debug this query?
|
|
227
|
+
ON ${O}`}),g};return i.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:()=>c(!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(Pa,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:i,generateSQLPreview:x})})]})}),(n==null?void 0:n.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:n.relationshipsUsed.map((p,b)=>e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:p},b))})]})})]})}),e.jsx(Je,{open:l,onOpenChange:c,joinPlan:r,availableDataSources:i,onSave:o,onCancel:u,onRemove:d,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(Je,{open:l,onOpenChange:c,joinPlan:r,availableDataSources:i,onSave:o,onCancel:u,onRemove:d,children:e.jsxs(s.Button,{onClick:()=>c(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Ba({open:t,onOpenChange:n}){const[a,r]=w.useState([]),{updateDataSource:l}=s.useEditorActions(),c=s.useDashboardStore(g=>g.dashboard.aiContext),i=(c==null?void 0:c.selectedEntities)||[];w.useEffect(()=>{t&&r([])},[t]);const o=g=>{r(v=>v.some(k=>k.name===g.name&&k.type===g.type)?v.filter(k=>!(k.name===g.name&&k.type===g.type)):[...v,g])},d=()=>{r([...i])},u=()=>{r([])},x=()=>{if(a.length===0)return;const g=a[0],v=g.connectionId||"",S=g.connectionType||"",O=a.some(T=>T.type==="dataset")?"semanticDomain":"database";l({connectionId:v,connectionType:S,mode:O,selectedEntities:a}),n(!1)},m=g=>{switch(g.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ht,{className:"h-4 w-4"});case"model":return e.jsx(yt,{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"})}},h=g=>"label"in g&&g.label?g.label:g.name,p=g=>{if("description"in g&&g.description)return g.description;const v=[];return g.database&&v.push(g.database),g.schema&&v.push(g.schema),g.name&&v.push(g.name),v.join(".")},b=g=>a.some(v=>v.name===g.name&&v.type===g.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,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:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,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:a.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",i.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((g,v)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",b(g)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:b(g),onCheckedChange:()=>o(g)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:m(g)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(g)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(g)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:g.type})]},`${g.type}-${g.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:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:x,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function Va({entity:t,title:n,maxDetails:a=10}){const l=s.getEntityDetails(t).slice(0,a),c=l.find(o=>o.label==="Description"),i=l.filter(o=>o.label==="Description"?!1:!["Connection","Database","Schema"].includes(o.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:n||s.getDisplayName(t)}),c&&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:c.value})]}),i.length>0&&e.jsx("div",{className:"space-y-0.5",children:i.map((o,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},d))})]})})}function Ra({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((n,a)=>{const r=s.getEntityDetails(n),l=r.find(i=>i.label==="Description"),c=r.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.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(n)}),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})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((i,o)=>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})]},o))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function qs(){const t=s.useEditorStore(i=>i.card.dataSource),{setSelectedConnectionId:n,setSelectedDatabaseName:a,setSelectedSchemaName:r,setSelectedTableName:l,setSelectedDatamodelId:c}=s.useEditorActions();w.useEffect(()=>{var p;if(!t)return;const{tableName:i,schemaName:o,databaseName:d,connectionId:u}=es(t),x=(p=t.selectedEntities)==null?void 0:p[0],h=(x==null?void 0:x.type)==="model"&&"id"in x?x.id:"";n(u||""),a(d||""),r(o||""),l(i||""),c(h)},[t,n,a,r,l,c])}function $s({isVisible:t}){const n=s.useEditorStore(h=>h.isDevMode);qs();const[a,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(!0),d=s.useEditorStore(h=>h.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),x={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},m={...x,...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:()=>o(!i),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:i?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 ${i?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[m.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.selectedEntities.slice(0,3).map((h,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(h),e.jsx("button",{onClick:b=>{b.stopPropagation();const g=m.selectedEntities.filter(v=>!(v.name===h.name&&v.type===h.type));u({...x,...d,selectedEntities:g})},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(Va,{entity:h})]},`${h.type}-${h.name}-${p}`)),m.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:["+",m.selectedEntities.length-3," more"]})}),e.jsx(Ra,{entities:m.selectedEntities.slice(3)})]})]})}),!n&&e.jsx(Oa,{})]})]}),e.jsx(zs,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:m}),e.jsx(Ba,{open:l,onOpenChange:c})]})}function ss({error:t,errorSql:n,onSendFeedback:a,onOpenInEditor:r,className:l,showFeedbackButton:c=!0,errorTitle:i="Query Error"}){const[o,d]=w.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:i}),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:o,onOpenChange:d,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?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&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Ts,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),c&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),e.jsx(s.Collapsible,{open:o,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:n?"Error SQL Query":"SQL Query"}),n&&e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),n?e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,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 Gs({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(g=>g.isDevMode),{setIsDevMode:c,setCardSql:i,setRunSql:o}=s.useEditorActions(),[d,u]=w.useState(!1),x=s.useEditorStore(g=>g.card),m=s.useEditorStore(g=>g.frame),h=s.useDashboardStore(g=>g.selectedSheetId),p=s.useDashboardStore(g=>{var v;return(v=g.dashboard)==null?void 0:v.id});function b(g){c(!0),i(g||t),setTimeout(()=>{o(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!n&&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(Ts,{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(ks,{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:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.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: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:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:h||"N/A"})]}),e.jsx(s.CopyButton,{text:h||"",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:[n&&e.jsx(ss,{error:n,errorSql:a,showFeedbackButton:!1,onOpenInEditor:()=>b(a)}),!n&&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"})]})})]}),n&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Et,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function za({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(ks,{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(Gs,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function qa(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 Us(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(g=>g.theme),r=s.useEditorStore(g=>g.frame),l=s.useEditorStore(g=>g.card),c=s.useEditorStore(g=>g.activeTabCardId),i=s.Le(),{refetch:o}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),x=w.useRef(),m=w.useRef({}),h=r.cards.find(g=>g.id===c),p=w.useCallback(()=>{let g="";return t==="python"&&(g=(h==null?void 0:h.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(g=(h==null?void 0:h.sql)||""),g},[t,h]);w.useEffect(()=>{if(c&&l.id&&l.id!==c){if(x.current&&i){const g=x.current.getModel();g&&(m.current[l.id]=g);let v=m.current[c];if(!v){const S=p();v=i.editor.createModel(S,t),m.current[c]=v}x.current.setModel(v)}d(c,l),u(!0)}},[c,l,d,i,u,t,p]),w.useEffect(()=>{if(!i)return;const g=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=a==="system"?g:a;i.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),i.editor.setTheme("default")},[n,a,i]),w.useEffect(()=>{const g=x.current;g&&i&&l&&g.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return o(),!1})},[i,o,l]);function b(g,v){if(x.current=g,!m.current[l.id]){const S=g.getModel(),k=p();m.current[l.id]=S||(v==null?void 0:v.editor.createModel(k,t))||g.getModel()}g.setModel(m.current[l.id])}return{handleEditorDidMount:b}}function $a(){const t=s.useEditorStore(i=>i.card.sql),n=s.useEditorStore(i=>i.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Us("sql");function c(i){a(i),s.isObjectEmpty(n)||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:c,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ga(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Us("python");function r(l){n(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:a})}function Ua({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 Ka(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=w.useState(!1),[l,c]=w.useState(!1);s.useEditorStore(R=>R.frame);const i=s.useEditorStore(R=>R.card);s.useEditorStore(R=>R.isShowingVisual),s.useEditorStore(R=>R.selectedConnectionId),s.useEditorStore(R=>R.tempQueryData),s.useEditorStore(R=>R.selectedDatabaseName),s.useEditorStore(R=>R.selectedDatamodelId),s.useEditorStore(R=>R.selectedSchemaName);const o=s.useEditorStore(R=>R.showAIDialog);s.useEditorStore(R=>R.selectedTableName);const d=s.useEditorStore(R=>{var _;return(_=R==null?void 0:R.card)==null?void 0:_.sql}),u=s.useEditorStore(R=>{var _;return(_=R==null?void 0:R.card)==null?void 0:_.python}),{cardFilterValues:x}=s.useCardFilterValues((i==null?void 0:i.id)??""),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:p,setTempQueryData:b,setPythonStdOut:g,setCardPreferences:v,setCardType:S,setCardPython:k,runAssistant:O,setShowAIDialog:M}=s.useEditorActions();s.useEditorStore(R=>R.onSave),s.useEditorStore(R=>R.onClose),s.useEditorStore(R=>R.actions.setSqlGen);const T=s.useEditorStore(R=>R.runSql),y=s.useEditorStore(R=>R.actions.setRunSql),f=s.useEditorStore(R=>R.actions.setIsSqlRunning),{data:j,isLoading:N,isFetching:F,isSuccess:C,isError:P,error:A,errorSql:D,queryKey:E,refetch:L,errorMessage:I}=s.useDashboardCardQuery(i);w.useEffect(()=>{if(j&&(j.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((j==null?void 0:j.output)||""),j.records.length>0)){const{dimensionKeys:R}=s.getKeys(j.records);h(R)}},[j,h,g]),w.useEffect(()=>{(N||F)&&f(!0),(P||C)&&f(!1),P&&(h([]),g(""))},[N,F,j,g,P,C,f,h,A]),w.useEffect(()=>{T&&(t.getQueryData(E)||L(),y(!1))},[T,L,y,E,t]);async function B(){const R=`Can you help me debug this query?
|
|
218
228
|
|
|
219
229
|
Error:
|
|
220
230
|
|
|
@@ -230,6 +240,6 @@ ${v.joinType} JOIN ${S.name}
|
|
|
230
240
|
|
|
231
241
|
${u?`Python:
|
|
232
242
|
${u}`:""}
|
|
233
|
-
`;P(R)}function z(){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($a,{jsonString:JSON.stringify(x,null,2)})})}),x&&x.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>c(!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 K(){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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(za,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&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(qa,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function U(){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:()=>{L()},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(Va,{errorSql:D,sql:j==null?void 0:j.sql,error:I,onDebugWithAssistant:B}),e.jsx(Qe,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:R=>r(R),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Ra,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!o&&e.jsxs("button",{disabled:o,onClick:()=>{M(!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-2 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:[K(),z()]}),U()]})}const Ua=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:Re}];function Ka({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),c=["table","aggregateTable","pivotTable"].includes(n.type),i=s.hasValidCardConfig(n.config);if(!c||!i)return null;const o=d=>{var x;const u=d;if(u==="aggregateTable"&&((x=n.config)!=null&&x.pivotByColumns)&&n.config.pivotByColumns.length>0){const m={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(m),l(m)}else{a(u);const m={...n,type:u};l(m)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:o,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Ua.map(d=>{const u=d.icon,x=n.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",x?"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 _a({card:t}){var P,M,T,y,f,j,N,A,C,O,F;const[n,a]=w.useState(!1),[r,l]=w.useState([]),{authToken:c}=s.useSemaphorContext(),{theme:i}=s.useTheme(),o=s.getTokenParams(c==null?void 0:c.accessToken),d=s.useDashboardStore(D=>D.themeStyle),u={mode:i||"system",colors:((M=(P=d==null?void 0:d.chart)==null?void 0:P.dataset)==null?void 0:M.backgroundColor)||[]};(T=t.customCardPreferences)!=null&&T.inputData;const{getCard:x}=s.useCustomVisual(((y=t.customCardPreferences)==null?void 0:y.url)||""),m=((f=t.customCardPreferences)==null?void 0:f.visualType)||"single",h=s.useEditorStore(D=>D.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),g=w.useCallback((D,E)=>{l(L=>({...L,[D]:E}))},[]);if(!((j=t.customCardPreferences)!=null&&j.componentName))return null;const v=x((N=t.customCardPreferences)==null?void 0:N.componentName);function S(D){a(D)}const k=Object.keys(((A=t.customCardPreferences)==null?void 0:A.dataInputCardIds)||{}).map(D=>{var I,B,z;const E=(B=(I=t.customCardPreferences)==null?void 0:I.dataInputCardIds)==null?void 0:B[D].cardId,L=(z=h==null?void 0:h.cards)==null?void 0:z.find(K=>K.id===E);return L||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(w.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[v&&m==="single"&&e.jsx(v,{editing:!0,params:o,theme:u,settings:(C=t.customCardPreferences)==null?void 0:C.settings,onDataChange:g,data:(b==null?void 0:b.records)||[]}),v&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((O=t.customCardPreferences)==null?void 0:O.dataInputCardIds)||{}).map(D=>{var I,B,z;const E=(B=(I=t.customCardPreferences)==null?void 0:I.dataInputCardIds)==null?void 0:B[D].cardId,L=(z=h==null?void 0:h.cards)==null?void 0:z.find(K=>K.id===E);if(L)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:S,onDataChange:g,dataInputIndex:D,card:L},L.id+D)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(v,{theme:u,onDataChange:g,settings:k.map(D=>{var E;return(E=D==null?void 0:D.customCardPreferences)==null?void 0:E.settings}),data:k.map(D=>D!=null&&D.id?r==null?void 0:r[D.id]:[])})})]})]},(F=t.customCardPreferences)==null?void 0:F.componentName)})}function Ha({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(h=>h.selectedFrameId),l=s.useManagementStore(h=>h.selectedVisual),c=s.useEditorStore(h=>h.frame);let i;if(t)i=t;else if(n!==void 0)i=n?"linked":"library";else if(!!!(c!=null&&c.visualId||l!=null&&l.id)&&r)i="local";else if(l&&!r)i="library";else if(c!=null&&c.visualId&&r)i="linked";else if(l!=null&&l.id&&r)i="library";else return null;if(i==="local")return null;const o={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"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},m={linked:e.jsx(At,{className:"h-3.5 w-3.5"}),library:e.jsx(It,{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",o[i],a),children:m[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:d[i]})]})]})})}function Us({className:t,...n}){var I;const a=s.useEditorStore(B=>B.card),r=((I=a.customCardPreferences)==null?void 0:I.showCardHeader)??!0,l=s.useEditorStore(B=>B.frame),c=s.useDashboardStore(B=>B.dashboard.filters),[i,o]=w.useState(!1),{currentUser:d}=s.useCurrentUserInfo(),{tokenProps:u}=w.useContext(s.SemaphorContext),x=s.useEditorStore(B=>B.actions.setRunSql),{updateFilter:m}=s.useDashboardActions(),h=c==null?void 0:c.find(B=>B.id===l.filterId),{data:p,isLoading:b,isFetching:g,errorMessage:v,errorSql:S,pagination:k}=s.useDashboardCardQuery(a),{setCard:P,updateCardInFrame:M,setIsDevMode:T,setCardSql:y}=s.useEditorActions(),{data:f}=s.useTopoJson(a),j=w.useMemo(()=>{var B;return a.type!=="pivotTable"||!((B=p==null?void 0:p.records)!=null&&B.length)?null:{records:p.records,columnSubtotalMeta:p.columnSubtotalMeta,subtotalColumns:p.subtotalColumns||[],pivotSchema:p.pivotSchema||[],groupByColumns:p.groupByColumns}},[a.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(a,j),A=B=>{T(!0),y(B||S||a.sql||a.python||""),setTimeout(()=>{x(!0)},100)},C=()=>{o(!0)},O=w.useMemo(()=>{const B=typeof window<"u"?window.location.href:"",z=typeof navigator<"u"?navigator.userAgent:"",K=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:d,tokenContext:u,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:c,errorMessage:v||void 0,errorSql:S||a.sql||a.python,generatedSql:S||a.sql},metadata:{url:B,userAgent:z,timestamp:new Date().toISOString(),viewport:K}}},[d,u,a,c,v,S]),F=(B,z)=>{var U,R;const K={...a,paginationConfig:{page:B+1,pageSize:z}};P(K),M(K),a.sql&&((R=(U=a.preferences)==null?void 0:U.tablePrefs)!=null&&R.enableDevModePagination)&&x(!0)},D=w.useMemo(()=>!a.id||!(p!=null&&p.records)?null:s.createChartConfig({card:a,data:p==null?void 0:p.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,p==null?void 0:p.records,a.type,a.customCfg,a.preferences,f]);function E(B){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(_a,{card:B})})}function L(){if(p!=null&&p.records&&(p==null?void 0:p.records.length)===0&&!b&&!g)return v?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(Ze,{error:v,errorSql:S||a.sql||a.python,onOpenInEditor:A,onSendFeedback:C,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||g)&&a.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(!a.id)return null;if(a.type==="custom")return E(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&D)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:b||g?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:D})});if(a.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:a,data:(p==null?void 0:p.records)||[],paginationMetadata:k,onPaginationChange:F,isLoading:b||g})});if(a.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:a,data:N.data,options:N.options,onAggregationChange:B=>{const z=s.handleAggregationChange(B,a.config),K={...a,config:z};P(K),M(K)},onAggregationLabelChange:B=>{const z=s.handleAggregationLabelChange(B,a.config),K={...a,config:z};P(K),M(K)}})});if(a.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:a,data:(p==null?void 0:p.records)||[],groupByColumns:p==null?void 0:p.groupByColumns,pivotSchema:p==null?void 0:p.pivotSchema,paginationMetadata:k,onPaginationChange:F,onAggregationChange:B=>{const z=s.handleAggregationChange(B,a.config),K={...a,config:z};P(K),M(K)},isLoading:b||g})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,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:a.title,onSave:B=>P({...a,title:B}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Ha,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Ka,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:B=>P({...a,description:B}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),h&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:h.title||h.column,onSave:B=>m({...h,title:B}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:h})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:L()}),e.jsx(s.FeedbackDialog,{open:i,onOpenChange:o,feedbackData:O,showDebugInfo:!0})]})}const qe=({language:t,value:n,onChange:a,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:n,onChange:a}),Ja=()=>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."})]})]}),Qa=({customCode:t,cardCustomCfgString:n,mergedConfig:a,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(qe,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{language:"javascript",value:t,onChange:l})})]}),Wa=({error:t,hasCardCustomConfig:n,onReset:a,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:!n,onClick:a,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 Ya(){const[t,n]=w.useState(!1),[a,r]=w.useState(""),[l,c]=w.useState(""),[i,o]=w.useState(""),[d,u]=w.useState(""),x=s.useEditorStore(T=>T.card),m=s.useEditorStore(T=>T.card.customCfg),h=m?JSON.stringify(m,null,2):"",{data:p}=s.useDashboardCardQuery(x),{data:b}=s.useTopoJson(x),{setCardCustomCfg:g,setCustomVisualCode:v}=s.useEditorActions(),S=T=>{var y,f;return JSON.stringify({...T,data:{...T.data,datasets:(f=(y=T.data)==null?void 0:y.datasets)==null?void 0:f.map(j=>({...j,data:[]}))}},null,2)},k=()=>{var y,f;if(!((y=p==null?void 0:p.records)!=null&&y.length))return;const T=s.createChartConfig({card:x,data:p.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:b});if(T){r(S(T)),o(((f=x.preferences)==null?void 0:f.customVisualCode)||"");const j=s.merge(T,m);c(S(j))}},P=()=>{try{if(i&&v(i),l){const T=JSON.parse(l),y=s.getObjectDiff(JSON.parse(a),T);g(y),u("")}}catch{u("Invalid JSON configuration")}},M=Object.keys(m||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:k,className:M?"":"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(Ja,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Us,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Qa,{customCode:i,cardCustomCfgString:h,mergedConfig:l,onConfigChange:T=>c(T??""),onCodeChange:T=>o(T??"")})]}),e.jsx(Wa,{error:d,hasCardCustomConfig:!!m,onReset:()=>{c(a),g(null)},onApply:P,onClose:()=>n(!1)})]})]})}function ze(t){const[n,a]=w.useState(null);return n}function Ks(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:c}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:c}}function _s(){const{data:t,isLoading:n,isError:a}=Ks(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(o=>({queryKey:["manifest",o.value],queryFn:()=>s.loadManifest(o.value),enabled:!!o.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let c=n,i=a;return r.forEach((o,d)=>{var u;if(o.isLoading&&(c=!0),o.isError&&(i=!0),o.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const x=t.plugins[d],m=o.data.visuals.map(h=>({name:h.name,pluginName:x.label,componentType:h.componentType,pluginType:x.type,icon:h.icon,chartType:h.chartType,url:x.value}));l.push(...m)}}),{data:l,isLoading:c,isError:i}}function Xa({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:c,isLoading:i,isError:o}=_s(),d=w.useCallback((u,x)=>{n(null),a({}),r(u),x&&l({type:"component",visualType:"single",url:x.url,componentName:x.name,icon:x.icon}),t==null||t()},[n,a,r,l,t]);return i?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..."})]}):o?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"})]}):!c||c.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:c.map((u,x)=>e.jsx(Za,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${x}`))})]})}const Za=({text:t,icon:n,onClick:a})=>{const r=ze();return e.jsxs("button",{onClick:a,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 en({onChartTypeChange:t,iconClassName:n,searchQuery:a=""}){const{setCardType:r,setCardPreferences:l,setIsDevMode:c}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:o,setQueryConfig:d}=s.useEditorActions();function u(h,p){i(null),l({}),r(h),["custom","text","map"].includes(h)&&(c(!0),d(void 0)),t==null||t()}const m=[{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:"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(h=>h.name.toLowerCase().includes(a.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:m.map(h=>{const p=h.icon;return e.jsxs("button",{onClick:()=>u(h.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",n),strokeWidth:h.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:h.name})]},h.type)})})}function sn({chartType:t,className:n,customIcon:a,componentName:r}){const l=ze();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(s.Type,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Hs({variant:t="ghost"}){var o,d;const[n,a]=w.useState(!1),[r,l]=w.useState(""),c=s.useEditorStore(u=>u.card),i=c.type;return e.jsxs(s.Popover,{open:n,onOpenChange:u=>{a(u),u||l("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(sn,{className:"size-4",chartType:i,customIcon:(o=c.customCardPreferences)==null?void 0:o.icon,componentName:(d=c.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(en,{onChartTypeChange:()=>a(!1),searchQuery:r}),e.jsx(Xa,{onChartTypeChange:()=>a(!1)})]})]})]})}function tn({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,c]=w.useState(!1),i=w.useRef(null),o=w.useRef(!1);function d(){t&&!o.current&&navigator.clipboard.writeText(t)}function u(h){(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),d())}function x(){const h=window.getSelection();if(h&&h.toString().trim()!==""){const p=h.toString();navigator.clipboard.writeText(p),c(!0),o.current=!0,setTimeout(()=>{c(!1),o.current=!1},1e3)}else o.current=!1}function m(){c(!1),o.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 ${n}`,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:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:x,onMouseDown:m,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 an(){const t=s.useEditorStore(c=>{var i,o;return(o=(i=c.card.preferences)==null?void 0:i.chartOptions)==null?void 0:o.indexAxis}),n=s.useEditorStore(c=>c.card.type),{setChartOrientation:a}=s.useEditorStore(c=>c.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(us,{className:"size-4"}):e.jsx(ds,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(us,{className:"size-4"}):e.jsx(ds,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function nn({className:t}){var h,p,b,g,v,S,k,P;const n=s.useEditorStore(M=>M.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[c,i]=w.useState(!1),o=((p=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:p.showFilterInfo)??!0,d=((g=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:g.showCardToolbar)??!0,u=((S=(v=n.preferences)==null?void 0:v.displayOptions)==null?void 0:S.showChrome)??!0,x=((P=(k=n.preferences)==null?void 0:k.displayOptions)==null?void 0:P.allowScroll)??!0,m=(M,T)=>{var j;const y={...n.preferences,displayOptions:{...(j=n.preferences)==null?void 0:j.displayOptions,[M]:T}};a(y);const f={...n,preferences:y};l(f),r(f)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:i,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(Ts,{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:o,onCheckedChange:M=>{m("showFilterInfo",M)},onSelect:M=>M.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:M=>{m("showCardToolbar",M)},onSelect:M=>M.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:M=>{m("showChrome",M)},onSelect:M=>M.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:x,onCheckedChange:M=>{m("allowScroll",M)},onSelect:M=>M.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 Js(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i,o;return(o=(i=c.card)==null?void 0:i.preferences)==null?void 0:o.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const c=["xy","none","x","y"],o=(c.indexOf(a)+1)%c.length;r(c[o])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(an,{})}),!["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:[(a==="xy"||!a)&&e.jsx(Re,{className:"size-4"}),a==="x"&&e.jsx(bt,{className:"size-4"}),a==="y"&&e.jsx(Rt,{className:"size-4"}),a==="none"&&e.jsx(qt,{className:"size-4"})]}),e.jsx(nn,{})]})}function rn(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:c}=s.useEditorActions(),i=(b,g)=>{b.dataTransfer.setData("tabIndex",g.toString())},o=b=>{b.preventDefault()},d=(b,g)=>{const v=b.dataTransfer.getData("tabIndex");if(v===g.toString())return;const S=Array.from(t.cards),[k]=S.splice(parseInt(v),1);S.splice(g,0,k),a({...t,cards:S})};function u(b){const g=t.cards.filter(k=>k.id!==b),v=g[0],S={...t,cards:g,activeCardId:v.id};a(S),r(v.id),l(v)}function x(b,g){const v={...t,cards:[...t.cards,g],activeCardId:b.id};a(v),r(g.id)}function m(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};x(n,b)}function h(b){const g={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"};x(b,g)}function p(b,g){return b.cards.length===1&&(g.displayTab===!0||g.displayTab===void 0)||b.activeCardId!==g.id&&(g.displayTab===!0||g.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=g.displayTab===void 0?!1:!g.displayTab;l({...g,displayTab:v}),c({...g,displayTab:v})},children:g.displayTab===!0||g.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Ct,{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,g)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>i(v,g),onDragOver:o,onDrop:v=>d(v,g),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({...n,tabTitle:v}),c({...n,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(),m()}}),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:()=>h(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Qs(){const t=s.useEditorStore(v=>v.frame),n=s.useEditorStore(v=>v.card),a=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:l,setActiveTabCardId:c,setCard:i,setIsDevMode:o,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:x,isFetching:m,isError:h}=s.useDashboardCardQuery(n);function p(v){const S=t.cards.find(k=>k.id===v);if(S!=null&&S.sql){r||o(!0),c(v);return}if(S!=null&&S.queryConfig){r&&o(!1),b(v),c(v);return}r||b(v),c(v)}function b(v){const S={...t,cards:t.cards.map(P=>P.id===n.id?n:P),activeCardId:v};l(S);const k=S.cards.find(P=>P.id===v);k.sql&&d(!0),i(k)}function g(){return n.type==="kpi"?x||m?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:n,data:u==null?void 0:u.records,isPending:x||m,isError:h})})}):n.type==="text"?x||m?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:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Us,{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:g()},v.id)),e.jsx(rn,{})]})}function ps({children:t}){var y,f;s.useEditorStore(j=>j.frame);const n=s.useEditorStore(j=>j.card),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.isShowingVisual),l=s.useDashboardStore(j=>j.isVisualEditing),c=s.useEditorStore(j=>j.pythonStdOut);s.useEditorStore(j=>j.actions.setRunSql);const{setFrame:i,setCard:o,setActiveTabCardId:d,runAssistant:u,setIsDevMode:x,setCardPreferences:m}=s.useEditorActions(),{data:h,isLoading:p,isFetching:b,errorMessage:g,refetch:v}=s.useDashboardCardQuery(n),[S,k]=w.useState(!1);w.useEffect(()=>{b||k(!1)},[b]);function P(){const j=JSON.stringify(h==null?void 0:h.records,null,2),N=new Blob([j],{type:"application/json"}),A=URL.createObjectURL(N),C=document.createElement("a");C.href=A,C.download=`${n.title}.json`,C.click()}function M(){const N=[Object.keys(h==null?void 0:h.records.reduce((F,D)=>({...F,...D}),{})).join(","),...((h==null?void 0:h.records)||[]).map(F=>Object.values(F).join(","))].join(`
|
|
234
|
-
`),A=new Blob([N],{type:"text/csv"}),C=URL.createObjectURL(A),O=document.createElement("a");O.href=C,O.download=`${n.title}.csv`,O.click()}function T(){const j=`Can you get the documentation for ${n.type} chart?`;u(j)}return n?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(Hs,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:T,children:e.jsx(ft,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(Ya,{})]}),!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:M,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:P,children:e.jsx(St,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.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:()=>{k(!0),v()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":S})})}),e.jsx(Js,{})]}),n.type==="table"&&n.sql&&a&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((f=(y=n.preferences)==null?void 0:y.tablePrefs)==null?void 0:f.enableDevModePagination)??!1,onCheckedChange:j=>{var N;m({...n.preferences,tablePrefs:{...(N=n.preferences)==null?void 0:N.tablePrefs,enableDevModePagination:j}}),v()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(on,{})]}),r?e.jsx(Qs,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[c&&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:c&&e.jsx(ln,{})}),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":c}),children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(h==null?void 0:h.records)||[]}),g&&e.jsx(tn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ln(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=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:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function on(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.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:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ye({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:c,icon:i,showPlaceholderLabel:o=!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",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),o&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function cn(){var g,v;const t=s.useEditorStore(S=>S.card.customCardPreferences),{data:n}=Ks(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(S=>S.card),l=s.useEditorStore(S=>S.frame),c=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:o,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(g=d==null?void 0:d.visuals)==null?void 0:g.find(S=>S.name===(t==null?void 0:t.componentName));function x(S,k){if(!t)return;const M={...(t==null?void 0:t.dataInputCardIds)||{},[S]:{cardId:k,hookRef:null}};i({...t,dataInputCardIds:M})}function m(S){var P,M;const k=(P=l==null?void 0:l.cards)==null?void 0:P.filter(T=>{var y;return((y=T==null?void 0:T.customCardPreferences)==null?void 0:y.visualType)!=="multiple"}).map(T=>({value:T.id,label:T.tabTitle||T.title}));return e.jsx("div",{className:"space-y-2",children:(M=S==null?void 0:S.dataInputs)==null?void 0:M.map((T,y)=>{var f,j;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:T}),e.jsx(ye,{className:"col-span-6 h-8 w-full justify-between",label:"",options:k||[],value:((j=(f=t==null?void 0:t.dataInputCardIds)==null?void 0:f[y])==null?void 0:j.cardId)||"",onValueChange:N=>x(y,N)})]},y+Math.random())})})}function h(S,k,P=[],M=""){var T,y;return t?S==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((T=t==null?void 0:t.settings)==null?void 0:T[k])||M,onChange:f=>{i({...t,settings:{...t==null?void 0:t.settings,[k]:f.target.value}})}},k):S==="select"?e.jsx(ye,{className:"h-8 w-full",label:"",options:P,value:((y=t==null?void 0:t.settings)==null?void 0:y[k])||M,onValueChange:f=>{i({...t,settings:{...t==null?void 0:t.settings,[k]:f}})}}):null:null}function p(S){const k=Object.entries((S==null?void 0:S.settings)||{});return e.jsx("div",{className:"space-y-3",children:k.map(([P,M])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:M.title}),h(M.ui,P,M.options,M.defaultValue)]},P))})}function b(S){t&&i({...t,visualType:S,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(pt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:S=>i({...t||{url:"",componentName:""},url:S})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:c,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:o&&e.jsx(ye,{icon:e.jsx(vt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.filter(S=>S.type===c).map(S=>({value:S.name,label:S.name})))||[],value:t.componentName,onValueChange:S=>{console.log("changing value",S),i({...t,componentName:S})}})})]})})]}),((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:m(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,n]=w.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),c=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),w.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function i(u,x){var m,h;x?a!=null&&a.onClickFilter&&((m=a==null?void 0:a.onClickFilter)==null?void 0:m.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(h=a==null?void 0:a.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==u)}),n(p=>{const b=[...p];return b[u]=!1,b}))}function o(u,x){var h;const m=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===u?{...p,expression:x.target.value}:p);l({...a,onClickFilter:m})}function d(u){var x,m,h,p;if(t!=null&&t[u]||(m=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(b=>b.columnIndex===u))!=null&&m.expression)return e.jsx(s.Input,{value:(p=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(b=>b.columnIndex===u))==null?void 0:p.expression,onChange:b=>o(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:c==null?void 0:c.map((u,x)=>{var m,h;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:!!((m=a==null?void 0:a.onClickFilter)!=null&&m.find(p=>p.columnIndex===x)),onCheckedChange:p=>i(x,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:((h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{n(p=>{const b=[...p];return b[x]=!p[x],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(x)]})},u)})})}function dn({idx:t}){var o;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(o=n==null?void 0:n.chartOptions)==null?void 0:o.indexAxis,c=a==null?void 0:a.find(d=>d.idx===t);function i(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:d!=="none",align:d,anchor:d,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:x}]});else{const m={...c};m.datalabels=x;const h=a==null?void 0:a.map(p=>p.idx===u?m:p);r({...n,datasetOptions:h})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Es,{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:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ft,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Lt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Mt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function un(){const t=s.useEditorStore(c=>c.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!s.METADATA_KEYS.includes(c));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const c=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:i}=s.getKeys(c);l=i.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function es({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Ws(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,x,m;return(m=(x=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:m.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:c,transformedMetricKeys:i,keys:o}=un();return o.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:c.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Ys(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:i.map((d,u)=>e.jsx(Xs,{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 Ys(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Xs({col:t,idx:n,className:a,iconClassName:r,children:l}){const c=s.useEditorStore(x=>{var m;return(m=x.card)==null?void 0:m.preferences}),i=s.useEditorStore(x=>{var m,h;return(h=(m=x.card)==null?void 0:m.preferences)==null?void 0:h.datasetOptions}),o=i==null?void 0:i.find(x=>x.idx===n),{setCardPreferences:d}=s.useEditorStore(x=>x.actions);function u(x){if(!o)d({...c,datasetOptions:[...i||[],{idx:n,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const m={...o};m.type=x==="area"?"line":x,m.fill=x==="area"?"origin":"";const h=i==null?void 0:i.map(p=>p.idx===n?m:p);d({...c,datasetOptions:h})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(es,{className:"max-w-[100px]",title:t,children:Ys(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(dn,{idx:n})]})]})}function Fe(){const t=s.useDashboardStore(o=>o.dashboard.filters),n=s.useEditorStore(o=>o.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Vs();function c(o){const d=l(o,"frame");a({...n,filterId:d})}const i=t==null?void 0:t.find(o=>o.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(mn,{onSelect:c,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function mn({columns:t,onSelect:n}){var i;const[a,r]=Ue.useState(!1),[l,c]=Ue.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(i=t.find(o=>o.column_name===l))==null?void 0:i.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(o=>e.jsxs(s.CommandItem,{value:o.column_name,onSelect:d=>{const u=d===l?"":d;c(u),r(!1),u&&n(o)},children:[o.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===o.column_name?"opacity-100":"opacity-0")})]},o.column_name))})]})]})})]})}function hn({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:n=>n.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(Ws,{})})]}),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(Fe,{})]})]})]})})}function xn({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="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"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:c=>c.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:n(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(Fe,{})]})]})]})})}function Zs(){const t=s.useEditorStore(o=>o.card.type),n=s.useEditorStore(o=>o.isDevMode),a=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:r}=s.useEditorStore(o=>o.actions);function l(o){var x;const d={datalabels:{display:o!=="none",align:o,anchor:o,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(x=a==null?void 0:a.chartOptions)==null?void 0:x.plugins,...d}}};r(u)}function c(){var o,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=(o=a==null?void 0:a.chartOptions)==null?void 0:o.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 i(){var o,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(o=a==null?void 0:a.chartOptions)==null?void 0:o.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:n?c():i()})}const pn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},fn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function gn(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:jn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Zs,{}),e.jsx(Te,{}),e.jsx(Fe,{})]})]})}function jn(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(pn,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(fn,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 bn({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(i,o,d){const u=[...t];u[i]={...u[i],[o]:d},n(u)}function l(i){const o=[...t];o.splice(i,1),n(o)}function c(){n([...t,a])}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:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,o)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(o,"start",d.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:i.end,onChange:d=>r(o,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(o,"color",d.target.value),value:i.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(o),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},o))]})}function vn(){var x,m,h,p,b;const t=s.useEditorStore(g=>g.card.preferences),n=s.useEditorStore(g=>g.actions.setCardPreferences),a=s.useEditorStore(g=>g.card),r=s.hasValidCardConfig(a.config),l=s.useEditorStore(g=>g.actions.setNumberFormat);s.useEditorStore(g=>{var v,S;return(S=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:S.decimalPlaces});const c=s.useEditorStore(g=>{var v,S;return(S=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:S.locale}),i=s.useEditorStore(g=>{var v,S;return(S=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:S.currency});s.useEditorStore(g=>g.actions.setFilterOnClickField);const o=s.useEditorStore(g=>{var v,S;return(S=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:S.colorRanges})||[],d=s.useEditorStore(g=>g.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(g=>g.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:g=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:g}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((m=t==null?void 0:t.formatNumber)==null?void 0:m.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:c||"none",onValueChange:g=>{var v,S,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((S=t==null?void 0:t.formatNumber)==null?void 0:S.currency)||"",g,((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g.locale,children:g.locale},g.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:g=>{var v,S,k;console.log("currency",g),l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,g==="none"?"":g,((S=t==null?void 0:t.formatNumber)==null?void 0:S.locale)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g,children:g},g))]})})]})]})]}),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=(h=t==null?void 0:t.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:p.toString())||"0",onValueChange:g=>{var v,S,k;return l(Number(g),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((S=t==null?void 0:t.formatNumber)==null?void 0:S.locale)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g,children:g},g))})]})]}),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:g=>{var v,S,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((S=t==null?void 0:t.formatNumber)==null?void 0:S.currency)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.locale)||"",g.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(bn,{colorRanges:o,setColorRanges:d})]})]})}function yn(){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(vn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function $e({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,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:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Nn=[{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"}],Cn=["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"],Sn=Cn.map(t=>({label:t,value:t}));function wn(){var d,u,x,m,h,p,b,g,v,S,k,P,M,T,y,f,j,N;const t=s.useEditorStore(A=>A.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=w.useState(((m=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:c}=s.useTopoJson(t),i=Object.keys((c==null?void 0:c.objects)||{}).map(A=>({label:A,value:A}))||[],o=[{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:o,onValueChange:A=>{console.log("value",A),l({...t.preferences,mapVisualOptions:{topoJsonUrl:A}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:A=>{r(A.target.value)},onBlur:()=>{var A;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(A=t.preferences)==null?void 0:A.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),c&&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:i,value:((p=(h=t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:A=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,objectKey:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ye,{className:"h-9",options:Nn,value:((g=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:g.projection)||"",label:"Projection",onValueChange:A=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projection:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ye,{className:"h-9",options:Sn,value:((S=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:S.colorScale)||"",label:"Select Color Scale",onValueChange:A=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.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:((P=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:P.projectionScale)||1,onChange:A=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.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:((y=(T=(M=t.preferences)==null?void 0:M.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:y[0])||0,onChange:A=>{var C,O,F,D;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projectionOffset:[Number(A.target.value),((D=(F=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:F.projectionOffset)==null?void 0:D[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=(j=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:j.projectionOffset)==null?void 0:N[1])||0,onChange:A=>{var C,O,F,D;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projectionOffset:[((D=(F=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:F.projectionOffset)==null?void 0:D[0])||0,Number(A.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Te,{})]})}function Dn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...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:a,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:n,suffix:a="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)} ${a}`}),e.jsx(s.AccordionContent,{children: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 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(Dn,{})})]}),!["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(Fe,{})]})]})]})})}function kn(){const t=s.useEditorStore(r=>{var l,c;return(c=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:c.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){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=>{n(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:[a(),e.jsx(Ws,{})]})]}),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(Fe,{})]})]})]})})}function Tn({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,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(Fe,{})]})]})}),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 et({color:t,onColorChange:n,onClose:a}){const[r,l]=w.useState(0),[c,i]=w.useState(100),[o,d]=w.useState(50),[u,x]=w.useState(t);w.useEffect(()=>{const v=fs(t);if(v){const S=gs(v.r,v.g,v.b);l(S.h),i(S.s),d(S.l),x(t)}},[t]);const m=v=>{l(v),p(v,c,o)},h=v=>{const S=v.currentTarget.getBoundingClientRect(),k=Math.max(0,Math.min(1,(v.clientX-S.left)/S.width)),P=Math.max(0,Math.min(1,(v.clientY-S.top)/S.height)),M=k*100,T=(1-P)*100;i(M),d(T),p(r,M,T)},p=(v,S,k)=>{const P=In(v,S,k),M=En(P.r,P.g,P.b);x(M)},b=v=>{if(x(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const S=fs(v);if(S){const k=gs(S.r,S.g,S.b);l(k.h),i(k.s),d(k.l)}}},g=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};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:h,onMouseMove:v=>{v.buttons===1&&h(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:`${c}%`,top:`${100-o}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>m(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:a,children:"Cancel"}),e.jsx(s.Button,{onClick:g,children:"OK"})]})]})}function fs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function En(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function gs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let c=0,i=0;const o=(r+l)/2;if(r!==l){const d=r-l;switch(i=o>.5?d/(2-r-l):d/(r+l),r){case t:c=((n-a)/d+(n<a?6:0))/6;break;case n:c=((a-t)/d+2)/6;break;case a:c=((t-n)/d+4)/6;break}}return{h:Math.round(c*360),s:Math.round(i*100),l:Math.round(o*100)}}function In(t,n,a){t/=360,n/=100,a/=100;let r,l,c;if(n===0)r=l=c=a;else{const i=(u,x,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?u+(x-u)*6*m:m<.5?x:m<.6666666666666666?u+(x-u)*(.6666666666666666-m)*6:u),o=a<.5?a*(1+n):a+n-a*n,d=2*a-o;r=i(d,o,t+1/3),l=i(d,o,t),c=i(d,o,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(c*255)}}const An=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function st(){var P,M,T,y,f,j,N,A,C,O;const t=s.useEditorStore(F=>F.card),n=s.useEditorStore(F=>{var D;return(D=F.card)==null?void 0:D.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[c,i]=w.useState({}),[o,d]=w.useState(null),[u,x]=w.useState(null),m=w.useMemo(()=>{var L,I,B,z,K,U,R;if(!(l!=null&&l.records)||l.records.length===0)return[];const F=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",D=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",E=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((F||D)&&E){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const _=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&_.add(Z.alias)}),Array.from(_)}if(l.records.length>0){const _=l.records[0],Z=Object.keys(_),ne=new Set;(I=t==null?void 0:t.config)!=null&&I.groupByColumns&&t.config.groupByColumns.forEach(H=>{ne.add(H.label||H.name),ne.add(H.alias||H.name)});const te=new Set;return(B=t==null?void 0:t.config)!=null&&B.metricColumns&&t.config.metricColumns.forEach(H=>{const $=H.alias||H.name;te.add($),te.add(`${$}_count`),te.add(`${$}_sum`),te.add(`${$}_avg`),te.add(`${$}_min`),te.add(`${$}_max`);const ee=H.entityName||H.qualifiedEntityName;ee&&(te.add(`${ee}_${$}`),te.add(`${ee}_${$}_count`))}),Z.filter(H=>!ne.has(H)&&!te.has(H))}}if((D||F)&&!E&&((K=(z=t==null?void 0:t.config)==null?void 0:z.metricColumns)!=null&&K.length))return t.config.metricColumns.map(_=>_.alias||_.label||_.name);if((R=(U=t==null?void 0:t.config)==null?void 0:U.groupByColumns)!=null&&R.length){const _=t.config.groupByColumns[0],Z=_.label||_.name,ne=new Set;return l.records.forEach(te=>{const J=te[Z];J!=null&&ne.add(String(J))}),Array.from(ne)}return[]},[l,(P=t==null?void 0:t.config)==null?void 0:P.groupByColumns,(M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns,(T=t==null?void 0:t.config)==null?void 0:T.metricColumns,t==null?void 0:t.type]),h=w.useMemo(()=>s.getDefaultChartColors(),[]);w.useEffect(()=>{const F={};m.forEach((D,E)=>{F[D]=s.getColorForValue(D,E,n==null?void 0:n.colorConfig)}),i(F)},[m,n==null?void 0:n.colorConfig,h]);const p=(F,D)=>{const E={...c,[F]:D};i(E);const L={...n||{},colorConfig:{segments:E}};a(L);const I={...t,preferences:L};r(I)},b=(F,D)=>{var K;const E=h[D%h.length],{[F]:L,...I}=((K=n==null?void 0:n.colorConfig)==null?void 0:K.segments)||{},B={...n||{},colorConfig:{segments:I}};a(B);const z={...t,preferences:B};r(z),i(U=>({...U,[F]:E}))};if(!m.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(y=t==null?void 0:t.config)==null?void 0:y.groupByColumns)==null?void 0:f.length)||((N=(j=t==null?void 0:t.config)==null?void 0:j.pivotByColumns)==null?void 0:N.length):(C=(A=t==null?void 0:t.config)==null?void 0:A.groupByColumns)==null?void 0:C.length)||["table","kpi","text","custom"].includes(t.type))return null;const S=()=>{const F={...n||{},colorConfig:{segments:{}}};a(F);const D={...t,preferences:F};r(D);const E={};m.forEach((L,I)=>{E[L]=s.getColorForValue(L,I,void 0)}),i(E)},k=Object.keys(((O=n==null?void 0:n.colorConfig)==null?void 0:O.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(Bt,{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:k&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:S,children:[e.jsx(ms,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:m.map((F,D)=>{const E=s.isDefaultColor(c[F],D),L=!E;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:o===F,onOpenChange:I=>d(I?F: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:c[F]}})}),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:h.slice(0,10).map((I,B)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[F]===I?"border-gray-900":"border-transparent"),style:{backgroundColor:I},onClick:()=>{p(F,I),d(null)},children:[B===D%h.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:I})]},`default-${B}`))})]}),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:An.map((I,B)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[F]===I?"border-2 border-gray-900":I==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:I},onClick:()=>{p(F,I),d(null)},children:e.jsx("span",{className:"sr-only",children:I})},`preset-${B}`))})]}),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:()=>{x({value:F,color:c[F]}),d(null)},children:"Custom color"}),!E&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(F,D),d(null)},children:[e.jsx(ms,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:F}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},F)})}),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:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(et,{color:u.color,onColorChange:F=>{p(u.value,F),x(null)},onClose:()=>x(null)})})]})]})})]})}function Ne({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[c,i]=w.useState(t??""),[o,d]=w.useState(!1);w.useEffect(()=>{i(t??"")},[t]);const u=()=>{n(c),d(!1)},x=()=>{i(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:o?c:t??"",onChange:m=>{i(m.target.value),d(!0)},onFocus:()=>d(!0),onClick:m=>m.stopPropagation(),className:"h-8 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&o&&c!==t?u():m.key==="Escape"&&x()},"aria-label":a||"Edit field"}),o&&c!==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:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Fn=["auto","number","currency","percent","scientific","date"],Mn=[{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"}],Ln=[{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"}],Pn=t=>t.charAt(0).toUpperCase()+t.slice(1);function ss({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",c=(o,d)=>{n({...t,[o]:d})},i=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:o=>c("type",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Fn.map(o=>e.jsx(s.SelectItem,{value:o,className:"text-xs",children:o==="auto"?"Auto (Default)":Pn(o)},o))})]})]}),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??i(),onChange:o=>c("decimalPlaces",parseInt(o.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:o=>c("currency",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Mn.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.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:o=>c("useSuffix",o)})]}),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:o=>c("locale",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ln.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.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:o=>c("prefix",o.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:o=>c("suffix",o.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:o=>c("negativeInParentheses",o)})]}),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:o=>c("multiplyBy",o.target.value?parseFloat(o.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:o=>c("dateFormat",o.target.value),className:"h-8 text-xs"})})]})]})]})}function js({axis:t,label:n,type:a,config:r,onChange:l}){var m,h,p,b,g,v,S,k,P,M,T,y;const c=(f,j)=>{l({...r,[f]:j})},i=(f,j)=>{var N,A;l({...r,name:{enabled:f==="enabled"?j:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,text:f==="text"?j:(A=r==null?void 0:r.name)==null?void 0:A.text}})},o=(f,j)=>{var N,A;l({...r,labels:{enabled:f==="enabled"?j:((N=r==null?void 0:r.labels)==null?void 0:N.enabled)??!0,rotation:f==="rotation"?j:(A=r==null?void 0:r.labels)==null?void 0:A.rotation}})},d=(f,j)=>{l({...r,scale:{...r==null?void 0:r.scale,[f]:j===""?"auto":Number(j)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["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:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>c("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:((m=r==null?void 0:r.name)==null?void 0:m.enabled)??!1,onCheckedChange:f=>i("enabled",f)})]}),((h=r==null?void 0:r.name)==null?void 0:h.enabled)&&e.jsx(Ne,{placeholder:`${n} title`,value:((p=r==null?void 0:r.name)==null?void 0:p.text)||"",onSave:f=>i("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=>c("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=>o("enabled",f)})]}),((g=r==null?void 0:r.labels)==null?void 0:g.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=>o("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:x.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),a==="value"&&e.jsx(ss,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>l({...r,formatOptions:f}),showTitle:!0,title:"FORMAT"}),a==="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:((S=r==null?void 0:r.scale)==null?void 0:S.min)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.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:((P=r==null?void 0:r.scale)==null?void 0:P.max)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.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:((T=r==null?void 0:r.scale)==null?void 0:T.stepSize)==="auto"||((y=r==null?void 0:r.scale)==null?void 0:y.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>d("stepSize",f),className:""})})]})]})]})]})]})}function tt(){const t=s.useEditorStore(i=>i.card),n=s.useEditorStore(i=>{var o;return(o=i.card)==null?void 0:o.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const c=(i,o)=>{const u={...n||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:o};a(u);const x={...t,preferences:u};r(x)};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(Ts,{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(js,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:i=>c("x",i)}),l.hasYAxis&&e.jsx(js,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:i=>c("y",i)})]})})]})}function at(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var x,m,h,p;return(p=(h=(m=(x=u.card)==null?void 0:x.preferences)==null?void 0:m.chartOptions)==null?void 0:h.plugins)==null?void 0:p.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",c=!(t.type==="stackedBar"||t.type==="stackedLine"),i=(u,x)=>{const m={...n,[u]:x};a(m)},o=["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(Et,{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:(n==null?void 0:n.display)??c,onCheckedChange:u=>i("display",u)})]}),((n==null?void 0:n.display)??c)&&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:(n==null?void 0:n.position)||r,onValueChange:u=>i("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.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:(n==null?void 0:n.align)||l,onValueChange:u=>i("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 nt(){var j,N,A,C,O,F,D,E,L;const t=s.useEditorStore(I=>I.card),n=s.useEditorStore(I=>{var B,z;return(z=(B=I.card)==null?void 0:B.preferences)==null?void 0:z.dataLabelsConfig}),a=s.useEditorStore(I=>{var B;return(B=I.card)==null?void 0:B.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const c=((j=a==null?void 0:a.chartOptions)==null?void 0:j.indexAxis)==="y",i=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!o,u=(A=(N=a==null?void 0:a.chartOptions)==null?void 0:N.plugins)==null?void 0:A.datalabels,x=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),m=(n==null?void 0:n.enabled)!==void 0?n.enabled:x,h=(I,B)=>{const z={...n,[I]:B},K={...t.preferences||{},dataLabelsConfig:z};r(K);const U={...t,preferences:K};l(U)},p=(I,B)=>{const z={...n,font:{...n==null?void 0:n.font,[I]:B}},K={...t.preferences||{},dataLabelsConfig:z};r(K);const U={...t,preferences:K};l(U)},b=(I,B)=>{const z={...n,formatOptions:{...n==null?void 0:n.formatOptions,[I]:B}},K={...t.preferences||{},dataLabelsConfig:z};r(K);const U={...t,preferences:K};l(U)},v=(()=>{const I=t.type;return I==="stackedBar"||I==="stackedLine"||I==="pie"||I==="doughnut"?"center":c?"right":"top"})();let S=[];i||o?S=["center"]:S=["auto",...(c?["center","left","right"]:["center","top","bottom"]).filter(B=>B!==v),"custom"];const k=()=>s.titleCase(v),P=["center","start","end"],M=["center","start","end","top","bottom"],T=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],y=[{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"}],f=[{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(Gt,{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:m,onCheckedChange:I=>h("enabled",I)})]}),m&&e.jsxs(e.Fragment,{children:[!i&&!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:I=>h("position",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(I=>e.jsx(s.SelectItem,{value:I,className:"text-xs",children:I==="auto"?k():I==="custom"?"Custom (Advanced)":s.titleCase(I)},I))})]})]}),i&&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:(n==null?void 0:n.showTotal)??!1,onCheckedChange:I=>h("showTotal",I)})]}),(n==null?void 0:n.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:(n==null?void 0:n.anchor)||"center",onValueChange:I=>h("anchor",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:P.map(I=>e.jsx(s.SelectItem,{value:I,className:"text-xs",children:s.titleCase(I)},I))})]})]}),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((n==null?void 0:n.align)||"center"),onValueChange:I=>h("align",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:M.map(I=>e.jsx(s.SelectItem,{value:I,className:"text-xs",children:s.titleCase(I)},I))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:I=>h("format",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(I=>e.jsx(s.SelectItem,{value:I,className:"text-xs",children:I==="auto"&&d?"Auto (Use Axis)":I==="none"?"None (Raw Value)":s.titleCase(I)},I))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.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(((C=n==null?void 0:n.formatOptions)==null?void 0:C.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:I=>b("decimalPlaces",Number(I)),className:""})})]}),n.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:((O=n==null?void 0:n.formatOptions)==null?void 0:O.currency)||"USD",onValueChange:I=>b("currency",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(I=>e.jsx(s.SelectItem,{value:I.value,className:"text-xs",children:I.label},I.value))})]})]}),["number","currency"].includes(n.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:((F=n==null?void 0:n.formatOptions)==null?void 0:F.useSuffix)??!1,onCheckedChange:I=>b("useSuffix",I)})]}),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:((D=n==null?void 0:n.formatOptions)==null?void 0:D.locale)||"en-US",onValueChange:I=>b("locale",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(I=>e.jsx(s.SelectItem,{value:I.value,className:"text-xs",children:I.label},I.value))})]})]})]}),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(((E=n==null?void 0:n.font)==null?void 0:E.size)||12),onSave:I=>p("size",Number(I)),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:((L=n==null?void 0:n.font)==null?void 0:L.weight)||"normal",onValueChange:I=>p("weight",I),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:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:I=>{I==="auto"&&h("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((n==null?void 0:n.rotation)||0),onSave:I=>h("rotation",Number(I)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function On(){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:[e.jsx(st,{}),e.jsx(tt,{}),e.jsx(at,{}),e.jsx(nt,{})]})]})}const Bn=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."]})]}),Vn=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."]})]}),Rn=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 zn(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=c=>r.includes(a)?c:e.jsxs(e.Fragment,{children:[c,e.jsx(On,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(kn,{}));case"tornado":case"pyramid":return l(e.jsx(Oe,{docContent:Bn,cardType:a}));case"kpi":return e.jsx(yn,{});case"line":case"bar":return l(e.jsx(hn,{cardType:a}));case"range":return l(e.jsx(Oe,{docContent:Vn,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Oe,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(xn,{cardType:a}));case"table":return e.jsx(Tn,{cardType:a});case"text":return e.jsx(Oe,{docContent:Rn,cardType:a,suffix:"Visual"});case"map":return e.jsx(wn,{});case"custom":return e.jsx(cn,{});default:return l(e.jsx(gn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function qn(){const t=w.useRef(null),n=w.useRef(null),a=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return w.useEffect(()=>{var l,c,i,o;r?((l=t.current)==null||l.resize(0),(c=n.current)==null||c.resize(0)):((i=t.current)==null||i.resize(25),(o=n.current)==null||o.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(Ga,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!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(zn,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(ps,{})})]}):e.jsx(ps,{})})]})}function $n(t){var ae;s.useAIInteractionStore(q=>q.currentAIContext);const[n,a]=w.useState(""),[r,l]=w.useState(null),{authToken:c,tokenProps:i}=s.useSemaphorContext(),o=s.useEditorStore(q=>{var Q;return(Q=q==null?void 0:q.card)==null?void 0:Q.sql}),d=s.useEditorStore(q=>q.isDevMode),u=s.useEditorStore(q=>{var Q;return(Q=q==null?void 0:q.card)==null?void 0:Q.python}),{setCardPython:x,setCardSql:m,setRunSql:h,switchCardType:p,setQueryConfig:b}=s.useEditorActions(),g=s.useEditorStore(q=>q.currentAssitantScope)||[],v=s.useEditorStore(q=>q.userInputForAI),S=s.useEditorStore(q=>q.triggerAIRun),k=s.useEditorStore(q=>q.card),P=s.useEditorStore(q=>q.selectedDatabaseName),M=s.useEditorStore(q=>q.selectedTableName),T=s.useEditorStore(q=>q.selectedConnectionId),y=s.useEditorStore(q=>q.selectedSchemaName),f=s.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:j,refetch:N,data:A}=s.useDashboardCardQuery(k),{setTriggerAIRun:C,setCurrentAssitantScope:O,setCardConfig:F}=s.useEditorActions(),{selectedDatamodelName:D,connectionType:E,selectedDatamodelId:L}=s.useEditorAside(),I=(ae=s.useDashboardQuery().data)==null?void 0:ae.assistantProfileId,{messages:B,setMessages:z,regenerate:K,error:U,sendMessage:R,status:_,addToolResult:Z,stop:ne,clearError:te}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const q=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:I,isDevMode:d,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:q.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:Q})=>({body:{...Q,messages:s.cleanupIncompleteMessages(q)}})}),onError:q=>{var Q;if(q.name==="AbortError"||(Q=q.message)!=null&&Q.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",q)},onToolCall:J,onFinish({isAbort:q,isDisconnect:Q,isError:le}){a(""),console.log(q?"[Editor Assistant] Stream aborted by user":Q?"[Editor Assistant] Stream disconnected (network error)":le?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});w.useEffect(()=>{S&&v&&(R({role:"user",parts:[{type:"text",text:v}]}),C(!1))},[S,v,R,C]);async function J({toolCall:q}){var Q,le,pe,fe,de,V,se,Y,je,ge,be,ve,he,Ee,Se,we;if(["createChartFromSql","createForecast"].includes(q.toolName)){const W=((Q=q.input)==null?void 0:Q.sql)??((le=q.args)==null?void 0:le.sql),re=((pe=q.input)==null?void 0:pe.python)??((fe=q.args)==null?void 0:fe.python),oe=((de=q.input)==null?void 0:de.chartType)??((V=q.args)==null?void 0:V.chartType);p(oe),m(W),x(re),h(!0),Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(q.toolName==="getUserSql"){if(!o){Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:o,python:u||""}})}else if(q.toolName==="generateQueryConfig"){a("Generating query config...");const W=((se=q.input)==null?void 0:se.chartType)??((Y=q.args)==null?void 0:Y.chartType),re=((je=q.input)==null?void 0:je.queryConfig)??((ge=q.args)==null?void 0:ge.queryConfig);((be=q.input)==null?void 0:be.cardConfig)??((ve=q.args)==null||ve.cardConfig),p(W),F(re),m(void 0),x(void 0);const oe=await N();if((he=oe==null?void 0:oe.data)!=null&&he.error){Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:re,message:(Ee=oe==null?void 0:oe.data)==null?void 0:Ee.error.message}});return}if((Se=oe==null?void 0:oe.data)!=null&&Se.records){Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:re,message:"The data has been visualized"}});return}Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:re,message:"The data has been visualized",records:(we=oe==null?void 0:oe.data)==null?void 0:we.records}})}else a("Analyzing...")}function H(q){const Q=s.removeFromScopeArray(g,q);$(Q)}function $(q){const Q=s.sanitizeAIScope(q);O(Q),z(le=>[...le,{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 ee(){const q={databaseName:P||"",schemaName:y||"",tableName:M||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(D),connectionId:T||"",connectionType:E||""},Q=s.dedup([...g,q]);$(Q)}function X(){const q={databaseName:P||"",schemaName:y||"",tableName:M||"",datamodelName:s.resolveDatamodelName(D),connectionId:T||"",connectionType:E||"",datamodelId:L||""};if(!s.isInAiScopeArray([...f||[],...g],q)||g.length===0){const le=s.dedup([...f||[],...g,q]).filter(pe=>pe.connectionId===q.connectionId);$(le)}}const ue=!["ready","error"].includes(_),me=s.getErrorMessage(U);return{messages:B,setMessages:z,sendMessage:R,regenerate:K,isLoading:ue,handleSetAIScope:X,handleAddCurrentTableToScope:ee,removeFromCurrentSelections:H,currentAssitantScope:g,setCurrentAssitantScope:O,stop:ne,status:_,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:me,clearError:te}}const Gn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function bs({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=w.useRef(null),[l,c]=w.useState(!1),[i,o]=w.useState(s.isDevEnv),[d,u]=w.useState(!1),[x,m]=w.useState(!1),[h,p]=w.useState(!1),b=t??h,g=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:S}=s.useQueueActions(),{clearFileAttachments:k}=s.useFileActions(),P=s.useFileAttachments("editor"),M=s.useDashboardStore(W=>W.dashboard.aiContext),T=s.useEditorStore(W=>W.card.dataSource),y=s.useEditorStore(W=>W.actions.setCardSql),f=s.useEditorStore(W=>W.actions.setRunSql),j=s.useEditorStore(W=>W.showAIDialog),N=s.useDashboardStore(W=>W.handleOpenAssistantProfile),{setShowAIDialog:A,setCardPython:C}=s.useEditorActions(),{setDataSource:O}=s.useEditorActions(),{assistantProfile:F}=s.useAssistantProfile(),{messages:D,setMessages:E,sendMessage:L,isLoading:I,stop:B,status:z,llmUsage:K,errorMessage:U,clearError:R}=$n(),[_,Z]=w.useState(""),ne=W=>{Z(W.target.value)},te=W=>{W.preventDefault();const re=_.trim();if(!re&&P.length===0)return;const oe=[];re&&oe.push({type:"text",text:re}),P.forEach(De=>{De.data&&oe.push({type:"file",mediaType:De.type,filename:De.name,url:`data:${De.type};base64,${De.data}`})}),L({role:"user",parts:oe}),Z(""),k("editor"),Q({force:!0})},{visibleMessages:J,hasMoreMessages:H,totalMessageCount:$,loadMoreMessages:ee,resetMessageWindow:X}=s.useMessageWindow(D,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ue,isAtBottom:me,hasNewMessages:ae,newMessageCount:q,scrollToBottom:Q,handleScroll:le,resetNewMessageCount:pe}=s.useAutoScroll(J,{threshold:50,behavior:"smooth",isStreaming:I});w.useEffect(()=>{var W;j&&((W=r.current)==null||W.focus(),v({selectedEntities:(T==null?void 0:T.selectedEntities)||[]}))},[j,T,v]),s.useAutoSubmitQueue({assistantType:"editor",status:z,isLoading:I,sendMessage:L});const{hasActiveTools:fe}=s.useActiveToolStatus(D),de=w.useCallback(W=>{n==null||n(W),t===void 0&&p(W)},[t,n]);w.useEffect(()=>{if(!b)return;function W(re){re.key==="Escape"&&de(!1)}return window.addEventListener("keydown",W),()=>{window.removeEventListener("keydown",W)}},[b,de]);const V=w.useCallback(W=>{L({role:"user",parts:[{type:"text",text:W}]}),Q({force:!0})},[L,Q]),se=w.useCallback(async()=>{const W=JSON.stringify(D??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(W),s.ue.success("Conversation copied")}catch(re){console.error("Failed to copy conversation",re),s.ue.error("Unable to copy conversation")}},[D]),Y=w.useCallback(()=>{de(!b)},[b,de]);function je(W,re){re==="sql"?(y(W),f(!0)):re==="python"&&(C(W),f(!0))}function ge(){g.selectedEntities.length===0&&v({selectedEntities:(M==null?void 0:M.selectedEntities)||[]})}function be(W){ge();const re={role:"user",parts:[{type:"text",text:W.title+" "+W.subtitle}]};L(re)}function ve(W){ge(),L({role:"user",parts:[{type:"text",text:W}]})}function he(){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:c,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:o,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&&(D==null?void 0:D.filter(W=>W.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:(F==null?void 0:F.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[he(),i&&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:Y,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:()=>{E([]),S("editor"),R(),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:ue,className:"mt-2 flex w-full grow basis-0",onScroll:le,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[H&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:ee,className:"text-xs",children:["Load ",Math.min(5,$-J.length)," ","more messages (",$-J.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:J,showTools:i,handleRun:je,showSystemMessage:d,onQuickReply:V,disableQuickReplies:I}),!fe&&e.jsx(s.AssistantStatus,{status:z,errorMessage:U})]})}),!me&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{Q({force:!0}),pe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ae&&q>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:q>9?"9+":q})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Se&&!F&&e.jsx(s.Placeholders,{onClick:be,placeholders:Gn}),e.jsx("div",{children:Se&&F&&e.jsx(s.SeedQuestions,{seedQuestions:F.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:Z,stop:B,input:_,handleInputChange:ne,handleSubmit:W=>{ge(),te(W),Q({force:!0})},isLoading:I,status:z,assistantType:"editor",onFocus:()=>{}})]}),K&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",K.inputTokens," prompt tokens, ",K.outputTokens," ","completion tokens, ",K.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(T==null?void 0:T.selectedEntities)||[],open:x,onOpenChange:m,dataSource:T||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?ht.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})}),a):we}function ts(t,n){const[a,r]=w.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):n});return w.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}const Un="chart-selector-standard-first";function Kn(){const[t,n]=ts(Un,!0);return{standardFirst:t,updatePreference:n}}const vs=({pluginVisual:t,index:n,onSelect:a})=>{const r=ze(t.icon||""),l=t.name.charAt(0).toUpperCase(),c=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,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"}):c||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}-${n}`)},ys=["default","standardPlugin","customPlugin"];function _n({selectedChart:t,onChartChange:n}){var M;const[a,r]=w.useState(!1),{data:l}=_s();Kn();const i=((M=s.useEditorStore(T=>T.card).customCardPreferences)==null?void 0:M.url)||"";Je(i);const{setCardType:o,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(T=>T.actions),{setCardCustomCfg:x,setCustomCardPreferences:m,setQueryConfig:h}=s.useEditorActions(),[p,b]=ts("chart-section-active",null),g=w.useMemo(()=>p?[p,...ys.filter(T=>T!==p)]:ys,[p]);function v(T){x(null),d({}),o(T),["custom","map"].includes(T)&&(u(!0),h(void 0)),n(T),r(!1)}function S(T){x(null),d({}),o("custom"),m({type:"component",visualType:"single",url:T.url,componentName:T.name,icon:T.icon,pluginChartType:T.chartType}),h(void 0),n("custom"),r(!1)}const k=()=>{var y;if(t==="custom"){const f=s.useEditorStore.getState().card;return((y=f==null?void 0:f.customCardPreferences)==null?void 0:y.componentName)||"Custom Visual"}const T=s.chartTypes.find(f=>f.id===t);return(T==null?void 0:T.label)||"Select chart type"},P=()=>{var y,f;if(t==="custom"){const j=s.useEditorStore.getState().card,N=(y=j==null?void 0:j.customCardPreferences)==null?void 0:y.icon,A=(f=j==null?void 0:j.customCardPreferences)==null?void 0:f.componentName;if(N&&A)return e.jsx(Hn,{icon:N,componentName:A});if(A){const C=s.getAutoDetectedChartIcon(A);if(C)return C}return e.jsx(Ae,{className:"h-4 w-4"})}const T=s.chartTypes.find(j=>j.id===t);if(T){const j=T.icon;return e.jsx(j,{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:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[P(),e.jsx("span",{children:k()})]}),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."}),g.map(T=>{if(T==="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:y=>b(y?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(y=>{const f=y.icon;return e.jsx(s.CommandItem,{value:`${y.label} ${y.id} chart graph visualization`,onSelect:()=>v(y.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(f,{className:"h-4 w-4"}),e.jsx("span",{children:y.label})]})},y.id)})},"default");if(T==="standardPlugin"){const y=l.filter(f=>f.pluginType==="standard");return y.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:f=>b(f?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:y.filter(f=>f.componentType==="chart").map((f,j)=>e.jsx(vs,{pluginVisual:f,index:j,onSelect:()=>S(f)},`${f.url}-${f.name}-${j}`))},"standardPlugin"):null}if(T==="customPlugin"){const y=l.filter(f=>f.pluginType==="custom");return y.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:f=>b(f?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:y.map((f,j)=>e.jsx(vs,{pluginVisual:f,index:j,onSelect:()=>S(f)},`${f.url}-${f.name}-${j}`))},"customPlugin"):null}return null})]})]})})]})})}const Hn=({icon:t,componentName:n})=>{const a=ze(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},Jn=[{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"}];function Qn({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(c=>c.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Jn.map(c=>{if(c.requiresPivot&&!r)return null;const i=c.icon,o=t===c.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(c.id),className:s.cn("h-8 w-8 p-0",o&&"bg-accent text-accent-foreground"),children:[e.jsx(i,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:c.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:c.label})})]},c.id)})})}const as=({dataType:t})=>s.getFieldIconComponent(t);function Wn({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=w.useState(t),[l,c]=w.useState(!1),i=(d=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:d[0],o=i?`e.g. Min Sales in {{${i.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:o,value:l?a:t,onChange:u=>{r(u.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),c(!1)):u.key==="Escape"&&(r(t),c(!1))},"aria-label":"Edit alias template"}),l&&a!==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:()=>{n(a),c(!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),c(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Yn({valueAliases:t,onValueAliasesChange:n}){const[a,r]=w.useState(null),[l,c]=w.useState(""),[i,o]=w.useState(""),d=()=>{n({...t,"":""})},u=m=>{const h={...t};delete h[m],n(h)},x=m=>{const h={...t};delete h[m],h[l]=i,n(h),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(([m,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:a===m?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?x(m):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:i,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?x(m):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:()=>x(m),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:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),o(h)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),o(h)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(m),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},m+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 Xn({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,x;return(x=(u=d.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),c=l?r.indexOf(l):-1;function i(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Xs,{idx:c,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function o(){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(Zs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&i(),["pie","doughnut"].includes(n)&&o()]})}function Zn({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),c=s.useEditorStore(u=>u.card),i=c==null?void 0:c.dataSource,o=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:o,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",x);const m=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(b=>{const g=b[h]||b[t.alias||h]||b[t.label];return{id:g||"",value:g||"",label:String(g||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.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 er({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:c}){var P,M;const i=!!l,[o,d]=w.useState(i?"values":"fields"),[u,x]=w.useState(""),[m,h]=w.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=a.filter(T=>{var f;return i?!1:!((f=r==null?void 0:r.conditions)==null?void 0:f.some(j=>j.field.id===T.id))&&T.label.toLowerCase().includes(u.toLowerCase())}),b=T=>{h({...m,field:T}),d("values")},g=()=>{if(m.field&&m.selectedValues.length>0){const T={id:m.id,field:m.field,operator:"in",value:m.selectedValues};let y;if(i){const f=((r==null?void 0:r.conditions)||[]).map(j=>j.id===l.id?T:j);y={...r,conditions:f}}else{const f=(r==null?void 0:r.conditions)||[];y={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...f,T],groups:[]}}c(y),n(!1)}},v=()=>{if(!i||!l)return;const T=((r==null?void 0:r.conditions)||[]).filter(y=>y.id!==l.id);if(T.length>0){const y={...r,conditions:T};c(y)}else c(void 0);n(!1)},S=T=>{h({...m,selectedValues:T})},k=()=>{i&&l?(h({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(h({id:s.v4(),field:null,selectedValues:[]}),d("fields")),x("")};return w.useEffect(()=>{t&&k()},[t,i,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(P=m.field)==null?void 0:P.label}`:o==="fields"?"Select Field to Filter":`Select Values for ${(M=m.field)==null?void 0:M.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&o==="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(T=>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:[T.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(T.value)?`${T.value.length} values`:String(T.value)})]},T.id))})]}),o==="fields"&&!i?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:T=>x(T.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:p.map(T=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(T),children:[e.jsx(as,{dataType:s.getDataType(T.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:T.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[T.entityName,".",T.name]})]})]},T.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&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(sr,{field:m.field,selectedValues:m.selectedValues,onValuesChange:S,onBack:i?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:k,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:g,disabled:!m.field||m.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function sr({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,c]=w.useState(""),{values:i,isLoading:o,isFetching:d}=Zn({field:t,searchQuery:l,limit:500}),u=l?i.filter(h=>String(h.value).toLowerCase().includes(l.toLowerCase())):i,x=h=>{const p=n.includes(h);a(p?n.filter(b=>b!==h):[...n,h])},m=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(h=>h.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:h=>c(h.target.value),className:"pl-10"})]}),o||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:n.length===u.length&&u.length>0,onCheckedChange:m}),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(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(h.value),children:[e.jsx(s.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>x(h.value)}),e.jsx(es,{className:"text-sm",children:h.label})]},h.id))})]})]})}function tr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:c=!1,cardType:i}){var rs,ls,os,is;const{attributes:o,listeners:d,setNodeRef:u,transform:x,transition:m,isDragging:h}=s.useSortable({id:t.id}),p=s.useEditorStore(G=>G.card),{updateLabel:b,handleAggregationChange:g,handleDateFormatChange:v,handleGranularityChange:S,handleAliasTemplateChange:k,handleValueAliasesChange:P,removeField:M,handleKpiComparisonTypeChange:T,handleKpiShowTrendlineChange:y,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:j,handleKpiTargetValueChange:N}=Ye(p),[A,C]=w.useState(!1),[O,F]=w.useState(!1),[D,E]=w.useState(null),[L,I]=w.useState(t.dateFormat||"YYYY-MM-DD"),[B,z]=w.useState(t.customFormat||""),[K,U]=w.useState(!!t.customFormat),[R,_]=w.useState(t.granularity||"day"),[Z,ne]=w.useState(t.aliasTemplate||""),[te,J]=w.useState(t.valueAliases||{}),[H,$]=w.useState((rs=t.parameters)==null?void 0:rs.filters),ee=G=>{G==="custom"?U(!0):(U(!1),I(G),n==="groupBy"&&v(a,G,""))},X=G=>{z(G),n==="groupBy"&&v(a,"custom",G)},ue=G=>{var xe;_(G);const ce=(xe=s.getDateFormatOptionsForGranularity(G)[0])==null?void 0:xe.value;ce&&!K&&(I(ce),n==="groupBy"&&v(a,ce,"")),n==="groupBy"&&S(a,G)},me=G=>{ne(G),n==="metrics"&&k(a,G)},ae=G=>{J(G),n==="metrics"&&P(a,G)},q=G=>{b(n,a,G)},Q=G=>{var ie;if($(G),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:G}},xe=[...((ie=p.config)==null?void 0:ie.metricColumns)||[]];xe[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:xe})}F(!1)},le=()=>{M(n,a)},pe={transform:s.CSS.Transform.toString(x),transition:m},fe=s.getDataType(t.dataType),de=fe==="date",V=i==="kpi",se=s.getDateFormatOptionsForGranularity(R),Y=n!=="pivotBy",je=de&&n==="groupBy"&&(!V||((ls=p.config)==null?void 0:ls.comparisonType)==="start_vs_end"),ge=!V&&de&&n==="groupBy",be=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&de&&n==="groupBy",ve=i==="kpi"&&de&&n==="groupBy",he=i&&i!=="pivotTable"&&n==="metrics"&&((os=p.config)==null?void 0:os.comparisonType)==="target",Ee=n==="metrics",Se=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:G=>{G.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=()=>Y?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:q,placeholder:"Display label...",type:"text"})]}):null,W=()=>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:R,onValueChange:ue,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(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,re=()=>ge?e.jsxs(e.Fragment,{children:[W(),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:K?"custom":L,onValueChange:ee,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(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),K&&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:B,onChange:G=>{G.stopPropagation(),X(G.target.value)},onClick:G=>G.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,oe=()=>{var ce,xe,Ce,Me,cs;const G=be,ie=ve;return!G&&!ie?null:e.jsxs(e.Fragment,{children:[G&&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:((ce=p.config)==null?void 0:ce.comparisonType)||"none",onValueChange:T,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"})]})]})]}),ie&&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:((xe=p.config)==null?void 0:xe.showTrendline)||!1,onCheckedChange:y})]})}),((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:((Me=p.config)==null?void 0:Me.trendlineWindow)||30,onChange:ut=>{const mt=parseInt(ut.target.value)||30;f(mt)},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:((cs=p.config)==null?void 0:cs.trendlineGranularity)||"day",onValueChange:j,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 G,ie;return he?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:((G=p.config)==null?void 0:G.targetValue)!==void 0&&((ie=p.config)==null?void 0:ie.targetValue)!==null?String(p.config.targetValue):"",onSave:ce=>{!isNaN(Number(ce))&&ce!==null?N(Number(ce)):N(0)},placeholder:"Enter target value...",type:"text"})]}):null},it=()=>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:G=>{g(a,G)},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"}),(H==null?void 0:H.conditions)&&H.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:H.conditions.map(G=>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:()=>{E(G),F(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.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(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.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 (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((ie,ce)=>e.jsx("div",{children:String(ie)},ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var xe;ie.stopPropagation();const ce=H.conditions.filter(Ce=>Ce.id!==G.id);if(ce.length>0){const Ce={...H,conditions:ce};Q(Ce)}else if($(void 0),n==="metrics"){const Ce={...t,parameters:{...t.parameters,filters:void 0}},Me=[...((xe=p.config)==null?void 0:xe.metricColumns)||[]];Me[a]=Ce,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Me})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{E(null),F(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Xn,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Wn,{aliasTemplate:Z,onAliasTemplateChange:me}),e.jsx(Yn,{valueAliases:te,onValueAliasesChange:ae})]})]}):null,{columns:ct=[]}=s.useColumns(),dt=(H==null?void 0:H.conditions)&&H.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:pe,...o,...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 ${h?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(as,{dataType:fe}),e.jsx(es,{className:s.cn("w-[140px] flex-1 text-sm",dt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((is=H==null?void 0:H.conditions)==null?void 0:is.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:H.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:H.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:G=>{G.stopPropagation(),C(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ie=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ie),l(ie)},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:G=>{G.stopPropagation(),le()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[Se(),we(),i==="kpi"&&W(),re(),oe(),De(),it()]})]}),O&&e.jsx(er,{open:O,onOpenChange:G=>{F(G),G||E(null)},availableFields:ct,existingFilters:H,editingCondition:D,onSave:G=>{var ie;if(G)Q(G);else if($(void 0),n==="metrics"){const ce={...t,parameters:{...t.parameters,filters:void 0}},xe=[...((ie=p.config)==null?void 0:ie.metricColumns)||[]];xe[a]=ce,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:xe})}E(null)}})]})}function ar({concept:t}){const n=()=>{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:n()})]})})}function Be({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:c=!1,activeField:i=null}){const{isOver:o,setNodeRef:d}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(v=>v.card),m=s.useEditorStore(v=>v.card.type),h=n.length>0,p=w.useMemo(()=>!i||!o?!0:Le(i,t,m).isValid,[i,o,t,m]),b=(v,S)=>{var P;!((P=x.config)!=null&&P.sortByColumns)||x.config.sortByColumns.findIndex(M=>M.id===v)===-1||u(x.id,v,{direction:S})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="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:a}),g&&e.jsx(ar,{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":o&&p,"border-red-500 bg-red-50 dark:bg-red-950":o&&!p,"border-muted-foreground/30 bg-muted/40":!o&&h,"min-h-[60px] border-muted-foreground/20 bg-background":!o&&!h}),children:n.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:n.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((v,S)=>{const P=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(tr,{field:v,zone:t,index:S,sortDirection:P,onSortDirectionChange:M=>b(v.id,M),hasPivotColumns:c,cardType:m})})},v.id)})})})})]})}const Ns=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],nr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Ge({value:t,onChange:n,label:a}){const[r,l]=w.useState(!1),[c,i]=w.useState(!1),o=()=>{const d=Ns.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Ns[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:o()},"aria-label":`Change color for ${a}`})}),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:nr.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",o()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(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:()=>{i(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&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:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(et,{color:o(),onColorChange:d=>{n(d),i(!1)},onClose:()=>i(!1)})})]})]})}const Cs={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%
|
|
235
|
-
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 rr(){var h,p,b,g,v,S,k,P,M,T,y;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((h=t.config)==null?void 0:h.metricColumns)||[],r=((p=t.config)==null?void 0:p.groupByColumns)||[],l=a.length===2&&r.length===0,c=a.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||c)))return null;const o=((g=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:g.metricComparison)||{},d=f=>{var N;const j={...t.preferences,kpiVisualOptions:{...(N=t.preferences)==null?void 0:N.kpiVisualOptions,metricComparison:{...o,...f}}};n(j)},u=c||o.enabled,x=((v=t.config)==null?void 0:v.comparisonType)||"none",m=x==="previous_period"||x==="same_period_last_year"||x==="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(Dt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&a.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:o.enabled||!1,onCheckedChange:f=>d({enabled:f,...f&&!o.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=o.calculationType||"difference",j=Cs[f];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:j==null?void 0:j.label}),e.jsx("p",{children:j==null?void 0:j.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:j==null?void 0:j.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",j==null?void 0:j.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.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(Cs).map(([f,j])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:j.label},f))})]})]}),e.jsx(ss,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>d({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),(m||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:o.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:o.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:o.showColor!==!1,onCheckedChange:f=>d({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Ge,{value:((S=o.colorConfig)==null?void 0:S.increase)||"green",onChange:f=>d({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(Ge,{value:((k=o.colorConfig)==null?void 0:k.decrease)||"red",onChange:f=>d({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(Ge,{value:((P=o.colorConfig)==null?void 0:P.noChange)||"neutral",onChange:f=>d({colorConfig:{...o.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:o.conditionalLabel||!1,onCheckedChange:f=>d({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.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:((M=o.conditionalLabels)==null?void 0:M.increase)??"Increase",onChange:f=>d({conditionalLabels:{...o.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:((T=o.conditionalLabels)==null?void 0:T.decrease)??"Decrease",onChange:f=>d({conditionalLabels:{...o.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:((y=o.conditionalLabels)==null?void 0:y.noChange)??"No change",onChange:f=>d({conditionalLabels:{...o.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:o.labelName??"",onChange:f=>d({labelName:f.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function lr(){var l,c;const t=s.useEditorStore(i=>i.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((c=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:c.formatOptions)||{},r=i=>{var d;const o={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:i}};n(o)};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(ss,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function or({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,activeField:l}){const c=s.useEditorStore(v=>{var S;return((S=v.card.customCardPreferences)==null?void 0:S.url)&&v.card.type==="custom"}),i=s.useEditorStore(v=>v.card),o=i==null?void 0:i.type,d=t.length>0||a.length>0,u=o!=="kpi"||a.length<=2,x=o!=="kpi",m=o!=="kpi"&&d,h=["pie","doughnut","polar","funnel","aggregateTable"].includes(o),p=x&&!h,b=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>o==="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(Be,{zone:"groupBy",fields:t,label:b().label,placeholder:b().placeholder,activeField:l}),p&&e.jsx(Be,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Be,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0,activeField:l}),m&&e.jsx(Be,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&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(lr,{}),e.jsx(rr,{}),e.jsx(st,{}),e.jsx(tt,{}),e.jsx(at,{}),e.jsx(nt,{})]})})]})]})}function ir({onEditJoins:t}){const n=s.useEditorStore(o=>o.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const c=o=>!o||o.length===0?"No conditions":o.map(d=>{var h,p,b,g;const u=`${(h=d.source)==null?void 0:h.entityName}.${(p=d.source)==null?void 0:p.name}`,x=`${(b=d.target)==null?void 0:b.entityName}.${(g=d.target)==null?void 0:g.name}`,m=d.operator||"=";return`${u} ${m} ${x}`}).join(" AND "),i=o=>!o.joinKeyGroups||o.joinKeyGroups.length===0?"No conditions defined":o.joinKeyGroups.length===1?c(o.joinKeyGroups[0].keys):o.joinKeyGroups.map((d,u)=>({id:u,operator:d.operator,condition:c(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(_t,{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((o,d)=>{const u=i(o),x=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:o.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:o.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:o.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(m=>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:m.condition}),m.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",m.operator,")"]})]},m.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})})})]},o.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 Ss={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function cr({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:i}){var f,j;const[o,d]=w.useState(()=>Ss.getItem("chart-selector-expanded")==="true"),[u,x]=w.useState(!1),m=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.actions.updateCardConfig),p=a.length>0||r.length>0||l.length>0,{data:b,autoJoinMetadata:g}=s.useDashboardCardQuery(m),v=((f=m==null?void 0:m.config)==null?void 0:f.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),S=((j=m==null?void 0:m.dataSource)==null?void 0:j.selectedEntities)||[],k=N=>{h(m.id,{...m==null?void 0:m.config,joinPlan:N}),x(!1)},P=()=>{h(m.id,{...m==null?void 0:m.config,joinPlan:void 0}),x(!1)},M=()=>{x(!1)},T=()=>{x(!0)};w.useEffect(()=>{Ss.setItem("chart-selector-expanded",String(o))},[o]);const y=()=>{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":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(_n,{selectedChart:t,onChartChange:n})}),e.jsxs("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center gap-1",children:[e.jsx(Qn,{selectedChart:t,onChartChange:n}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:y,className:"h-8 w-8 p-0","aria-label":o?"Hide all charts":"Show all charts",children:o?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:o?"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(Qe,{})})}),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(ir,{onEditJoins:T}),e.jsx(or,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(He,{open:u,onOpenChange:x,joinPlan:v,availableDataSources:S,onSave:k,onCancel:M,onRemove:P,children:e.jsx("div",{})})]})}function dr({initialFilters:t,availableFields:n}={}){const[a,r]=w.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(T=>T.card.dataSource);const{columns:l,isLoading:c}=s.useColumns(),o=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=T=>{const y=f=>{if(f.id===T){const j=o[0]||d,N=s.getDataType(j.dataType)==="date";return{...f,conditions:[...f.conditions,{id:`condition-${Date.now()}`,field:j,operator:N?"between":"=",value:N?[]:""}]}}return{...f,groups:f.groups.map(y)}};r(y(a))},x=T=>{const y=f=>{if(f.id===T){const j=o[0]||d,N=s.getDataType(j.dataType)==="date";return{...f,groups:[...f.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:j,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...f,groups:f.groups.map(y)}};r(y(a))},m=(T,y)=>{const f=j=>j.id===T?{...j,conditions:j.conditions.filter(N=>N.id!==y)}:{...j,groups:j.groups.map(f)};r(f(a))},h=(T,y)=>{const f=j=>j.id===T?{...j,groups:j.groups.filter(N=>N.id!==y)}:{...j,groups:j.groups.map(f)};r(f(a))},p=(T,y,f,j)=>{if(f==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=A=>A.id===T?{...A,conditions:A.conditions.map(C=>C.id===y?{...C,[f]:j}:C)}:{...A,groups:A.groups.map(N)};r(N(a))},b=(T,y,f)=>{const j=N=>N.id===T?{...N,conditions:N.conditions.map(A=>A.id===y?{...A,...f}:A)}:{...N,groups:N.groups.map(j)};r(j(a))},g=(T,y)=>{const f=j=>j.id===T?{...j,logicalOperator:y}:{...j,groups:j.groups.map(f)};r(f(a))},v=(T,y)=>{const f=j=>j.id===T?{...j,negate:y}:{...j,groups:j.groups.map(f)};r(f(a))},S=(T,y,f)=>{const j=N=>N.id===T?{...N,conditions:s.arrayMove(N.conditions,y,f)}:{...N,groups:N.groups.map(j)};r(j(a))},k=(T,y,f)=>{const j=N=>N.id===T?{...N,groups:s.arrayMove(N.groups,y,f)}:{...N,groups:N.groups.map(j)};r(j(a))},P=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const y=j=>{let N="";typeof j.field=="object"?N=j.field.entityName?`${j.field.entityName}.${j.field.name}`:j.field.name:N=String(j.field);const A=j.operator;let C=j.value;if(j.field.dataType==="string"&&!["in","not in"].includes(j.operator))typeof C=="string"?C=`'${C}'`:Array.isArray(C)&&(C=`'${C.join(", ")}'`);else if(j.field.dataType==="date"||j.field.dataType==="datetime"||j.field.dataType==="timestamp")if(j.operator==="between"&&Array.isArray(C)&&C.length===2){const O=C[0]?`'${C[0]}'`:"NULL",F=C[1]?`'${C[1]}'`:"NULL";return`${N} BETWEEN ${O} AND ${F}`}else if((j.operator==="in"||j.operator==="not in")&&Array.isArray(C)){const O=C.map(F=>F?`'${F}'`:"NULL").join(", ");return`${N} ${A} (${O})`}else typeof C=="string"||C instanceof Date?C=`'${C}'`:Array.isArray(C)&&C.length>0&&(C=`'${C[0]}'`);else if(["in","not in"].includes(j.operator)){let O=[];Array.isArray(C)?O=C.map(F=>typeof F=="string"?`'${F}'`:String(F)):typeof C=="string"?O=C.split(",").map(F=>{const D=F.trim();return j.field.dataType==="string"?`'${D}'`:D}):typeof C=="number"&&(O=[String(C)]),C=`(${O.join(", ")})`}switch(A){case"contains":return typeof C=="string"?`${N} LIKE '%${C.replace(/'/g,"")}'`:`${N} LIKE '%${String(C)}'`;case"startsWith":return typeof C=="string"?`${N} LIKE '${C.replace(/'/g,"")}%'`:`${N} LIKE '${String(C)}%'`;case"endsWith":return typeof C=="string"?`${N} LIKE '%${C.replace(/'/g,"")}'`:`${N} LIKE '%${String(C)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${A} ${C}`}},f=j=>{const N=j.conditions.map(y),A=j.groups.map(D=>f(D)),C=[...N,...A].filter(Boolean);if(C.length===0)return"";const O=C.join(` ${j.logicalOperator} `),F=C.length>1?`(${O})`:O;return j.negate?`NOT ${F}`:F};return f(T)},M=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:o,isLoading:c,addCondition:u,addGroup:x,removeCondition:m,removeGroup:h,updateCondition:p,updateConditionFields:b,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:S,reorderGroups:k,generateSQLPreview:P,hasAnyFilters:M}}function ur({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const mr=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"})}},hr=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function xr({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[c,i]=w.useState(!1),o=w.useMemo(()=>{const d={};return a.forEach(u=>{const x=hr(u);d[x]||(d[x]={}),d[x][u.entityId]||(d[x][u.entityId]=[]),d[x][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(ur,{children:[t.entityName,".",t.name]})}):r,e.jsx(gt,{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(o).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(([x,m])=>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:[mr(m[0].entityType),e.jsx("span",{children:m[0].entityName})]}),m.map((h,p)=>e.jsxs(s.CommandItem,{value:h.id,onSelect:()=>{n(h),i(!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)===h.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:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+p))]},`${d}-${x}`))},d))})]})})]})}function ns(t){var g;const n=s.useEditorStore(v=>v.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(v=>v.card.config),c=l==null?void 0:l.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},o={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...i,role:"sortby",direction:"asc"},u={joinPlan:c,groupByColumns:[i],metricColumns:[o],sortByColumns:[d]},x=((g=n.dataSource)==null?void 0:g.connectionId)||n.connectionId,{data:m,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:n.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:h,error:p}}function pr({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[c,i]=Ue.useState(!1),{filterValues:o}=ns(t),d=x=>{a(n.filter(m=>m!==x))},u=x=>{n.includes(x)?a(n.filter(m=>m!==x)):a([...n,x])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:c,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,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:n.length>0?n.map(x=>{const m=o.find(h=>h.value===x);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.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:h=>{h.key==="Enter"&&d(x)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),d(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):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:o.map((x,m)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+m))})]})]})})]})})}function fr({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:c,isPending:i,error:o}=ns(t);return i?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..."]}):o?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:c.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function gr({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),c=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,i=w.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,n]),o=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),a([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),a([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:o,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const jr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],br=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],vr=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],yr=["=","!=","isNull","isNotNull"],Nr=["between","isNull","isNotNull"],Cr={"=":"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 ws(t){return Cr[t]||s.titleCase(t)}function Sr(t){switch(t){case"string":return br;case"number":return vr;case"boolean":return yr;case"date":return Nr;default:return jr}}function rt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:c,onUpdateGroupOperator:i,availableFields:o,updateConditionFields:d}){const{attributes:u,listeners:x,setNodeRef:m,transform:h,transition:p,isDragging:b}=s.useSortable({id:t.id}),{isPending:g,error:v}=ns(t.field),S={transform:s.CSS.Transform.toString(h),transition:p};return e.jsxs("div",{ref:m,style:S,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,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:k=>i(a,k),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"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(xr,{value:t.field,onValueChange:k=>{const P=k,M=s.getDataType(P.dataType)==="date";d(a,t.id,{field:P,value:"",operator:M?"between":"="})},availableFields:o,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:k=>{k==="in"||k==="not in"?d(a,t.id,{operator:k,value:[]}):k==="isNull"||k==="isNotNull"?d(a,t.id,{operator:k,value:null}):d(a,t.id,{operator:k,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?ws(t.operator):""})}),e.jsx(s.SelectContent,{children:Sr(s.getDataType(t.field.dataType)).map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k,children:ws(k)},k))})]}),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"?g?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(pr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(k=>typeof k=="string")?t.value:[],onChange:k=>d(a,t.id,{value:k}),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:k=>d(a,t.id,{value:k.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(fr,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:k=>d(a,t.id,{value:k}),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:k=>d(a,t.id,{value:k==="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(gr,{value:t.value,operator:t.operator,onChange:k=>d(a,t.id,{value:k}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:k=>l(a,t.id,"value",k.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:()=>c(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function wr({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:c,onUpdateCondition:i,onUpdateField:o,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:x,onAddCondition:m,onAddGroup:h,availableFields:p,renderFilterGroup:b,updateConditionFields:g}){const{attributes:v,listeners:S,setNodeRef:k,transform:P,transition:M,isDragging:T}=s.useSortable({id:t.id}),y={transform:s.CSS.Transform.toString(P),transition:M},f=N=>{const{active:A,over:C}=N;if(C&&A.id!==C.id){const O=t.conditions.findIndex(D=>D.id===A.id),F=t.conditions.findIndex(D=>D.id===C.id);O!==-1&&F!==-1&&u(t.id,O,F)}},j=N=>{const{active:A,over:C}=N;if(C&&A.id!==C.id&&a){const O=t.groups.findIndex(D=>D.id===A.id),F=t.groups.findIndex(D=>D.id===C.id);O!==-1&&F!==-1&&x(a,O,F)}};return e.jsxs("div",{ref:k,style:y,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${T?"z-50 opacity-50":""}`,children:[n>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,...S,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:()=>a&&c(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>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(rt,{condition:N,index:A,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:o,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:g},N.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:j,children:e.jsx(s.SortableContext,{items:t.groups.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(N=>b(N,n+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:()=>m(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:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Dr({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:c,availableFields:i,isLoading:o,addCondition:d,addGroup:u,removeCondition:x,removeGroup:m,updateCondition:h,updateConditionFields:p,updateGroupOperator:b,updateGroupNegate:g,reorderConditions:v,reorderGroups:S,generateSQLPreview:k,hasAnyFilters:P,setCurrentFilters:M}=dr({initialFilters:t,availableFields:n}),T=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[y,f]=w.useState(!1),j=(C,O,F)=>{const D=E=>E.id===C?{...E,conditions:E.conditions.map(L=>L.id===O?{...L,field:F,dataType:F.dataType}:L)}:{...E,groups:E.groups.map(D)};M(D(c))},N=(C,O=0,F)=>O===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:E,over:L}=D;if(L&&E.id!==L.id){const I=C.conditions.findIndex(z=>z.id===E.id),B=C.conditions.findIndex(z=>z.id===L.id);I!==-1&&B!==-1&&v(C.id,I,B)}},children:e.jsx(s.SortableContext,{items:C.conditions.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:C.conditions.map((D,E)=>e.jsx(rt,{condition:D,index:E,groupId:C.id,groupLogicalOperator:C.logicalOperator,onUpdateCondition:h,onUpdateField:j,onRemoveCondition:x,onUpdateGroupOperator:b,availableFields:i,updateConditionFields:p},D.id))})}),e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:E,over:L}=D;if(L&&E.id!==L.id){const I=C.groups.findIndex(z=>z.id===E.id),B=C.groups.findIndex(z=>z.id===L.id);I!==-1&&B!==-1&&S(C.id,I,B)}},children:e.jsx(s.SortableContext,{items:C.groups.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:C.groups.map(D=>N(D,O+1,C.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(C.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),y&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(C.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},C.id):e.jsx(wr,{group:C,depth:O,parentGroupId:F,onUpdateGroupOperator:b,onUpdateGroupNegate:g,onRemoveGroup:m,onUpdateCondition:h,onUpdateField:j,onRemoveCondition:x,onReorderConditions:v,onReorderGroups:S,onAddCondition:d,onAddGroup:u,availableFields:i,renderFilterGroup:N,updateConditionFields:p},C.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:[o?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(c),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:y,onCheckedChange:C=>f(C)}),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)"})]})}),P&&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:k(c)})})]})]})})}),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:()=>a(P?c:null),children:"Apply Filters"})]})]})}function kr({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:c,onOpenChange:i}){const o=u=>{a(t,u),i(!1)},d=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:i,children:[c&&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(Dr,{filters:n,availableFields:l,onSave:o,onCancel:()=>i(!1),onClearAll:d})]})]})}function Tr({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var v,S;const[l,c]=w.useState(null),i=s.useEditorStore(k=>k.card),o=s.useEditorStore(k=>k.actions.updateCardConfig),d=(v=i==null?void 0:i.config)==null?void 0:v.joinPlan,u=(S=i==null?void 0:i.dataSource)==null?void 0:S.semanticDomainId,{data:x}=We(u),m=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],h=w.useCallback(k=>k.startsWith("card-")?null:k.startsWith("source-")||n.find(P=>P.id===k)?"source":a("groupBy").find(P=>P.id===k)?"groupBy":a("metrics").find(P=>P.id===k)?"metrics":a("pivotBy").find(P=>P.id===k)?"pivotBy":a("sortBy").find(P=>P.id===k)?"sortBy":null,[n,a]),p=w.useCallback(k=>{c(k.active.id)},[]),b=w.useCallback(k=>{var N;const{active:P,over:M}=k;if(!M||!t){c(null);return}const T=P.id,y=M.id,f=h(T),j=h(y)||y;if(j==="sortBy"){if(f==="source"){const A=n.find(O=>O.id===T);if(!A){c(null);return}if(!(a("groupBy").some(O=>O.name===A.name&&O.qualifiedEntityName===A.qualifiedEntityName)||a("metrics").some(O=>O.name===A.name&&O.qualifiedEntityName===A.qualifiedEntityName))){c(null);return}}else if(f==="pivotBy"){c(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"){c(null);return}}if(f==="source"&&j==="sortBy"){const A=[...n].find(D=>D.id===T);if(!A){c(null);return}const C=a("sortBy");if(s.fieldAlreadyExists(A,C)){c(null);return}const O=Le(A,"sortBy",i.type);if(!O.isValid){s.ue.error("Invalid Field Type",{description:O.reason,position:"top-center",duration:3e3}),c(null);return}const F=s.getNewField(A,"sortBy",C);c(null),r("sortBy",[...C,F]);return}if(f==="source"&&j!=="source"&&j!=="sortBy"){const A=[...n].find(L=>L.id===T);if(!A){c(null);return}const C=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(C.length>0){const L=C[0].qualifiedEntityName;if(!L){c(null);return}if(L!==A.qualifiedEntityName&&A.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(A,{joinabilityMap:x.joinabilityMap,selectedFields:C,baseEntityName:(N=d==null?void 0:d.baseEntity)==null?void 0:N.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!d){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(L,A.qualifiedEntityName,d)){s.showJoinRequiredNotification(),c(null);return}}}const O=a(j);if(s.fieldAlreadyExists(A,O)){c(null);return}const F=Le(A,j,i.type);if(!F.isValid){s.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),c(null);return}const D=s.getNewField(A,j,O),E=[...O,D];c(null),r(j,E),j==="metrics"&&t&&_e(i.type,i.config,o,t,E);return}if(f&&j&&f!=="source"&&j!=="source"&&f!==j){const A=a(f),C=a(j),O=A.find(I=>I.id===T);if(!O){c(null);return}const F=Le(O,j,i.type);if(!F.isValid){s.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),c(null);return}const D=s.getNewField(O,j,C);if(c(null),j==="sortBy"){s.fieldAlreadyExists(O,C)||r(j,[...C,D]);return}const E=A.filter(I=>I.id!==T),L=[...C,D];r(f,E),r(j,L),j==="metrics"&&t&&_e(i.type,i.config,o,t,L);return}if(f&&j&&f===j&&f!=="source"){const A=a(f),C=A.findIndex(F=>F.id===T),O=A.findIndex(F=>F.id===y);if(C!==O){const F=s.arrayMove(A,C,O);r(f,F)}}c(null)},[t,n,a,r,h,d,u,x,i.type,o,i.config]),g=l?m.find(k=>k.id===l):null;return{activeId:l,activeField:g,handleDragStart:p,handleDragEnd:b}}function Er({activeView:t,onViewChange:n}){const a=s.useEditorStore(i=>i.card),{config:r}=w.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:i=>n(i),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"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&l&&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 Ir=[{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 Ar(){var d,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=w.useState(!1),[l,c]=w.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),n(t.id,parseInt(x))},o=x=>{const m=x.target.value;c(m),m&&!isNaN(parseInt(m))&&n(t.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:o,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:i,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:Ir.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Fr({isOpen:t,onClose:n}){const a=Is(n,{enabled:t}),r=s.useEditorStore(x=>{var m;return((m=x.card.customCardPreferences)==null?void 0:m.url)||""}),l=s.useEditorStore(x=>x.card),c=s.useEditorStore(x=>{var m;return((m=x.card.customCardPreferences)==null?void 0:m.pluginChartType)||""}),i=s.useEditorStore(x=>{var m;return((m=x.card.customCardPreferences)==null?void 0:m.settings)||{}}),{data:o}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=w.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,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:n,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(w.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(o==null?void 0:o.records)||[],chartType:c,settings:i})})})]})})}function Mr({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,activeCard:c,columns:i,columnsLoading:o,columnsError:d}){var Z,ne,te;const u=s.useEditorStore(J=>J.card),x=s.useDashboardStore(J=>J.filterValues),{updateCardConfig:m,setCard:h,updateCardInFrame:p,setShowAIDialog:b}=s.useEditorActions(),g=s.useEditorStore(J=>J.showAIDialog),v=s.useDashboardStore(J=>J.isVisualEditing),[S,k]=w.useState(!1),[P,M]=w.useState(!1),[T,y]=w.useState(null),{config:f}=w.useContext(s.SemaphorContext).tokenProps,j=(f==null?void 0:f.showInfoTab)!==!1,N=s.useEditorStore(J=>{var H;return((H=J.card.customCardPreferences)==null?void 0:H.url)&&J.card.type==="custom"}),{data:A,errorMessage:C,isLoading:O,isFetching:F,errorSql:D,pagination:E,refetch:L,comparisonMetadata:I}=s.useDashboardCardQuery(c),[B,z]=w.useState(!1);w.useEffect(()=>{F||z(!1)},[F]);const K=(J,H)=>{const $={...c,paginationConfig:{page:J+1,pageSize:H}};h($),p($)};function U(){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(x||{},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(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:o?"Loading...":d?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const R=J=>{if(!u.config)return;if(!J.length){m(u.id,{...u.config,sortByColumns:[]});return}const H=u.config,$=J.map(({id:ee,desc:X})=>{var q,Q;const ue=(q=H.metricColumns)==null?void 0:q.find(le=>le.label===ee),me=(Q=H.groupByColumns)==null?void 0:Q.find(le=>le.label===ee),ae=ue||me;return ae?{id:s.getFieldId("sortBy",ae),name:ae.name,dataType:ae.dataType,label:ae.label,qualifiedEntityName:ae.qualifiedEntityName,entityId:ae.entityId,entityName:ae.entityName,entityType:ae.entityType,role:"sortby",direction:X?"desc":"asc"}:null}).filter(ee=>ee!==null);m(u.id,{...H,sortByColumns:$})},_=w.useMemo(()=>{var J,H;return(H=(J=u.config)==null?void 0:J.sortByColumns)==null?void 0:H.map($=>({id:$.label,desc:$.direction==="desc"}))},[(Z=u.config)==null?void 0:Z.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":g&&v}),children:[a&&U(),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"&&g&&e.jsx(Hs,{variant:"outline"}),e.jsx(Er,{activeView:t,onViewChange:n}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:(ne=c.config)==null?void 0:ne.filters,cardFilterCount:s.getFilterCount(((te=c.config)==null?void 0:te.filters)||null),onFiltersClick:l}),I&&e.jsx(s.ComparisonMetadataBadge,{metadata:I,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Ar,{})}),g&&e.jsx(Qe,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:O||F,onClick:()=>{z(!0),L()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":B})})}),t==="chart"&&e.jsx(Js,{}),!g&&e.jsx(s.IconButton,{onClick:()=>b(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!S&&N&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>k(!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:"flex grow flex-col pb-6",children:e.jsx(Qs,{})}),t==="table"&&(A==null?void 0:A.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:c,data:(A==null?void 0:A.records)||[],paginationMetadata:E,onPaginationChange:K,isLoading:O||F,onSortChange:R,sortState:_})}),t==="info"&&j&&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:C?e.jsx(Ze,{error:C,errorSql:D,onSendFeedback:()=>{const J=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:c.dataSource,dashboardFilters:x,errorMessage:C,errorSql:D,generatedSql:A==null?void 0:A.sql});y(J),M(!0)},onOpenInEditor:()=>{b(!0),setTimeout(()=>{const J=s.useEditorStore.getState().actions;J.setIsDevMode(!0),J.setCardSql(D||""),setTimeout(()=>{J.setRunSql(!0)},100)},100)}}):e.jsx($s,{sql:A==null?void 0:A.sql,error:C,errorSql:D})})})]}),e.jsx(Fr,{isOpen:S,onClose:()=>k(!1)}),T&&e.jsx(s.FeedbackDialog,{open:P,onOpenChange:M,feedbackData:T})]})]})}function Lr({activeField:t}){const[n,a]=w.useState(!0);return w.useEffect(()=>{t&&a(!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 ${n?"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(as,{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 Pr=()=>{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 n=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},a=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",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Or(){var z,K;const[t,n]=w.useState("chart"),[a,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(!0),d=s.useEditorStore(U=>U.showAIDialog),u=s.useDashboardStore(U=>U.isVisualEditing),{setCardType:x}=s.useEditorActions(),m=s.useEditorStore(U=>U.card.type);w.useEffect(()=>Pr(),[]);const h=U=>{x(U)},p=s.useEditorStore(U=>U.frame),b=s.useEditorStore(U=>U.card);s.useEditorStore(U=>U.activeTabCardId),s.useEditorStore(U=>U.actions.getAvailableFields);const{addCard:g,removeCard:v,updateCard:S,setActiveCard:k,updateFilters:P}=s.useEditorActions(),{columns:M=[],isLoading:T,error:y}=s.useColumns(),f=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),j=b,{getFieldsForContainer:N,setFieldsForContainer:A}=Ye(j),{activeField:C,handleDragStart:O,handleDragEnd:F}=Tr({activeCardId:p.activeCardId,sourceFields:M,getFieldsForContainer:N,setFieldsForContainer:A}),D=(U,R)=>{R&&P(U,R)},E=U=>{var R;S(U,{config:{...(R=p.cards.find(_=>_.id===U))==null?void 0:R.config,filters:void 0}})},L=M,I=U=>{if(!U)return 0;let R=U.conditions.length;return U.groups.forEach(_=>{R+=I(_)}),R},B=I(((z=j==null?void 0:j.config)==null?void 0:z.filters)||null);return e.jsxs(s.DndContext,{sensors:f,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:F,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(qs,{isVisible:i,onToggleVisibility:()=>o(!i)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(cr,{selectedChart:m,onChartChange:h,groupByFields:N("groupBy"),pivotByFields:N("pivotBy"),metricsFields:N("metrics"),sortByFields:N("sortBy"),activeField:C}),e.jsx(Mr,{selectedChart:m,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:B,activeCard:j,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:M,columnsLoading:T,columnsError:y,getFieldsForContainer:N,cards:p.cards,activeCardId:p.activeCardId,addCard:g,setActiveCard:k})]}),!i&&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:()=>o(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),j&&e.jsx(kr,{cardId:j.id,filters:((K=j.config)==null?void 0:K.filters)||null,onFiltersChange:D,onClearFilters:E,availableFields:L,isOpen:l,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Lr,{activeField:C||null})})]})}function Br({authToken:t,onSave:n,onClose:a}){const r=w.useRef(null),l=s.useEditorStore(y=>y.showAIDialog),c=s.useEditorStore(y=>y.isDevMode),i=s.useAssistantLayoutStore(y=>y.setFullscreen),o=s.useAssistantLayoutStore(y=>y.setPanelOpen),d=s.useAssistantLayoutStore(y=>y.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),m=s.useAssistantContainer("editor"),h=x==="editor",p=w.useCallback(y=>{d("editor",y)},[d]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:g,setOnSave:v,setOnClose:S}=s.useEditorActions(),{setActiveAssistantType:k}=s.useAIActions();w.useEffect(()=>{n&&v(n),a&&S(a)},[n,v,a,S]),w.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),w.useEffect(()=>{var y,f;l?((y=r.current)==null||y.resize(40),o("editor",!0),k("editor")):((f=r.current)==null||f.resize(0),o("editor",!1),x==="editor"&&i(null),k(null))},[l,o,k,i,x]);function P(y){y<1?(g(!1),o("editor",!1),x==="editor"&&i(null),k(null)):(l||(g(!0),k("editor")),u.isOpen||o("editor",!0))}function M(){return e.jsxs(e.Fragment,{children:[e.jsx(qs,{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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(qn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:P,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(bs,{isFullscreen:h,onFullscreenChange:y=>i(y?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function T(){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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Or,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:P,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(bs,{isFullscreen:h,onFullscreenChange:y=>i(y?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:M()}):T()})}function Vr(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(i=>i.actions),a=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function l(i){t&&(r(t,i),n(!1))}function c(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(Br,{onSave:l,onClose:c})})}function Rr(){zs();const t=s.useDashboardStore(d=>d.selectedSheetId),n=s.useDashboardStore(d=>d.selectedFrameId),a=s.useDashboardStore(d=>d.dashboard),r=s.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:c}=s.useEditorActions(),i=s.useEditorStore(d=>d.card.dataSource);return w.useEffect(()=>{var u,x;let d=r();if(!d){const m=(u=a==null?void 0:a.sheets)==null?void 0:u.find(p=>p.id===t),h=(x=m==null?void 0:m.frames)==null?void 0:x[0];h&&(l(h.id),d=h)}if(d){const m=d.cards.find(h=>h.id===d.activeCardId);m&&c(m)}},[r,t,n,a,l,c]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function zr(){const t=s.useDashboardStore(a=>a.actions.setShowFilters),{hasEntities:n}=Rr();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,{})})]}),!n&&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"})]}),n&&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(Rs,{context:"filter"})})})})]})}function qr(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.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)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.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 $r(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(qr,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(zr,{})})]})}function Gr(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),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),n(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 lt(){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,n)=>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"})]})]},n))})]})})}const Ur=t=>{const n=s.useDashboardStore(l=>l.isVisualEditing),a=s.useDashboardStore(l=>l.selectedFrameId),r=s.useEditorStore(l=>l.frame);return!!(n&&a&&(r==null?void 0:r.visualId)===t)};function Kr({visual:t,isDeleting:n,isDuplicating:a,onAddVisual:r,onOpenVisual:l,onEditDetails:c,onDeleteClick:i,onDuplicateVisual:o,onShareVisual:d,formatDate:u}){var T,y,f,j;const{selectVisual:x}=s.useManagementActions(),m=s.useIsVisualSelected(t.id),h=Ur(t.id),{isConsoleMode:p}=s.useDashboardPreferences(),b=w.useRef(null),[g,v]=w.useState(!1),[S,k]=w.useState(!1);w.useEffect(()=>{a?(v(!0),k(!0)):S&&(v(!1),k(!1))},[a,S]),w.useEffect(()=>{h&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[h]);const P=()=>e.jsx(Re,{className:"h-4 w-4"}),M=()=>{x(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",h?"border-purple-500":m&&"border-primary"),onClick:M,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:P()}),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:(T=t.description)!=null&&T.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",m&&"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(),c==null||c(t)},title:"Edit details",children:e.jsx(s.PenLine,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,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(wt,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),o(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),c==null||c(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(),i(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"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:[(((y=t.ownership.createdBy)==null?void 0:y.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:((j=t.ownership.createdBy)==null?void 0:j.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 _r({open:t,onOpenChange:n,onSubmit:a,isCreating:r}){const[l,c]=w.useState(""),[i,o]=w.useState("");w.useEffect(()=>{t||(c(""),o(""))},[t]);const d=()=>{l.trim()&&a({title:l,description:i})},u=x=>{n(x)};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:x=>c(x.target.value),disabled:r,onKeyDown:x=>{x.key==="Enter"&&!x.shiftKey&&(x.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:i,onChange:x=>o(x.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 Hr(){const[t,n]=w.useState(""),[a,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(null),[d,u]=w.useState(!1),[x,m]=w.useState(null),[h,p]=w.useState(null),[b,g]=w.useState(null),{selectVisual:v}=s.useManagementActions(),{handleEditLibraryVisual:S,handleAddLibraryVisual:k}=ke(),{resources:P,isLoading:M,isError:T,createResource:y,updateResource:f,deleteResource:j,duplicateResource:N,isCreating:A,isDeleting:C}=s.useVisualManagement(()=>{u(!1),m(null)},$=>{r(!1),$&&(v($),S($))});s.useCurrentUserInfo();const O=P.filter($=>{var ee,X;return((ee=$==null?void 0:$.title)==null?void 0:ee.toLowerCase().includes(t.toLowerCase()))||((X=$==null?void 0:$.description)==null?void 0:X.toLowerCase().includes(t.toLowerCase()))}),F=$=>new Date($).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),D=$=>{y({title:$.title,description:$.description,isPrivate:!1})},E=$=>{m($),u(!0)},L=()=>{x&&j(x.id)},{startUpdating:I,stopUpdating:B,isUpdating:z}=s.useResourceUpdateState(),K=($,ee,X)=>{var q;const ue=Object.fromEntries(Object.entries(ee).filter(([,Q])=>Q!==void 0));if(Object.keys(ue).length===0){(q=X==null?void 0:X.onSuccess)==null||q.call(X);return}const me=Object.keys(ue),ae=me.length===1?me[0]:void 0;I($,ae),f({resourceId:$,data:ue},{onSuccess:()=>{var Q;B($,ae),(Q=X==null?void 0:X.onSuccess)==null||Q.call(X)},onError:()=>{var Q;B($,ae),(Q=X==null?void 0:X.onError)==null||Q.call(X)}})},U=$=>{p($),N($,{onSettled:()=>p(null)})},R=$=>{S($)},_=$=>{k($)},Z=$=>{const ee=P.find(X=>X.id===$);ee&&f({resourceId:$,data:{isPrivate:!ee.isPrivate}})},ne=$=>{o($),c(!0)},te=$=>{g($)},J=()=>{g(null)},H=({title:$,description:ee})=>{if(!b)return;const X={};$!==b.title&&(X.title=$),(b.description||"")!==ee&&(X.description=ee),K(b.id,X,{onSuccess:()=>{g(null)}})};return M?e.jsx(lt,{}):T?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:[P&&P.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:$=>n($.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:O.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(Re,{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"]})]}):O.map($=>e.jsx(Kr,{visual:$,onAddVisual:_,onOpenVisual:R,onEditDetails:te,onDeleteClick:E,onDuplicateVisual:U,onTogglePrivacy:Z,onShareVisual:ne,isDeleting:C,isDuplicating:h===$.id,formatDate:F},$.id))})}),l&&i&&e.jsx(s.ShareDialog,{resource:i,resourceType:s.ResourceType.VISUAL,onClose:()=>{c(!1),o(null)}}),b&&e.jsx(s.ResourceEditDialog,{open:!!b,resourceLabel:"Visual",initialTitle:b.title||"",initialDescription:b.description||"",onClose:J,onSave:H,isSaving:z(b.id)}),e.jsx(s.AlertDialog,{open:d,onOpenChange:$=>{!$&&C||(u($),$||m(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 "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:C,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:$=>{$.preventDefault(),$.stopPropagation(),L()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:C,children:[C?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"}),C?"Deleting...":"Delete"]})]})]})}),e.jsx(_r,{open:a,onOpenChange:r,onSubmit:D,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 Jr({dashboard:t,isDeleting:n,isDuplicating:a,onLoadDashboard:r,onEditDetails:l,onDeleteClick:c,onDuplicateDashboard:i,onShareDashboard:o,formatDate:d,onDashboardItemClick:u}){var k,P;const{selectDashboard:x}=s.useManagementActions(),m=s.useIsDashboardSelected(t.id),{userContext:h,isLoading:p}=s.useCurrentUserInfo(),b=((k=h==null?void 0:h.permissions)==null?void 0:k.canEdit)??!1,g=p||!b,v=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4"}),S=()=>{x(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",m&&"border-primary"),onClick:S,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:(P=t.description)!=null&&P.trim()?t.description:"No description"}),e.jsx(s.DashboardActionsMenu,{dashboard:t,isDeleting:n,isDuplicating:a,shouldHideActions:g,onEditDetails:l,onDeleteClick:c,onDuplicateDashboard:i,onShareDashboard:o,formatDate:d})]})]})]})},t.id)}function Qr({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 Wr(t){var de;const{onLoadDashboard:n,onEditDashboard:a,onDashboardItemClick:r}=t,[l,c]=w.useState(""),[i,o]=w.useState(!1),[d,u]=w.useState(!1),[x,m]=w.useState(null),[h,p]=w.useState(!1),[b,g]=w.useState(null),[v,S]=w.useState(null),[k,P]=w.useState(null),M=s.useManagementStore(V=>V.lastSelectedDashboard),T=s.useManagementStore(V=>V.selectedDashboard),y=s.useManagementStore(V=>V.actions.selectDashboard),f=s.useManagementStore(V=>V.actions.clearSelectedDashboard),{tokenProps:j,id:N}=s.useSemaphorContext();s.useRoleAwareDisplayPreferences();const{onCreateSuccess:A}=s.useDashboardCreation({onDashboardSelect:r}),{resources:C,isLoading:O,isError:F,createResource:D,updateResource:E,deleteResource:L,duplicateResource:I,isCreating:B,isDeleting:z,refetch:K}=s.useDashboardManagement(()=>{p(!1);const V=b==null?void 0:b.id;g(null),(T==null?void 0:T.id)===V&&(!(j!=null&&j.dashboard_id)&&!N?f():M&&M.id!==V&&y(M))},V=>{o(!1),A(V,K)}),{currentUser:U,userContext:R}=s.useCurrentUserInfo(),_=((de=R==null?void 0:R.permissions)==null?void 0:de.canCreateDashboard)??!1,Z=C.filter(V=>{var se,Y;return((se=V==null?void 0:V.title)==null?void 0:se.toLowerCase().includes(l.toLowerCase()))||((Y=V==null?void 0:V.description)==null?void 0:Y.toLowerCase().includes(l.toLowerCase()))}),ne=V=>new Date(V).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),te=V=>{D({title:V.title,description:V.description,isPrivate:!1})},J=V=>{n==null||n(V)},H=V=>{g(V),p(!0)},$=()=>{b&&L(b.id)},ee=V=>{S(V),I(V,{onSettled:()=>S(null)})},{startUpdating:X,stopUpdating:ue,isUpdating:me}=s.useResourceUpdateState(),ae=(V,se,Y)=>{var ve;const je=Object.fromEntries(Object.entries(se).filter(([,he])=>he!==void 0));if(Object.keys(je).length===0){(ve=Y==null?void 0:Y.onSuccess)==null||ve.call(Y);return}const ge=Object.keys(je),be=ge.length===1?ge[0]:void 0;X(V,be),E({resourceId:V,data:je},{onSuccess:()=>{var he;ue(V,be),(he=Y==null?void 0:Y.onSuccess)==null||he.call(Y)},onError:()=>{var he;ue(V,be),(he=Y==null?void 0:Y.onError)==null||he.call(Y)}})},q=V=>{const se=C.find(Y=>Y.id===V);se&&E({resourceId:V,data:{isPrivate:!se.isPrivate}})},Q=V=>{m(V),U==null||U.type,u(!0)},le=V=>{a==null||a(V.id),P(V)},pe=()=>{P(null)},fe=({title:V,description:se})=>{if(!k)return;const Y={};V!==k.title&&(Y.title=V),(k.description||"")!==se&&(Y.description=se),ae(k.id,Y,{onSuccess:()=>{P(null)}})};return O?e.jsx(lt,{}):F?e.jsx(Qr,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[C&&C.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:V=>c(V.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:Z.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:()=>o(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):Z.map(V=>e.jsx(Jr,{dashboard:V,isDeleting:z,isDuplicating:v===V.id,onLoadDashboard:J,onEditDetails:le,onDeleteClick:H,onDuplicateDashboard:ee,onTogglePrivacy:q,onShareDashboard:Q,formatDate:ne,onDashboardItemClick:r},V.id))})}),d&&x&&e.jsx(s.ShareDialog,{resource:x,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),m(null)}}),e.jsx(s.AlertDialog,{open:h,onOpenChange:V=>{!V&&z||(p(V),V||g(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:z,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:V=>{V.preventDefault(),V.stopPropagation(),$()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:z,children:[z?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"}),z?"Deleting...":"Delete"]})]})]})}),k&&e.jsx(s.ResourceEditDialog,{open:!!k,resourceLabel:"Dashboard",initialTitle:k.title||"",initialDescription:k.description||"",onClose:pe,onSave:fe,isSaving:me(k.id)}),e.jsx(s.CreateDashboardDialog,{open:i,onOpenChange:o,onSubmit:te,isCreating:B}),_&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>o(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function ot({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(y=>y.dashboard);const c=s.useDashboardStore(y=>y.isDashboardEditing),{setDashboard:i,addSheet:o}=s.useDashboardStore(y=>y.actions),{currentUser:d}=s.useCurrentUserInfo(),u=d,{permissions:x}=s.useRoleAwareDisplayPreferences(),h=s.useSelectedDashboard()&&x.canAccessVisuals&&c,p="dashboards",[b,g]=ts("resource-management-active-tab",p),v=h?b:"dashboards",S=l==="overlay",k=Is(n,{enabled:t&&S}),P=s.cn("flex h-full flex-col border-r bg-background",S?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",a),M=y=>{},T=y=>{console.log("Editing dashboard:",y)};return e.jsx(s.TooltipProvider,{children:(!S||t)&&e.jsxs("div",{ref:k,className:P,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:n,tooltip:"Close Sidebar",children:e.jsx(Vt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:v,onValueChange:h?g:void 0,className:"flex h-9 grow flex-col",children:[h&&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(Wr,{onLoadDashboard:M,onEditDashboard:T,onDashboardItemClick:r})}),h&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(Hr,{})})]})})]})})}function Yr({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen);s.useDashboardStore(h=>h.isVisualEditing);const l=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),c=20,i=20,o=30,d=r,u=w.useRef(null),x=w.useRef(null);w.useEffect(()=>{u.current&&x.current&&(r?(u.current.resize(c),x.current.resize(100-c)):(u.current.resize(0),x.current.resize(100)))},[r]);const{preferences:m}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:m,children:[e.jsx(Gr,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(wa,{}),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?c:0,minSize:d?i:0,maxSize:d?o:0,children:e.jsx(ot,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{className:s.cn("",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:x,className:"flex min-w-0 flex-1",defaultSize:d?100-c:100,minSize:d?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Vr,{}),e.jsx($r,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Ps;exports.DashboardPlus=Yr;exports.ResourceManagementPanel=ot;exports.ScheduleDashboard=Fs;exports.VisualEditingControls=Ls;exports.cleanCard=As;exports.getDashbaordStateWithoutData=Ve;
|
|
243
|
+
`;O(R)}function z(){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(Ua,{jsonString:JSON.stringify(x,null,2)})})}),x&&x.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>c(!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 K(){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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx($a,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&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(Ga,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function U(){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||F,onClick:()=>{L()},className:"h-8 shrink-0",size:"sm",children:[N||F?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(za,{errorSql:D,sql:j==null?void 0:j.sql,error:I,onDebugWithAssistant:B}),e.jsx(Ye,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:R=>r(R),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(qa,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!o&&e.jsxs("button",{disabled:o,onClick:()=>{M(!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-2 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:[K(),z()]}),U()]})}const _a=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:Re}];function Ha({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),c=["table","aggregateTable","pivotTable"].includes(n.type),i=s.hasValidCardConfig(n.config);if(!c||!i)return null;const o=d=>{var x;const u=d;if(u==="aggregateTable"&&((x=n.config)!=null&&x.pivotByColumns)&&n.config.pivotByColumns.length>0){const m={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(m),l(m)}else{a(u);const m={...n,type:u};l(m)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:o,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:_a.map(d=>{const u=d.icon,x=n.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",x?"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 Ja({card:t}){var O,M,T,y,f,j,N,F,C,P,A;const[n,a]=w.useState(!1),[r,l]=w.useState([]),{authToken:c}=s.useSemaphorContext(),{theme:i}=s.useTheme(),o=s.getTokenParams(c==null?void 0:c.accessToken),d=s.useDashboardStore(D=>D.themeStyle),u={mode:i||"system",colors:((M=(O=d==null?void 0:d.chart)==null?void 0:O.dataset)==null?void 0:M.backgroundColor)||[]};(T=t.customCardPreferences)!=null&&T.inputData;const{getCard:x}=s.useCustomVisual(((y=t.customCardPreferences)==null?void 0:y.url)||""),m=((f=t.customCardPreferences)==null?void 0:f.visualType)||"single",h=s.useEditorStore(D=>D.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),g=w.useCallback((D,E)=>{l(L=>({...L,[D]:E}))},[]);if(!((j=t.customCardPreferences)!=null&&j.componentName))return null;const v=x((N=t.customCardPreferences)==null?void 0:N.componentName);function S(D){a(D)}const k=Object.keys(((F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)||{}).map(D=>{var I,B,z;const E=(B=(I=t.customCardPreferences)==null?void 0:I.dataInputCardIds)==null?void 0:B[D].cardId,L=(z=h==null?void 0:h.cards)==null?void 0:z.find(K=>K.id===E);return L||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(w.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[v&&m==="single"&&e.jsx(v,{editing:!0,params:o,theme:u,settings:(C=t.customCardPreferences)==null?void 0:C.settings,onDataChange:g,data:(b==null?void 0:b.records)||[]}),v&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((P=t.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(D=>{var I,B,z;const E=(B=(I=t.customCardPreferences)==null?void 0:I.dataInputCardIds)==null?void 0:B[D].cardId,L=(z=h==null?void 0:h.cards)==null?void 0:z.find(K=>K.id===E);if(L)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:S,onDataChange:g,dataInputIndex:D,card:L},L.id+D)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(v,{theme:u,onDataChange:g,settings:k.map(D=>{var E;return(E=D==null?void 0:D.customCardPreferences)==null?void 0:E.settings}),data:k.map(D=>D!=null&&D.id?r==null?void 0:r[D.id]:[])})})]})]},(A=t.customCardPreferences)==null?void 0:A.componentName)})}function Qa({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(h=>h.selectedFrameId),l=s.useManagementStore(h=>h.selectedVisual),c=s.useEditorStore(h=>h.frame);let i;if(t)i=t;else if(n!==void 0)i=n?"linked":"library";else if(!!!(c!=null&&c.visualId||l!=null&&l.id)&&r)i="local";else if(l&&!r)i="library";else if(c!=null&&c.visualId&&r)i="linked";else if(l!=null&&l.id&&r)i="library";else return null;if(i==="local")return null;const o={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"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},m={linked:e.jsx(Ft,{className:"h-3.5 w-3.5"}),library:e.jsx(At,{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",o[i],a),children:m[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:d[i]})]})]})})}function Ks({className:t,...n}){var I;const a=s.useEditorStore(B=>B.card),r=((I=a.customCardPreferences)==null?void 0:I.showCardHeader)??!0,l=s.useEditorStore(B=>B.frame),c=s.useDashboardStore(B=>B.dashboard.filters),[i,o]=w.useState(!1),{currentUser:d}=s.useCurrentUserInfo(),{tokenProps:u}=w.useContext(s.SemaphorContext),x=s.useEditorStore(B=>B.actions.setRunSql),{updateFilter:m}=s.useDashboardActions(),h=c==null?void 0:c.find(B=>B.id===l.filterId),{data:p,isLoading:b,isFetching:g,errorMessage:v,errorSql:S,pagination:k}=s.useDashboardCardQuery(a),{setCard:O,updateCardInFrame:M,setIsDevMode:T,setCardSql:y}=s.useEditorActions(),{data:f}=s.useTopoJson(a),j=w.useMemo(()=>{var B;return a.type!=="pivotTable"||!((B=p==null?void 0:p.records)!=null&&B.length)?null:{records:p.records,columnSubtotalMeta:p.columnSubtotalMeta,subtotalColumns:p.subtotalColumns||[],pivotSchema:p.pivotSchema||[],groupByColumns:p.groupByColumns}},[a.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(a,j),F=B=>{T(!0),y(B||S||a.sql||a.python||""),setTimeout(()=>{x(!0)},100)},C=()=>{o(!0)},P=w.useMemo(()=>{const B=typeof window<"u"?window.location.href:"",z=typeof navigator<"u"?navigator.userAgent:"",K=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:d,tokenContext:u,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:c,errorMessage:v||void 0,errorSql:S||a.sql||a.python,generatedSql:S||a.sql},metadata:{url:B,userAgent:z,timestamp:new Date().toISOString(),viewport:K}}},[d,u,a,c,v,S]),A=(B,z)=>{var U,R;const K={...a,paginationConfig:{page:B+1,pageSize:z}};O(K),M(K),a.sql&&((R=(U=a.preferences)==null?void 0:U.tablePrefs)!=null&&R.enableDevModePagination)&&x(!0)},D=w.useMemo(()=>!a.id||!(p!=null&&p.records)?null:s.createChartConfig({card:a,data:p==null?void 0:p.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,p==null?void 0:p.records,a.type,a.customCfg,a.preferences,f]);function E(B){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ja,{card:B})})}function L(){if(p!=null&&p.records&&(p==null?void 0:p.records.length)===0&&!b&&!g)return v?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ss,{error:v,errorSql:S||a.sql||a.python,onOpenInEditor:F,onSendFeedback:C,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||g)&&a.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(!a.id)return null;if(a.type==="custom")return E(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&D)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:b||g?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:D})});if(a.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:a,data:(p==null?void 0:p.records)||[],paginationMetadata:k,onPaginationChange:A,isLoading:b||g})});if(a.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:a,data:N.data,options:N.options,onAggregationChange:B=>{const z=s.handleAggregationChange(B,a.config),K={...a,config:z};O(K),M(K)},onAggregationLabelChange:B=>{const z=s.handleAggregationLabelChange(B,a.config),K={...a,config:z};O(K),M(K)}})});if(a.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:a,data:(p==null?void 0:p.records)||[],groupByColumns:p==null?void 0:p.groupByColumns,pivotSchema:p==null?void 0:p.pivotSchema,paginationMetadata:k,onPaginationChange:A,onAggregationChange:B=>{const z=s.handleAggregationChange(B,a.config),K={...a,config:z};O(K),M(K)},isLoading:b||g})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,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:a.title,onSave:B=>O({...a,title:B}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Qa,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Ha,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:B=>O({...a,description:B}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),h&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:h.title||h.column,onSave:B=>m({...h,title:B}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:h})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:L()}),e.jsx(s.FeedbackDialog,{open:i,onOpenChange:o,feedbackData:P,showDebugInfo:!0})]})}const $e=({language:t,value:n,onChange:a,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:n,onChange:a}),Wa=()=>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."})]})]}),Ya=({customCode:t,cardCustomCfgString:n,mergedConfig:a,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($e,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx($e,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx($e,{language:"javascript",value:t,onChange:l})})]}),Xa=({error:t,hasCardCustomConfig:n,onReset:a,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:!n,onClick:a,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 Za(){const[t,n]=w.useState(!1),[a,r]=w.useState(""),[l,c]=w.useState(""),[i,o]=w.useState(""),[d,u]=w.useState(""),x=s.useEditorStore(T=>T.card),m=s.useEditorStore(T=>T.card.customCfg),h=m?JSON.stringify(m,null,2):"",{data:p}=s.useDashboardCardQuery(x),{data:b}=s.useTopoJson(x),{setCardCustomCfg:g,setCustomVisualCode:v}=s.useEditorActions(),S=T=>{var y,f;return JSON.stringify({...T,data:{...T.data,datasets:(f=(y=T.data)==null?void 0:y.datasets)==null?void 0:f.map(j=>({...j,data:[]}))}},null,2)},k=()=>{var y,f;if(!((y=p==null?void 0:p.records)!=null&&y.length))return;const T=s.createChartConfig({card:x,data:p.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:b});if(T){r(S(T)),o(((f=x.preferences)==null?void 0:f.customVisualCode)||"");const j=s.merge(T,m);c(S(j))}},O=()=>{try{if(i&&v(i),l){const T=JSON.parse(l),y=s.getObjectDiff(JSON.parse(a),T);g(y),u("")}}catch{u("Invalid JSON configuration")}},M=Object.keys(m||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:k,className:M?"":"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(Wa,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ks,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Ya,{customCode:i,cardCustomCfgString:h,mergedConfig:l,onConfigChange:T=>c(T??""),onCodeChange:T=>o(T??"")})]}),e.jsx(Xa,{error:d,hasCardCustomConfig:!!m,onReset:()=>{c(a),g(null)},onApply:O,onClose:()=>n(!1)})]})]})}function ze(t){const[n,a]=w.useState(null);return n}function _s(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{data:a,isLoading:r,isFetching:l,isError:c}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(n.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:a,isLoading:r,isFetching:l,isError:c}}function Hs(){const{data:t,isLoading:n,isError:a}=_s(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(o=>({queryKey:["manifest",o.value],queryFn:()=>s.loadManifest(o.value),enabled:!!o.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let c=n,i=a;return r.forEach((o,d)=>{var u;if(o.isLoading&&(c=!0),o.isError&&(i=!0),o.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const x=t.plugins[d],m=o.data.visuals.map(h=>({name:h.name,pluginName:x.label,componentType:h.componentType,pluginType:x.type,icon:h.icon,chartType:h.chartType,url:x.value}));l.push(...m)}}),{data:l,isLoading:c,isError:i}}function en({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:c,isLoading:i,isError:o}=Hs(),d=w.useCallback((u,x)=>{n(null),a({}),r(u),x&&l({type:"component",visualType:"single",url:x.url,componentName:x.name,icon:x.icon}),t==null||t()},[n,a,r,l,t]);return i?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..."})]}):o?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"})]}):!c||c.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:c.map((u,x)=>e.jsx(sn,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${x}`))})]})}const sn=({text:t,icon:n,onClick:a})=>{const r=ze();return e.jsxs("button",{onClick:a,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 tn({onChartTypeChange:t,iconClassName:n,searchQuery:a=""}){const{setCardType:r,setCardPreferences:l,setIsDevMode:c}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:o,setQueryConfig:d}=s.useEditorActions();function u(h,p){i(null),l({}),r(h),["custom","text","map"].includes(h)&&(c(!0),d(void 0)),t==null||t()}const m=[{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:"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(h=>h.name.toLowerCase().includes(a.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:m.map(h=>{const p=h.icon;return e.jsxs("button",{onClick:()=>u(h.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",n),strokeWidth:h.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:h.name})]},h.type)})})}function an({chartType:t,className:n,customIcon:a,componentName:r}){const l=ze();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(s.Type,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Js({variant:t="ghost"}){var o,d;const[n,a]=w.useState(!1),[r,l]=w.useState(""),c=s.useEditorStore(u=>u.card),i=c.type;return e.jsxs(s.Popover,{open:n,onOpenChange:u=>{a(u),u||l("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(an,{className:"size-4",chartType:i,customIcon:(o=c.customCardPreferences)==null?void 0:o.icon,componentName:(d=c.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(tn,{onChartTypeChange:()=>a(!1),searchQuery:r}),e.jsx(en,{onChartTypeChange:()=>a(!1)})]})]})]})}function nn({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,c]=w.useState(!1),i=w.useRef(null),o=w.useRef(!1);function d(){t&&!o.current&&navigator.clipboard.writeText(t)}function u(h){(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),d())}function x(){const h=window.getSelection();if(h&&h.toString().trim()!==""){const p=h.toString();navigator.clipboard.writeText(p),c(!0),o.current=!0,setTimeout(()=>{c(!1),o.current=!1},1e3)}else o.current=!1}function m(){c(!1),o.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 ${n}`,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:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:x,onMouseDown:m,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 rn(){const t=s.useEditorStore(c=>{var i,o;return(o=(i=c.card.preferences)==null?void 0:i.chartOptions)==null?void 0:o.indexAxis}),n=s.useEditorStore(c=>c.card.type),{setChartOrientation:a}=s.useEditorStore(c=>c.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(ms,{className:"size-4"}):e.jsx(us,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(ms,{className:"size-4"}):e.jsx(us,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():r()})}function ln({className:t}){var h,p,b,g,v,S,k,O;const n=s.useEditorStore(M=>M.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[c,i]=w.useState(!1),o=((p=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:p.showFilterInfo)??!0,d=((g=(b=n.preferences)==null?void 0:b.displayOptions)==null?void 0:g.showCardToolbar)??!0,u=((S=(v=n.preferences)==null?void 0:v.displayOptions)==null?void 0:S.showChrome)??!0,x=((O=(k=n.preferences)==null?void 0:k.displayOptions)==null?void 0:O.allowScroll)??!0,m=(M,T)=>{var j;const y={...n.preferences,displayOptions:{...(j=n.preferences)==null?void 0:j.displayOptions,[M]:T}};a(y);const f={...n,preferences:y};l(f),r(f)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:i,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(Es,{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:o,onCheckedChange:M=>{m("showFilterInfo",M)},onSelect:M=>M.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:M=>{m("showCardToolbar",M)},onSelect:M=>M.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:M=>{m("showChrome",M)},onSelect:M=>M.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:x,onCheckedChange:M=>{m("allowScroll",M)},onSelect:M=>M.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 Qs(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i,o;return(o=(i=c.card)==null?void 0:i.preferences)==null?void 0:o.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const c=["xy","none","x","y"],o=(c.indexOf(a)+1)%c.length;r(c[o])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(rn,{})}),!["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:[(a==="xy"||!a)&&e.jsx(Re,{className:"size-4"}),a==="x"&&e.jsx(bt,{className:"size-4"}),a==="y"&&e.jsx(zt,{className:"size-4"}),a==="none"&&e.jsx(Gt,{className:"size-4"})]}),e.jsx(ln,{})]})}function on(){const t=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:c}=s.useEditorActions(),i=(b,g)=>{b.dataTransfer.setData("tabIndex",g.toString())},o=b=>{b.preventDefault()},d=(b,g)=>{const v=b.dataTransfer.getData("tabIndex");if(v===g.toString())return;const S=Array.from(t.cards),[k]=S.splice(parseInt(v),1);S.splice(g,0,k),a({...t,cards:S})};function u(b){const g=t.cards.filter(k=>k.id!==b),v=g[0],S={...t,cards:g,activeCardId:v.id};a(S),r(v.id),l(v)}function x(b,g){const v={...t,cards:[...t.cards,g],activeCardId:b.id};a(v),r(g.id)}function m(){const b={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};x(n,b)}function h(b){const g={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"};x(b,g)}function p(b,g){return b.cards.length===1&&(g.displayTab===!0||g.displayTab===void 0)||b.activeCardId!==g.id&&(g.displayTab===!0||g.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=g.displayTab===void 0?!1:!g.displayTab;l({...g,displayTab:v}),c({...g,displayTab:v})},children:g.displayTab===!0||g.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Ct,{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,g)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>i(v,g),onDragOver:o,onDrop:v=>d(v,g),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({...n,tabTitle:v}),c({...n,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(),m()}}),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:()=>h(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Qe(){const t=s.useEditorStore(v=>v.frame),n=s.useEditorStore(v=>v.card),a=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:l,setActiveTabCardId:c,setCard:i,setIsDevMode:o,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:x,isFetching:m,isError:h}=s.useDashboardCardQuery(n);function p(v){const S=t.cards.find(k=>k.id===v);if(S!=null&&S.sql){r||o(!0),c(v);return}if(S!=null&&S.queryConfig){r&&o(!1),b(v),c(v);return}r||b(v),c(v)}function b(v){const S={...t,cards:t.cards.map(O=>O.id===n.id?n:O),activeCardId:v};l(S);const k=S.cards.find(O=>O.id===v);k.sql&&d(!0),i(k)}function g(){return n.type==="kpi"?x||m?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:n,data:u==null?void 0:u.records,isPending:x||m,isError:h})})}):n.type==="text"?x||m?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:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ks,{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:g()},v.id)),e.jsx(on,{})]})}function fs({children:t}){var y,f;s.useEditorStore(j=>j.frame);const n=s.useEditorStore(j=>j.card),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.isShowingVisual),l=s.useDashboardStore(j=>j.isVisualEditing),c=s.useEditorStore(j=>j.pythonStdOut);s.useEditorStore(j=>j.actions.setRunSql);const{setFrame:i,setCard:o,setActiveTabCardId:d,runAssistant:u,setIsDevMode:x,setCardPreferences:m}=s.useEditorActions(),{data:h,isLoading:p,isFetching:b,errorMessage:g,refetch:v}=s.useDashboardCardQuery(n),[S,k]=w.useState(!1);w.useEffect(()=>{b||k(!1)},[b]);function O(){const j=JSON.stringify(h==null?void 0:h.records,null,2),N=new Blob([j],{type:"application/json"}),F=URL.createObjectURL(N),C=document.createElement("a");C.href=F,C.download=`${n.title}.json`,C.click()}function M(){const N=[Object.keys(h==null?void 0:h.records.reduce((A,D)=>({...A,...D}),{})).join(","),...((h==null?void 0:h.records)||[]).map(A=>Object.values(A).join(","))].join(`
|
|
244
|
+
`),F=new Blob([N],{type:"text/csv"}),C=URL.createObjectURL(F),P=document.createElement("a");P.href=C,P.download=`${n.title}.csv`,P.click()}function T(){const j=`Can you get the documentation for ${n.type} chart?`;u(j)}return n?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(Js,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:T,children:e.jsx(ft,{className:"size-4"})}),!["table","custom"].includes(n.type)&&l&&e.jsx(Za,{})]}),!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:M,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(St,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.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:()=>{k(!0),v()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":S})})}),e.jsx(Qs,{})]}),n.type==="table"&&n.sql&&a&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((f=(y=n.preferences)==null?void 0:y.tablePrefs)==null?void 0:f.enableDevModePagination)??!1,onCheckedChange:j=>{var N;m({...n.preferences,tablePrefs:{...(N=n.preferences)==null?void 0:N.tablePrefs,enableDevModePagination:j}}),v()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(dn,{})]}),r?e.jsx(Qe,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[c&&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:c&&e.jsx(cn,{})}),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":c}),children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(h==null?void 0:h.records)||[]}),g&&e.jsx(nn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function cn(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=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:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function dn(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.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:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ye({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:c,icon:i,showPlaceholderLabel:o=!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",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),o&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function un(){var g,v;const t=s.useEditorStore(S=>S.card.customCardPreferences),{data:n}=_s(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(S=>S.card),l=s.useEditorStore(S=>S.frame),c=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:o,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(g=d==null?void 0:d.visuals)==null?void 0:g.find(S=>S.name===(t==null?void 0:t.componentName));function x(S,k){if(!t)return;const M={...(t==null?void 0:t.dataInputCardIds)||{},[S]:{cardId:k,hookRef:null}};i({...t,dataInputCardIds:M})}function m(S){var O,M;const k=(O=l==null?void 0:l.cards)==null?void 0:O.filter(T=>{var y;return((y=T==null?void 0:T.customCardPreferences)==null?void 0:y.visualType)!=="multiple"}).map(T=>({value:T.id,label:T.tabTitle||T.title}));return e.jsx("div",{className:"space-y-2",children:(M=S==null?void 0:S.dataInputs)==null?void 0:M.map((T,y)=>{var f,j;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:T}),e.jsx(ye,{className:"col-span-6 h-8 w-full justify-between",label:"",options:k||[],value:((j=(f=t==null?void 0:t.dataInputCardIds)==null?void 0:f[y])==null?void 0:j.cardId)||"",onValueChange:N=>x(y,N)})]},y+Math.random())})})}function h(S,k,O=[],M=""){var T,y;return t?S==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((T=t==null?void 0:t.settings)==null?void 0:T[k])||M,onChange:f=>{i({...t,settings:{...t==null?void 0:t.settings,[k]:f.target.value}})}},k):S==="select"?e.jsx(ye,{className:"h-8 w-full",label:"",options:O,value:((y=t==null?void 0:t.settings)==null?void 0:y[k])||M,onValueChange:f=>{i({...t,settings:{...t==null?void 0:t.settings,[k]:f}})}}):null:null}function p(S){const k=Object.entries((S==null?void 0:S.settings)||{});return e.jsx("div",{className:"space-y-3",children:k.map(([O,M])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:M.title}),h(M.ui,O,M.options,M.defaultValue)]},O))})}function b(S){t&&i({...t,visualType:S,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(pt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:S=>i({...t||{url:"",componentName:""},url:S})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:c,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:o&&e.jsx(ye,{icon:e.jsx(vt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.filter(S=>S.type===c).map(S=>({value:S.name,label:S.name})))||[],value:t.componentName,onValueChange:S=>{console.log("changing value",S),i({...t,componentName:S})}})})]})})]}),((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:m(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,n]=w.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),c=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),w.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function i(u,x){var m,h;x?a!=null&&a.onClickFilter&&((m=a==null?void 0:a.onClickFilter)==null?void 0:m.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(h=a==null?void 0:a.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==u)}),n(p=>{const b=[...p];return b[u]=!1,b}))}function o(u,x){var h;const m=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===u?{...p,expression:x.target.value}:p);l({...a,onClickFilter:m})}function d(u){var x,m,h,p;if(t!=null&&t[u]||(m=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(b=>b.columnIndex===u))!=null&&m.expression)return e.jsx(s.Input,{value:(p=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(b=>b.columnIndex===u))==null?void 0:p.expression,onChange:b=>o(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:c==null?void 0:c.map((u,x)=>{var m,h;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:!!((m=a==null?void 0:a.onClickFilter)!=null&&m.find(p=>p.columnIndex===x)),onCheckedChange:p=>i(x,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:((h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{n(p=>{const b=[...p];return b[x]=!p[x],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(x)]})},u)})})}function mn({idx:t}){var o;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(o=n==null?void 0:n.chartOptions)==null?void 0:o.indexAxis,c=a==null?void 0:a.find(d=>d.idx===t);function i(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:d!=="none",align:d,anchor:d,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:x}]});else{const m={...c};m.datalabels=x;const h=a==null?void 0:a.map(p=>p.idx===u?m:p);r({...n,datasetOptions:h})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Is,{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:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Mt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Pt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Lt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function hn(){const t=s.useEditorStore(c=>c.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!s.METADATA_KEYS.includes(c));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const c=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:i}=s.getKeys(c);l=i.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function ts({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Ws(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,x,m;return(m=(x=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:m.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:c,transformedMetricKeys:i,keys:o}=hn();return o.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:c.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Ys(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:i.map((d,u)=>e.jsx(Xs,{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 Ys(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Xs({col:t,idx:n,className:a,iconClassName:r,children:l}){const c=s.useEditorStore(x=>{var m;return(m=x.card)==null?void 0:m.preferences}),i=s.useEditorStore(x=>{var m,h;return(h=(m=x.card)==null?void 0:m.preferences)==null?void 0:h.datasetOptions}),o=i==null?void 0:i.find(x=>x.idx===n),{setCardPreferences:d}=s.useEditorStore(x=>x.actions);function u(x){if(!o)d({...c,datasetOptions:[...i||[],{idx:n,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const m={...o};m.type=x==="area"?"line":x,m.fill=x==="area"?"origin":"";const h=i==null?void 0:i.map(p=>p.idx===n?m:p);d({...c,datasetOptions:h})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(ts,{className:"max-w-[100px]",title:t,children:Ys(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(mn,{idx:n})]})]})}function Fe(){const t=s.useDashboardStore(o=>o.dashboard.filters),n=s.useEditorStore(o=>o.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Rs();function c(o){const d=l(o,"frame");a({...n,filterId:d})}const i=t==null?void 0:t.find(o=>o.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(xn,{onSelect:c,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function xn({columns:t,onSelect:n}){var i;const[a,r]=Ke.useState(!1),[l,c]=Ke.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(i=t.find(o=>o.column_name===l))==null?void 0:i.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(o=>e.jsxs(s.CommandItem,{value:o.column_name,onSelect:d=>{const u=d===l?"":d;c(u),r(!1),u&&n(o)},children:[o.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===o.column_name?"opacity-100":"opacity-0")})]},o.column_name))})]})]})})]})}function pn({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:n=>n.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(Ws,{})})]}),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(Fe,{})]})]})]})})}function fn({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="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"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:c=>c.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:n(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(Fe,{})]})]})]})})}function Zs(){const t=s.useEditorStore(o=>o.card.type),n=s.useEditorStore(o=>o.isDevMode),a=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:r}=s.useEditorStore(o=>o.actions);function l(o){var x;const d={datalabels:{display:o!=="none",align:o,anchor:o,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(x=a==null?void 0:a.chartOptions)==null?void 0:x.plugins,...d}}};r(u)}function c(){var o,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=(o=a==null?void 0:a.chartOptions)==null?void 0:o.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 i(){var o,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(o=a==null?void 0:a.chartOptions)==null?void 0:o.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:n?c():i()})}const gn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},jn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function bn(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:vn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Zs,{}),e.jsx(Te,{}),e.jsx(Fe,{})]})]})}function vn(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(gn,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(jn,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 yn({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(i,o,d){const u=[...t];u[i]={...u[i],[o]:d},n(u)}function l(i){const o=[...t];o.splice(i,1),n(o)}function c(){n([...t,a])}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:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,o)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(o,"start",d.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:i.end,onChange:d=>r(o,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(o,"color",d.target.value),value:i.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(o),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},o))]})}function Nn(){var x,m,h,p,b;const t=s.useEditorStore(g=>g.card.preferences),n=s.useEditorStore(g=>g.actions.setCardPreferences),a=s.useEditorStore(g=>g.card),r=s.hasValidCardConfig(a.config),l=s.useEditorStore(g=>g.actions.setNumberFormat);s.useEditorStore(g=>{var v,S;return(S=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:S.decimalPlaces});const c=s.useEditorStore(g=>{var v,S;return(S=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:S.locale}),i=s.useEditorStore(g=>{var v,S;return(S=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:S.currency});s.useEditorStore(g=>g.actions.setFilterOnClickField);const o=s.useEditorStore(g=>{var v,S;return(S=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:S.colorRanges})||[],d=s.useEditorStore(g=>g.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(g=>g.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:g=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:g}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((m=t==null?void 0:t.formatNumber)==null?void 0:m.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:c||"none",onValueChange:g=>{var v,S,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((S=t==null?void 0:t.formatNumber)==null?void 0:S.currency)||"",g,((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g.locale,children:g.locale},g.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:g=>{var v,S,k;console.log("currency",g),l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,g==="none"?"":g,((S=t==null?void 0:t.formatNumber)==null?void 0:S.locale)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g,children:g},g))]})})]})]})]}),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=(h=t==null?void 0:t.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:p.toString())||"0",onValueChange:g=>{var v,S,k;return l(Number(g),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((S=t==null?void 0:t.formatNumber)==null?void 0:S.locale)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g,children:g},g))})]})]}),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:g=>{var v,S,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((S=t==null?void 0:t.formatNumber)==null?void 0:S.currency)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.locale)||"",g.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(yn,{colorRanges:o,setColorRanges:d})]})]})}function Cn(){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(Nn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ge({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,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:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Sn=[{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"}],wn=["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"],Dn=wn.map(t=>({label:t,value:t}));function kn(){var d,u,x,m,h,p,b,g,v,S,k,O,M,T,y,f,j,N;const t=s.useEditorStore(F=>F.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=w.useState(((m=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:c}=s.useTopoJson(t),i=Object.keys((c==null?void 0:c.objects)||{}).map(F=>({label:F,value:F}))||[],o=[{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(Ge,{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(Ge,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ye,{className:"h-9",options:o,onValueChange:F=>{console.log("value",F),l({...t.preferences,mapVisualOptions:{topoJsonUrl:F}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:F=>{r(F.target.value)},onBlur:()=>{var F;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(F=t.preferences)==null?void 0:F.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),c&&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:i,value:((p=(h=t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:F=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,objectKey:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ye,{className:"h-9",options:Sn,value:((g=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:g.projection)||"",label:"Projection",onValueChange:F=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projection:F}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ye,{className:"h-9",options:Dn,value:((S=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:S.colorScale)||"",label:"Select Color Scale",onValueChange:F=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,colorScale:F}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ge,{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=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:F=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projectionScale:Number(F.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((y=(T=(M=t.preferences)==null?void 0:M.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:y[0])||0,onChange:F=>{var C,P,A,D;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projectionOffset:[Number(F.target.value),((D=(A=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:D[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=(j=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:j.projectionOffset)==null?void 0:N[1])||0,onChange:F=>{var C,P,A,D;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projectionOffset:[((D=(A=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:D[0])||0,Number(F.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Te,{})]})}function Tn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...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:a,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:n,suffix:a="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)} ${a}`}),e.jsx(s.AccordionContent,{children: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 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(Tn,{})})]}),!["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(Fe,{})]})]})]})})}function En(){const t=s.useEditorStore(r=>{var l,c;return(c=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:c.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){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=>{n(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:[a(),e.jsx(Ws,{})]})]}),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(Fe,{})]})]})]})})}function In({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,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(Fe,{})]})]})}),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 et({color:t,onColorChange:n,onClose:a}){const[r,l]=w.useState(0),[c,i]=w.useState(100),[o,d]=w.useState(50),[u,x]=w.useState(t);w.useEffect(()=>{const v=gs(t);if(v){const S=js(v.r,v.g,v.b);l(S.h),i(S.s),d(S.l),x(t)}},[t]);const m=v=>{l(v),p(v,c,o)},h=v=>{const S=v.currentTarget.getBoundingClientRect(),k=Math.max(0,Math.min(1,(v.clientX-S.left)/S.width)),O=Math.max(0,Math.min(1,(v.clientY-S.top)/S.height)),M=k*100,T=(1-O)*100;i(M),d(T),p(r,M,T)},p=(v,S,k)=>{const O=Fn(v,S,k),M=An(O.r,O.g,O.b);x(M)},b=v=>{if(x(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const S=gs(v);if(S){const k=js(S.r,S.g,S.b);l(k.h),i(k.s),d(k.l)}}},g=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};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:h,onMouseMove:v=>{v.buttons===1&&h(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:`${c}%`,top:`${100-o}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>m(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:a,children:"Cancel"}),e.jsx(s.Button,{onClick:g,children:"OK"})]})]})}function gs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function An(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function js(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let c=0,i=0;const o=(r+l)/2;if(r!==l){const d=r-l;switch(i=o>.5?d/(2-r-l):d/(r+l),r){case t:c=((n-a)/d+(n<a?6:0))/6;break;case n:c=((a-t)/d+2)/6;break;case a:c=((t-n)/d+4)/6;break}}return{h:Math.round(c*360),s:Math.round(i*100),l:Math.round(o*100)}}function Fn(t,n,a){t/=360,n/=100,a/=100;let r,l,c;if(n===0)r=l=c=a;else{const i=(u,x,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?u+(x-u)*6*m:m<.5?x:m<.6666666666666666?u+(x-u)*(.6666666666666666-m)*6:u),o=a<.5?a*(1+n):a+n-a*n,d=2*a-o;r=i(d,o,t+1/3),l=i(d,o,t),c=i(d,o,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(c*255)}}const Mn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function st(){var O,M,T,y,f,j,N,F,C,P;const t=s.useEditorStore(A=>A.card),n=s.useEditorStore(A=>{var D;return(D=A.card)==null?void 0:D.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[c,i]=w.useState({}),[o,d]=w.useState(null),[u,x]=w.useState(null),m=w.useMemo(()=>{var L,I,B,z,K,U,R;if(!(l!=null&&l.records)||l.records.length===0)return[];const A=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",D=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",E=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((A||D)&&E){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const _=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&_.add(Z.alias)}),Array.from(_)}if(l.records.length>0){const _=l.records[0],Z=Object.keys(_),ne=new Set;(I=t==null?void 0:t.config)!=null&&I.groupByColumns&&t.config.groupByColumns.forEach(Y=>{ne.add(Y.label||Y.name),ne.add(Y.alias||Y.name)});const se=new Set;return(B=t==null?void 0:t.config)!=null&&B.metricColumns&&t.config.metricColumns.forEach(Y=>{const $=Y.alias||Y.name;se.add($),se.add(`${$}_count`),se.add(`${$}_sum`),se.add(`${$}_avg`),se.add(`${$}_min`),se.add(`${$}_max`);const H=Y.entityName||Y.qualifiedEntityName;H&&(se.add(`${H}_${$}`),se.add(`${H}_${$}_count`))}),Z.filter(Y=>!ne.has(Y)&&!se.has(Y))}}if((D||A)&&!E&&((K=(z=t==null?void 0:t.config)==null?void 0:z.metricColumns)!=null&&K.length))return t.config.metricColumns.map(_=>_.alias||_.label||_.name);if((R=(U=t==null?void 0:t.config)==null?void 0:U.groupByColumns)!=null&&R.length){const _=t.config.groupByColumns[0],Z=_.label||_.name,ne=new Set;return l.records.forEach(se=>{const ae=se[Z];ae!=null&&ne.add(String(ae))}),Array.from(ne)}return[]},[l,(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns,(M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns,(T=t==null?void 0:t.config)==null?void 0:T.metricColumns,t==null?void 0:t.type]),h=w.useMemo(()=>s.getDefaultChartColors(),[]);w.useEffect(()=>{const A={};m.forEach((D,E)=>{A[D]=s.getColorForValue(D,E,n==null?void 0:n.colorConfig)}),i(A)},[m,n==null?void 0:n.colorConfig,h]);const p=(A,D)=>{const E={...c,[A]:D};i(E);const L={...n||{},colorConfig:{segments:E}};a(L);const I={...t,preferences:L};r(I)},b=(A,D)=>{var K;const E=h[D%h.length],{[A]:L,...I}=((K=n==null?void 0:n.colorConfig)==null?void 0:K.segments)||{},B={...n||{},colorConfig:{segments:I}};a(B);const z={...t,preferences:B};r(z),i(U=>({...U,[A]:E}))};if(!m.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(y=t==null?void 0:t.config)==null?void 0:y.groupByColumns)==null?void 0:f.length)||((N=(j=t==null?void 0:t.config)==null?void 0:j.pivotByColumns)==null?void 0:N.length):(C=(F=t==null?void 0:t.config)==null?void 0:F.groupByColumns)==null?void 0:C.length)||["table","kpi","text","custom"].includes(t.type))return null;const S=()=>{const A={...n||{},colorConfig:{segments:{}}};a(A);const D={...t,preferences:A};r(D);const E={};m.forEach((L,I)=>{E[L]=s.getColorForValue(L,I,void 0)}),i(E)},k=Object.keys(((P=n==null?void 0:n.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(Vt,{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:k&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:S,children:[e.jsx(hs,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:m.map((A,D)=>{const E=s.isDefaultColor(c[A],D),L=!E;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:o===A,onOpenChange:I=>d(I?A: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:c[A]}})}),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:h.slice(0,10).map((I,B)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[A]===I?"border-gray-900":"border-transparent"),style:{backgroundColor:I},onClick:()=>{p(A,I),d(null)},children:[B===D%h.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:I})]},`default-${B}`))})]}),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:Mn.map((I,B)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[A]===I?"border-2 border-gray-900":I==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:I},onClick:()=>{p(A,I),d(null)},children:e.jsx("span",{className:"sr-only",children:I})},`preset-${B}`))})]}),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:()=>{x({value:A,color:c[A]}),d(null)},children:"Custom color"}),!E&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(A,D),d(null)},children:[e.jsx(hs,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:A}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},A)})}),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:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(et,{color:u.color,onColorChange:A=>{p(u.value,A),x(null)},onClose:()=>x(null)})})]})]})})]})}function Ne({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[c,i]=w.useState(t??""),[o,d]=w.useState(!1);w.useEffect(()=>{i(t??"")},[t]);const u=()=>{n(c),d(!1)},x=()=>{i(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:o?c:t??"",onChange:m=>{i(m.target.value),d(!0)},onFocus:()=>d(!0),onClick:m=>m.stopPropagation(),className:"h-8 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&o&&c!==t?u():m.key==="Escape"&&x()},"aria-label":a||"Edit field"}),o&&c!==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:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Ln=["auto","number","currency","percent","scientific","date"],Pn=[{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"}],On=[{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"}],Bn=t=>t.charAt(0).toUpperCase()+t.slice(1);function as({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",c=(o,d)=>{n({...t,[o]:d})},i=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:o=>c("type",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ln.map(o=>e.jsx(s.SelectItem,{value:o,className:"text-xs",children:o==="auto"?"Auto (Default)":Bn(o)},o))})]})]}),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??i(),onChange:o=>c("decimalPlaces",parseInt(o.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:o=>c("currency",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Pn.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.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:o=>c("useSuffix",o)})]}),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:o=>c("locale",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:On.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.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:o=>c("prefix",o.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:o=>c("suffix",o.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:o=>c("negativeInParentheses",o)})]}),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:o=>c("multiplyBy",o.target.value?parseFloat(o.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:o=>c("dateFormat",o.target.value),className:"h-8 text-xs"})})]})]})]})}function bs({axis:t,label:n,type:a,config:r,onChange:l}){var m,h,p,b,g,v,S,k,O,M,T,y;const c=(f,j)=>{l({...r,[f]:j})},i=(f,j)=>{var N,F;l({...r,name:{enabled:f==="enabled"?j:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,text:f==="text"?j:(F=r==null?void 0:r.name)==null?void 0:F.text}})},o=(f,j)=>{var N,F;l({...r,labels:{enabled:f==="enabled"?j:((N=r==null?void 0:r.labels)==null?void 0:N.enabled)??!0,rotation:f==="rotation"?j:(F=r==null?void 0:r.labels)==null?void 0:F.rotation}})},d=(f,j)=>{l({...r,scale:{...r==null?void 0:r.scale,[f]:j===""?"auto":Number(j)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["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:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>c("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:((m=r==null?void 0:r.name)==null?void 0:m.enabled)??!1,onCheckedChange:f=>i("enabled",f)})]}),((h=r==null?void 0:r.name)==null?void 0:h.enabled)&&e.jsx(Ne,{placeholder:`${n} title`,value:((p=r==null?void 0:r.name)==null?void 0:p.text)||"",onSave:f=>i("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=>c("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=>o("enabled",f)})]}),((g=r==null?void 0:r.labels)==null?void 0:g.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=>o("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:x.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),a==="value"&&e.jsx(as,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>l({...r,formatOptions:f}),showTitle:!0,title:"FORMAT"}),a==="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:((S=r==null?void 0:r.scale)==null?void 0:S.min)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.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"||((M=r==null?void 0:r.scale)==null?void 0:M.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:((T=r==null?void 0:r.scale)==null?void 0:T.stepSize)==="auto"||((y=r==null?void 0:r.scale)==null?void 0:y.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>d("stepSize",f),className:""})})]})]})]})]})]})}function tt(){const t=s.useEditorStore(i=>i.card),n=s.useEditorStore(i=>{var o;return(o=i.card)==null?void 0:o.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const c=(i,o)=>{const u={...n||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:o};a(u);const x={...t,preferences:u};r(x)};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(Es,{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(bs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:i=>c("x",i)}),l.hasYAxis&&e.jsx(bs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:i=>c("y",i)})]})})]})}function at(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var x,m,h,p;return(p=(h=(m=(x=u.card)==null?void 0:x.preferences)==null?void 0:m.chartOptions)==null?void 0:h.plugins)==null?void 0:p.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",c=!(t.type==="stackedBar"||t.type==="stackedLine"),i=(u,x)=>{const m={...n,[u]:x};a(m)},o=["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(It,{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:(n==null?void 0:n.display)??c,onCheckedChange:u=>i("display",u)})]}),((n==null?void 0:n.display)??c)&&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:(n==null?void 0:n.position)||r,onValueChange:u=>i("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.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:(n==null?void 0:n.align)||l,onValueChange:u=>i("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 nt(){var j,N,F,C,P,A,D,E,L;const t=s.useEditorStore(I=>I.card),n=s.useEditorStore(I=>{var B,z;return(z=(B=I.card)==null?void 0:B.preferences)==null?void 0:z.dataLabelsConfig}),a=s.useEditorStore(I=>{var B;return(B=I.card)==null?void 0:B.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const c=((j=a==null?void 0:a.chartOptions)==null?void 0:j.indexAxis)==="y",i=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!o,u=(F=(N=a==null?void 0:a.chartOptions)==null?void 0:N.plugins)==null?void 0:F.datalabels,x=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),m=(n==null?void 0:n.enabled)!==void 0?n.enabled:x,h=(I,B)=>{const z={...n,[I]:B},K={...t.preferences||{},dataLabelsConfig:z};r(K);const U={...t,preferences:K};l(U)},p=(I,B)=>{const z={...n,font:{...n==null?void 0:n.font,[I]:B}},K={...t.preferences||{},dataLabelsConfig:z};r(K);const U={...t,preferences:K};l(U)},b=(I,B)=>{const z={...n,formatOptions:{...n==null?void 0:n.formatOptions,[I]:B}},K={...t.preferences||{},dataLabelsConfig:z};r(K);const U={...t,preferences:K};l(U)},v=(()=>{const I=t.type;return I==="stackedBar"||I==="stackedLine"||I==="pie"||I==="doughnut"?"center":c?"right":"top"})();let S=[];i||o?S=["center"]:S=["auto",...(c?["center","left","right"]:["center","top","bottom"]).filter(B=>B!==v),"custom"];const k=()=>s.titleCase(v),O=["center","start","end"],M=["center","start","end","top","bottom"],T=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],y=[{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"}],f=[{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(Kt,{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:m,onCheckedChange:I=>h("enabled",I)})]}),m&&e.jsxs(e.Fragment,{children:[!i&&!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:I=>h("position",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(I=>e.jsx(s.SelectItem,{value:I,className:"text-xs",children:I==="auto"?k():I==="custom"?"Custom (Advanced)":s.titleCase(I)},I))})]})]}),i&&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:(n==null?void 0:n.showTotal)??!1,onCheckedChange:I=>h("showTotal",I)})]}),(n==null?void 0:n.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:(n==null?void 0:n.anchor)||"center",onValueChange:I=>h("anchor",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:O.map(I=>e.jsx(s.SelectItem,{value:I,className:"text-xs",children:s.titleCase(I)},I))})]})]}),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((n==null?void 0:n.align)||"center"),onValueChange:I=>h("align",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:M.map(I=>e.jsx(s.SelectItem,{value:I,className:"text-xs",children:s.titleCase(I)},I))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:I=>h("format",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(I=>e.jsx(s.SelectItem,{value:I,className:"text-xs",children:I==="auto"&&d?"Auto (Use Axis)":I==="none"?"None (Raw Value)":s.titleCase(I)},I))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.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(((C=n==null?void 0:n.formatOptions)==null?void 0:C.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:I=>b("decimalPlaces",Number(I)),className:""})})]}),n.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:((P=n==null?void 0:n.formatOptions)==null?void 0:P.currency)||"USD",onValueChange:I=>b("currency",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(I=>e.jsx(s.SelectItem,{value:I.value,className:"text-xs",children:I.label},I.value))})]})]}),["number","currency"].includes(n.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:((A=n==null?void 0:n.formatOptions)==null?void 0:A.useSuffix)??!1,onCheckedChange:I=>b("useSuffix",I)})]}),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:((D=n==null?void 0:n.formatOptions)==null?void 0:D.locale)||"en-US",onValueChange:I=>b("locale",I),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(I=>e.jsx(s.SelectItem,{value:I.value,className:"text-xs",children:I.label},I.value))})]})]})]}),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(((E=n==null?void 0:n.font)==null?void 0:E.size)||12),onSave:I=>p("size",Number(I)),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:((L=n==null?void 0:n.font)==null?void 0:L.weight)||"normal",onValueChange:I=>p("weight",I),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:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:I=>{I==="auto"&&h("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((n==null?void 0:n.rotation)||0),onSave:I=>h("rotation",Number(I)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Vn(){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:[e.jsx(st,{}),e.jsx(tt,{}),e.jsx(at,{}),e.jsx(nt,{})]})]})}const Rn=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."]})]}),zn=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."]})]}),qn=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(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=c=>r.includes(a)?c:e.jsxs(e.Fragment,{children:[c,e.jsx(Vn,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(En,{}));case"tornado":case"pyramid":return l(e.jsx(Oe,{docContent:Rn,cardType:a}));case"kpi":return e.jsx(Cn,{});case"line":case"bar":return l(e.jsx(pn,{cardType:a}));case"range":return l(e.jsx(Oe,{docContent:zn,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Oe,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(fn,{cardType:a}));case"table":return e.jsx(In,{cardType:a});case"text":return e.jsx(Oe,{docContent:qn,cardType:a,suffix:"Visual"});case"map":return e.jsx(kn,{});case"custom":return e.jsx(un,{});default:return l(e.jsx(bn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Gn(){const t=w.useRef(null),n=w.useRef(null),a=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return w.useEffect(()=>{var l,c,i,o;r?((l=t.current)==null||l.resize(0),(c=n.current)==null||c.resize(0)):((i=t.current)==null||i.resize(25),(o=n.current)==null||o.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(Ka,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!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(fs,{})})]}):e.jsx(fs,{})})]})}function Un(t){var me;s.useAIInteractionStore(q=>q.currentAIContext);const[n,a]=w.useState(""),[r,l]=w.useState(null),{authToken:c,tokenProps:i}=s.useSemaphorContext(),o=s.useEditorStore(q=>{var W;return(W=q==null?void 0:q.card)==null?void 0:W.sql}),d=s.useEditorStore(q=>q.isDevMode),u=s.useEditorStore(q=>{var W;return(W=q==null?void 0:q.card)==null?void 0:W.python}),{setCardPython:x,setCardSql:m,setRunSql:h,switchCardType:p,setQueryConfig:b}=s.useEditorActions(),g=s.useEditorStore(q=>q.currentAssitantScope)||[],v=s.useEditorStore(q=>q.userInputForAI),S=s.useEditorStore(q=>q.triggerAIRun),k=s.useEditorStore(q=>q.card),O=s.useEditorStore(q=>q.selectedDatabaseName),M=s.useEditorStore(q=>q.selectedTableName),T=s.useEditorStore(q=>q.selectedConnectionId),y=s.useEditorStore(q=>q.selectedSchemaName),f=s.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:j,refetch:N,data:F}=s.useDashboardCardQuery(k),{setTriggerAIRun:C,setCurrentAssitantScope:P,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:D,connectionType:E,selectedDatamodelId:L}=s.useEditorAside(),I=(me=s.useDashboardQuery().data)==null?void 0:me.assistantProfileId,{messages:B,setMessages:z,regenerate:K,error:U,sendMessage:R,status:_,addToolResult:Z,stop:ne,clearError:se}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const q=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:I,isDevMode:d,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:q.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:W})=>({body:{...W,messages:s.cleanupIncompleteMessages(q)}})}),onError:q=>{var W;if(q.name==="AbortError"||(W=q.message)!=null&&W.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",q)},onToolCall:ae,onFinish({isAbort:q,isDisconnect:W,isError:te}){a(""),console.log(q?"[Editor Assistant] Stream aborted by user":W?"[Editor Assistant] Stream disconnected (network error)":te?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});w.useEffect(()=>{S&&v&&(R({role:"user",parts:[{type:"text",text:v}]}),C(!1))},[S,v,R,C]);async function ae({toolCall:q}){var W,te,he,xe,le,V,ee,X,je,ge,be,ve,pe,Ee,Se,we;if(["createChartFromSql","createForecast"].includes(q.toolName)){const J=((W=q.input)==null?void 0:W.sql)??((te=q.args)==null?void 0:te.sql),oe=((he=q.input)==null?void 0:he.python)??((xe=q.args)==null?void 0:xe.python),ie=((le=q.input)==null?void 0:le.chartType)??((V=q.args)==null?void 0:V.chartType);p(ie),m(J),x(oe),h(!0),Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(q.toolName==="getUserSql"){if(!o){Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:o,python:u||""}})}else if(q.toolName==="generateQueryConfig"){a("Generating query config...");const J=((ee=q.input)==null?void 0:ee.chartType)??((X=q.args)==null?void 0:X.chartType),oe=((je=q.input)==null?void 0:je.queryConfig)??((ge=q.args)==null?void 0:ge.queryConfig);((be=q.input)==null?void 0:be.cardConfig)??((ve=q.args)==null||ve.cardConfig),p(J),A(oe),m(void 0),x(void 0);const ie=await N();if((pe=ie==null?void 0:ie.data)!=null&&pe.error){Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:oe,message:(Ee=ie==null?void 0:ie.data)==null?void 0:Ee.error.message}});return}if((Se=ie==null?void 0:ie.data)!=null&&Se.records){Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:oe,message:"The data has been visualized"}});return}Z({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:oe,message:"The data has been visualized",records:(we=ie==null?void 0:ie.data)==null?void 0:we.records}})}else a("Analyzing...")}function Y(q){const W=s.removeFromScopeArray(g,q);$(W)}function $(q){const W=s.sanitizeAIScope(q);P(W),z(te=>[...te,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(W)}`}]}])}function H(){const q={databaseName:O||"",schemaName:y||"",tableName:M||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(D),connectionId:T||"",connectionType:E||""},W=s.dedup([...g,q]);$(W)}function Q(){const q={databaseName:O||"",schemaName:y||"",tableName:M||"",datamodelName:s.resolveDatamodelName(D),connectionId:T||"",connectionType:E||"",datamodelId:L||""};if(!s.isInAiScopeArray([...f||[],...g],q)||g.length===0){const te=s.dedup([...f||[],...g,q]).filter(he=>he.connectionId===q.connectionId);$(te)}}const re=!["ready","error"].includes(_),ue=s.getErrorMessage(U);return{messages:B,setMessages:z,sendMessage:R,regenerate:K,isLoading:re,handleSetAIScope:Q,handleAddCurrentTableToScope:H,removeFromCurrentSelections:Y,currentAssitantScope:g,setCurrentAssitantScope:P,stop:ne,status:_,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ue,clearError:se}}const Kn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function vs({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=w.useRef(null),[l,c]=w.useState(!1),[i,o]=w.useState(s.isDevEnv),[d,u]=w.useState(!1),[x,m]=w.useState(!1),[h,p]=w.useState(!1),b=t??h,g=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:S}=s.useQueueActions(),{clearFileAttachments:k}=s.useFileActions(),O=s.useFileAttachments("editor"),M=s.useDashboardStore(J=>J.dashboard.aiContext),T=s.useEditorStore(J=>J.card.dataSource),y=s.useEditorStore(J=>J.actions.setCardSql),f=s.useEditorStore(J=>J.actions.setRunSql),j=s.useEditorStore(J=>J.showAIDialog),N=s.useDashboardStore(J=>J.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:C}=s.useEditorActions(),{setDataSource:P}=s.useEditorActions(),{assistantProfile:A}=s.useAssistantProfile(),{messages:D,setMessages:E,sendMessage:L,isLoading:I,stop:B,status:z,llmUsage:K,errorMessage:U,clearError:R}=Un(),[_,Z]=w.useState(""),ne=J=>{Z(J.target.value)},se=J=>{J.preventDefault();const oe=_.trim();if(!oe&&O.length===0)return;const ie=[];oe&&ie.push({type:"text",text:oe}),O.forEach(De=>{De.data&&ie.push({type:"file",mediaType:De.type,filename:De.name,url:`data:${De.type};base64,${De.data}`})}),L({role:"user",parts:ie}),Z(""),k("editor"),W({force:!0})},{visibleMessages:ae,hasMoreMessages:Y,totalMessageCount:$,loadMoreMessages:H,resetMessageWindow:Q}=s.useMessageWindow(D,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:re,isAtBottom:ue,hasNewMessages:me,newMessageCount:q,scrollToBottom:W,handleScroll:te,resetNewMessageCount:he}=s.useAutoScroll(ae,{threshold:50,behavior:"smooth",isStreaming:I});w.useEffect(()=>{var J;j&&((J=r.current)==null||J.focus(),v({selectedEntities:(T==null?void 0:T.selectedEntities)||[]}))},[j,T,v]),s.useAutoSubmitQueue({assistantType:"editor",status:z,isLoading:I,sendMessage:L});const{hasActiveTools:xe}=s.useActiveToolStatus(D),le=w.useCallback(J=>{n==null||n(J),t===void 0&&p(J)},[t,n]);w.useEffect(()=>{if(!b)return;function J(oe){oe.key==="Escape"&&le(!1)}return window.addEventListener("keydown",J),()=>{window.removeEventListener("keydown",J)}},[b,le]);const V=w.useCallback(J=>{L({role:"user",parts:[{type:"text",text:J}]}),W({force:!0})},[L,W]),ee=w.useCallback(async()=>{const J=JSON.stringify(D??[],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(oe){console.error("Failed to copy conversation",oe),s.ue.error("Unable to copy conversation")}},[D]),X=w.useCallback(()=>{le(!b)},[b,le]);function je(J,oe){oe==="sql"?(y(J),f(!0)):oe==="python"&&(C(J),f(!0))}function ge(){g.selectedEntities.length===0&&v({selectedEntities:(M==null?void 0:M.selectedEntities)||[]})}function be(J){ge();const oe={role:"user",parts:[{type:"text",text:J.title+" "+J.subtitle}]};L(oe)}function ve(J){ge(),L({role:"user",parts:[{type:"text",text:J}]})}function pe(){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:c,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:o,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&&(D==null?void 0:D.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:(A==null?void 0:A.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[pe(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:ee,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:X,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:()=>{E([]),S("editor"),R(),Q()},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:()=>{F(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:re,className:"mt-2 flex w-full grow basis-0",onScroll:te,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,$-ae.length)," ","more messages (",$-ae.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:ae,showTools:i,handleRun:je,showSystemMessage:d,onQuickReply:V,disableQuickReplies:I}),!xe&&e.jsx(s.AssistantStatus,{status:z,errorMessage:U})]})}),j&&!ue&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{W({force:!0}),he()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),me&&q>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:q>9?"9+":q})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Se&&!A&&e.jsx(s.Placeholders,{onClick:be,placeholders:Kn}),e.jsx("div",{children:Se&&A&&e.jsx(s.SeedQuestions,{seedQuestions:A.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:Z,stop:B,input:_,handleInputChange:ne,handleSubmit:J=>{ge(),se(J),W({force:!0})},isLoading:I,status:z,assistantType:"editor",onFocus:()=>{}})]}),K&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",K.inputTokens," prompt tokens, ",K.outputTokens," ","completion tokens, ",K.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(T==null?void 0:T.selectedEntities)||[],open:x,onOpenChange:m,dataSource:T||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?ht.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})}),a):we}function qe(t,n){const[a,r]=w.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):n});return w.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}const _n="chart-selector-standard-first";function Hn(){const[t,n]=qe(_n,!0);return{standardFirst:t,updatePreference:n}}const ys=({pluginVisual:t,index:n,onSelect:a})=>{const r=ze(t.icon||""),l=t.name.charAt(0).toUpperCase(),c=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,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"}):c||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}-${n}`)},Ns=["default","standardPlugin","customPlugin"];function Jn({selectedChart:t,onChartChange:n}){var M;const[a,r]=w.useState(!1),{data:l}=Hs();Hn();const i=((M=s.useEditorStore(T=>T.card).customCardPreferences)==null?void 0:M.url)||"";We(i);const{setCardType:o,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(T=>T.actions),{setCardCustomCfg:x,setCustomCardPreferences:m,setQueryConfig:h}=s.useEditorActions(),[p,b]=qe("chart-section-active",null),g=w.useMemo(()=>p?[p,...Ns.filter(T=>T!==p)]:Ns,[p]);function v(T){x(null),d({}),o(T),["custom","map"].includes(T)&&(u(!0),h(void 0)),n(T),r(!1)}function S(T){x(null),d({}),o("custom"),m({type:"component",visualType:"single",url:T.url,componentName:T.name,icon:T.icon,pluginChartType:T.chartType}),h(void 0),n("custom"),r(!1)}const k=()=>{var y;if(t==="custom"){const f=s.useEditorStore.getState().card;return((y=f==null?void 0:f.customCardPreferences)==null?void 0:y.componentName)||"Custom Visual"}const T=s.chartTypes.find(f=>f.id===t);return(T==null?void 0:T.label)||"Select chart type"},O=()=>{var y,f;if(t==="custom"){const j=s.useEditorStore.getState().card,N=(y=j==null?void 0:j.customCardPreferences)==null?void 0:y.icon,F=(f=j==null?void 0:j.customCardPreferences)==null?void 0:f.componentName;if(N&&F)return e.jsx(Qn,{icon:N,componentName:F});if(F){const C=s.getAutoDetectedChartIcon(F);if(C)return C}return e.jsx(Ae,{className:"h-4 w-4"})}const T=s.chartTypes.find(j=>j.id===t);if(T){const j=T.icon;return e.jsx(j,{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:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[O(),e.jsx("span",{children:k()})]}),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."}),g.map(T=>{if(T==="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:y=>b(y?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(y=>{const f=y.icon;return e.jsx(s.CommandItem,{value:`${y.label} ${y.id} chart graph visualization`,onSelect:()=>v(y.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(f,{className:"h-4 w-4"}),e.jsx("span",{children:y.label})]})},y.id)})},"default");if(T==="standardPlugin"){const y=l.filter(f=>f.pluginType==="standard");return y.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:f=>b(f?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:y.filter(f=>f.componentType==="chart").map((f,j)=>e.jsx(ys,{pluginVisual:f,index:j,onSelect:()=>S(f)},`${f.url}-${f.name}-${j}`))},"standardPlugin"):null}if(T==="customPlugin"){const y=l.filter(f=>f.pluginType==="custom");return y.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:f=>b(f?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:y.map((f,j)=>e.jsx(ys,{pluginVisual:f,index:j,onSelect:()=>S(f)},`${f.url}-${f.name}-${j}`))},"customPlugin"):null}return null})]})]})})]})})}const Qn=({icon:t,componentName:n})=>{const a=ze(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},Wn=[{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"}];function Yn({selectedChart:t,onChartChange:n}){var l;const a=s.useEditorStore(c=>c.card),r=((l=a==null?void 0:a.config)==null?void 0:l.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Wn.map(c=>{if(c.requiresPivot&&!r)return null;const i=c.icon,o=t===c.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(c.id),className:s.cn("h-8 w-8 p-0",o&&"bg-accent text-accent-foreground"),children:[e.jsx(i,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:c.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:c.label})})]},c.id)})})}const ns=({dataType:t})=>s.getFieldIconComponent(t);function Xn({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=w.useState(t),[l,c]=w.useState(!1),i=(d=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:d[0],o=i?`e.g. Min Sales in {{${i.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:o,value:l?a:t,onChange:u=>{r(u.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),c(!1)):u.key==="Escape"&&(r(t),c(!1))},"aria-label":"Edit alias template"}),l&&a!==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:()=>{n(a),c(!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),c(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Zn({valueAliases:t,onValueAliasesChange:n}){const[a,r]=w.useState(null),[l,c]=w.useState(""),[i,o]=w.useState(""),d=()=>{n({...t,"":""})},u=m=>{const h={...t};delete h[m],n(h)},x=m=>{const h={...t};delete h[m],h[l]=i,n(h),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(([m,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:a===m?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?x(m):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:i,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?x(m):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:()=>x(m),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:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),o(h)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),o(h)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(m),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},m+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 er({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,x;return(x=(u=d.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),c=l?r.indexOf(l):-1;function i(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Xs,{idx:c,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function o(){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(Zs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&i(),["pie","doughnut"].includes(n)&&o()]})}function sr({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),c=s.useEditorStore(u=>u.card),i=c==null?void 0:c.dataSource,o=["attribute-values",t.entityName,t.name,n,a],d=s.useQuery({queryKey:o,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",x);const m=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(b=>{const g=b[h]||b[t.alias||h]||b[t.label];return{id:g||"",value:g||"",label:String(g||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.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 tr({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:c}){var O,M;const i=!!l,[o,d]=w.useState(i?"values":"fields"),[u,x]=w.useState(""),[m,h]=w.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=a.filter(T=>{var f;return i?!1:!((f=r==null?void 0:r.conditions)==null?void 0:f.some(j=>j.field.id===T.id))&&T.label.toLowerCase().includes(u.toLowerCase())}),b=T=>{h({...m,field:T}),d("values")},g=()=>{if(m.field&&m.selectedValues.length>0){const T={id:m.id,field:m.field,operator:"in",value:m.selectedValues};let y;if(i){const f=((r==null?void 0:r.conditions)||[]).map(j=>j.id===l.id?T:j);y={...r,conditions:f}}else{const f=(r==null?void 0:r.conditions)||[];y={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...f,T],groups:[]}}c(y),n(!1)}},v=()=>{if(!i||!l)return;const T=((r==null?void 0:r.conditions)||[]).filter(y=>y.id!==l.id);if(T.length>0){const y={...r,conditions:T};c(y)}else c(void 0);n(!1)},S=T=>{h({...m,selectedValues:T})},k=()=>{i&&l?(h({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(h({id:s.v4(),field:null,selectedValues:[]}),d("fields")),x("")};return w.useEffect(()=>{t&&k()},[t,i,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(O=m.field)==null?void 0:O.label}`:o==="fields"?"Select Field to Filter":`Select Values for ${(M=m.field)==null?void 0:M.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&o==="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(T=>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:[T.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(T.value)?`${T.value.length} values`:String(T.value)})]},T.id))})]}),o==="fields"&&!i?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:T=>x(T.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:p.map(T=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(T),children:[e.jsx(ns,{dataType:s.getDataType(T.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:T.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[T.entityName,".",T.name]})]})]},T.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&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(ar,{field:m.field,selectedValues:m.selectedValues,onValuesChange:S,onBack:i?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:k,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:g,disabled:!m.field||m.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function ar({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,c]=w.useState(""),{values:i,isLoading:o,isFetching:d}=sr({field:t,searchQuery:l,limit:500}),u=l?i.filter(h=>String(h.value).toLowerCase().includes(l.toLowerCase())):i,x=h=>{const p=n.includes(h);a(p?n.filter(b=>b!==h):[...n,h])},m=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(h=>h.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:h=>c(h.target.value),className:"pl-10"})]}),o||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:n.length===u.length&&u.length>0,onCheckedChange:m}),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(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(h.value),children:[e.jsx(s.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>x(h.value)}),e.jsx(ts,{className:"text-sm",children:h.label})]},h.id))})]})]})}function nr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:c=!1,cardType:i}){var ls,os,is,cs;const{attributes:o,listeners:d,setNodeRef:u,transform:x,transition:m,isDragging:h}=s.useSortable({id:t.id}),p=s.useEditorStore(G=>G.card),{updateLabel:b,handleAggregationChange:g,handleDateFormatChange:v,handleGranularityChange:S,handleAliasTemplateChange:k,handleValueAliasesChange:O,removeField:M,handleKpiComparisonTypeChange:T,handleKpiShowTrendlineChange:y,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:j,handleKpiTargetValueChange:N}=Ze(p),[F,C]=w.useState(!1),[P,A]=w.useState(!1),[D,E]=w.useState(null),[L,I]=w.useState(t.dateFormat||"YYYY-MM-DD"),[B,z]=w.useState(t.customFormat||""),[K,U]=w.useState(!!t.customFormat),[R,_]=w.useState(t.granularity||"day"),[Z,ne]=w.useState(t.aliasTemplate||""),[se,ae]=w.useState(t.valueAliases||{}),[Y,$]=w.useState((ls=t.parameters)==null?void 0:ls.filters),H=G=>{G==="custom"?U(!0):(U(!1),I(G),n==="groupBy"&&v(a,G,""))},Q=G=>{z(G),n==="groupBy"&&v(a,"custom",G)},re=G=>{var fe;_(G);const de=(fe=s.getDateFormatOptionsForGranularity(G)[0])==null?void 0:fe.value;de&&!K&&(I(de),n==="groupBy"&&v(a,de,"")),n==="groupBy"&&S(a,G)},ue=G=>{ne(G),n==="metrics"&&k(a,G)},me=G=>{ae(G),n==="metrics"&&O(a,G)},q=G=>{b(n,a,G)},W=G=>{var ce;if($(G),n==="metrics"){const de={...t,parameters:{...t.parameters,filters:G}},fe=[...((ce=p.config)==null?void 0:ce.metricColumns)||[]];fe[a]=de,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:fe})}A(!1)},te=()=>{M(n,a)},he={transform:s.CSS.Transform.toString(x),transition:m},xe=s.getDataType(t.dataType),le=xe==="date",V=i==="kpi",ee=s.getDateFormatOptionsForGranularity(R),X=n!=="pivotBy",je=le&&n==="groupBy"&&(!V||((os=p.config)==null?void 0:os.comparisonType)==="start_vs_end"),ge=!V&&le&&n==="groupBy",be=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&le&&n==="groupBy",ve=i==="kpi"&&le&&n==="groupBy",pe=i&&i!=="pivotTable"&&n==="metrics"&&((is=p.config)==null?void 0:is.comparisonType)==="target",Ee=n==="metrics",Se=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:G=>{G.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=()=>X?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:q,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:R,onValueChange:re,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(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G,children:s.toTitleCase(G)},G))})]})]}):null,oe=()=>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:K?"custom":L,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:ee.map(G=>e.jsx(s.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),K&&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:B,onChange:G=>{G.stopPropagation(),Q(G.target.value)},onClick:G=>G.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,ie=()=>{var de,fe,Ce,Me,ds;const G=be,ce=ve;return!G&&!ce?null:e.jsxs(e.Fragment,{children:[G&&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:((de=p.config)==null?void 0:de.comparisonType)||"none",onValueChange:T,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"})]})]})]}),ce&&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:((fe=p.config)==null?void 0:fe.showTrendline)||!1,onCheckedChange:y})]})}),((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:((Me=p.config)==null?void 0:Me.trendlineWindow)||30,onChange:ut=>{const mt=parseInt(ut.target.value)||30;f(mt)},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:((ds=p.config)==null?void 0:ds.trendlineGranularity)||"day",onValueChange:j,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 G,ce;return pe?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:((G=p.config)==null?void 0:G.targetValue)!==void 0&&((ce=p.config)==null?void 0:ce.targetValue)!==null?String(p.config.targetValue):"",onSave:de=>{!isNaN(Number(de))&&de!==null?N(Number(de)):N(0)},placeholder:"Enter target value...",type:"text"})]}):null},it=()=>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:G=>{g(a,G)},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(G=>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:()=>{E(G),A(!0)},children:[e.jsxs("span",{className:"font-medium",children:[G.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(G.value)?G.value.length===1?String(G.value[0]):G.value.length<=2?G.value.join(", "):`${G.value.slice(0,2).join(", ")} +${G.value.length-2}`:String(G.value)})}),Array.isArray(G.value)&&G.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 (",G.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:G.value.map((ce,de)=>e.jsx("div",{children:String(ce)},de))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ce=>{var fe;ce.stopPropagation();const de=Y.conditions.filter(Ce=>Ce.id!==G.id);if(de.length>0){const Ce={...Y,conditions:de};W(Ce)}else if($(void 0),n==="metrics"){const Ce={...t,parameters:{...t.parameters,filters:void 0}},Me=[...((fe=p.config)==null?void 0:fe.metricColumns)||[]];Me[a]=Ce,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Me})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},G.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{E(null),A(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(er,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Xn,{aliasTemplate:Z,onAliasTemplateChange:ue}),e.jsx(Zn,{valueAliases:se,onValueAliasesChange:me})]})]}):null,{columns:ct=[]}=s.useColumns(),dt=(Y==null?void 0:Y.conditions)&&Y.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:he,...o,...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 ${h?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ns,{dataType:xe}),e.jsx(ts,{className:s.cn("w-[140px] flex-1 text-sm",dt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((cs=Y==null?void 0:Y.conditions)==null?void 0:cs.length)&&!F&&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(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:G=>{G.stopPropagation(),C(!F)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${F?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:G=>{G.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ce=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ce),l(ce)},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:G=>{G.stopPropagation(),te()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),F&&e.jsxs("div",{className:"space-y-3",children:[Se(),we(),i==="kpi"&&J(),oe(),ie(),De(),it()]})]}),P&&e.jsx(tr,{open:P,onOpenChange:G=>{A(G),G||E(null)},availableFields:ct,existingFilters:Y,editingCondition:D,onSave:G=>{var ce;if(G)W(G);else if($(void 0),n==="metrics"){const de={...t,parameters:{...t.parameters,filters:void 0}},fe=[...((ce=p.config)==null?void 0:ce.metricColumns)||[]];fe[a]=de,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:fe})}E(null)}})]})}function rr({concept:t}){const n=()=>{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:n()})]})})}function Be({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:c=!1,activeField:i=null}){const{isOver:o,setNodeRef:d}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(v=>v.card),m=s.useEditorStore(v=>v.card.type),h=n.length>0,p=w.useMemo(()=>!i||!o?!0:Le(i,t,m).isValid,[i,o,t,m]),b=(v,S)=>{var O;!((O=x.config)!=null&&O.sortByColumns)||x.config.sortByColumns.findIndex(M=>M.id===v)===-1||u(x.id,v,{direction:S})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&m!=="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:a}),g&&e.jsx(rr,{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":o&&p,"border-red-500 bg-red-50 dark:bg-red-950":o&&!p,"border-muted-foreground/30 bg-muted/40":!o&&h,"min-h-[60px] border-muted-foreground/20 bg-background":!o&&!h}),children:n.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:n.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((v,S)=>{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(nr,{field:v,zone:t,index:S,sortDirection:O,onSortDirectionChange:M=>b(v.id,M),hasPivotColumns:c,cardType:m})})},v.id)})})})})]})}const Cs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],lr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Ue({value:t,onChange:n,label:a}){const[r,l]=w.useState(!1),[c,i]=w.useState(!1),o=()=>{const d=Cs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Cs[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:o()},"aria-label":`Change color for ${a}`})}),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:lr.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",o()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{n(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:()=>{i(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&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:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(et,{color:o(),onColorChange:d=>{n(d),i(!1)},onClose:()=>i(!1)})})]})]})}const Ss={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 or(){var h,p,b,g,v,S,k,O,M,T,y;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((h=t.config)==null?void 0:h.metricColumns)||[],r=((p=t.config)==null?void 0:p.groupByColumns)||[],l=a.length===2&&r.length===0,c=a.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||c)))return null;const o=((g=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:g.metricComparison)||{},d=f=>{var N;const j={...t.preferences,kpiVisualOptions:{...(N=t.preferences)==null?void 0:N.kpiVisualOptions,metricComparison:{...o,...f}}};n(j)},u=c||o.enabled,x=((v=t.config)==null?void 0:v.comparisonType)||"none",m=x==="previous_period"||x==="same_period_last_year"||x==="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(kt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&a.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:o.enabled||!1,onCheckedChange:f=>d({enabled:f,...f&&!o.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=o.calculationType||"difference",j=Ss[f];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:j==null?void 0:j.label}),e.jsx("p",{children:j==null?void 0:j.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:j==null?void 0:j.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",j==null?void 0:j.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.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(Ss).map(([f,j])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:j.label},f))})]})]}),e.jsx(as,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>d({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),(m||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:o.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:o.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:o.showColor!==!1,onCheckedChange:f=>d({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Ue,{value:((S=o.colorConfig)==null?void 0:S.increase)||"green",onChange:f=>d({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(Ue,{value:((k=o.colorConfig)==null?void 0:k.decrease)||"red",onChange:f=>d({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(Ue,{value:((O=o.colorConfig)==null?void 0:O.noChange)||"neutral",onChange:f=>d({colorConfig:{...o.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:o.conditionalLabel||!1,onCheckedChange:f=>d({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.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:((M=o.conditionalLabels)==null?void 0:M.increase)??"Increase",onChange:f=>d({conditionalLabels:{...o.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:((T=o.conditionalLabels)==null?void 0:T.decrease)??"Decrease",onChange:f=>d({conditionalLabels:{...o.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:((y=o.conditionalLabels)==null?void 0:y.noChange)??"No change",onChange:f=>d({conditionalLabels:{...o.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:o.labelName??"",onChange:f=>d({labelName:f.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function ir(){var l,c;const t=s.useEditorStore(i=>i.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((c=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:c.formatOptions)||{},r=i=>{var d;const o={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:i}};n(o)};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(as,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function cr({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,activeField:l}){const c=s.useEditorStore(v=>{var S;return((S=v.card.customCardPreferences)==null?void 0:S.url)&&v.card.type==="custom"}),i=s.useEditorStore(v=>v.card),o=i==null?void 0:i.type,d=t.length>0||a.length>0,u=o!=="kpi"||a.length<=2,x=o!=="kpi",m=o!=="kpi"&&d,h=["pie","doughnut","polar","funnel","aggregateTable"].includes(o),p=x&&!h,b=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>o==="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(Be,{zone:"groupBy",fields:t,label:b().label,placeholder:b().placeholder,activeField:l}),p&&e.jsx(Be,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Be,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0,activeField:l}),m&&e.jsx(Be,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&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(ir,{}),e.jsx(or,{}),e.jsx(st,{}),e.jsx(tt,{}),e.jsx(at,{}),e.jsx(nt,{})]})})]})]})}function dr({onEditJoins:t}){const n=s.useEditorStore(o=>o.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const c=o=>!o||o.length===0?"No conditions":o.map(d=>{var h,p,b,g;const u=`${(h=d.source)==null?void 0:h.entityName}.${(p=d.source)==null?void 0:p.name}`,x=`${(b=d.target)==null?void 0:b.entityName}.${(g=d.target)==null?void 0:g.name}`,m=d.operator||"=";return`${u} ${m} ${x}`}).join(" AND "),i=o=>!o.joinKeyGroups||o.joinKeyGroups.length===0?"No conditions defined":o.joinKeyGroups.length===1?c(o.joinKeyGroups[0].keys):o.joinKeyGroups.map((d,u)=>({id:u,operator:d.operator,condition:c(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(Jt,{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((o,d)=>{const u=i(o),x=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:o.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:o.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:o.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(m=>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:m.condition}),m.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",m.operator,")"]})]},m.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})})})]},o.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 ws={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function ur({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:i}){var f,j;const[o,d]=w.useState(()=>ws.getItem("chart-selector-expanded")==="true"),[u,x]=w.useState(!1),m=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.actions.updateCardConfig),p=a.length>0||r.length>0||l.length>0,{data:b,autoJoinMetadata:g}=s.useDashboardCardQuery(m),v=((f=m==null?void 0:m.config)==null?void 0:f.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),S=((j=m==null?void 0:m.dataSource)==null?void 0:j.selectedEntities)||[],k=N=>{h(m.id,{...m==null?void 0:m.config,joinPlan:N}),x(!1)},O=()=>{h(m.id,{...m==null?void 0:m.config,joinPlan:void 0}),x(!1)},M=()=>{x(!1)},T=()=>{x(!0)};w.useEffect(()=>{ws.setItem("chart-selector-expanded",String(o))},[o]);const y=()=>{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":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(Jn,{selectedChart:t,onChartChange:n})}),e.jsxs("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center gap-1",children:[e.jsx(Yn,{selectedChart:t,onChartChange:n}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:y,className:"h-8 w-8 p-0","aria-label":o?"Hide all charts":"Show all charts",children:o?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:o?"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(Ye,{})})}),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(dr,{onEditJoins:T}),e.jsx(cr,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Je,{open:u,onOpenChange:x,joinPlan:v,availableDataSources:S,onSave:k,onCancel:M,onRemove:O,children:e.jsx("div",{})})]})}function mr({initialFilters:t,availableFields:n}={}){const[a,r]=w.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(T=>T.card.dataSource);const{columns:l,isLoading:c}=s.useColumns(),o=n||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=T=>{const y=f=>{if(f.id===T){const j=o[0]||d,N=s.getDataType(j.dataType)==="date";return{...f,conditions:[...f.conditions,{id:`condition-${Date.now()}`,field:j,operator:N?"between":"=",value:N?[]:""}]}}return{...f,groups:f.groups.map(y)}};r(y(a))},x=T=>{const y=f=>{if(f.id===T){const j=o[0]||d,N=s.getDataType(j.dataType)==="date";return{...f,groups:[...f.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:j,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...f,groups:f.groups.map(y)}};r(y(a))},m=(T,y)=>{const f=j=>j.id===T?{...j,conditions:j.conditions.filter(N=>N.id!==y)}:{...j,groups:j.groups.map(f)};r(f(a))},h=(T,y)=>{const f=j=>j.id===T?{...j,groups:j.groups.filter(N=>N.id!==y)}:{...j,groups:j.groups.map(f)};r(f(a))},p=(T,y,f,j)=>{if(f==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=F=>F.id===T?{...F,conditions:F.conditions.map(C=>C.id===y?{...C,[f]:j}:C)}:{...F,groups:F.groups.map(N)};r(N(a))},b=(T,y,f)=>{const j=N=>N.id===T?{...N,conditions:N.conditions.map(F=>F.id===y?{...F,...f}:F)}:{...N,groups:N.groups.map(j)};r(j(a))},g=(T,y)=>{const f=j=>j.id===T?{...j,logicalOperator:y}:{...j,groups:j.groups.map(f)};r(f(a))},v=(T,y)=>{const f=j=>j.id===T?{...j,negate:y}:{...j,groups:j.groups.map(f)};r(f(a))},S=(T,y,f)=>{const j=N=>N.id===T?{...N,conditions:s.arrayMove(N.conditions,y,f)}:{...N,groups:N.groups.map(j)};r(j(a))},k=(T,y,f)=>{const j=N=>N.id===T?{...N,groups:s.arrayMove(N.groups,y,f)}:{...N,groups:N.groups.map(j)};r(j(a))},O=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const y=j=>{let N="";typeof j.field=="object"?N=j.field.entityName?`${j.field.entityName}.${j.field.name}`:j.field.name:N=String(j.field);const F=j.operator;let C=j.value;if(j.field.dataType==="string"&&!["in","not in"].includes(j.operator))typeof C=="string"?C=`'${C}'`:Array.isArray(C)&&(C=`'${C.join(", ")}'`);else if(j.field.dataType==="date"||j.field.dataType==="datetime"||j.field.dataType==="timestamp")if(j.operator==="between"&&Array.isArray(C)&&C.length===2){const P=C[0]?`'${C[0]}'`:"NULL",A=C[1]?`'${C[1]}'`:"NULL";return`${N} BETWEEN ${P} AND ${A}`}else if((j.operator==="in"||j.operator==="not in")&&Array.isArray(C)){const P=C.map(A=>A?`'${A}'`:"NULL").join(", ");return`${N} ${F} (${P})`}else typeof C=="string"||C instanceof Date?C=`'${C}'`:Array.isArray(C)&&C.length>0&&(C=`'${C[0]}'`);else if(["in","not in"].includes(j.operator)){let P=[];Array.isArray(C)?P=C.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof C=="string"?P=C.split(",").map(A=>{const D=A.trim();return j.field.dataType==="string"?`'${D}'`:D}):typeof C=="number"&&(P=[String(C)]),C=`(${P.join(", ")})`}switch(F){case"contains":return typeof C=="string"?`${N} LIKE '%${C.replace(/'/g,"")}'`:`${N} LIKE '%${String(C)}'`;case"startsWith":return typeof C=="string"?`${N} LIKE '${C.replace(/'/g,"")}%'`:`${N} LIKE '${String(C)}%'`;case"endsWith":return typeof C=="string"?`${N} LIKE '%${C.replace(/'/g,"")}'`:`${N} LIKE '%${String(C)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${F} ${C}`}},f=j=>{const N=j.conditions.map(y),F=j.groups.map(D=>f(D)),C=[...N,...F].filter(Boolean);if(C.length===0)return"";const P=C.join(` ${j.logicalOperator} `),A=C.length>1?`(${P})`:P;return j.negate?`NOT ${A}`:A};return f(T)},M=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:o,isLoading:c,addCondition:u,addGroup:x,removeCondition:m,removeGroup:h,updateCondition:p,updateConditionFields:b,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:S,reorderGroups:k,generateSQLPreview:O,hasAnyFilters:M}}function hr({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const xr=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"})}},pr=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function fr({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[c,i]=w.useState(!1),o=w.useMemo(()=>{const d={};return a.forEach(u=>{const x=pr(u);d[x]||(d[x]={}),d[x][u.entityId]||(d[x][u.entityId]=[]),d[x][u.entityId].push(u)}),d},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(hr,{children:[t.entityName,".",t.name]})}):r,e.jsx(gt,{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(o).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(([x,m])=>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:[xr(m[0].entityType),e.jsx("span",{children:m[0].entityName})]}),m.map((h,p)=>e.jsxs(s.CommandItem,{value:h.id,onSelect:()=>{n(h),i(!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)===h.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:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+p))]},`${d}-${x}`))},d))})]})})]})}function rs(t){var g;const n=s.useEditorStore(v=>v.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(v=>v.card.config),c=l==null?void 0:l.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},o={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...i,role:"sortby",direction:"asc"},u={joinPlan:c,groupByColumns:[i],metricColumns:[o],sortByColumns:[d]},x=((g=n.dataSource)==null?void 0:g.connectionId)||n.connectionId,{data:m,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:n.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:h,error:p}}function gr({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[c,i]=Ke.useState(!1),{filterValues:o}=rs(t),d=x=>{a(n.filter(m=>m!==x))},u=x=>{n.includes(x)?a(n.filter(m=>m!==x)):a([...n,x])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:c,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,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:n.length>0?n.map(x=>{const m=o.find(h=>h.value===x);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.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:h=>{h.key==="Enter"&&d(x)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),d(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):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:o.map((x,m)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+m))})]})]})})]})})}function jr({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:c,isPending:i,error:o}=rs(t);return i?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..."]}):o?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:c.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function br({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),c=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,i=w.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,n]),o=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),a([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),a([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:o,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const vr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],yr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Nr=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Cr=["=","!=","isNull","isNotNull"],Sr=["between","isNull","isNotNull"],wr={"=":"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 Ds(t){return wr[t]||s.titleCase(t)}function Dr(t){switch(t){case"string":return yr;case"number":return Nr;case"boolean":return Cr;case"date":return Sr;default:return vr}}function rt({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:c,onUpdateGroupOperator:i,availableFields:o,updateConditionFields:d}){const{attributes:u,listeners:x,setNodeRef:m,transform:h,transition:p,isDragging:b}=s.useSortable({id:t.id}),{isPending:g,error:v}=rs(t.field),S={transform:s.CSS.Transform.toString(h),transition:p};return e.jsxs("div",{ref:m,style:S,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,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:k=>i(a,k),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"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(fr,{value:t.field,onValueChange:k=>{const O=k,M=s.getDataType(O.dataType)==="date";d(a,t.id,{field:O,value:"",operator:M?"between":"="})},availableFields:o,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:k=>{k==="in"||k==="not in"?d(a,t.id,{operator:k,value:[]}):k==="isNull"||k==="isNotNull"?d(a,t.id,{operator:k,value:null}):d(a,t.id,{operator:k,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Ds(t.operator):""})}),e.jsx(s.SelectContent,{children:Dr(s.getDataType(t.field.dataType)).map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k,children:Ds(k)},k))})]}),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"?g?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(gr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(k=>typeof k=="string")?t.value:[],onChange:k=>d(a,t.id,{value:k}),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:k=>d(a,t.id,{value:k.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(jr,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:k=>d(a,t.id,{value:k}),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:k=>d(a,t.id,{value:k==="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(br,{value:t.value,operator:t.operator,onChange:k=>d(a,t.id,{value:k}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:k=>l(a,t.id,"value",k.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:()=>c(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function kr({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:c,onUpdateCondition:i,onUpdateField:o,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:x,onAddCondition:m,onAddGroup:h,availableFields:p,renderFilterGroup:b,updateConditionFields:g}){const{attributes:v,listeners:S,setNodeRef:k,transform:O,transition:M,isDragging:T}=s.useSortable({id:t.id}),y={transform:s.CSS.Transform.toString(O),transition:M},f=N=>{const{active:F,over:C}=N;if(C&&F.id!==C.id){const P=t.conditions.findIndex(D=>D.id===F.id),A=t.conditions.findIndex(D=>D.id===C.id);P!==-1&&A!==-1&&u(t.id,P,A)}},j=N=>{const{active:F,over:C}=N;if(C&&F.id!==C.id&&a){const P=t.groups.findIndex(D=>D.id===F.id),A=t.groups.findIndex(D=>D.id===C.id);P!==-1&&A!==-1&&x(a,P,A)}};return e.jsxs("div",{ref:k,style:y,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${T?"z-50 opacity-50":""}`,children:[n>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,...S,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:()=>a&&c(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>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,F)=>e.jsx(rt,{condition:N,index:F,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:o,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:g},N.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:j,children:e.jsx(s.SortableContext,{items:t.groups.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(N=>b(N,n+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:()=>m(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:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Tr({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:c,availableFields:i,isLoading:o,addCondition:d,addGroup:u,removeCondition:x,removeGroup:m,updateCondition:h,updateConditionFields:p,updateGroupOperator:b,updateGroupNegate:g,reorderConditions:v,reorderGroups:S,generateSQLPreview:k,hasAnyFilters:O,setCurrentFilters:M}=mr({initialFilters:t,availableFields:n}),T=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[y,f]=w.useState(!1),j=(C,P,A)=>{const D=E=>E.id===C?{...E,conditions:E.conditions.map(L=>L.id===P?{...L,field:A,dataType:A.dataType}:L)}:{...E,groups:E.groups.map(D)};M(D(c))},N=(C,P=0,A)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:E,over:L}=D;if(L&&E.id!==L.id){const I=C.conditions.findIndex(z=>z.id===E.id),B=C.conditions.findIndex(z=>z.id===L.id);I!==-1&&B!==-1&&v(C.id,I,B)}},children:e.jsx(s.SortableContext,{items:C.conditions.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:C.conditions.map((D,E)=>e.jsx(rt,{condition:D,index:E,groupId:C.id,groupLogicalOperator:C.logicalOperator,onUpdateCondition:h,onUpdateField:j,onRemoveCondition:x,onUpdateGroupOperator:b,availableFields:i,updateConditionFields:p},D.id))})}),e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:E,over:L}=D;if(L&&E.id!==L.id){const I=C.groups.findIndex(z=>z.id===E.id),B=C.groups.findIndex(z=>z.id===L.id);I!==-1&&B!==-1&&S(C.id,I,B)}},children:e.jsx(s.SortableContext,{items:C.groups.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:C.groups.map(D=>N(D,P+1,C.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(C.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),y&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(C.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},C.id):e.jsx(kr,{group:C,depth:P,parentGroupId:A,onUpdateGroupOperator:b,onUpdateGroupNegate:g,onRemoveGroup:m,onUpdateCondition:h,onUpdateField:j,onRemoveCondition:x,onReorderConditions:v,onReorderGroups:S,onAddCondition:d,onAddGroup:u,availableFields:i,renderFilterGroup:N,updateConditionFields:p},C.id),F=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:[o?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(c),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:y,onCheckedChange:C=>f(C)}),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:k(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),F>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(O?c:null),children:"Apply Filters"})]})]})}function Er({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:c,onOpenChange:i}){const o=u=>{a(t,u),i(!1)},d=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:i,children:[c&&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(Tr,{filters:n,availableFields:l,onSave:o,onCancel:()=>i(!1),onClearAll:d})]})]})}function Ir({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var v,S;const[l,c]=w.useState(null),i=s.useEditorStore(k=>k.card),o=s.useEditorStore(k=>k.actions.updateCardConfig),d=(v=i==null?void 0:i.config)==null?void 0:v.joinPlan,u=(S=i==null?void 0:i.dataSource)==null?void 0:S.semanticDomainId,{data:x}=Xe(u),m=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],h=w.useCallback(k=>k.startsWith("card-")?null:k.startsWith("source-")||n.find(O=>O.id===k)?"source":a("groupBy").find(O=>O.id===k)?"groupBy":a("metrics").find(O=>O.id===k)?"metrics":a("pivotBy").find(O=>O.id===k)?"pivotBy":a("sortBy").find(O=>O.id===k)?"sortBy":null,[n,a]),p=w.useCallback(k=>{c(k.active.id)},[]),b=w.useCallback(k=>{var N;const{active:O,over:M}=k;if(!M||!t){c(null);return}const T=O.id,y=M.id,f=h(T),j=h(y)||y;if(j==="sortBy"){if(f==="source"){const F=n.find(P=>P.id===T);if(!F){c(null);return}if(!(a("groupBy").some(P=>P.name===F.name&&P.qualifiedEntityName===F.qualifiedEntityName)||a("metrics").some(P=>P.name===F.name&&P.qualifiedEntityName===F.qualifiedEntityName))){c(null);return}}else if(f==="pivotBy"){c(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"){c(null);return}}if(f==="source"&&j==="sortBy"){const F=[...n].find(D=>D.id===T);if(!F){c(null);return}const C=a("sortBy");if(s.fieldAlreadyExists(F,C)){c(null);return}const P=Le(F,"sortBy",i.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),c(null);return}const A=s.getNewField(F,"sortBy",C);c(null),r("sortBy",[...C,A]);return}if(f==="source"&&j!=="source"&&j!=="sortBy"){const F=[...n].find(L=>L.id===T);if(!F){c(null);return}const C=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(C.length>0){const L=C[0].qualifiedEntityName;if(!L){c(null);return}if(L!==F.qualifiedEntityName&&F.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(F,{joinabilityMap:x.joinabilityMap,selectedFields:C,baseEntityName:(N=d==null?void 0:d.baseEntity)==null?void 0:N.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!d){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(L,F.qualifiedEntityName,d)){s.showJoinRequiredNotification(),c(null);return}}}const P=a(j);if(s.fieldAlreadyExists(F,P)){c(null);return}const A=Le(F,j,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),c(null);return}const D=s.getNewField(F,j,P),E=[...P,D];c(null),r(j,E),j==="metrics"&&t&&He(i.type,i.config,o,t,E);return}if(f&&j&&f!=="source"&&j!=="source"&&f!==j){const F=a(f),C=a(j),P=F.find(I=>I.id===T);if(!P){c(null);return}const A=Le(P,j,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),c(null);return}const D=s.getNewField(P,j,C);if(c(null),j==="sortBy"){s.fieldAlreadyExists(P,C)||r(j,[...C,D]);return}const E=F.filter(I=>I.id!==T),L=[...C,D];r(f,E),r(j,L),j==="metrics"&&t&&He(i.type,i.config,o,t,L);return}if(f&&j&&f===j&&f!=="source"){const F=a(f),C=F.findIndex(A=>A.id===T),P=F.findIndex(A=>A.id===y);if(C!==P){const A=s.arrayMove(F,C,P);r(f,A)}}c(null)},[t,n,a,r,h,d,u,x,i.type,o,i.config]),g=l?m.find(k=>k.id===l):null;return{activeId:l,activeField:g,handleDragStart:p,handleDragEnd:b}}function Ar({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(d=>d.card),{config:l}=w.useContext(s.SemaphorContext).tokenProps,c=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:i}=s.useDashboardCardQuery(r),o=()=>!a&&r.type!=="table";return e.jsx(s.Tabs,{value:t,onValueChange:d=>n(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"}),o()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&c&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",i&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:i?"Error":"Info"})]})})}const Fr=[{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 Mr(){var d,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=w.useState(!1),[l,c]=w.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),n(t.id,parseInt(x))},o=x=>{const m=x.target.value;c(m),m&&!isNaN(parseInt(m))&&n(t.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:l,onChange:o,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:i,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:Fr.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Lr({card:t,queryData:n,isLoading:a,isFetching:r,pagination:l,onPaginationChange:c,onSortChange:i,sortState:o,splitViewEnabled:d}){return!d||t.type==="table"?e.jsx(Qe,{}):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(Qe,{})}),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:(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:(n==null?void 0:n.records)||[],paginationMetadata:l,onPaginationChange:c,isLoading:a||r,onSortChange:i,sortState:o})})})]})}const Pr="semaphor-split-view-enabled";function Or(){return qe(Pr,!0)}function Br({isOpen:t,onClose:n}){const a=As(n,{enabled:t}),r=s.useEditorStore(x=>{var m;return((m=x.card.customCardPreferences)==null?void 0:m.url)||""}),l=s.useEditorStore(x=>x.card),c=s.useEditorStore(x=>{var m;return((m=x.card.customCardPreferences)==null?void 0:m.pluginChartType)||""}),i=s.useEditorStore(x=>{var m;return((m=x.card.customCardPreferences)==null?void 0:m.settings)||{}}),{data:o}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=w.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:a,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:n,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(w.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(o==null?void 0:o.records)||[],chartType:c,settings:i})})})]})})}function Vr({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,activeCard:c,columns:i,columnsLoading:o,columnsError:d}){var ae,Y,$;const u=s.useEditorStore(H=>H.card),x=s.useDashboardStore(H=>H.filterValues),{updateCardConfig:m,setCard:h,updateCardInFrame:p,setShowAIDialog:b}=s.useEditorActions(),g=s.useEditorStore(H=>H.showAIDialog),v=s.useDashboardStore(H=>H.isVisualEditing),[S,k]=w.useState(!1),[O,M]=w.useState(!1),[T,y]=w.useState(null),{config:f}=w.useContext(s.SemaphorContext).tokenProps,j=(f==null?void 0:f.showInfoTab)!==!1,[N,F]=Or(),C=s.useEditorStore(H=>{var Q;return((Q=H.card.customCardPreferences)==null?void 0:Q.url)&&H.card.type==="custom"}),{data:P,errorMessage:A,isLoading:D,isFetching:E,errorSql:L,pagination:I,refetch:B,comparisonMetadata:z}=s.useDashboardCardQuery(c),[K,U]=w.useState(!1);w.useEffect(()=>{E||U(!1)},[E]);const R=()=>{const H=!N;H&&t==="table"&&n("chart"),F(H)},_=(H,Q)=>{const re={...c,paginationConfig:{page:H+1,pageSize:Q}};h(re),p(re)};function Z(){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(x||{},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(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:o?"Loading...":d?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const ne=H=>{if(!u.config)return;if(!H.length){m(u.id,{...u.config,sortByColumns:[]});return}const Q=u.config,re=H.map(({id:ue,desc:me})=>{var he,xe;const q=(he=Q.metricColumns)==null?void 0:he.find(le=>le.label===ue),W=(xe=Q.groupByColumns)==null?void 0:xe.find(le=>le.label===ue),te=q||W;return te?{id:s.getFieldId("sortBy",te),name:te.name,dataType:te.dataType,label:te.label,qualifiedEntityName:te.qualifiedEntityName,entityId:te.entityId,entityName:te.entityName,entityType:te.entityType,role:"sortby",direction:me?"desc":"asc"}:null}).filter(ue=>ue!==null);m(u.id,{...Q,sortByColumns:re})},se=w.useMemo(()=>{var H,Q;return(Q=(H=u.config)==null?void 0:H.sortByColumns)==null?void 0:Q.map(re=>({id:re.label,desc:re.direction==="desc"}))},[(ae=u.config)==null?void 0:ae.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":g&&v}),children:[a&&Z(),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"&&g&&e.jsx(Js,{variant:"outline"}),e.jsx(Ar,{activeView:t,onViewChange:n,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:(Y=c.config)==null?void 0:Y.filters,cardFilterCount:s.getFilterCount((($=c.config)==null?void 0:$.filters)||null),onFiltersClick:l}),z&&e.jsx(s.ComparisonMetadataBadge,{metadata:z,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Mr,{})}),g&&e.jsx(Ye,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:D||E,onClick:()=>{U(!0),B()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":K})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:R,children:N?e.jsx(Dt,{className:"size-4"}):e.jsx($t,{className:"size-4"})}),t==="chart"&&e.jsx(Qs,{}),!g&&e.jsx(s.IconButton,{onClick:()=>b(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!S&&C&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>k(!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&&c.type!=="table"}),children:e.jsx(Lr,{card:c,queryData:P,isLoading:D,isFetching:E,pagination:I,onPaginationChange:_,onSortChange:ne,sortState:se,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:c,data:(P==null?void 0:P.records)||[],paginationMetadata:I,onPaginationChange:_,isLoading:D||E,onSortChange:ne,sortState:se})}),t==="info"&&j&&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:A?e.jsx(ss,{error:A,errorSql:L,onSendFeedback:()=>{const H=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:c.dataSource,dashboardFilters:x,errorMessage:A,errorSql:L,generatedSql:P==null?void 0:P.sql});y(H),M(!0)},onOpenInEditor:()=>{b(!0),setTimeout(()=>{const H=s.useEditorStore.getState().actions;H.setIsDevMode(!0),H.setCardSql(L||""),setTimeout(()=>{H.setRunSql(!0)},100)},100)}}):e.jsx(Gs,{sql:P==null?void 0:P.sql,error:A,errorSql:L})})})]}),e.jsx(Br,{isOpen:S,onClose:()=>k(!1)}),T&&e.jsx(s.FeedbackDialog,{open:O,onOpenChange:M,feedbackData:T})]})]})}function Rr({activeField:t}){const[n,a]=w.useState(!0);return w.useEffect(()=>{t&&a(!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 ${n?"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(ns,{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 zr=()=>{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 n=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},a=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",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function qr(){var z,K;const[t,n]=w.useState("chart"),[a,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(!0),d=s.useEditorStore(U=>U.showAIDialog),u=s.useDashboardStore(U=>U.isVisualEditing),{setCardType:x}=s.useEditorActions(),m=s.useEditorStore(U=>U.card.type);w.useEffect(()=>zr(),[]);const h=U=>{x(U)},p=s.useEditorStore(U=>U.frame),b=s.useEditorStore(U=>U.card);s.useEditorStore(U=>U.activeTabCardId),s.useEditorStore(U=>U.actions.getAvailableFields);const{addCard:g,removeCard:v,updateCard:S,setActiveCard:k,updateFilters:O}=s.useEditorActions(),{columns:M=[],isLoading:T,error:y}=s.useColumns(),f=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),j=b,{getFieldsForContainer:N,setFieldsForContainer:F}=Ze(j),{activeField:C,handleDragStart:P,handleDragEnd:A}=Ir({activeCardId:p.activeCardId,sourceFields:M,getFieldsForContainer:N,setFieldsForContainer:F}),D=(U,R)=>{R&&O(U,R)},E=U=>{var R;S(U,{config:{...(R=p.cards.find(_=>_.id===U))==null?void 0:R.config,filters:void 0}})},L=M,I=U=>{if(!U)return 0;let R=U.conditions.length;return U.groups.forEach(_=>{R+=I(_)}),R},B=I(((z=j==null?void 0:j.config)==null?void 0:z.filters)||null);return e.jsxs(s.DndContext,{sensors:f,collisionDetection:s.closestCenter,onDragStart:P,onDragEnd:A,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx($s,{isVisible:i,onToggleVisibility:()=>o(!i)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(ur,{selectedChart:m,onChartChange:h,groupByFields:N("groupBy"),pivotByFields:N("pivotBy"),metricsFields:N("metrics"),sortByFields:N("sortBy"),activeField:C}),e.jsx(Vr,{selectedChart:m,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:B,activeCard:j,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:M,columnsLoading:T,columnsError:y,getFieldsForContainer:N,cards:p.cards,activeCardId:p.activeCardId,addCard:g,setActiveCard:k})]}),!i&&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:()=>o(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),j&&e.jsx(Er,{cardId:j.id,filters:((K=j.config)==null?void 0:K.filters)||null,onFiltersChange:D,onClearFilters:E,availableFields:L,isOpen:l,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Rr,{activeField:C||null})})]})}function $r({authToken:t,onSave:n,onClose:a}){const r=w.useRef(null),l=s.useEditorStore(y=>y.showAIDialog),c=s.useEditorStore(y=>y.isDevMode),i=s.useAssistantLayoutStore(y=>y.setFullscreen),o=s.useAssistantLayoutStore(y=>y.setPanelOpen),d=s.useAssistantLayoutStore(y=>y.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),m=s.useAssistantContainer("editor"),h=x==="editor",p=w.useCallback(y=>{d("editor",y)},[d]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:g,setOnSave:v,setOnClose:S}=s.useEditorActions(),{setActiveAssistantType:k}=s.useAIActions();w.useEffect(()=>{n&&v(n),a&&S(a)},[n,v,a,S]),w.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),w.useEffect(()=>{var y,f;l?((y=r.current)==null||y.resize(40),o("editor",!0),k("editor")):((f=r.current)==null||f.resize(0),o("editor",!1),x==="editor"&&i(null),k(null))},[l,o,k,i,x]);function O(y){y<1?(g(!1),o("editor",!1),x==="editor"&&i(null),k(null)):(l||(g(!0),k("editor")),u.isOpen||o("editor",!0))}function M(){return e.jsxs(e.Fragment,{children:[e.jsx($s,{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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Gn,{})}),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(vs,{isFullscreen:h,onFullscreenChange:y=>i(y?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function T(){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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(qr,{})}),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(vs,{isFullscreen:h,onFullscreenChange:y=>i(y?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:M()}):T()})}function Gr(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(i=>i.actions),a=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function l(i){t&&(r(t,i),n(!1))}function c(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx($r,{onSave:l,onClose:c})})}function Ur(){qs();const t=s.useDashboardStore(d=>d.selectedSheetId),n=s.useDashboardStore(d=>d.selectedFrameId),a=s.useDashboardStore(d=>d.dashboard),r=s.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:c}=s.useEditorActions(),i=s.useEditorStore(d=>d.card.dataSource);return w.useEffect(()=>{var u,x;let d=r();if(!d){const m=(u=a==null?void 0:a.sheets)==null?void 0:u.find(p=>p.id===t),h=(x=m==null?void 0:m.frames)==null?void 0:x[0];h&&(l(h.id),d=h)}if(d){const m=d.cards.find(h=>h.id===d.activeCardId);m&&c(m)}},[r,t,n,a,l,c]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function Kr(){const t=s.useDashboardStore(a=>a.actions.setShowFilters),{hasEntities:n}=Ur();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,{})})]}),!n&&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"})]}),n&&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(zs,{context:"filter"})})})})]})}function _r(){const t=s.useDashboardStore(r=>r.dashboard.filters),n=s.useDashboardStore(r=>r.theme),a=t==null?void 0:t.filter(r=>r.hide);return a!=null&&a.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)]":n==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":n==="dark"}),children:a==null?void 0:a.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 Hr(){const t=s.useDashboardStore(r=>r.showFilters),n=s.useDashboardStore(r=>r.isVisualEditing),a=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":n,"flex grow overflow-auto":!n}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[a&&e.jsx(_r,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Kr,{})})]})}function Jr(){const t=s.useDashboardStore(l=>l.dashboard),n=s.useDashboardStore(l=>l.actions.setDashboard),a=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!a}),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),n(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 lt(){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,n)=>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"})]})]},n))})]})})}const Qr=t=>{const n=s.useDashboardStore(l=>l.isVisualEditing),a=s.useDashboardStore(l=>l.selectedFrameId),r=s.useEditorStore(l=>l.frame);return!!(n&&a&&(r==null?void 0:r.visualId)===t)};function Wr({visual:t,isDeleting:n,isDuplicating:a,onAddVisual:r,onOpenVisual:l,onEditDetails:c,onDeleteClick:i,onDuplicateVisual:o,onShareVisual:d,formatDate:u}){var T,y,f,j;const{selectVisual:x}=s.useManagementActions(),m=s.useIsVisualSelected(t.id),h=Qr(t.id),{isConsoleMode:p}=s.useDashboardPreferences(),b=w.useRef(null),[g,v]=w.useState(!1),[S,k]=w.useState(!1);w.useEffect(()=>{a?(v(!0),k(!0)):S&&(v(!1),k(!1))},[a,S]),w.useEffect(()=>{h&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[h]);const O=()=>e.jsx(Re,{className:"h-4 w-4"}),M=()=>{x(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",h?"border-purple-500":m&&"border-primary"),onClick:M,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:(T=t.description)!=null&&T.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",m&&"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(),c==null||c(t)},title:"Edit details",children:e.jsx(s.PenLine,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,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(wt,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),o(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),c==null||c(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(),i(t)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"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:[(((y=t.ownership.createdBy)==null?void 0:y.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:((j=t.ownership.createdBy)==null?void 0:j.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 Yr({open:t,onOpenChange:n,onSubmit:a,isCreating:r}){const[l,c]=w.useState(""),[i,o]=w.useState("");w.useEffect(()=>{t||(c(""),o(""))},[t]);const d=()=>{l.trim()&&a({title:l,description:i})},u=x=>{n(x)};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:x=>c(x.target.value),disabled:r,onKeyDown:x=>{x.key==="Enter"&&!x.shiftKey&&(x.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:i,onChange:x=>o(x.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 Xr(){const[t,n]=w.useState(""),[a,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(null),[d,u]=w.useState(!1),[x,m]=w.useState(null),[h,p]=w.useState(null),[b,g]=w.useState(null),{selectVisual:v}=s.useManagementActions(),{handleEditLibraryVisual:S,handleAddLibraryVisual:k}=ke(),{resources:O,isLoading:M,isError:T,createResource:y,updateResource:f,deleteResource:j,duplicateResource:N,isCreating:F,isDeleting:C}=s.useVisualManagement(()=>{u(!1),m(null)},$=>{r(!1),$&&(v($),S($))});s.useCurrentUserInfo();const P=O.filter($=>{var H,Q;return((H=$==null?void 0:$.title)==null?void 0:H.toLowerCase().includes(t.toLowerCase()))||((Q=$==null?void 0:$.description)==null?void 0:Q.toLowerCase().includes(t.toLowerCase()))}),A=$=>new Date($).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),D=$=>{y({title:$.title,description:$.description,isPrivate:!1})},E=$=>{m($),u(!0)},L=()=>{x&&j(x.id)},{startUpdating:I,stopUpdating:B,isUpdating:z}=s.useResourceUpdateState(),K=($,H,Q)=>{var q;const re=Object.fromEntries(Object.entries(H).filter(([,W])=>W!==void 0));if(Object.keys(re).length===0){(q=Q==null?void 0:Q.onSuccess)==null||q.call(Q);return}const ue=Object.keys(re),me=ue.length===1?ue[0]:void 0;I($,me),f({resourceId:$,data:re},{onSuccess:()=>{var W;B($,me),(W=Q==null?void 0:Q.onSuccess)==null||W.call(Q)},onError:()=>{var W;B($,me),(W=Q==null?void 0:Q.onError)==null||W.call(Q)}})},U=$=>{p($),N($,{onSettled:()=>p(null)})},R=$=>{S($)},_=$=>{k($)},Z=$=>{const H=O.find(Q=>Q.id===$);H&&f({resourceId:$,data:{isPrivate:!H.isPrivate}})},ne=$=>{o($),c(!0)},se=$=>{g($)},ae=()=>{g(null)},Y=({title:$,description:H})=>{if(!b)return;const Q={};$!==b.title&&(Q.title=$),(b.description||"")!==H&&(Q.description=H),K(b.id,Q,{onSuccess:()=>{g(null)}})};return M?e.jsx(lt,{}):T?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:$=>n($.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(Re,{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($=>e.jsx(Wr,{visual:$,onAddVisual:_,onOpenVisual:R,onEditDetails:se,onDeleteClick:E,onDuplicateVisual:U,onTogglePrivacy:Z,onShareVisual:ne,isDeleting:C,isDuplicating:h===$.id,formatDate:A},$.id))})}),l&&i&&e.jsx(s.ShareDialog,{resource:i,resourceType:s.ResourceType.VISUAL,onClose:()=>{c(!1),o(null)}}),b&&e.jsx(s.ResourceEditDialog,{open:!!b,resourceLabel:"Visual",initialTitle:b.title||"",initialDescription:b.description||"",onClose:ae,onSave:Y,isSaving:z(b.id)}),e.jsx(s.AlertDialog,{open:d,onOpenChange:$=>{!$&&C||(u($),$||m(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 "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:C,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:$=>{$.preventDefault(),$.stopPropagation(),L()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:C,children:[C?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"}),C?"Deleting...":"Delete"]})]})]})}),e.jsx(Yr,{open:a,onOpenChange:r,onSubmit:D,isCreating:F}),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 Zr({dashboard:t,isDeleting:n,isDuplicating:a,onLoadDashboard:r,onEditDetails:l,onDeleteClick:c,onDuplicateDashboard:i,onShareDashboard:o,formatDate:d,onDashboardItemClick:u}){var k,O;const{selectDashboard:x}=s.useManagementActions(),m=s.useIsDashboardSelected(t.id),{userContext:h,isLoading:p}=s.useCurrentUserInfo(),b=((k=h==null?void 0:h.permissions)==null?void 0:k.canEdit)??!1,g=p||!b,v=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4"}),S=()=>{x(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",m&&"border-primary"),onClick:S,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:n,isDuplicating:a,shouldHideActions:g,onEditDetails:l,onDeleteClick:c,onDuplicateDashboard:i,onShareDashboard:o,formatDate:d})]})]})]})},t.id)}function el({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 sl(t){var le;const{onLoadDashboard:n,onEditDashboard:a,onDashboardItemClick:r}=t,[l,c]=w.useState(""),[i,o]=w.useState(!1),[d,u]=w.useState(!1),[x,m]=w.useState(null),[h,p]=w.useState(!1),[b,g]=w.useState(null),[v,S]=w.useState(null),[k,O]=w.useState(null),M=s.useManagementStore(V=>V.lastSelectedDashboard),T=s.useManagementStore(V=>V.selectedDashboard),y=s.useManagementStore(V=>V.actions.selectDashboard),f=s.useManagementStore(V=>V.actions.clearSelectedDashboard),{tokenProps:j,id:N}=s.useSemaphorContext();s.useRoleAwareDisplayPreferences();const{onCreateSuccess:F}=s.useDashboardCreation({onDashboardSelect:r}),{resources:C,isLoading:P,isError:A,createResource:D,updateResource:E,deleteResource:L,duplicateResource:I,isCreating:B,isDeleting:z,refetch:K}=s.useDashboardManagement(()=>{p(!1);const V=b==null?void 0:b.id;g(null),(T==null?void 0:T.id)===V&&(!(j!=null&&j.dashboard_id)&&!N?f():M&&M.id!==V&&y(M))},V=>{o(!1),F(V,K)}),{currentUser:U,userContext:R}=s.useCurrentUserInfo(),_=((le=R==null?void 0:R.permissions)==null?void 0:le.canCreateDashboard)??!1,Z=C.filter(V=>{var ee,X;return((ee=V==null?void 0:V.title)==null?void 0:ee.toLowerCase().includes(l.toLowerCase()))||((X=V==null?void 0:V.description)==null?void 0:X.toLowerCase().includes(l.toLowerCase()))}),ne=V=>new Date(V).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),se=V=>{D({title:V.title,description:V.description,isPrivate:!1})},ae=V=>{n==null||n(V)},Y=V=>{g(V),p(!0)},$=()=>{b&&L(b.id)},H=V=>{S(V),I(V,{onSettled:()=>S(null)})},{startUpdating:Q,stopUpdating:re,isUpdating:ue}=s.useResourceUpdateState(),me=(V,ee,X)=>{var ve;const je=Object.fromEntries(Object.entries(ee).filter(([,pe])=>pe!==void 0));if(Object.keys(je).length===0){(ve=X==null?void 0:X.onSuccess)==null||ve.call(X);return}const ge=Object.keys(je),be=ge.length===1?ge[0]:void 0;Q(V,be),E({resourceId:V,data:je},{onSuccess:()=>{var pe;re(V,be),(pe=X==null?void 0:X.onSuccess)==null||pe.call(X)},onError:()=>{var pe;re(V,be),(pe=X==null?void 0:X.onError)==null||pe.call(X)}})},q=V=>{const ee=C.find(X=>X.id===V);ee&&E({resourceId:V,data:{isPrivate:!ee.isPrivate}})},W=V=>{m(V),U==null||U.type,u(!0)},te=V=>{a==null||a(V.id),O(V)},he=()=>{O(null)},xe=({title:V,description:ee})=>{if(!k)return;const X={};V!==k.title&&(X.title=V),(k.description||"")!==ee&&(X.description=ee),me(k.id,X,{onSuccess:()=>{O(null)}})};return P?e.jsx(lt,{}):A?e.jsx(el,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[C&&C.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:V=>c(V.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:Z.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:()=>o(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):Z.map(V=>e.jsx(Zr,{dashboard:V,isDeleting:z,isDuplicating:v===V.id,onLoadDashboard:ae,onEditDetails:te,onDeleteClick:Y,onDuplicateDashboard:H,onTogglePrivacy:q,onShareDashboard:W,formatDate:ne,onDashboardItemClick:r},V.id))})}),d&&x&&e.jsx(s.ShareDialog,{resource:x,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),m(null)}}),e.jsx(s.AlertDialog,{open:h,onOpenChange:V=>{!V&&z||(p(V),V||g(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:z,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:V=>{V.preventDefault(),V.stopPropagation(),$()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:z,children:[z?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"}),z?"Deleting...":"Delete"]})]})]})}),k&&e.jsx(s.ResourceEditDialog,{open:!!k,resourceLabel:"Dashboard",initialTitle:k.title||"",initialDescription:k.description||"",onClose:he,onSave:xe,isSaving:ue(k.id)}),e.jsx(s.CreateDashboardDialog,{open:i,onOpenChange:o,onSubmit:se,isCreating:B}),_&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>o(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function ot({isOpen:t,onClose:n,className:a,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(y=>y.dashboard);const c=s.useDashboardStore(y=>y.isDashboardEditing),{setDashboard:i,addSheet:o}=s.useDashboardStore(y=>y.actions),{currentUser:d}=s.useCurrentUserInfo(),u=d,{permissions:x}=s.useRoleAwareDisplayPreferences(),h=s.useSelectedDashboard()&&x.canAccessVisuals&&c,p="dashboards",[b,g]=qe("resource-management-active-tab",p),v=h?b:"dashboards",S=l==="overlay",k=As(n,{enabled:t&&S}),O=s.cn("flex h-full flex-col border-r bg-background",S?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",a),M=y=>{},T=y=>{console.log("Editing dashboard:",y)};return e.jsx(s.TooltipProvider,{children:(!S||t)&&e.jsxs("div",{ref:k,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:n,tooltip:"Close Sidebar",children:e.jsx(Rt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:v,onValueChange:h?g:void 0,className:"flex h-9 grow flex-col",children:[h&&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(sl,{onLoadDashboard:M,onEditDashboard:T,onDashboardItemClick:r})}),h&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(Xr,{})})]})})]})})}function tl({showControls:t=!1,showFooter:n=!0,...a}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen);s.useDashboardStore(h=>h.isVisualEditing);const l=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),c=20,i=20,o=30,d=r,u=w.useRef(null),x=w.useRef(null);w.useEffect(()=>{u.current&&x.current&&(r?(u.current.resize(c),x.current.resize(100-c)):(u.current.resize(0),x.current.resize(100)))},[r]);const{preferences:m}=a;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:a,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:m,children:[e.jsx(Jr,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(ka,{}),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?c:0,minSize:d?i:0,maxSize:d?o:0,children:e.jsx(ot,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{className:s.cn("",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:x,className:"flex min-w-0 flex-1",defaultSize:d?100-c:100,minSize:d?40:100,children:e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(Gr,{}),e.jsx(Hr,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Os;exports.DashboardPlus=tl;exports.ResourceManagementPanel=ot;exports.ScheduleDashboard=Ms;exports.VisualEditingControls=Ps;exports.cleanCard=Fs;exports.getDashbaordStateWithoutData=Ve;
|