react-semaphor 0.1.52 → 0.1.53

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.
@@ -0,0 +1,235 @@
1
+ "use strict";const e=require("react/jsx-runtime"),s=require("./index-B0yZKR31.js"),w=require("react"),ct=require("react-dom");function dt(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const Ue=dt(w);/**
2
+ * @license lucide-react v0.453.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const ut=s.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
7
+ * @license lucide-react v0.453.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const mt=s.createLucideIcon("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/**
12
+ * @license lucide-react v0.453.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const ht=s.createLucideIcon("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
17
+ * @license lucide-react v0.453.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const xt=s.createLucideIcon("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/**
22
+ * @license lucide-react v0.453.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const pt=s.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
27
+ * @license lucide-react v0.453.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const ft=s.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
32
+ * @license lucide-react v0.453.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const gt=s.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
37
+ * @license lucide-react v0.453.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const jt=s.createLucideIcon("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/**
42
+ * @license lucide-react v0.453.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const bt=s.createLucideIcon("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/**
47
+ * @license lucide-react v0.453.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const vt=s.createLucideIcon("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/**
52
+ * @license lucide-react v0.453.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */const yt=s.createLucideIcon("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
57
+ * @license lucide-react v0.453.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
60
+ * See the LICENSE file in the root directory of this source tree.
61
+ */const Nt=s.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
62
+ * @license lucide-react v0.453.0 - ISC
63
+ *
64
+ * This source code is licensed under the ISC license.
65
+ * See the LICENSE file in the root directory of this source tree.
66
+ */const Ct=s.createLucideIcon("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/**
67
+ * @license lucide-react v0.453.0 - ISC
68
+ *
69
+ * This source code is licensed under the ISC license.
70
+ * See the LICENSE file in the root directory of this source tree.
71
+ */const St=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"}]]);/**
72
+ * @license lucide-react v0.453.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */const wt=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
+ * @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 Re=s.createLucideIcon("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
82
+ * @license lucide-react v0.453.0 - ISC
83
+ *
84
+ * This source code is licensed under the ISC license.
85
+ * See the LICENSE file in the root directory of this source tree.
86
+ */const Dt=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
+ * @license lucide-react v0.453.0 - ISC
88
+ *
89
+ * This source code is licensed under the ISC license.
90
+ * See the LICENSE file in the root directory of this source tree.
91
+ */const kt=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
+ * @license lucide-react v0.453.0 - ISC
93
+ *
94
+ * This source code is licensed under the ISC license.
95
+ * See the LICENSE file in the root directory of this source tree.
96
+ */const Tt=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"}]]);/**
97
+ * @license lucide-react v0.453.0 - ISC
98
+ *
99
+ * This source code is licensed under the ISC license.
100
+ * See the LICENSE file in the root directory of this source tree.
101
+ */const Et=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"}]]);/**
102
+ * @license lucide-react v0.453.0 - ISC
103
+ *
104
+ * This source code is licensed under the ISC license.
105
+ * See the LICENSE file in the root directory of this source tree.
106
+ */const It=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"}]]);/**
107
+ * @license lucide-react v0.453.0 - ISC
108
+ *
109
+ * This source code is licensed under the ISC license.
110
+ * See the LICENSE file in the root directory of this source tree.
111
+ */const At=s.createLucideIcon("Logs",[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]]);/**
112
+ * @license lucide-react v0.453.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const Ft=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"}]]);/**
117
+ * @license lucide-react v0.453.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const Lt=s.createLucideIcon("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
122
+ * @license lucide-react v0.453.0 - ISC
123
+ *
124
+ * This source code is licensed under the ISC license.
125
+ * See the LICENSE file in the root directory of this source tree.
126
+ */const is=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"}]]);/**
127
+ * @license lucide-react v0.453.0 - ISC
128
+ *
129
+ * This source code is licensed under the ISC license.
130
+ * See the LICENSE file in the root directory of this source tree.
131
+ */const cs=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"}]]);/**
132
+ * @license lucide-react v0.453.0 - ISC
133
+ *
134
+ * This source code is licensed under the ISC license.
135
+ * See the LICENSE file in the root directory of this source tree.
136
+ */const Mt=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"}]]);/**
137
+ * @license lucide-react v0.453.0 - ISC
138
+ *
139
+ * This source code is licensed under the ISC license.
140
+ * See the LICENSE file in the root directory of this source tree.
141
+ */const Pt=s.createLucideIcon("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
142
+ * @license lucide-react v0.453.0 - ISC
143
+ *
144
+ * This source code is licensed under the ISC license.
145
+ * See the LICENSE file in the root directory of this source tree.
146
+ */const ds=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"}]]);/**
147
+ * @license lucide-react v0.453.0 - ISC
148
+ *
149
+ * This source code is licensed under the ISC license.
150
+ * See the LICENSE file in the root directory of this source tree.
151
+ */const Bt=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"}]]);/**
152
+ * @license lucide-react v0.453.0 - ISC
153
+ *
154
+ * This source code is licensed under the ISC license.
155
+ * See the LICENSE file in the root directory of this source tree.
156
+ */const Ie=s.createLucideIcon("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/**
157
+ * @license lucide-react v0.453.0 - ISC
158
+ *
159
+ * This source code is licensed under the ISC license.
160
+ * See the LICENSE file in the root directory of this source tree.
161
+ */const Le=s.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
162
+ * @license lucide-react v0.453.0 - ISC
163
+ *
164
+ * This source code is licensed under the ISC license.
165
+ * See the LICENSE file in the root directory of this source tree.
166
+ */const Ot=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"}]]);/**
167
+ * @license lucide-react v0.453.0 - ISC
168
+ *
169
+ * This source code is licensed under the ISC license.
170
+ * See the LICENSE file in the root directory of this source tree.
171
+ */const Vt=s.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
172
+ * @license lucide-react v0.453.0 - ISC
173
+ *
174
+ * This source code is licensed under the ISC license.
175
+ * See the LICENSE file in the root directory of this source tree.
176
+ */const Ss=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"}]]);/**
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 Rt=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
182
+ * @license lucide-react v0.453.0 - ISC
183
+ *
184
+ * This source code is licensed under the ISC license.
185
+ * See the LICENSE file in the root directory of this source tree.
186
+ */const zt=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
+ * @license lucide-react v0.453.0 - ISC
188
+ *
189
+ * This source code is licensed under the ISC license.
190
+ * See the LICENSE file in the root directory of this source tree.
191
+ */const ws=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
+ * @license lucide-react v0.453.0 - ISC
193
+ *
194
+ * This source code is licensed under the ISC license.
195
+ * See the LICENSE file in the root directory of this source tree.
196
+ */const qt=s.createLucideIcon("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/**
197
+ * @license lucide-react v0.453.0 - ISC
198
+ *
199
+ * This source code is licensed under the ISC license.
200
+ * See the LICENSE file in the root directory of this source tree.
201
+ */const $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
+ * @license lucide-react v0.453.0 - ISC
203
+ *
204
+ * This source code is licensed under the ISC license.
205
+ * See the LICENSE file in the root directory of this source tree.
206
+ */const Gt=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
+ * @license lucide-react v0.453.0 - ISC
208
+ *
209
+ * This source code is licensed under the ISC license.
210
+ * See the LICENSE file in the root directory of this source tree.
211
+ */const Ut=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 Ds(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,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 n&&document.addEventListener(r,c),()=>{document.removeEventListener(r,c)}},[t,n,r]),l}function Kt(){const{setTheme:t}=s.useTheme(),a=s.useDashboardStore(n=>n.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(zt,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Lt,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),a("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),a("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),a("system")},children:"System"})]})]})}function Ve(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var c;return{...l,cards:(c=l.cards)==null?void 0:c.map(i=>ks(i))}})}})}}function ks(t){return{...t,customCfg:_t(t.customCfg),data:[]}}function _t(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ht(t,a,n,r,l){if(!l)return null;const c=JSON.stringify(n),i=`${t}/v1/lens`;return await s.postRequest(i,l,{name:a,template:c,filterValues:r,operation:"create"})}async function Ke(t,a,n){if(!n)return null;const{id:r,template:l,filterValues:c,isDefault:i,shared:o}=a,d=`${t}/v1/lens`;return await s.postRequest(d,n,{lensId:r,template:l,filterValues:c,isDefault:i,shared:o,operation:"update"})}async function Jt(t,a,n){if(!n)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,n,{operation:"delete",lensId:a})}function Qt(){const[t,a]=w.useState(""),[n,r]=w.useState(!1),l=s.useDashboardStore(v=>v.lenses),{setLenses:c,setSelectedLensId:i}=s.useDashboardActions(),[o,d]=w.useState(!1),[u,m]=w.useState(!1),h=s.useDashboardStore(v=>v.dashboard),x=s.useDashboardStore(v=>v.filterValues),{authToken:j,tokenProps:b}=s.useSemaphorContext();async function g(){d(!0);const v=Ve(h),D=await Ht(b.apiServiceUrl,t,v,x,j==null?void 0:j.accessToken);D&&(c([...l||[],D]),i(D.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:v=>{a(v.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:g,disabled:o,children:o?"Creating...":"Add"})})]})]})}function Wt(){const[t,a]=w.useState(!1),n=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),{authToken:i,tokenProps:o}=s.useSemaphorContext();async function d(h){c(h)}async function u(h){if(await Jt(o.apiServiceUrl,h,i==null?void 0:i.accessToken)){const j=n==null?void 0:n.filter(b=>b.id!==h);l(j||[]),c("original")}}async function m(h){const x=n==null?void 0:n.map(g=>g.id===h.id?{...g,isDefault:!h.isDefault}:{...g,isDefault:!1});l(x||[]);const j={...h,isDefault:!h.isDefault};await Ke(o.apiServiceUrl,j,i==null?void 0:i.accessToken);const b=n==null?void 0:n.find(g=>g.isDefault);if(b&&b.id!==h.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:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(wt,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Yt({iconClassName:t}){const[a,n]=w.useState(!1),[r,l]=w.useState(""),[c,i]=w.useState(!1),o=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;n(!1),l(""),i(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled: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:()=>n(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:a,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:c?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>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:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function Ts({triggerButtonClassName:t}){const[a,n]=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:()=>n(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:a,onOpenChange:n,dashboardId:r,dashboardName:l})]}):null}function Es({type:t,isLinked:a,className:n}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),c=s.useEditorStore(u=>u.frame);let i;if(t)i=t;else if(a!==void 0)i=a?"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;const o={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},d={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",o[i],n),children:d[i]})}const Xt=async(t,a,n)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,a,n)},Zt=async(t,a,n)=>{const r=`${t}/management/v1/groups/${n}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}});if(!l.ok){const c=await l.text();throw new Error(c||"Failed to delete group")}},ea=async(t,a,n,r)=>{const l=`${t}/management/v1/groups/${n}/members`;return await s.postRequestRegular(l,a,r)},sa=async(t,a,n,r)=>{const l=`${t}/management/v1/groups/${n}/members`,c=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(r)});if(!c.ok){const i=await c.text();throw new Error(i||"Failed to remove group members")}};function ta(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:r=>Xt(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function aa(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:r=>Zt(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["groups"]}),n.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function na(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>ea(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["group",l.groupId]}),n.invalidateQueries({queryKey:["group-members",l.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function ra(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>sa(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{n.invalidateQueries({queryKey:["group",l.groupId]}),n.invalidateQueries({queryKey:["group-members",l.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function la({onSuccess:t,tenantId:a,isTenantUser:n}){const[r,l]=w.useState(""),[c,i]=w.useState(""),[o,d]=w.useState({}),u=ta(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",c&&c.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const j={name:r.trim(),description:c.trim()||void 0,type:n?"TENANT_GROUP":"ORG_GROUP",...n&&a?{tenantId:a}:{}};try{await u.mutateAsync(j),l(""),i(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:x=>{l(x.target.value),o.name&&d(j=>({...j,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:x=>{i(x.target.value),o.description&&d(j=>({...j,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 oa({open:t,onOpenChange:a,group:n,onUpdate:r}){const[l,c]=w.useState("members"),[i,o]=w.useState(""),[d,u]=w.useState([]),[m,h]=w.useState([]),{data:x,isLoading:j,refetch:b}=s.useGroupMembers(n.id),g=n.type==="TENANT_GROUP"?"tenant":"organization",{users:v,isLoading:D}=s.useUnifiedUsers({type:g,tenantId:n.tenantId||void 0,active:!0,limit:100}),k=na(),P=ra(),L=(x==null?void 0:x.members)||[],T=w.useMemo(()=>new Set(L.map(A=>A.userId)),[L]),N=w.useMemo(()=>v.filter(A=>!T.has(A.id)),[v,T]),p=w.useMemo(()=>{if(!i)return N;const A=i.toLowerCase();return N.filter(F=>{var E,M;return((E=F.name)==null?void 0:E.toLowerCase().includes(A))||((M=F.email)==null?void 0:M.toLowerCase().includes(A))})},[N,i]),f=w.useMemo(()=>{if(!i)return L;const A=i.toLowerCase();return L.filter(F=>{var E,M,S,O;return((M=(E=F.user)==null?void 0:E.name)==null?void 0:M.toLowerCase().includes(A))||((O=(S=F.user)==null?void 0:S.email)==null?void 0:O.toLowerCase().includes(A))})},[L,i]),y=async()=>{if(d.length!==0)try{await k.mutateAsync({groupId:n.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)}},I=async()=>{if(m.length!==0)try{await P.mutateAsync({groupId:n.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(A){console.error("Failed to remove members:",A)}},C=A=>{u(F=>F.includes(A)?F.filter(E=>E!==A):[...F,A])},B=A=>{h(F=>F.includes(A)?F.filter(E=>E!==A):[...F,A])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:n.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[L.length," ",L.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",n.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:A=>{c(A),o(""),h([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:i,onChange:A=>o(A.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:j?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.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:f.map(A=>e.jsx(ia,{member:A,selected:m.includes(A.userId),onToggle:()=>B(A.userId)},A.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:I,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:A=>o(A.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:D?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(A=>e.jsx(s.Skeleton,{className:"h-16 w-full"},A))}):p.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:p.map(A=>e.jsx(ca,{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:y,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 ia({member:t,selected:a,onToggle:n}){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:n,children:[e.jsx(s.Checkbox,{checked:a}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((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 ca({user:t,selected:a,onToggle:n}){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:n,children:[e.jsx(s.Checkbox,{checked:a}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function da({open:t,onOpenChange:a}){const[n,r]=w.useState("groups"),[l,c]=w.useState(""),[i,o]=w.useState(null),[d,u]=w.useState(!1),[m,h]=w.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:j}=s.useCurrentUserInfo(),b=aa(),g=(j==null?void 0:j.type)==="tenant",v=x==null?void 0:x.tenantId,{groups:D,isLoading:k,refetch:P}=s.useGroups({type:g?"TENANT_GROUP":"all",tenantId:g?v:void 0,includeMembers:!1}),L=D.filter(f=>{var y;return f.name.toLowerCase().includes(l.toLowerCase())||((y=f.description)==null?void 0:y.toLowerCase().includes(l.toLowerCase()))}),T=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),P()}catch(f){console.error("Failed to delete group:",f)}},N=f=>{o(f),u(!0)},p=()=>{r("groups"),P()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:n,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:f=>c(f.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(f=>e.jsx(s.Skeleton,{className:"h-24 w-full"},f))}):L.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:l?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:L.map(f=>e.jsx(ua,{group:f,onManageMembers:()=>N(f),onDelete:()=>h(f),currentUserId:j==null?void 0:j.id},f.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(la,{onSuccess:p,tenantId:v,isTenantUser:g})})]})]})}),i&&e.jsx(oa,{open:d,onOpenChange:u,group:i,onUpdate:()=>P()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick: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 ua({group:t,onManageMembers:a,onDelete:n,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function Je(t){const[a,n]=w.useState(null),[r,l]=w.useState(null);return w.useEffect(()=>{if(!t||t.trim()===""){n(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const 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");n(()=>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),n(null)}})()},[t]),a}function ma(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let c=t.length;if(l!==-1&&(c=l),r!==-1&&r<c&&(c=r),a!==-1){const i=t.substring(0,a),o=t.substring(a);return`${i} {{ filters | where }} AND ${o.substring(6)}`}else if(n!==-1){const i=t.substring(0,n),o=t.substring(n);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 ha(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const c=r.split("__")[0],i=t.find(o=>o.tabTitle===c);return i?i.id:t[0].id}return a}}return t[0].id}async function us(t,a,n,r){if(!a||!n)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",n],c=r.getQueryData(l);if(c)return console.log("Using cached visual data for:",n),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",n);const i=s.ue.loading("Loading visual...",{position:"top-center"});try{const o=await fetch(`${t}/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${a}`}});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 Is(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function xa(t,a){var c,i;const n=(t==null?void 0:t.frameObject)??((c=t==null?void 0:t.visual)==null?void 0:c.frameObject);if(!n)return!1;const r=Is(n);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({...a,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function pa(){var x;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),r=Je(((x=n.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(j=>j.selectedSchemaName),c=s.useEditorStore(j=>j.selectedDatamodelId),i=s.useEditorStore(j=>j.selectedDatabaseName),o=s.useEditorStore(j=>j.selectedTableName),d=s.useEditorStore(j=>j.selectedConnectionId),u=s.useEditorStore(j=>j.isShowingVisual),m=n.sql;return{getUpdatedFrame:w.useCallback(()=>{var D;let j=m;m&&!m.includes("{{")&&(j=ma(m),t(j));const b=(D=r==null?void 0:r.getState())==null?void 0:D.settings,g={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:c,lastSelectedDatabase:i,lastSelectedTable:o,connectionId:d,sql:j,customCfg:u?n.customCfg:null,preferences:n.preferences,...b&&{customCardPreferences:{...n.customCardPreferences,settings:b}}},v=a.cards.map(k=>k.id===n.id?g:k);return{...a,cards:v,activeCardId:ha(v,a.activeCardId)}},[n,a,u,l,c,i,o,d,t,r,m])}}function ke(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),n=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:c,setCard:i,setIsDevMode:o,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:j,setSelectedTableName:b,setSelectedDatamodelId:g,setFilterValues:v,setApplyFilters:D}=s.useEditorActions(),{setIsDashboardEditing:k,setIsVisualEditing:P,setSelectedFrameId:L,clearSelectedFrameId:T,addFrame:N,setIsDashboardPanelOpen:p}=s.useDashboardActions(),f=s.useDashboardStore(E=>E.selectedSheetId),y=s.useDashboardStore(E=>E.selectedFrameId),I=s.useDashboardStore(E=>E.dashboard),C=s.useDashboardStore(E=>E.filterValues),B=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:M,fromCache:S}=await us(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",E.id,n);if(!xa(M,{setFrame:c,setCard:i,setIsDevMode:o,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:j,setSelectedTableName:b,setSelectedDatamodelId:g,setFilterValues:v,setApplyFilters:D,setIsDashboardEditing:k,setIsVisualEditing:P,dashboard:I,selectedSheetId:f,selectedFrameId:y,filterValues:C}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:S}}catch(M){return console.error("Error editing visual:",M),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a.apiServiceUrl,n,l,c,i,k,P,o,d,u,m,h,x,j,b,g,v,D,T,I,f,y,C]),F=w.useCallback(async E=>{var M;try{if(l(E),!f)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:S,fromCache:O}=await us(a.apiServiceUrl,(t==null?void 0:t.accessToken)||"",E.id,n),R=(S==null?void 0:S.frameObject)??((M=S==null?void 0:S.visual)==null?void 0:M.frameObject);if(!R)return{success:!1,error:"Visual has no frame data"};const _=Is(R);if(!(_!=null&&_.cards)||_.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const G={..._,id:s.v4(),visualId:E.id};return N(f,G,"end"),k(!0),L(G.id),p(!1),{success:!0,fromCache:O}}catch(S){return console.error("Error adding visual:",S),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a.apiServiceUrl,n,l,f,N,k,L,p]);return{visual:B.data,isLoading:B.isLoading,isError:B.isError,error:B.error,handleEditLibraryVisual:A,handleAddLibraryVisual:F,getUpdatedFrame:pa().getUpdatedFrame,refetch:B.refetch}}function fa({open:t,onOpenChange:a,isLibraryVisual:n,currentVisualName:r,isSaving:l=!1,onConfirm:c}){const[i,o]=w.useState(n&&r?`Copy of ${r}`:r||""),[d,u]=w.useState(""),[m,h]=w.useState(!n),[x,j]=w.useState(!0);w.useEffect(()=>{t&&(o(n&&r?`Copy of ${r}`:r||""),u(""),h(!n),j(!0))},[t,n,r]);const b=()=>{i.trim()&&(!m&&!x||c({name:i.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},g=i.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:n?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value: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:x,onCheckedChange:v=>j(!!v),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:n?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:v=>h(!!v),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:n?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!g||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function ga({className:t,variant:a="outline"}){var o;const{setCardSql:n}=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:a,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function ja({className:t,variant:a="default"}){const n=s.useQueryClient(),[r,l]=w.useState(!1),c=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),{setIsVisualEditing:i}=s.useDashboardActions(),{getUpdatedFrame:o}=ke(),d=s.useSelectedVisual(),u=s.useEditorStore(x=>x.frame),m=s.useUpdateVisualMutation(),h=()=>{const x=o(),j=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!j){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:j,data:{frameObject:x}},{onSuccess:()=>{l(!1),c(!0),s.ue.success("Visual updated successfully"),n.invalidateQueries({queryKey:["resource-by-id","visual",j],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:a,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function ba({className:t}){const a=s.useQueryClient(),[n,r]=w.useState(!1),l=s.useSelectedVisual(),c=s.useEditorStore(x=>x.frame),i=s.useDashboardStore(x=>x.selectedSheetId),{updateFrame:o,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=ke(),m=s.useUpdateVisualMutation(),h=async()=>{if(!i){s.ue.error("No sheet selected");return}const x=(c==null?void 0:c.visualId)||(l==null?void 0:l.id);if(!x){s.ue.error("No visual to update");return}r(!0);try{const j=u();await m.mutateAsync({visualId:x,data:{frameObject:j}});const b={...j,visualId:x};o(i,b),a.invalidateQueries({queryKey:["visuals"]}),a.invalidateQueries({queryKey:["visual",x]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(j){console.error("Failed to save and apply:",j),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function va({className:t}){const{getUpdatedFrame:a}=ke();s.useEditorStore(d=>d.frame);const n=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[c,i]=w.useState(!1),o=()=>{if(!n){s.ue.error("No sheet selected");return}i(!0);const u={...a(),visualId:void 0};r(n,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 ya({className:t}){const{setTempQueryData:a,setSqlGen:n}=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:m}=l;u&&m&&r.setQueryData(u,m)}n({}),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(),a=s.useQueryClient();s.useEditorStore(g=>g.isDevMode);const n=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:m,clearQueryConfig:h,setCardConfig:x,setCardType:j}=s.useEditorActions();function b(){const g=a.getQueryData(l);n!=null&&n.queryData||t({queryKey:l,queryData:g}),a.setQueryData(l,null),a.removeQueries({queryKey:l,exact:!0}),c(""),i({}),h(),x(void 0),o(""),d(""),u({}),j("bar")}return e.jsxs(s.Button,{onClick:b,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(bt,{className:"mr-2 size-4"}),"Clear"]})}function Na(){const[t,a]=w.useState(!1),[n,r]=w.useState(!1),[l,c]=w.useState(null),i=s.useEditorStore(L=>L.frame),o=s.useEditorStore(L=>L.card),d=s.useSelectedVisual(),u=s.useDashboardStore(L=>L.selectedSheetId),m=s.useDashboardStore(L=>L.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=ke(),{selectVisual:x}=s.useManagementActions(),{addFrame:j,setSelectedFrameId:b,setIsVisualEditing:g}=s.useDashboardActions(),v=!!(i!=null&&i.visualId),D=(d==null?void 0:d.title)||(o==null?void 0:o.title)||"Untitled Visual",k=s.useCreateVisualWithFrame(L=>{if(L!=null&&L.id){if(x(L),n&&l&&u){const T={...l,id:s.v4(),visualId:L.id};j(u,T,"end"),b(T.id),r(!1),c(null),g(!1)}m(!0),a(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:a,handleSaveAs:async L=>{if(!u){s.ue.error("No sheet selected");return}const T=h();if(L.saveToLibrary){r(L.saveToCurrentDashboard),c(T);const N={title:L.name,description:L.description,frameObject:T,isPrivate:!1};k.mutate(N)}else if(L.saveToCurrentDashboard){const N={...T,id:s.v4(),visualId:void 0,cards:T.cards.map(p=>({...p,title:p.id===o.id?L.name:p.title}))};j(u,N,"end"),b(N.id),s.ue.success("Visual saved to dashboard"),a(!1),g(!1)}},isLibraryVisual:v,currentVisualName:D,isSaving:k.isPending}}function As({className:t}){const a=s.useEditorStore(k=>k.frame),n=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=!!(a!=null&&a.visualId||r!=null&&r.id),d=!!(a!=null&&a.visualId&&l),u=o&&!d,{saveAsDialogOpen:m,setSaveAsDialogOpen:h,handleSaveAs:x,isLibraryVisual:j,currentVisualName:b,isSaving:g}=Na(),{handleAddLibraryVisual:v}=ke(),D=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(ga,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[d&&e.jsx(va,{className:t}),u&&c&&n&&(n.sql||s.hasValidCardConfig(n.config))&&e.jsxs(s.Button,{onClick:D,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(xt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(ja,{className:t,variant:"default"}),d&&e.jsx(ba,{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(),h(!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:()=>h(!0),children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(ya,{className:t}),e.jsx(fa,{open:m,onOpenChange:k=>{g||h(k)},isLibraryVisual:j,currentVisualName:b,isSaving:g,onConfirm:x})]})}function Fs({className:t,labelClassName:a,switchClassName:n}){const r=s.useEditorStore(d=>d.isDevMode),l=s.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:c}=s.useEditorActions(),{config:i}=w.useContext(s.SemaphorContext).tokenProps,o=(i==null?void 0:i.showAdvancedMode)!==!1;return!l||!o?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",n),checked:r,onCheckedChange:()=>c(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",a),children:"Advanced Mode"})]})}function Ca(){var ce,K,de;const{authToken:t,tokenProps:a,id:n}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:c}=s.useRoleAwareDisplayPreferences(),i=s.useHasDashboardId(),{isLoading:o}=s.useDashboardQuery();s.useDashboardStore(z=>z.theme);const d=s.useDashboardStore(z=>z.lenses),u=s.useDashboardStore(z=>z.selectedLensId),m=d==null?void 0:d.find(z=>z.id===u),h=s.useDashboardStore(z=>z.dashboard);s.useDashboardStore(z=>z.selectedSheetId);const x=s.useDashboardStore(z=>z.isDashboardEditing),{setDashboardTitle:j}=s.useDashboardStore(z=>z.actions),[b,g]=w.useState(!1),[v,D]=w.useState(!1),[k,P]=w.useState(!1),L=s.useDashboardStore(z=>z.isDashboardPanelOpen),T=s.useDashboardStore(z=>z.actions.setIsDashboardPanelOpen),N=s.useDashboardStore(z=>z.filterValues),p=s.useDashboardStore(z=>z.isVisualEditing),f=s.useEditorStore(z=>z.card),y=s.useManagementStore(z=>z.selectedDashboard),I=s.useManagementStore(z=>z.initialDashboard),C=s.useManagementStore(z=>z.selectedVisual);s.useDashboardStore(z=>z.selectedFrameId),s.useEditorStore(z=>z.frame);const B=y?(K=y==null?void 0:y.permissions)==null?void 0:K.canEdit:(ce=I==null?void 0:I.permissions)==null?void 0:ce.canEdit,A=s.useDashboardStore(z=>z.showFilters),F=s.useDashboardStore(z=>z.showDashboardJSON),E=s.useDashboardStore(z=>z.onSaveFunction),M=s.useDashboardStore(z=>z.actions.setShowFilters),{setIsDashboardEditing:S,setShowDashboardJSON:O}=s.useDashboardStore(z=>z.actions),{setInitialDashboard:R,clearSelectedDashboard:_}=s.useManagementStore(z=>z.actions),{resources:G}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:V}=s.useCurrentUserInfo(),J=s.canUserManageGroups(V),X=y||I,ie=X?{id:X.id,title:(h==null?void 0:h.title)||X.title||"Dashboard"}:null,{handleAddNewFrame:se}=s.useAddNewFrame(),[ae,Y]=w.useState(!1),$=s.useUpdateResource(s.ResourceType.DASHBOARD),ee=async(z,le)=>{if(!(h!=null&&h.id)){console.log("No dashboard ID found");return}console.log("Updating dashboard title:",{dashboardId:h.id,newTitle:z,previousTitle:le}),$.mutate({resourceId:h.id,data:{title:z}},{onSuccess:()=>{console.log("Dashboard title updated successfully"),s.ue.success("Dashboard title updated")},onError:pe=>{console.error("Failed to update dashboard title:",pe),s.ue.error("Failed to update dashboard title"),j(le)}})};w.useEffect(()=>{if(G&&G.length>0){const z=h==null?void 0:h.id;if(z){const le=G.find(pe=>pe.id===z);le&&R(le)}}},[G,h==null?void 0:h.id,R]);const H=a.orgUserId||a.tenantId,Z=x&&!p&&H&&B,te=()=>{S(!0)};async function ne(){const z=Ve(h);Y(!0);const le={template:z};$.mutate({resourceId:z.id,data:le},{onSuccess:()=>{Y(!1),s.ue.success("Dashboard saved!")},onError:()=>{Y(!1),s.ue.error("Failed to save dashboard")}})}async function q(){if(g(!0),!u||!m)return;const z=Ve(h),le=JSON.stringify(z),pe={...m,template:le,filterValues:N};await Ke(a.apiServiceUrl,pe,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),E==null||E(z),g(!1)}const Q=(m==null?void 0:m.name)||h.title;$.isPending&&console.log("Title during update:",{title:Q,dashboardStateTitle:h.title,dashboardId:h==null?void 0:h.id,currentLensName:m==null?void 0:m.name});const re=G&&G.length>0&&(a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail),fe=y&&!(a!=null&&a.dashboard_id)&&!n;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[re&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{T(!L)},className:"h-7 p-2",children:e.jsx(Ft,{className:"h-4 w-4"})}),fe&&!p&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>_(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!p&&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:Q||"Untitled Dashboard",onSave:z=>{console.log("EditableText onSave called:",{newTitle:z,canEditDashboard:B,dashboardId:h==null?void 0:h.id});const le=(h==null?void 0:h.title)||"";j(z),ee(z,le)},isEditable:B&&!m,displayClassName:"text-sm font-medium",inputClassName:"text-sm font-medium",placeholder:"Dashboard Title",isPending:$.isPending})),p&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(C==null?void 0:C.title)||(f==null?void 0:f.title)||"Untitled Visual"}),e.jsx(Es,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p&&e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"mr-2"}),e.jsx(As,{className:"h-7"})]}),r&&!p&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(a.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ot,{className:"h-4 w-4"})}),!p&&i&&e.jsx(Yt,{}),!p&&i&&e.jsx(Ts,{}),!p&&i&&J&&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"})}),!p&&i&&((de=X==null?void 0:X.permissions)==null?void 0:de.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>D(!0),className:"h-7 p-2",children:e.jsx(s.Share2,{className:"h-4 w-4"})}),!A&&!p&&x&&c.canUseFilters&&i&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>M(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),x&&!p&&H&&r&&i&&e.jsx(Qt,{}),!p&&H&&r&&i&&e.jsx(Wt,{}),x&&!p&&H&&m&&r&&i&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:b,onClick:q,size:"sm",children:[e.jsx(Ie,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),x&&!p&&i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!x,onClick:()=>se(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!p&&!x&&c.canEdit&&i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:te,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),Z&&i&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:ae,onClick:ne,size:"sm",children:[ae?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),ae?"Saving...":"Save"]}),!p&&x&&r&&i&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>O(!F),size:"sm",variant:"ghost",children:e.jsx(s.Code,{className:"h-4 w-4"})})}),!p&&r&&e.jsx(Kt,{}),x&&!p&&i&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{S(!1),O(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),v&&ie&&e.jsx(s.ShareDialog,{resource:ie,resourceType:s.ResourceType.DASHBOARD,onClose:()=>D(!1)}),e.jsx(da,{open:k,onOpenChange:P})]})]})}function We(t){const{tokenProps:a,authToken:n}=s.useSemaphorContext(),r=a==null?void 0:a.apiServiceUrl;return s.useQuery({queryKey:["joinability-map",t],queryFn:async()=>{if(!t||!(n!=null&&n.accessToken))return null;const l=`${r}/v1/domains/${t}/joinability`;return s.getRequest(l,n.accessToken)},enabled:!!t&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function Fe(t,a,n){if(a==="source")return{isValid:!0};const r=s.getDataType(t.dataType);if(n==="kpi"){if(a==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(a==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function _e(t,a,n,r,l){if(t!=="kpi"||l.length<3)return;const c=(a==null?void 0:a.groupByColumns)&&a.groupByColumns.length>0,i=(a==null?void 0:a.comparisonType)==="none";!c&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const Ye=t=>{var A;const a=(A=t==null?void 0:t.dataSource)==null?void 0:A.semanticDomainId,{data:n}=We(a),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:c,updatePivotByColumn:i,updateSortByColumn:o,removeGroupByColumn:d,removeMetricColumn:u,removePivotByColumn:m,removeSortByColumn:h}=s.useEditorActions(),x=s.useEditorStore(F=>F.card.type),j=t==null?void 0:t.id,b=w.useCallback(F=>{if(!(t!=null&&t.config))return[];switch(F){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((F,E)=>{if(j)switch(F){case"groupBy":{r(j,{groupByColumns:E});break}case"metrics":{r(j,{metricColumns:E});break}case"pivotBy":{r(j,{pivotByColumns:E});break}case"sortBy":{r(j,{sortByColumns:E});break}}},[j,r]),v=w.useCallback((F,E,M)=>{if(!j)return;const O=b(F)[E];if(O)switch(F){case"groupBy":l(j,O.id,{label:M});break;case"metrics":c(j,O.id,{label:M});break;case"pivotBy":i(j,O.id,{label:M});break;case"sortBy":o(j,O.id,{label:M});break}},[j,b,l,c,i,o]),D=w.useCallback((F,E)=>{if(!j)return;const S=b("metrics")[F];S&&c(j,S.id,{aggregate:E,label:s.getAggregationLabel(S.name,E)})},[j,b,c]),k=w.useCallback((F,E,M)=>{if(!j)return;const O=b("groupBy")[F];if(!O)return;const R={dateFormat:E};E==="custom"&&M?R.customFormat=M:R.customFormat=void 0,l(j,O.id,R)},[j,b,l]),P=w.useCallback((F,E)=>{if(!j)return;const S=b("groupBy")[F];S&&l(j,S.id,{granularity:E})},[j,b,l]),L=w.useCallback((F,E)=>{if(!j)return;const S=b("metrics")[F];S&&c(j,S.id,{aliasTemplate:E})},[j,b,c]),T=w.useCallback((F,E)=>{if(console.log("handleValueAliasesChange",F,E),!j)return;console.log("handleValueAliasesChange",F,E);const S=b("metrics")[F];S&&(console.log("handleValueAliasesChange",E),c(j,S.id,{valueAliases:E}))},[j,b,c]),N=w.useCallback(F=>{if(!j)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(j,{comparisonType:F})},[j,r,b]),p=w.useCallback(F=>{j&&r(j,{showTrendline:F})},[j,r]),f=w.useCallback(F=>{j&&r(j,{trendlineWindow:F})},[j,r]),y=w.useCallback(F=>{j&&r(j,{trendlineGranularity:F})},[j,r]),I=w.useCallback(F=>{j&&r(j,{targetValue:F})},[j,r]),C=w.useCallback(F=>{var G;if(!j)return;const E=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy")],M=s.validateEntityConsistency(F,E,{joinPlan:(G=t==null?void 0:t.config)==null?void 0:G.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:a});if(!M.isValid){M.showError&&s.showJoinRequiredNotification();return}const S=s.getSmartContainerForField(F,E,x);if(!S){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const O=Fe(F,S,x);if(!O.isValid){s.ue.error("Invalid Field Type",{description:O.reason,position:"top-center",duration:3e3});return}const R=b(S);if(s.fieldAlreadyExists(F,R))return;const _=s.getNewField(F,S,R);if(_){const V=[...R,_];g(S,V),S==="metrics"&&_e(x,t==null?void 0:t.config,r,j,V)}},[j,t==null?void 0:t.config,b,g,a,n,x,r]),B=w.useCallback((F,E)=>{if(!j)return;const S=b(F)[E];if(S){if(F!=="sortBy"){const O=b("sortBy"),R=O.filter(_=>!(_.name===S.name&&_.qualifiedEntityName===S.qualifiedEntityName));R.length!==O.length&&r(j,{sortByColumns:R})}switch(F){case"groupBy":d(j,S.id);break;case"metrics":u(j,S.id);break;case"pivotBy":m(j,S.id);break;case"sortBy":h(j,S.id);break}}},[j,b,d,u,m,h,r]);return{getFieldsForContainer:b,setFieldsForContainer:g,updateLabel:v,handleAggregationChange:D,handleDateFormatChange:k,handleGranularityChange:P,handleAliasTemplateChange:L,handleValueAliasesChange:T,removeField:B,handleFieldClick:C,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:p,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:I,cardType:x}};function Pe(t){return`${t}-${s.v4()}`}function ms(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Sa(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function 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 a=t.selectedEntities[0];return{tableName:a==null?void 0:a.name,schemaName:a==null?void 0:a.schema,databaseName:a==null?void 0:a.database,connectionId:t.connectionId,connectionType:t.connectionType}}function Ls(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const a=t.selectedEntities[0];return!!(a!=null&&a.name)}function Ms(){const t=s.useEditorStore(N=>N.sqlGen),a=s.useEditorStore(N=>N.isDevMode),n=s.useEditorStore(N=>N.card.dataSource),r=s.useEditorStore(N=>{var p,f;return(f=(p=N.card)==null?void 0:p.queryConfig)==null?void 0:f.metricColumns}),{tableName:l,schemaName:c,databaseName:i}=Xe(n),o=Ls(n),d=s.useEditorStore(N=>N.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:m,setCardSql:h,setRunSql:x,setSqlGen:j,setIsShowingVisual:b}=s.useEditorActions(),{connectionType:g,modelItems:v,selectedDatamodelName:D}=s.useEditorAside(),k=N=>({column_name:N.name,data_type:N.dataType,label:N.label,description:N.description});return{handleDevModeFieldClick:N=>{var f;if(!a)return;const p=k(N);if(a&&o&&l){const y=s.createSqlGenConfig(p,t);j(y);const I=(f=v==null?void 0:v.find(B=>B.id===d))==null?void 0:f.name,C=s.getSql(y,s.fmt(c||""),s.fmt(l),I||"",g,i||"");C&&(h(C),x(!0))}else if(!a){if(s.isTextDataType(p.data_type))if(r&&r.length>0){const y={...p,role:"groupby",id:Pe(p.column_name),name:p.column_name,type:p.data_type};m(y)}else{const y={...p,role:"metric",id:Pe(p.column_name),name:p.column_name,label:ms(p.column_name,"COUNT"),type:p.data_type,aggregate:"COUNT"};u(y)}if(s.isDateDataType(p.data_type)){const y={...p,role:"groupby",id:Pe(p.column_name),name:p.column_name,type:p.data_type,label:Sa(p.column_name,"month"),granularity:"month"};m(y)}if(s.isNumberDataType(p.data_type)){const y={...p,role:"metric",id:Pe(p.column_name),name:p.column_name,label:ms(p.column_name,"SUM"),type:p.data_type,aggregate:"SUM"};u(y)}}},handleShowSample:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const N=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:D,connectionType:g,databaseName:i||""});b(!1);const p=g==="MSSQL"?`SELECT top 10 * FROM ${N}`:`SELECT * FROM ${N} LIMIT 10`;h(p),x(!0)},handleShowCount:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const N=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:D,connectionType:g,databaseName:i||""});h(`SELECT COUNT(*) as count FROM ${N}`),x(!0)},isNumberField:N=>s.isNumberDataType(N.dataType)}}function Ps(){const t=s.useEditorStore(b=>b.selectedConnectionId),a=s.useEditorStore(b=>b.selectedDatamodelId),n=s.useEditorStore(b=>b.selectedDatabaseName),r=s.useEditorStore(b=>b.selectedSchemaName),l=s.useEditorStore(b=>b.selectedTableName),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:m,tableName:h,connectionType:x}=s.useEditorAside();function j(b,g="sheet",v){var y;const D=s.fmt(b.column_name),k=s.fmt(n||""),P=s.fmt(r||""),L=s.fmt(h);let T=s.getQualifiedTableName({schemaName:P,tableName:L,connectionType:x,databaseName:k}),N=`${T}.${D}`;const p=(y=m==null?void 0:m.find(I=>I.id===a))==null?void 0:y.name;a&&a!=="none"&&(N=`${s.DATAMODEL_NAMESPCACE}.${p}.${D}`,T=`${s.DATAMODEL_NAMESPCACE}.${p}`),v!=null&&v.qualifiedFieldName&&(N=v.qualifiedFieldName),v!=null&&v.entityName&&(T=v.entityName);let f;if(g==="sheet"&&i?f=s.filterExistsInSheet(c,N,L,n||"",k,i):f=c==null?void 0:c.find(I=>I.column===N&&I.table===L&&(I.database===k||I.database===n)),f)u(f.id),d(f.id);else{const I=s.v4(),C=g==="sheet"&&i?[i]:void 0;return h==="api"&&t?(o({location:g,id:I,column:N,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,D)}),I):(o({id:I,location:g,column:N,title:b.label||b.column_name,dataType:b.data_type,table:l||"",database:n||"",connectionId:t||"",operation:"in",applyToSheetIds:C,sql:s.getDefaultFilterSql(b.data_type,T,D)}),I)}}return{assignFilter:j}}function wa({column:t}){const[a,n]=w.useState(!1),r=s.useEditorStore(D=>D.card.dataSource),{tableName:l,schemaName:c,databaseName:i}=Xe(r),o=s.useEditorStore(D=>D.selectedDatamodelId),d=s.useEditorStore(D=>D.sqlGen),{modelItems:u,connectionType:m}=s.useEditorAside(),h=s.useEditorStore(D=>D.actions.setSqlGen),x=s.useEditorStore(D=>D.actions.setCardSql),j=s.useEditorStore(D=>D.actions.setRunSql),b=Ls(r);function g(D,k){var N;if(!b||!l){console.warn("Cannot generate SQL: missing table metadata");return}const P=s.createSqlGenConfig(D,d,k),L=(N=u==null?void 0:u.find(p=>p.id===o))==null?void 0:N.name;h(P);const T=s.getSql(P,s.fmt(c||""),s.fmt(l),L||"",m,i||"");T&&(x(T),j(!0)),n(!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:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:v()})]}):null}function Da({field:t,fieldState:a}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),a&&a.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:a.tooltip})}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function ka({field:t,context:a="editor",fieldState:n}){const r=s.useEditorStore(V=>V.isDevMode),l=a==="filter",c=r||l||(n==null?void 0:n.state)==="unreachable"&&!l,i=s.useDashboardStore(V=>V.dashboard.filters),o=s.useDashboardStore(V=>V.selectedSheetId),d=s.useDashboardStore(V=>V.actions.removeFilter),{removeFilterValues:u}=s.useDashboardActions(),{assignFilter:m}=Ps(),h=l?s.getSheetScopedFilters(i,o):i,x=l?h==null?void 0:h.find(V=>{var J;return V.title===t.name||((J=V.column)==null?void 0:J.includes(t.name))}):void 0,j=!!x,b=x&&l?i==null?void 0:i.find(V=>V.id===x.id):void 0,g=b&&(b.applyToSheetIds&&b.applyToSheetIds.length>1||b.excludeSheetIds&&b.excludeSheetIds.length>0||!b.applyToSheetIds&&!b.excludeSheetIds&&!b.sheetId);l&&j&&console.log("[SourceField Debug]",{fieldName:t.name,hasActiveFilter:j,activeFilterOnSheet:x?{id:x.id,title:x.title,column:x.column,applyToSheetIds:x.applyToSheetIds,excludeSheetIds:x.excludeSheetIds}:null,activeFilterForField:b?{id:b.id,title:b.title,column:b.column,applyToSheetIds:b.applyToSheetIds,excludeSheetIds:b.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:o});const[v,D]=w.useState(!1),[k,P]=w.useState(null),{attributes:L,listeners:T,setNodeRef:N,transform:p,transition:f,isDragging:y}=s.useSortable({id:t.id,disabled:c}),[I,C]=w.useState(!1),B=s.useEditorStore(V=>V.card),{handleFieldClick:A}=Ye(B),{handleDevModeFieldClick:F,isNumberField:E}=Ms(),M=()=>{b&&(console.log("[SourceField] Removing multi-sheet filter:",b.id),u(b.id),d(b.id)),P(null),D(!1)},S=()=>{if(l){const V={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};console.log("[SourceField Click]",{fieldName:t.name,hasActiveFilter:j,isMultiSheetFilter:g,willShowWarning:j&&g}),j&&g?(console.log("[SourceField] Showing warning dialog for multi-sheet filter"),P({column:V,field:t}),D(!0)):(console.log("[SourceField] Calling assignFilter directly (single-sheet or new filter)"),m(V,"sheet",t))}else r?F(t):A(t)},O={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},R={transform:s.CSS.Transform.toString(p),transition:f},G=(()=>{if(!n||l)return{};const J={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...J},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...J},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...J}}[n.state]||J})();return e.jsxs("div",{ref:N,style:R,...c?{}:L,...c?{}:T,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",y&&"scale-95 opacity-50",!y&&"border",G.borderColor||"border-transparent",G.bgColor||"",G.hoverBorderColor,G.hoverBgColor||"hover:bg-muted",G.opacity,G.cursor,j&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!c&&!r&&!l}),title:n==null?void 0:n.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:S,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 ${I?"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(Da,{field:t,fieldState:n})})]})}),r&&!l&&E(t)&&e.jsx("div",{onClick:V=>V.stopPropagation(),children:e.jsx(wa,{column:O})})]}),I&&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(ws,{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:D,children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Remove Filter from Multiple Sheets?"}),e.jsx(s.AlertDialogDescription,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:M,children:"Remove Filter"})]})]})})]})}function Ta({context:t="editor"}={}){var A,F,E,M;const[a,n]=w.useState(""),[r,l]=w.useState("all"),c=s.useEditorStore(S=>S.isDevMode),i=s.useEditorStore(S=>S.card.dataSource),o=s.useEditorStore(S=>S.card.config),d=s.useEditorStore(S=>S.card),{autoJoinMetadata:u}=s.useDashboardCardQuery(d),{columns:m=[],columnGroups:h=[],isLoading:x,error:j}=s.useColumns(),b=(i==null?void 0:i.mode)==="semanticDomain"?i.semanticDomainId:void 0,{data:g}=We(b),v=[...(o==null?void 0:o.groupByColumns)||[],...(o==null?void 0:o.metricColumns)||[]];(F=(A=o==null?void 0:o.joinPlan)==null?void 0:A.baseEntity)==null||F.name,(M=(E=u==null?void 0:u.resolvedJoinPlan)==null?void 0:E.baseEntity)==null||M.name;const{handleShowSample:D,handleShowCount:k}=Ms(),P=m.filter(S=>S.name.toLowerCase().includes(a.toLowerCase())||S.dataType.toLowerCase().includes(a.toLowerCase())||S.label&&S.label.toLowerCase().includes(a.toLowerCase())||S.qualifiedEntityName&&S.qualifiedEntityName.toLowerCase().includes(a.toLowerCase())),L=S=>{if(S.dataType==="number"||S.dataType==="integer"||S.dataType==="float"||S.dataType==="decimal"||S.dataType==="currency")return"metrics";const O=s.getDataType(S.dataType);return["date","string","boolean"].includes(O)?"dimensions":O==="number"?"metrics":"dimensions"},N=(r==="all"?P:P.filter(S=>L(S)===r)).reduce((S,O)=>{const R=O.qualifiedEntityName||"Other Fields";return S[R]||(S[R]={label:s.toLabel(O.entityName),fields:[]}),S[R].fields.push(O),S},{}),f=Object.keys(N),y=P.filter(S=>L(S)==="dimensions").length,I=P.filter(S=>L(S)==="metrics").length,C=P.filter(S=>L(S)==="calculated").length,B=P.length>0;return x?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"})}):j?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:j.message||"Failed to load column data"})]}):!i||!i.selectedEntities||i.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:[c&&t!=="filter"&&m.length>0&&e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:x,onClick:D,size:"sm",variant:"secondary",className:"grow",children:[x?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(At,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:x,onClick:k,size:"sm",variant:"secondary",className:"grow",children:[x?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Vt,{className:"mr-2 size-4"}),"Count"]})]}),m.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:a,onChange:S=>n(S.target.value)}),a&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),B&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:S=>l(S),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:P.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:I})]}),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:C})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:f,className:"space-y-2",children:Object.entries(N).map(([S,O])=>{const R=h.find(_=>_.entityName===S)||{entityName:S,label:O.label};return e.jsxs(s.AccordionItem,{value:S,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:R.label||R.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:R.label||R.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:O.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:O.fields.map(_=>{const G=s.calculateFieldState(_,{joinabilityMap:(g==null?void 0:g.joinabilityMap)||null,selectedFields:v,cardConfig:o,autoJoinMetadata:u});return e.jsx(ka,{field:_,context:t,fieldState:G},_.id)})})})]},S)})}),Object.keys(N).length===0&&m.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(N).length===0&&m.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 Bs({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(Ta,{context:t})," "]})}function Ea({initialJoinPlan:t,availableDataSources:a}){const[n,r]=w.useState(t),[l,c]=w.useState(new Set),i=()=>{const N=n.joins.length>0?Math.max(...n.joins.map(f=>f.sequence))+1:1,p={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:N,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,p]}),c(new Set([...l,p.id]))},o=N=>{r({...n,joins:n.joins.filter(p=>p.id!==N)}),c(new Set([...l].filter(p=>p!==N)))},d=(N,p)=>{var B,A,F,E,M;const f=n.joins.find(S=>S.id===N);if(!f)return;const y={...f,...p};if((B=y.source)!=null&&B.name&&((A=y.target)!=null&&A.name)&&y.source.name===y.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${y.source.name} to itself is not currently supported. Please select a different target table.`});return}const I=n.joins.filter(S=>{var O;return S.id!==N&&S.target.name===((O=y.target)==null?void 0:O.name)});if((F=y.target)!=null&&F.name&&I.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${y.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const C=n.joins.map(S=>S.id===N?y:S);if((E=y.source)!=null&&E.name&&((M=y.target)!=null&&M.name)&&y.joinKeyGroups[0].keys.length===0){const S=a.find(G=>{var V;return G.name===((V=y.source)==null?void 0:V.name)}),O=a.find(G=>{var V;return G.name===((V=y.target)==null?void 0:V.name)}),R={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="},_=[...y.joinKeyGroups];_[0]={..._[0],keys:[R]},y.joinKeyGroups=_,C[C.findIndex(G=>G.id===N)]=y}r({...n,joins:C})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:i,removeJoin:o,updateJoin:d,moveJoinUp:N=>{const p=n.joins.findIndex(f=>f.id===N);if(p>0){const f=[...n.joins],y={...f[p]},I={...f[p-1]};f[p]=I,f[p-1]=y,f.forEach((B,A)=>{B.sequence=A+1});const C={...n,joins:f};r(C)}},moveJoinDown:N=>{const p=n.joins.findIndex(f=>f.id===N);if(p<n.joins.length-1){const f=[...n.joins],y={...f[p]},I={...f[p+1]};f[p]=I,f[p+1]=y,f.forEach((B,A)=>{B.sequence=A+1});const C={...n,joins:f};r(C)}},toggleJoinExpansion:N=>{const p=new Set(l);p.has(N)?p.delete(N):p.add(N),c(p)},getAvailableSourceEntities:N=>{if(n.joins.length===0)return a;const p=n.joins.findIndex(y=>y.id===N);if(p===0)return a.filter(y=>y.name===n.baseEntity.name);const f=new Set;return n.baseEntity.name&&f.add(n.baseEntity.name),n.joins.slice(0,p).forEach(y=>{f.add(y.source.name),f.add(y.target.name)}),a.filter(y=>f.has(y.name))},getAvailableTargetEntities:N=>a.filter(p=>p.name!==N),addJoinKeyGroup:N=>{const p=n.joins.find(y=>y.id===N);if(!p)return;const f=[...p.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(N,{joinKeyGroups:f})},updateGroupOperator:(N,p,f)=>{const y=n.joins.find(C=>C.id===N);if(!y)return;const I=[...y.joinKeyGroups];I[p]={...I[p],operator:f},d(N,{joinKeyGroups:I})},removeJoinKeyGroup:(N,p)=>{const f=n.joins.find(I=>I.id===N);if(!f)return;const y=[...f.joinKeyGroups];y.splice(p,1),d(N,{joinKeyGroups:y})},addJoinKey:(N,p)=>{const f=n.joins.find(A=>A.id===N);if(!f)return;const y=a.find(A=>A.name===f.source.name),I=a.find(A=>A.name===f.target.name),C=[...f.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(y==null?void 0:y.name)||"",entityName:(y==null?void 0:y.name)||"",entityType:(y==null?void 0:y.type)||"table"},target:{id:`target-${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"},operator:"="};C[p]={...C[p],keys:[...C[p].keys,B]},d(N,{joinKeyGroups:C})},updateJoinKey:(N,p,f,y,I)=>{const C=n.joins.find(M=>M.id===N);if(!C)return;const B=a.find(M=>M.name===C.source.name),A=a.find(M=>M.name===C.target.name),F=[...C.joinKeyGroups],E=F[p].keys[f];y==="sourceColumnName"&&B?F[p].keys[f]={...E,source:{...E.source,name:I}}:y==="targetColumnName"&&A?F[p].keys[f]={...E,target:{...E.target,name:I}}:y==="operator"&&(F[p].keys[f]={...E,operator:I}),d(N,{joinKeyGroups:F})},removeJoinKey:(N,p,f)=>{const y=n.joins.find(C=>C.id===N);if(!y)return;const I=[...y.joinKeyGroups];I[p].keys.splice(f,1),d(N,{joinKeyGroups:I})},generateSQLPreview:()=>{const N=[...n.joins].sort((y,I)=>y.sequence-I.sequence),p=n.baseEntity;if(!p.name)return"SELECT * FROM table -- Please select a base entity";let f=`SELECT *
212
+ FROM ${p.name}`;return N.forEach(y=>{const I=a.find(A=>A.name===y.target.name);if(!I)return;const C=y.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const F=A.keys.filter(E=>{var M,S,O,R;return((M=E.source)==null?void 0:M.name)&&((S=E.target)==null?void 0:S.name)&&((O=E.source)==null?void 0:O.entityName)&&((R=E.target)==null?void 0:R.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return F.length>1?`(${F.join(` ${A.operator} `)})`:F[0]}).filter(Boolean),B=C.length>1?C.join(" OR "):C[0]||"condition_here";f+=`
213
+ ${y.joinType} JOIN ${I.name}
214
+ ON ${B}`}),f},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(y=>!y.source.name||!y.target.name)||n.joins.some(y=>y.joinKeyGroups.some(I=>I.keys.length===0))||n.joins.some(y=>y.joinKeyGroups.some(I=>I.keys.some(C=>!C.source.name||!C.target.name||!C.operator))))}}function Ia({joinPlan:t,availableDataSources:a,onSave:n,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:m,removeJoin:h,updateJoin:x,moveJoinUp:j,moveJoinDown:b,toggleJoinExpansion:g,getAvailableSourceEntities:v,getAvailableTargetEntities:D,addJoinKeyGroup:k,updateGroupOperator:P,removeJoinKeyGroup:L,addJoinKey:T,updateJoinKey:N,removeJoinKey:p,generateSQLPreview:f,isValidConfiguration:y}=Ea({initialJoinPlan:t,availableDataSources:a}),I=C=>{const B=i.find(A=>A.entityName===C);return(B==null?void 0:B.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 B=a.find(A=>A.name===C);u({...o,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:C,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.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:f()})]}),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:m,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 B=a.find(E=>E.name===C.source.name),A=a.find(E=>E.name===C.target.name),F=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,B&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(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:F?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(C.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),F&&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 M=a.find(S=>S.name===E);x(C.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:E,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(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=>x(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 M=a.find(S=>S.name===E);x(C.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:E,database:M==null?void 0:M.database,schema:M==null?void 0:M.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?D(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&&B&&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,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:E.operator,onValueChange:S=>P(C.id,M,S),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>L(C.id,M),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((S,O)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[O>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:S.source.name,onValueChange:R=>N(C.id,M,O,"sourceColumnName",R),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:I(C.source.name).map(R=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:R.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:R.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:R.dataType})]})},R.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:S.operator,onValueChange:R=>N(C.id,M,O,"operator",R),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:S.target.name,onValueChange:R=>N(C.id,M,O,"targetColumnName",R),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:I(C.target.name).map(R=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:R.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:R.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:R.dataType})]})},R.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>p(C.id,M,O),children:e.jsx(s.X,{className:"size-3.5"})})]},S.id||O))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>T(C.id,M),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:()=>n(o),disabled:!y(),children:"Save"})]})]})}function He({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:c,onSave:i,onCancel:o}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Ia,{joinPlan:r,availableDataSources:l,onSave:i,onCancel:o,onRemove:c})]}),t]})}function Aa({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((i,o)=>i.sequence-o.sequence),c=n.find(i=>i.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children: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=n.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=n.find(d=>d.name===l.source.name),o=n.find(d=>d.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children: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 Fa(){var h,x;const t=s.useEditorStore(j=>j.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(t),n=s.useEditorStore(j=>j.actions.updateCardConfig),r=((h=t==null?void 0:t.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[l,c]=w.useState(!1),i=((x=t==null?void 0:t.dataSource)==null?void 0:x.selectedEntities)||[],o=j=>{n(t.id,{...t==null?void 0:t.config,joinPlan:j}),c(!1)},d=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{c(!1)},m=()=>{const j=[...r.joins].sort((v,D)=>v.sequence-D.sequence),b=r.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
215
+ FROM ${b.name}`;return j.forEach(v=>{const D=i.find(L=>L.name===v.target.name);if(!D)return;const k=v.joinKeyGroups.filter(L=>L.keys&&L.keys.length>0).map(L=>{const T=L.keys.filter(N=>{var p,f,y,I;return((p=N.source)==null?void 0:p.name)&&((f=N.target)==null?void 0:f.name)&&((y=N.source)==null?void 0:y.entityName)&&((I=N.target)==null?void 0:I.entityName)}).map(N=>`${N.source.entityName}.${N.source.name} ${N.operator} ${N.target.entityName}.${N.target.name}`);return T.length>1?`(${T.join(` ${L.operator} `)})`:T[0]}).filter(Boolean),P=k.length>1?k.join(" OR "):k[0]||"condition_here";g+=`
216
+ ${v.joinType} JOIN ${D.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(Aa,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:i,generateSQLPreview:m})})]})}),(a==null?void 0:a.autoResolved)&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-6 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})}),e.jsx(s.TooltipContent,{side:"right",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium",children:"Auto-resolved using relationships:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:a.relationshipsUsed.map((j,b)=>e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:j},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 La({open:t,onOpenChange:a}){const[n,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([])},m=()=>{if(n.length===0)return;const g=n[0],v=g.connectionId||"",D=g.connectionType||"",P=n.some(T=>T.type==="dataset")?"semanticDomain":"database";l({connectionId:v,connectionType:D,mode:P,selectedEntities:n}),a(!1)},h=g=>{switch(g.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Gt,{className:"h-4 w-4"});case"model":return e.jsx(jt,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},x=g=>"label"in g&&g.label?g.label:g.name,j=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=>n.some(v=>v.name===g.name&&v.type===g.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:d,disabled:n.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",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:h(g)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:x(g)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:j(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:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:m,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function Ma({entity:t,title:a,maxDetails:n=10}){const l=s.getEntityDetails(t).slice(0,n),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:a||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 Pa({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((a,n)=>{const r=s.getEntityDetails(a),l=r.find(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(a)}),l&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),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-${a.type}-${a.name}-${n}`)})})]})})}function Os(){const t=s.useEditorStore(i=>i.card.dataSource),{setSelectedConnectionId:a,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:l,setSelectedDatamodelId:c}=s.useEditorActions();w.useEffect(()=>{var j;if(!t)return;const{tableName:i,schemaName:o,databaseName:d,connectionId:u}=Xe(t),m=(j=t.selectedEntities)==null?void 0:j[0],x=(m==null?void 0:m.type)==="model"&&"id"in m?m.id:"";a(u||""),n(d||""),r(o||""),l(i||""),c(x)},[t,a,n,r,l,c])}function Vs({isVisible:t}){const a=s.useEditorStore(x=>x.isDevMode);Os();const[n,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(!0),d=s.useEditorStore(x=>x.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:u}=s.useEditorActions(),m={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},h={...m,...d,selectedEntities:(d==null?void 0:d.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:"p-4 px-6 pb-2",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}),e.jsxs("div",{className:"relative px-6",children:[e.jsx("div",{className:"absolute inset-0 flex items-center px-6",children:e.jsx("div",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>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:[h.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.selectedEntities.slice(0,3).map((x,j)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[s.getDisplayName(x),e.jsx("button",{onClick:b=>{b.stopPropagation();const g=h.selectedEntities.filter(v=>!(v.name===x.name&&v.type===x.type));u({...m,...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(Ma,{entity:x})]},`${x.type}-${x.name}-${j}`)),h.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",h.selectedEntities.length-3," more"]})}),e.jsx(Pa,{entities:h.selectedEntities.slice(3)})]})]})}),!a&&e.jsx(Fa,{})]})]}),e.jsx(Bs,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:h}),e.jsx(La,{open:l,onOpenChange:c})]})}function Rs({error:t,errorSql:a,onSendFeedback:n,className:r,showFeedbackButton:l=!0}){const[c,i]=w.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),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:"Query Error"}),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:[a&&e.jsx(s.Collapsible,{open:c,onOpenChange:i,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?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"]})})})}),l&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:c,onOpenChange:i,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:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})})]})})})]})]})})}function zs({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:c,setCardSql:i,setRunSql:o}=s.useEditorActions();function d(){c(!l),i(t),setTimeout(()=>{o(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Rs,{error:a,errorSql:n,showFeedbackButton:!1}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!a&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(yt,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Dt,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Ba({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(pt,{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(zs,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Oa(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 qs(t){const{theme:a}=s.useTheme(),n=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(),m=w.useRef(),h=w.useRef({}),x=r.cards.find(g=>g.id===c),j=w.useCallback(()=>{let g="";return t==="python"&&(g=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(g=(x==null?void 0:x.sql)||""),g},[t,x]);w.useEffect(()=>{if(c&&l.id&&l.id!==c){if(m.current&&i){const g=m.current.getModel();g&&(h.current[l.id]=g);let v=h.current[c];if(!v){const D=j();v=i.editor.createModel(D,t),h.current[c]=v}m.current.setModel(v)}d(c,l),u(!0)}},[c,l,d,i,u,t,j]),w.useEffect(()=>{if(!i)return;const g=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=n==="system"?g:n;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")},[a,n,i]),w.useEffect(()=>{const g=m.current;g&&i&&l&&g.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return o(),!1})},[i,o,l]);function b(g,v){if(m.current=g,!h.current[l.id]){const D=g.getModel(),k=j();h.current[l.id]=D||(v==null?void 0:v.editor.createModel(k,t))||g.getModel()}g.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function Va(){const t=s.useEditorStore(i=>i.card.sql),a=s.useEditorStore(i=>i.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=qs("sql");function c(i){n(i),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:c,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Ra(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=qs("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function za({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function qa(){const t=s.useQueryClient(),{isConsoleMode:a}=s.useDashboardPreferences(),[n,r]=w.useState(!1),[l,c]=w.useState(!1);s.useEditorStore(V=>V.frame);const i=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const o=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const d=s.useEditorStore(V=>{var J;return(J=V==null?void 0:V.card)==null?void 0:J.sql}),u=s.useEditorStore(V=>{var J;return(J=V==null?void 0:V.card)==null?void 0:J.python}),{cardFilterValues:m}=s.useCardFilterValues((i==null?void 0:i.id)??""),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:j,setTempQueryData:b,setPythonStdOut:g,setCardPreferences:v,setCardType:D,setCardPython:k,runAssistant:P,setShowAIDialog:L}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const T=s.useEditorStore(V=>V.runSql),N=s.useEditorStore(V=>V.actions.setRunSql),p=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:f,isLoading:y,isFetching:I,isSuccess:C,isError:B,error:A,errorSql:F,queryKey:E,refetch:M,errorMessage:S}=s.useDashboardCardQuery(i);w.useEffect(()=>{if(f&&(f.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((f==null?void 0:f.output)||""),f.records.length>0)){const{dimensionKeys:V}=s.getKeys(f.records);x(V)}},[f,x,g]),w.useEffect(()=>{(y||I)&&p(!0),(B||C)&&p(!1),B&&(x([]),g(""))},[y,I,f,g,B,C,p,x,A]),w.useEffect(()=>{T&&(t.getQueryData(E)||M(),N(!1))},[T,M,N,E,t]);async function O(){const V=`Can you help me debug this query?
218
+
219
+ Error:
220
+
221
+ ${S}
222
+
223
+ Error SQL:
224
+
225
+ ${F}
226
+
227
+ Query:
228
+
229
+ ${d}
230
+
231
+ ${u?`Python:
232
+ ${u}`:""}
233
+ `;P(V)}function R(){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(za,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.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 _(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Va,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Ra,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function G(){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:y||I,onClick:()=>{M()},className:"h-8 shrink-0",size:"sm",children:[y||I?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(Ba,{errorSql:F,sql:f==null?void 0:f.sql,error:S,onDebugWithAssistant:O}),e.jsx(Qe,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:V=>r(V),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Oa,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:o,onClick:()=>{L(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:o?"":"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:[_(),R()]}),G()]})}const $a=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:Re}];function Ga({className:t}){const a=s.useEditorStore(d=>d.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),c=["table","aggregateTable","pivotTable"].includes(a.type),i=s.hasValidCardConfig(a.config);if(!c||!i)return null;const o=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=a.config)!=null&&m.pivotByColumns)&&a.config.pivotByColumns.length>0){const h={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(h),l(h)}else{n(u);const h={...a,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:o,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:$a.map(d=>{const u=d.icon,m=a.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function Ua({card:t}){var P,L,T,N,p,f,y,I,C,B,A;const[a,n]=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(F=>F.themeStyle),u={mode:i||"system",colors:((L=(P=d==null?void 0:d.chart)==null?void 0:P.dataset)==null?void 0:L.backgroundColor)||[]};(T=t.customCardPreferences)!=null&&T.inputData;const{getCard:m}=s.useCustomVisual(((N=t.customCardPreferences)==null?void 0:N.url)||""),h=((p=t.customCardPreferences)==null?void 0:p.visualType)||"single",x=s.useEditorStore(F=>F.frame),{setCustomCardPreferences:j}=s.useEditorActions(),{data:b}=s.useDashboardCardQuery(t),g=w.useCallback((F,E)=>{l(M=>({...M,[F]:E}))},[]);if(!((f=t.customCardPreferences)!=null&&f.componentName))return null;const v=m((y=t.customCardPreferences)==null?void 0:y.componentName);function D(F){n(F)}const k=Object.keys(((I=t.customCardPreferences)==null?void 0:I.dataInputCardIds)||{}).map(F=>{var S,O,R;const E=(O=(S=t.customCardPreferences)==null?void 0:S.dataInputCardIds)==null?void 0:O[F].cardId,M=(R=x==null?void 0:x.cards)==null?void 0:R.find(_=>_.id===E);return M||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(w.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[v&&h==="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&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((B=t.customCardPreferences)==null?void 0:B.dataInputCardIds)||{}).map(F=>{var S,O,R;const E=(O=(S=t.customCardPreferences)==null?void 0:S.dataInputCardIds)==null?void 0:O[F].cardId,M=(R=x==null?void 0:x.cards)==null?void 0:R.find(_=>_.id===E);if(M)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:D,onDataChange:g,dataInputIndex:F,card:M},M.id+F)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(v,{theme:u,onDataChange:g,settings:k.map(F=>{var E;return(E=F==null?void 0:F.customCardPreferences)==null?void 0:E.settings}),data:k.map(F=>F!=null&&F.id?r==null?void 0:r[F.id]:[])})})]})]},(A=t.customCardPreferences)==null?void 0:A.componentName)})}function $s({className:t,...a}){var f;const n=s.useEditorStore(y=>y.card),r=s.hasValidCardConfig(n.config),l=((f=n.customCardPreferences)==null?void 0:f.showCardHeader)??!0,c=s.useEditorStore(y=>y.frame),i=s.useDashboardStore(y=>y.dashboard.filters),o=s.useEditorStore(y=>y.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=i==null?void 0:i.find(y=>y.id===c.filterId),{data:m,isLoading:h,isFetching:x,errorMessage:j,pagination:b}=s.useDashboardCardQuery(n),{setCard:g,updateCardInFrame:v}=s.useEditorActions(),{data:D}=s.useTopoJson(n),k=w.useMemo(()=>{var y;return n.type!=="pivotTable"||!((y=m==null?void 0:m.records)!=null&&y.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[n.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),P=s.usePivotTableConfig(n,k),L=(y,I)=>{var B,A;const C={...n,paginationConfig:{page:y+1,pageSize:I}};g(C),v(C),n.sql&&((A=(B=n.preferences)==null?void 0:B.tablePrefs)!=null&&A.enableDevModePagination)&&o(!0)},T=w.useMemo(()=>!n.id||!(m!=null&&m.records)?null:s.createChartConfig({card:n,data:m==null?void 0:m.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:D}),[n.id,m==null?void 0:m.records,n.type,n.queryConfig,n.customCfg,n.preferences,D]);function N(y){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ua,{card:y})})}function p(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!x)return j?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):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((h||x)&&n.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return N(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&T)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||x?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:T})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:(m==null?void 0:m.records)||[],paginationMetadata:b,onPaginationChange:L,isLoading:h||x})});if(n.type==="pivotTable"&&P)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:n,data:P.data,options:P.options,onAggregationChange:y=>{const I=s.handleAggregationChange(y,n.config),C={...n,config:I};g(C),v(C)},onAggregationLabelChange:y=>{const I=s.handleAggregationLabelChange(y,n.config),C={...n,config:I};g(C),v(C)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:b,onPaginationChange:L,onAggregationChange:y=>{const I=s.handleAggregationChange(y,n.config),C={...n,config:I};g(C),v(C)},isLoading:h||x})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[l&&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 justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:y=>g({...n,title:y}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Ga,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:y=>g({...n,description:y}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:y=>d({...u,title:y}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:p()})]})}const qe=({language:t,value:a,onChange:n,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:a,onChange:n}),Ka=()=>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."})]})]}),_a=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{language:"javascript",value:t,onChange:l})})]}),Ha=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function Ja(){const[t,a]=w.useState(!1),[n,r]=w.useState(""),[l,c]=w.useState(""),[i,o]=w.useState(""),[d,u]=w.useState(""),m=s.useEditorStore(T=>T.card),h=s.useEditorStore(T=>T.card.customCfg),x=h?JSON.stringify(h,null,2):"",{data:j}=s.useDashboardCardQuery(m),{data:b}=s.useTopoJson(m),{setCardCustomCfg:g,setCustomVisualCode:v}=s.useEditorActions(),D=T=>{var N,p;return JSON.stringify({...T,data:{...T.data,datasets:(p=(N=T.data)==null?void 0:N.datasets)==null?void 0:p.map(f=>({...f,data:[]}))}},null,2)},k=()=>{var N,p;if(!((N=j==null?void 0:j.records)!=null&&N.length))return;const T=s.createChartConfig({card:m,data:j.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:b});if(T){r(D(T)),o(((p=m.preferences)==null?void 0:p.customVisualCode)||"");const f=s.merge(T,h);c(D(f))}},P=()=>{try{if(i&&v(i),l){const T=JSON.parse(l),N=s.getObjectDiff(JSON.parse(n),T);g(N),u("")}}catch{u("Invalid JSON configuration")}},L=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:k,className:L?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Ka,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx($s,{className:"w-1/2 rounded shadow-none"})}),e.jsx(_a,{customCode:i,cardCustomCfgString:x,mergedConfig:l,onConfigChange:T=>c(T??""),onCodeChange:T=>o(T??"")})]}),e.jsx(Ha,{error:d,hasCardCustomConfig:!!h,onReset:()=>{c(n),g(null)},onApply:P,onClose:()=>a(!1)})]})]})}function ze(t){const[a,n]=w.useState(null);return a}function Gs(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),{data:n,isLoading:r,isFetching:l,isError:c}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(a.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:n,isLoading:r,isFetching:l,isError:c}}function Us(){const{data:t,isLoading:a,isError:n}=Gs(),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=a,i=n;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 m=t.plugins[d],h=o.data.visuals.map(x=>({name:x.name,pluginName:m.label,componentType:x.componentType,pluginType:m.type,icon:x.icon,chartType:x.chartType,url:m.value}));l.push(...h)}}),{data:l,isLoading:c,isError:i}}function Qa({onChartTypeChange:t}){const{setCardCustomCfg:a,setCardPreferences:n,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:c,isLoading:i,isError:o}=Us(),d=w.useCallback((u,m)=>{a(null),n({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[a,n,r,l,t]);return i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):o?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"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-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:c.map((u,m)=>e.jsx(Wa,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const Wa=({text:t,icon:a,onClick:n})=>{const r=ze(),l=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:n,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):l})};function Ya({onChartTypeChange:t,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:l}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:c,setCustomCardPreferences:i,setQueryConfig:o}=s.useEditorActions();function d(m,h){c(null),r({}),n(m),["custom","text","map"].includes(m)&&(l(!0),o(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",a),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",a)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(Le,{className:s.cn("size-5",a)})})]})}function Xa({chartType:t,className:a,customIcon:n,componentName:r}){const l=ze();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:a});case"line":return e.jsx(s.ChartLine,{className:a});case"pie":return e.jsx(s.ChartPie,{className:a});case"radar":return e.jsx(s.Radar,{className:a});case"scatter":return e.jsx(s.ChartScatter,{className:a});case"bubble":return e.jsx(s.TbChartBubble,{className:a});case"doughnut":return e.jsx(s.Donut,{className:a});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:a});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:a});case"polarArea":return e.jsx(s.PiChartPolar,{className:a});case"funnel":return e.jsx(s.TbChartFunnel,{className:a});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:a});case"range":return e.jsx(s.ChartNoAxesGantt,{className:a});case"kpi":return e.jsx(s.TiSortNumerically,{className:a});case"text":return e.jsx(s.Type,{className:a});case"map":return e.jsx(s.Map,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Le,{className:a});default:return e.jsx(s.Table2,{className:a})}}function Ks({variant:t="ghost"}){var c,i;const[a,n]=w.useState(!1),r=s.useEditorStore(o=>o.card),l=r.type;return s.useDashboardStore(o=>o.isVisualEditing),e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Xa,{className:"size-4",chartType:l,customIcon:(c=r.customCardPreferences)==null?void 0:c.icon,componentName:(i=r.customCardPreferences)==null?void 0:i.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:o=>o.preventDefault(),className:"z-[51] w-72 p-1",children:[e.jsx(Ya,{onChartTypeChange:()=>n(!1)}),e.jsx(Qa,{onChartTypeChange:()=>n(!1)})]})]})}function Za({error:t,className:a="",textClassName:n="",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(x){(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d())}function m(){const x=window.getSelection();if(x&&x.toString().trim()!==""){const j=x.toString();navigator.clipboard.writeText(j),c(!0),o.current=!0,setTimeout(()=>{c(!1),o.current=!1},1e3)}else o.current=!1}function h(){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 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function en(){const t=s.useEditorStore(c=>{var i,o;return(o=(i=c.card.preferences)==null?void 0:i.chartOptions)==null?void 0:o.indexAxis}),a=s.useEditorStore(c=>c.card.type),{setChartOrientation:n}=s.useEditorStore(c=>c.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(cs,{className:"size-4"}):e.jsx(is,{className:"size-4"})})}function l(){return e.jsx(s.IconButton,{onClick:()=>{n(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(cs,{className:"size-4"}):e.jsx(is,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():r()})}function sn({className:t}){var x,j,b,g,v,D,k,P;const a=s.useEditorStore(L=>L.card),{setCardPreferences:n,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[c,i]=w.useState(!1),o=((j=(x=a.preferences)==null?void 0:x.displayOptions)==null?void 0:j.showFilterInfo)??!0,d=((g=(b=a.preferences)==null?void 0:b.displayOptions)==null?void 0:g.showCardToolbar)??!0,u=((D=(v=a.preferences)==null?void 0:v.displayOptions)==null?void 0:D.showChrome)??!0,m=((P=(k=a.preferences)==null?void 0:k.displayOptions)==null?void 0:P.allowScroll)??!0,h=(L,T)=>{var f;const N={...a.preferences,displayOptions:{...(f=a.preferences)==null?void 0:f.displayOptions,[L]:T}};n(N);const p={...a,preferences:N};l(p),r(p)};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(Ss,{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:L=>{h("showFilterInfo",L)},onSelect:L=>L.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:L=>{h("showCardToolbar",L)},onSelect:L=>L.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:L=>{h("showChrome",L)},onSelect:L=>L.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:L=>{h("allowScroll",L)},onSelect:L=>L.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]})]})]})})}function _s(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var i,o;return(o=(i=c.card)==null?void 0:i.preferences)==null?void 0:o.chartOptions}),n=s.getChartGridStyle(a),{setChartGrid:r}=s.useEditorActions();function l(){const c=["xy","none","x","y"],o=(c.indexOf(n)+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(en,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(n==="xy"||!n)&&e.jsx(Re,{className:"size-4"}),n==="x"&&e.jsx(ft,{className:"size-4"}),n==="y"&&e.jsx(Bt,{className:"size-4"}),n==="none"&&e.jsx(Rt,{className:"size-4"})]}),e.jsx(sn,{})]})}function tn(){const t=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),{setFrame:n,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 D=Array.from(t.cards),[k]=D.splice(parseInt(v),1);D.splice(g,0,k),n({...t,cards:D})};function u(b){const g=t.cards.filter(k=>k.id!==b),v=g[0],D={...t,cards:g,activeCardId:v.id};n(D),r(v.id),l(v)}function m(b,g){const v={...t,cards:[...t.cards,g],activeCardId:b.id};n(v),r(g.id)}function h(){const b={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,b)}function x(b){const 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"};m(b,g)}function j(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(vt,{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:[j(t,b),e.jsx(s.Editable,{enabled:t.activeCardId===b.id,text:b.tabTitle||b.title,onSave:v=>{l({...a,tabTitle:v}),c({...a,tabTitle:v})},children:b.tabTitle||b.title},b.id),t.activeCardId===b.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:v=>{v.stopPropagation(),h()}}),t.activeCardId===b.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(b.id)})]},b.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>x(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Hs(){const t=s.useEditorStore(v=>v.frame),a=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:l,setActiveTabCardId:c,setCard:i,setIsDevMode:o,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h,isError:x}=s.useDashboardCardQuery(a);function j(v){const D=t.cards.find(k=>k.id===v);if(D!=null&&D.sql){r||o(!0),c(v);return}if(D!=null&&D.queryConfig){r&&o(!1),b(v),c(v);return}r||b(v),c(v)}function b(v){const D={...t,cards:t.cards.map(P=>P.id===a.id?a:P),activeCardId:v};l(D);const k=D.cards.find(P=>P.id===v);k.sql&&d(!0),i(k)}function g(){return a.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:m||h,isError:x})})}):a.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx($s,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:j,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(tn,{})]})}function hs({children:t}){var N,p;s.useEditorStore(f=>f.frame);const a=s.useEditorStore(f=>f.card),n=s.useEditorStore(f=>f.isDevMode),r=s.useEditorStore(f=>f.isShowingVisual),l=s.useDashboardStore(f=>f.isVisualEditing),c=s.useEditorStore(f=>f.pythonStdOut);s.useEditorStore(f=>f.actions.setRunSql);const{setFrame:i,setCard:o,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:x,isLoading:j,isFetching:b,errorMessage:g,refetch:v}=s.useDashboardCardQuery(a),[D,k]=w.useState(!1);w.useEffect(()=>{b||k(!1)},[b]);function P(){const f=JSON.stringify(x==null?void 0:x.records,null,2),y=new Blob([f],{type:"application/json"}),I=URL.createObjectURL(y),C=document.createElement("a");C.href=I,C.download=`${a.title}.json`,C.click()}function L(){const y=[Object.keys(x==null?void 0:x.records.reduce((A,F)=>({...A,...F}),{})).join(","),...((x==null?void 0:x.records)||[]).map(A=>Object.values(A).join(","))].join(`
234
+ `),I=new Blob([y],{type:"text/csv"}),C=URL.createObjectURL(I),B=document.createElement("a");B.href=C,B.download=`${a.title}.csv`,B.click()}function T(){const f=`Can you get the documentation for ${a.type} chart?`;u(f)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ks,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:T,children:e.jsx(mt,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(Ja,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:L,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:P,children:e.jsx(Nt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(x==null?void 0:x.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:j||b,onClick:()=>{k(!0),v()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":D})})}),e.jsx(_s,{})]}),a.type==="table"&&a.sql&&n&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((p=(N=a.preferences)==null?void 0:N.tablePrefs)==null?void 0:p.enableDevModePagination)??!1,onCheckedChange:f=>{var y;h({...a.preferences,tablePrefs:{...(y=a.preferences)==null?void 0:y.tablePrefs,enableDevModePagination:f}}),v()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(nn,{})]}),r?e.jsx(Hs,{}):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(an,{})}),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:[(x==null?void 0:x.records)&&(x==null?void 0:x.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:(x==null?void 0:x.records)||[]}),g&&e.jsx(Za,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function an(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function nn(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ye({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className: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:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function rn(){var g,v;const t=s.useEditorStore(D=>D.card.customCardPreferences),{data:a}=Gs(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(D=>D.card),l=s.useEditorStore(D=>D.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(D=>D.name===(t==null?void 0:t.componentName));function m(D,k){if(!t)return;const L={...(t==null?void 0:t.dataInputCardIds)||{},[D]:{cardId:k,hookRef:null}};i({...t,dataInputCardIds:L})}function h(D){var P,L;const k=(P=l==null?void 0:l.cards)==null?void 0:P.filter(T=>{var N;return((N=T==null?void 0:T.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(T=>({value:T.id,label:T.tabTitle||T.title}));return e.jsx("div",{className:"space-y-2",children:(L=D==null?void 0:D.dataInputs)==null?void 0:L.map((T,N)=>{var p,f;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:((f=(p=t==null?void 0:t.dataInputCardIds)==null?void 0:p[N])==null?void 0:f.cardId)||"",onValueChange:y=>m(N,y)})]},N+Math.random())})})}function x(D,k,P=[],L=""){var T,N;return t?D==="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])||L,onChange:p=>{i({...t,settings:{...t==null?void 0:t.settings,[k]:p.target.value}})}},k):D==="select"?e.jsx(ye,{className:"h-8 w-full",label:"",options:P,value:((N=t==null?void 0:t.settings)==null?void 0:N[k])||L,onValueChange:p=>{i({...t,settings:{...t==null?void 0:t.settings,[k]:p}})}}):null:null}function j(D){const k=Object.entries((D==null?void 0:D.settings)||{});return e.jsx("div",{className:"space-y-3",children:k.map(([P,L])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:L.title}),x(L.ui,P,L.options,L.defaultValue)]},P))})}function b(D){t&&i({...t,visualType:D,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(ut,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:D=>i({...t||{url:"",componentName:""},url:D})}),((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(gt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.filter(D=>D.type===c).map(D=>({value:D.name,label:D.name})))||[],value:t.componentName,onValueChange:D=>{console.log("changing value",D),i({...t,componentName:D})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:j(u)})})]})]})]})}function Te(){const[t,a]=w.useState([]),n=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 m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),w.useEffect(()=>{c&&a(new Array(c.length).fill(!1))},[c]);function i(u,m){var h,x;m?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(x=n==null?void 0:n.onClickFilter)==null?void 0:x.filter(j=>j.columnIndex!==u)}),a(j=>{const b=[...j];return b[u]=!1,b}))}function o(u,m){var x;const h=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.map(j=>j.columnIndex===u?{...j,expression:m.target.value}:j);l({...n,onClickFilter:h})}function d(u){var m,h,x,j;if(t!=null&&t[u]||(h=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(b=>b.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(j=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(b=>b.columnIndex===u))==null?void 0:j.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,m)=>{var h,x;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(j=>j.columnIndex===m)),onCheckedChange:j=>i(m,j)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(j=>j.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(j=>{const b=[...j];return b[m]=!j[m],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function ln({idx:t}){var o;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(o=a==null?void 0:a.chartOptions)==null?void 0:o.indexAxis,c=n==null?void 0:n.find(d=>d.idx===t);function i(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!c)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const h={...c};h.datalabels=m;const x=n==null?void 0:n.map(j=>j.idx===u?h:j);r({...a,datasetOptions:x})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(ws,{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(Tt,{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(It,{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(Et,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function on(){const t=s.useEditorStore(c=>c.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(c=>!s.METADATA_KEYS.includes(c));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const c=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:i}=s.getKeys(c);l=i.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Ze({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Js(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:c,transformedMetricKeys:i,keys:o}=on();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:Qs(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(Ws,{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 Qs(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Ws({col:t,idx:a,className:n,iconClassName:r,children:l}){const c=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),i=s.useEditorStore(m=>{var h,x;return(x=(h=m.card)==null?void 0:h.preferences)==null?void 0:x.datasetOptions}),o=i==null?void 0:i.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!o)d({...c,datasetOptions:[...i||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...o};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const x=i==null?void 0:i.map(j=>j.idx===a?h:j);d({...c,datasetOptions:x})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Ze,{className:"max-w-[100px]",title:t,children:Qs(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(ln,{idx:a})]})]})}function Ae(){const t=s.useDashboardStore(o=>o.dashboard.filters),a=s.useEditorStore(o=>o.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Ps();function c(o){const d=l(o,"frame");n({...a,filterId:d})}const i=t==null?void 0:t.find(o=>o.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(cn,{onSelect:c,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function cn({columns:t,onSelect:a}){var i;const[n,r]=Ue.useState(!1),[l,c]=Ue.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(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&&a(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 dn({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Js,{})})]}),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(Ae,{})]})]})]})})}function un({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick: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:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Te,{}),e.jsx(Ae,{})]})]})]})})}function Ys(){const t=s.useEditorStore(o=>o.card.type),a=s.useEditorStore(o=>o.isDevMode),n=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:r}=s.useEditorStore(o=>o.actions);function l(o){var m;const d={datalabels:{display:o!=="none",align:o,anchor:o,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function 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=n==null?void 0:n.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=n==null?void 0:n.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:a?c():i()})}const mn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},hn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function xn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:pn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ys,{}),e.jsx(Te,{}),e.jsx(Ae,{})]})]})}function pn(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(mn,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(hn,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 fn({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(i,o,d){const u=[...t];u[i]={...u[i],[o]:d},a(u)}function l(i){const o=[...t];o.splice(i,1),a(o)}function c(){a([...t,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick: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 gn(){var m,h,x,j,b;const t=s.useEditorStore(g=>g.card.preferences),a=s.useEditorStore(g=>g.actions.setCardPreferences),n=s.useEditorStore(g=>g.card),r=s.hasValidCardConfig(n.config),l=s.useEditorStore(g=>g.actions.setNumberFormat);s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.decimalPlaces});const c=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.locale}),i=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.currency});s.useEditorStore(g=>g.actions.setFilterOnClickField);const o=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.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:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:g=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:g}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:c||"none",onValueChange:g=>{var v,D,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((D=t==null?void 0:t.formatNumber)==null?void 0:D.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,D,k;console.log("currency",g),l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,g==="none"?"":g,((D=t==null?void 0:t.formatNumber)==null?void 0:D.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:((j=(x=t==null?void 0:t.formatNumber)==null?void 0:x.decimalPlaces)==null?void 0:j.toString())||"0",onValueChange:g=>{var v,D,k;return l(Number(g),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((D=t==null?void 0:t.formatNumber)==null?void 0:D.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,D,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((D=t==null?void 0:t.formatNumber)==null?void 0:D.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(fn,{colorRanges:o,setColorRanges:d})]})]})}function jn(){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(gn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function $e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const bn=[{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"}],vn=["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"],yn=vn.map(t=>({label:t,value:t}));function Nn(){var d,u,m,h,x,j,b,g,v,D,k,P,L,T,N,p,f,y;const t=s.useEditorStore(I=>I.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=w.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:c}=s.useTopoJson(t),i=Object.keys((c==null?void 0:c.objects)||{}).map(I=>({label:I,value:I}))||[],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:I=>{console.log("value",I),l({...t.preferences,mapVisualOptions:{topoJsonUrl:I}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:I=>{r(I.target.value)},onBlur:()=>{var I;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(I=t.preferences)==null?void 0:I.mapVisualOptions,customTopoJsonUrl:n}})},value:n,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:((j=(x=t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:j.objectKey)||"",label:"Map Object",onValueChange:I=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,objectKey:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ye,{className:"h-9",options:bn,value:((g=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:g.projection)||"",label:"Projection",onValueChange:I=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projection:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ye,{className:"h-9",options:yn,value:((D=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:D.colorScale)||"",label:"Select Color Scale",onValueChange:I=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,colorScale:I}})}})]})]})]})}),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:I=>{var C;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projectionScale:Number(I.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(T=(L=t.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:N[0])||0,onChange:I=>{var C,B,A,F;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projectionOffset:[Number(I.target.value),((F=(A=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((y=(f=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:f.projectionOffset)==null?void 0:y[1])||0,onChange:I=>{var C,B,A,F;l({...t.preferences,mapVisualOptions:{...(C=t.preferences)==null?void 0:C.mapVisualOptions,projectionOffset:[((F=(A=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[0])||0,Number(I.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Te,{})]})}function Cn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Be({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Cn,{})})]}),!["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(Ae,{})]})]})]})})}function Sn(){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:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(ye,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Js,{})]})]}),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(Ae,{})]})]})]})})}function wn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var c;return(c=l.card)==null?void 0:c.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Te,{}),e.jsx(Ae,{})]})]})}),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 Xs({color:t,onColorChange:a,onClose:n}){const[r,l]=w.useState(0),[c,i]=w.useState(100),[o,d]=w.useState(50),[u,m]=w.useState(t);w.useEffect(()=>{const v=xs(t);if(v){const D=ps(v.r,v.g,v.b);l(D.h),i(D.s),d(D.l),m(t)}},[t]);const h=v=>{l(v),j(v,c,o)},x=v=>{const D=v.currentTarget.getBoundingClientRect(),k=Math.max(0,Math.min(1,(v.clientX-D.left)/D.width)),P=Math.max(0,Math.min(1,(v.clientY-D.top)/D.height)),L=k*100,T=(1-P)*100;i(L),d(T),j(r,L,T)},j=(v,D,k)=>{const P=kn(v,D,k),L=Dn(P.r,P.g,P.b);m(L)},b=v=>{if(m(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const D=xs(v);if(D){const k=ps(D.r,D.g,D.b);l(k.h),i(k.s),d(k.l)}}},g=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:x,onMouseMove:v=>{v.buttons===1&&x(v)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${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=>h(Number(v.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:v=>b(v.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:g,children:"OK"})]})]})}function xs(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Dn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function ps(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);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=((a-n)/d+(a<n?6:0))/6;break;case a:c=((n-t)/d+2)/6;break;case n:c=((t-a)/d+4)/6;break}}return{h:Math.round(c*360),s:Math.round(i*100),l:Math.round(o*100)}}function kn(t,a,n){t/=360,a/=100,n/=100;let r,l,c;if(a===0)r=l=c=n;else{const i=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),o=n<.5?n*(1+a):n+a-n*a,d=2*n-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 Tn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Zs(){var P,L,T,N,p,f,y,I,C,B;const t=s.useEditorStore(A=>A.card),a=s.useEditorStore(A=>{var F;return(F=A.card)==null?void 0:F.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[c,i]=w.useState({}),[o,d]=w.useState(null),[u,m]=w.useState(null),h=w.useMemo(()=>{var M,S,O,R,_,G,V;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",F=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",E=((M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)&&t.config.pivotByColumns.length>0;if((A||F)&&E){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const J=new Set;return l.pivotSchema.forEach(X=>{X.alias&&J.add(X.alias)}),Array.from(J)}if(l.records.length>0){const J=l.records[0],X=Object.keys(J),ie=new Set;(S=t==null?void 0:t.config)!=null&&S.groupByColumns&&t.config.groupByColumns.forEach(Y=>{ie.add(Y.label||Y.name),ie.add(Y.alias||Y.name)});const se=new Set;return(O=t==null?void 0:t.config)!=null&&O.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 ee=Y.entityName||Y.qualifiedEntityName;ee&&(se.add(`${ee}_${$}`),se.add(`${ee}_${$}_count`))}),X.filter(Y=>!ie.has(Y)&&!se.has(Y))}}if((F||A)&&!E&&((_=(R=t==null?void 0:t.config)==null?void 0:R.metricColumns)!=null&&_.length))return t.config.metricColumns.map(J=>J.alias||J.label||J.name);if((V=(G=t==null?void 0:t.config)==null?void 0:G.groupByColumns)!=null&&V.length){const J=t.config.groupByColumns[0],X=J.label||J.name,ie=new Set;return l.records.forEach(se=>{const ae=se[X];ae!=null&&ie.add(String(ae))}),Array.from(ie)}return[]},[l,(P=t==null?void 0:t.config)==null?void 0:P.groupByColumns,(L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns,(T=t==null?void 0:t.config)==null?void 0:T.metricColumns,t==null?void 0:t.type]),x=w.useMemo(()=>s.getDefaultChartColors(),[]);w.useEffect(()=>{const A={};h.forEach((F,E)=>{A[F]=s.getColorForValue(F,E,a==null?void 0:a.colorConfig)}),i(A)},[h,a==null?void 0:a.colorConfig,x]);const j=(A,F)=>{const E={...c,[A]:F};i(E);const M={...a||{},colorConfig:{segments:E}};n(M);const S={...t,preferences:M};r(S)},b=(A,F)=>{var _;const E=x[F%x.length],{[A]:M,...S}=((_=a==null?void 0:a.colorConfig)==null?void 0:_.segments)||{},O={...a||{},colorConfig:{segments:S}};n(O);const R={...t,preferences:O};r(R),i(G=>({...G,[A]:E}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((p=(N=t==null?void 0:t.config)==null?void 0:N.groupByColumns)==null?void 0:p.length)||((y=(f=t==null?void 0:t.config)==null?void 0:f.pivotByColumns)==null?void 0:y.length):(C=(I=t==null?void 0:t.config)==null?void 0:I.groupByColumns)==null?void 0:C.length)||["table","kpi","text","custom"].includes(t.type))return null;const D=()=>{const A={...a||{},colorConfig:{segments:{}}};n(A);const F={...t,preferences:A};r(F);const E={};h.forEach((M,S)=>{E[M]=s.getColorForValue(M,S,void 0)}),i(E)},k=Object.keys(((B=a==null?void 0:a.colorConfig)==null?void 0:B.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(Mt,{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:D,children:[e.jsx(ds,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((A,F)=>{const E=s.isDefaultColor(c[A],F),M=!E;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:o===A,onOpenChange:S=>d(S?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:x.slice(0,10).map((S,O)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[A]===S?"border-gray-900":"border-transparent"),style:{backgroundColor:S},onClick:()=>{j(A,S),d(null)},children:[O===F%x.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:S})]},`default-${O}`))})]}),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:Tn.map((S,O)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[A]===S?"border-2 border-gray-900":S==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:S},onClick:()=>{j(A,S),d(null)},children:e.jsx("span",{className:"sr-only",children:S})},`preset-${O}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value: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,F),d(null)},children:[e.jsx(ds,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:A}),M&&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:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Xs,{color:u.color,onColorChange:A=>{j(u.value,A),m(null)},onClose:()=>m(null)})})]})]})})]})}function Ne({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[c,i]=w.useState(t??""),[o,d]=w.useState(!1);w.useEffect(()=>{i(t??"")},[t]);const u=()=>{a(c),d(!1)},m=()=>{i(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:o?c:t??"",onChange:h=>{i(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&o&&c!==t?u():h.key==="Escape"&&m()},"aria-label":n||"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:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const En=["auto","number","currency","percent","scientific","date"],In=[{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"}],An=[{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"}],Fn=t=>t.charAt(0).toUpperCase()+t.slice(1);function es({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",c=(o,d)=>{a({...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:[n&&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:En.map(o=>e.jsx(s.SelectItem,{value:o,className:"text-xs",children:o==="auto"?"Auto (Default)":Fn(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:In.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:An.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 fs({axis:t,label:a,type:n,config:r,onChange:l}){var h,x,j,b,g,v,D,k,P,L,T,N;const c=(p,f)=>{l({...r,[p]:f})},i=(p,f)=>{var y,I;l({...r,name:{enabled:p==="enabled"?f:((y=r==null?void 0:r.name)==null?void 0:y.enabled)??!1,text:p==="text"?f:(I=r==null?void 0:r.name)==null?void 0:I.text}})},o=(p,f)=>{var y,I;l({...r,labels:{enabled:p==="enabled"?f:((y=r==null?void 0:r.labels)==null?void 0:y.enabled)??!0,rotation:p==="rotation"?f:(I=r==null?void 0:r.labels)==null?void 0:I.rotation}})},d=(p,f)=>{l({...r,scale:{...r==null?void 0:r.scale,[p]:f===""?"auto":Number(f)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:p=>c("enabled",p),onClick:p=>p.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:p=>i("enabled",p)})]}),((x=r==null?void 0:r.name)==null?void 0:x.enabled)&&e.jsx(Ne,{placeholder:`${a} title`,value:((j=r==null?void 0:r.name)==null?void 0:j.text)||"",onSave:p=>i("text",p),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:p=>c("position",p),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p==="auto"?"Auto (Default)":s.titleCase(p)},p))})]})]}),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:p=>o("enabled",p)})]}),((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:p=>o("rotation",p==="auto"?"auto":Number(p)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p==="auto"?"Auto (Default)":`${p}°`},p))})]})]})]}),n==="value"&&e.jsx(es,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:p=>l({...r,formatOptions:p}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"auto",value:((D=r==null?void 0:r.scale)==null?void 0:D.min)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.min)===void 0?"":String(r.scale.min),onSave:p=>d("min",p),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"||((L=r==null?void 0:r.scale)==null?void 0:L.max)===void 0?"":String(r.scale.max),onSave:p=>d("max",p),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"||((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)===void 0?"":String(r.scale.stepSize),onSave:p=>d("stepSize",p),className:""})})]})]})]})]})]})}function et(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>{var o;return(o=i.card)==null?void 0:o.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const c=(i,o)=>{const u={...a||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:o};n(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ss,{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(fs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:a==null?void 0:a.xAxisConfig,onChange:i=>c("x",i)}),l.hasYAxis&&e.jsx(fs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:a==null?void 0:a.yAxisConfig,onChange:i=>c("y",i)})]})})]})}function st(){const t=s.useEditorStore(u=>u.card),a=s.useEditorStore(u=>{var m,h,x,j;return(j=(x=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:x.plugins)==null?void 0:j.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",l="center",c=!(t.type==="stackedBar"||t.type==="stackedLine"),i=(u,m)=>{const h={...a,[u]:m};n(h)},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(kt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??c,onCheckedChange:u=>i("display",u)})]}),((a==null?void 0:a.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:(a==null?void 0:a.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:(a==null?void 0:a.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 tt(){var f,y,I,C,B,A,F,E,M;const t=s.useEditorStore(S=>S.card),a=s.useEditorStore(S=>{var O,R;return(R=(O=S.card)==null?void 0:O.preferences)==null?void 0:R.dataLabelsConfig}),n=s.useEditorStore(S=>{var O;return(O=S.card)==null?void 0:O.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const c=((f=n==null?void 0:n.chartOptions)==null?void 0:f.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=(I=(y=n==null?void 0:n.chartOptions)==null?void 0:y.plugins)==null?void 0:I.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(a==null?void 0:a.enabled)!==void 0?a.enabled:m,x=(S,O)=>{const R={...a,[S]:O},_={...t.preferences||{},dataLabelsConfig:R};r(_);const G={...t,preferences:_};l(G)},j=(S,O)=>{const R={...a,font:{...a==null?void 0:a.font,[S]:O}},_={...t.preferences||{},dataLabelsConfig:R};r(_);const G={...t,preferences:_};l(G)},b=(S,O)=>{const R={...a,formatOptions:{...a==null?void 0:a.formatOptions,[S]:O}},_={...t.preferences||{},dataLabelsConfig:R};r(_);const G={...t,preferences:_};l(G)},v=(()=>{const S=t.type;return S==="stackedBar"||S==="stackedLine"||S==="pie"||S==="doughnut"?"center":c?"right":"top"})();let D=[];i||o?D=["center"]:D=["auto",...(c?["center","left","right"]:["center","top","bottom"]).filter(O=>O!==v),"custom"];const k=()=>s.titleCase(v),P=["center","start","end"],L=["center","start","end","top","bottom"],T=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],N=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],p=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:S=>x("enabled",S)})]}),h&&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:(a==null?void 0:a.position)||"auto",onValueChange:S=>x("position",S),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(S=>e.jsx(s.SelectItem,{value:S,className:"text-xs",children:S==="auto"?k():S==="custom"?"Custom (Advanced)":s.titleCase(S)},S))})]})]}),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:(a==null?void 0:a.showTotal)??!1,onCheckedChange:S=>x("showTotal",S)})]}),(a==null?void 0:a.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(a==null?void 0:a.anchor)||"center",onValueChange:S=>x("anchor",S),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:P.map(S=>e.jsx(s.SelectItem,{value:S,className:"text-xs",children:s.titleCase(S)},S))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((a==null?void 0:a.align)||"center"),onValueChange:S=>x("align",S),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(S=>e.jsx(s.SelectItem,{value:S,className:"text-xs",children:s.titleCase(S)},S))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(a==null?void 0:a.format)||(d?"auto":"none"),onValueChange:S=>x("format",S),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:T.map(S=>e.jsx(s.SelectItem,{value:S,className:"text-xs",children:S==="auto"&&d?"Auto (Use Axis)":S==="none"?"None (Raw Value)":s.titleCase(S)},S))})]})]}),(a==null?void 0:a.format)&&!["auto","none"].includes(a.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(a.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String(((C=a==null?void 0:a.formatOptions)==null?void 0:C.decimalPlaces)??(a.format==="currency"?2:a.format==="percent"?1:0)),onSave:S=>b("decimalPlaces",Number(S)),className:""})})]}),a.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=a==null?void 0:a.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:S=>b("currency",S),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(S=>e.jsx(s.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]}),["number","currency"].includes(a.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((A=a==null?void 0:a.formatOptions)==null?void 0:A.useSuffix)??!1,onCheckedChange:S=>b("useSuffix",S)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((F=a==null?void 0:a.formatOptions)==null?void 0:F.locale)||"en-US",onValueChange:S=>b("locale",S),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(S=>e.jsx(s.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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=a==null?void 0:a.font)==null?void 0:E.size)||12),onSave:S=>j("size",Number(S)),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:((M=a==null?void 0:a.font)==null?void 0:M.weight)||"normal",onValueChange:S=>j("weight",S),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(a==null?void 0:a.color)==="auto"||!(a!=null&&a.color)?"auto":"custom",onValueChange:S=>{S==="auto"&&x("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{type:"number",placeholder:"0",value:String((a==null?void 0:a.rotation)||0),onSave:S=>x("rotation",Number(S)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Ln(){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(Zs,{}),e.jsx(et,{}),e.jsx(st,{}),e.jsx(tt,{})]})]})}const Mn=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."]})]}),Pn=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."]})]}),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 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 On(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=c=>r.includes(n)?c:e.jsxs(e.Fragment,{children:[c,e.jsx(Ln,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(Sn,{}));case"tornado":case"pyramid":return l(e.jsx(Be,{docContent:Mn,cardType:n}));case"kpi":return e.jsx(jn,{});case"line":case"bar":return l(e.jsx(dn,{cardType:n}));case"range":return l(e.jsx(Be,{docContent:Pn,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Be,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(un,{cardType:n}));case"table":return e.jsx(wn,{cardType:n});case"text":return e.jsx(Be,{docContent:Bn,cardType:n,suffix:"Visual"});case"map":return e.jsx(Nn,{});case"custom":return e.jsx(rn,{});default:return l(e.jsx(xn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Vn(){const t=w.useRef(null),a=w.useRef(null),n=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=a.current)==null||c.resize(0)):((i=t.current)==null||i.resize(25),(o=a.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(qa,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(On,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(hs,{})})]}):e.jsx(hs,{})})]})}function Rn(t){var ne;s.useAIInteractionStore(q=>q.currentAIContext);const[a,n]=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:m,setCardSql:h,setRunSql:x,switchCardType:j,setQueryConfig:b}=s.useEditorActions(),g=s.useEditorStore(q=>q.currentAssitantScope)||[],v=s.useEditorStore(q=>q.userInputForAI),D=s.useEditorStore(q=>q.triggerAIRun),k=s.useEditorStore(q=>q.card),P=s.useEditorStore(q=>q.selectedDatabaseName),L=s.useEditorStore(q=>q.selectedTableName),T=s.useEditorStore(q=>q.selectedConnectionId),N=s.useEditorStore(q=>q.selectedSchemaName),p=s.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:f,refetch:y,data:I}=s.useDashboardCardQuery(k),{setTriggerAIRun:C,setCurrentAssitantScope:B,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:F,connectionType:E,selectedDatamodelId:M}=s.useEditorAside(),S=(ne=s.useDashboardQuery().data)==null?void 0:ne.assistantProfileId,{messages:O,setMessages:R,regenerate:_,error:G,sendMessage:V,status:J,addToolResult:X,stop:ie,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:S,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:ae,onFinish({isAbort:q,isDisconnect:Q,isError:xe}){n(""),console.log(q?"[Editor Assistant] Stream aborted by user":Q?"[Editor Assistant] Stream disconnected (network error)":xe?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});w.useEffect(()=>{D&&v&&(V({role:"user",parts:[{type:"text",text:v}]}),C(!1))},[D,v,V,C]);async function ae({toolCall:q}){var Q,xe,re,fe,ce,K,de,z,le,pe,be,ve,ge,Ee,we,Ce;if(["createChartFromSql","createForecast"].includes(q.toolName)){const W=((Q=q.input)==null?void 0:Q.sql)??((xe=q.args)==null?void 0:xe.sql),oe=((re=q.input)==null?void 0:re.python)??((fe=q.args)==null?void 0:fe.python),ue=((ce=q.input)==null?void 0:ce.chartType)??((K=q.args)==null?void 0:K.chartType);j(ue),h(W),m(oe),x(!0),X({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){X({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}X({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:o,python:u||""}})}else if(q.toolName==="generateQueryConfig"){n("Generating query config...");const W=((de=q.input)==null?void 0:de.chartType)??((z=q.args)==null?void 0:z.chartType),oe=((le=q.input)==null?void 0:le.queryConfig)??((pe=q.args)==null?void 0:pe.queryConfig);((be=q.input)==null?void 0:be.cardConfig)??((ve=q.args)==null||ve.cardConfig),j(W),A(oe),h(void 0),m(void 0);const ue=await y();if((ge=ue==null?void 0:ue.data)!=null&&ge.error){X({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:oe,message:(Ee=ue==null?void 0:ue.data)==null?void 0:Ee.error.message}});return}if((we=ue==null?void 0:ue.data)!=null&&we.records){X({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:oe,message:"The data has been visualized"}});return}X({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:oe,message:"The data has been visualized",records:(Ce=ue==null?void 0:ue.data)==null?void 0:Ce.records}})}else n("Analyzing...")}function Y(q){const Q=s.removeFromScopeArray(g,q);$(Q)}function $(q){const Q=s.sanitizeAIScope(q);B(Q),R(xe=>[...xe,{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:N||"",tableName:L||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(F),connectionId:T||"",connectionType:E||""},Q=s.dedup([...g,q]);$(Q)}function H(){const q={databaseName:P||"",schemaName:N||"",tableName:L||"",datamodelName:s.resolveDatamodelName(F),connectionId:T||"",connectionType:E||"",datamodelId:M||""};if(!s.isInAiScopeArray([...p||[],...g],q)||g.length===0){const xe=s.dedup([...p||[],...g,q]).filter(re=>re.connectionId===q.connectionId);$(xe)}}const Z=!["ready","error"].includes(J),te=s.getErrorMessage(G);return{messages:O,setMessages:R,sendMessage:V,regenerate:_,isLoading:Z,handleSetAIScope:H,handleAddCurrentTableToScope:ee,removeFromCurrentSelections:Y,currentAssitantScope:g,setCurrentAssitantScope:B,stop:ie,status:J,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:te,clearError:se}}const zn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function gs({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=w.useRef(null),[l,c]=w.useState(!1),[i,o]=w.useState(s.isDevEnv),[d,u]=w.useState(!1),[m,h]=w.useState(!1),[x,j]=w.useState(!1),b=t??x,g=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:D}=s.useQueueActions(),{clearFileAttachments:k}=s.useFileActions(),P=s.useFileAttachments("editor"),L=s.useDashboardStore(W=>W.dashboard.aiContext),T=s.useEditorStore(W=>W.card.dataSource),N=s.useEditorStore(W=>W.actions.setCardSql),p=s.useEditorStore(W=>W.actions.setRunSql),f=s.useEditorStore(W=>W.showAIDialog),y=s.useDashboardStore(W=>W.handleOpenAssistantProfile),{setShowAIDialog:I,setCardPython:C}=s.useEditorActions(),{setDataSource:B}=s.useEditorActions(),{assistantProfile:A}=s.useAssistantProfile(),{messages:F,setMessages:E,sendMessage:M,isLoading:S,stop:O,status:R,llmUsage:_,errorMessage:G,clearError:V}=Rn(),[J,X]=w.useState(""),ie=W=>{X(W.target.value)},se=W=>{W.preventDefault();const oe=J.trim();if(!oe&&P.length===0)return;const ue=[];oe&&ue.push({type:"text",text:oe}),P.forEach(De=>{De.data&&ue.push({type:"file",mediaType:De.type,filename:De.name,url:`data:${De.type};base64,${De.data}`})}),M({role:"user",parts:ue}),X(""),k("editor"),Q({force:!0})},{visibleMessages:ae,hasMoreMessages:Y,totalMessageCount:$,loadMoreMessages:ee,resetMessageWindow:H}=s.useMessageWindow(F,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Z,isAtBottom:te,hasNewMessages:ne,newMessageCount:q,scrollToBottom:Q,handleScroll:xe,resetNewMessageCount:re}=s.useAutoScroll(ae,{threshold:50,behavior:"smooth",isStreaming:S});w.useEffect(()=>{var W;f&&((W=r.current)==null||W.focus(),v({selectedEntities:(T==null?void 0:T.selectedEntities)||[]}))},[f,T,v]),s.useAutoSubmitQueue({assistantType:"editor",status:R,isLoading:S,sendMessage:M});const{hasActiveTools:fe}=s.useActiveToolStatus(F),ce=w.useCallback(W=>{a==null||a(W),t===void 0&&j(W)},[t,a]);w.useEffect(()=>{if(!b)return;function W(oe){oe.key==="Escape"&&ce(!1)}return window.addEventListener("keydown",W),()=>{window.removeEventListener("keydown",W)}},[b,ce]);const K=w.useCallback(W=>{M({role:"user",parts:[{type:"text",text:W}]}),Q({force:!0})},[M,Q]),de=w.useCallback(async()=>{const W=JSON.stringify(F??[],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(oe){console.error("Failed to copy conversation",oe),s.ue.error("Unable to copy conversation")}},[F]),z=w.useCallback(()=>{ce(!b)},[b,ce]);function le(W,oe){oe==="sql"?(N(W),p(!0)):oe==="python"&&(C(W),p(!0))}function pe(){g.selectedEntities.length===0&&v({selectedEntities:(L==null?void 0:L.selectedEntities)||[]})}function be(W){pe();const oe={role:"user",parts:[{type:"text",text:W.title+" "+W.subtitle}]};M(oe)}function ve(W){pe(),M({role:"user",parts:[{type:"text",text:W}]})}function ge(){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 we=(J==null?void 0:J.length)===0&&(F==null?void 0:F.filter(W=>W.role==="user").length)===0,Ce=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(),y&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:y,children:(A==null?void 0:A.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[ge(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:de,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:z,children:b?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{E([]),D("editor"),V(),H()},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:()=>{I(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:Z,className:"mt-2 flex w-full grow basis-0",onScroll:xe,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:ee,className:"text-xs",children:["Load ",Math.min(5,$-ae.length)," ","more messages (",$-ae.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:ae,showTools:i,handleRun:le,showSystemMessage:d,onQuickReply:K,disableQuickReplies:S}),!fe&&e.jsx(s.AssistantStatus,{status:R,errorMessage:G})]})}),!te&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{Q({force:!0}),re()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ne&&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:[we&&!A&&e.jsx(s.Placeholders,{onClick:be,placeholders:zn}),e.jsx("div",{children:we&&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:X,stop:O,input:J,handleInputChange:ie,handleSubmit:W=>{pe(),se(W),Q({force:!0})},isLoading:S,status:R,assistantType:"editor",onFocus:()=>{}})]}),_&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",_.inputTokens," prompt tokens, ",_.outputTokens," ","completion tokens, ",_.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(T==null?void 0:T.selectedEntities)||[],open:m,onOpenChange:h,dataSource:T||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&n?ct.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:Ce})}),n):Ce}function ss(t,a){const[n,r]=w.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return w.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}const qn="chart-selector-standard-first";function $n(){const[t,a]=ss(qn,!0);return{standardFirst:t,updatePreference:a}}const js=({pluginVisual:t,index:a,onSelect:n})=>{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:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):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}-${a}`)},bs=["default","standardPlugin","customPlugin"];function Gn({selectedChart:t,onChartChange:a}){var L;const[n,r]=w.useState(!1),{data:l}=Us();$n();const i=((L=s.useEditorStore(T=>T.card).customCardPreferences)==null?void 0:L.url)||"";Je(i);const{setCardType:o,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(T=>T.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:x}=s.useEditorActions(),[j,b]=ss("chart-section-active",null),g=w.useMemo(()=>j?[j,...bs.filter(T=>T!==j)]:bs,[j]);function v(T){m(null),d({}),o(T),["custom","map"].includes(T)&&(u(!0),x(void 0)),a(T),r(!1)}function D(T){m(null),d({}),o("custom"),h({type:"component",visualType:"single",url:T.url,componentName:T.name,icon:T.icon,pluginChartType:T.chartType}),x(void 0),a("custom"),r(!1)}const k=()=>{var N;if(t==="custom"){const p=s.useEditorStore.getState().card;return((N=p==null?void 0:p.customCardPreferences)==null?void 0:N.componentName)||"Custom Visual"}const T=s.chartTypes.find(p=>p.id===t);return(T==null?void 0:T.label)||"Select chart type"},P=()=>{var N,p;if(t==="custom"){const f=s.useEditorStore.getState().card,y=(N=f==null?void 0:f.customCardPreferences)==null?void 0:N.icon,I=(p=f==null?void 0:f.customCardPreferences)==null?void 0:p.componentName;if(y&&I)return e.jsx(Un,{icon:y,componentName:I});if(I){const C=s.getAutoDetectedChartIcon(I);if(C)return C}return e.jsx(Le,{className:"h-4 w-4"})}const T=s.chartTypes.find(f=>f.id===t);if(T){const f=T.icon;return e.jsx(f,{className:"h-4 w-4"})}return e.jsx(Le,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[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:j==="default",onCheckedChange:N=>b(N?"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(N=>{const p=N.icon;return e.jsx(s.CommandItem,{value:`${N.label} ${N.id} chart graph visualization`,onSelect:()=>v(N.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(p,{className:"h-4 w-4"}),e.jsx("span",{children:N.label})]})},N.id)})},"default");if(T==="standardPlugin"){const N=l.filter(p=>p.pluginType==="standard");return N.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:j==="standardPlugin",onCheckedChange:p=>b(p?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:N.filter(p=>p.componentType==="chart").map((p,f)=>e.jsx(js,{pluginVisual:p,index:f,onSelect:()=>D(p)},`${p.url}-${p.name}-${f}`))},"standardPlugin"):null}if(T==="customPlugin"){const N=l.filter(p=>p.pluginType==="custom");return N.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:j==="customPlugin",onCheckedChange:p=>b(p?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:N.map((p,f)=>e.jsx(js,{pluginVisual:p,index:f,onSelect:()=>D(p)},`${p.url}-${p.name}-${f}`))},"customPlugin"):null}return null})]})]})})]})})}const Un=({icon:t,componentName:a})=>{const n=ze(),r=s.getAutoDetectedChartIcon(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Le,{className:"h-4 w-4"})},Kn=[{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 _n({selectedChart:t,onChartChange:a}){var l;const n=s.useEditorStore(c=>c.card),r=((l=n==null?void 0:n.config)==null?void 0:l.pivotByColumns)&&n.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:Kn.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:()=>a(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 ts=({dataType:t})=>{const a=s.getDataType(t);return a==="string"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(s.Type,{className:"h-3 w-3"})}):a==="number"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(s.Hash,{className:"h-3 w-3"})}):a==="date"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):a==="boolean"?e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(s.ToggleLeft,{className:"h-3 w-3"})}):e.jsx("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(s.Type,{className:"h-3 w-3"})})};function Hn({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=w.useState(t),[l,c]=w.useState(!1),i=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.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?n: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&&n!==t?(a(n),c(!1)):u.key==="Escape"&&(r(t),c(!1))},"aria-label":"Edit alias template"}),l&&n!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),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 Jn({valueAliases:t,onValueAliasesChange:a}){const[n,r]=w.useState(null),[l,c]=w.useState(""),[i,o]=w.useState(""),d=()=>{a({...t,"":""})},u=h=>{const x={...t};delete x[h],a(x)},m=h=>{const x={...t};delete x[h],x[l]=i,a(x),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,x],j)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:i,onChange:b=>o(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?m(h):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),c(h),o(x)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),c(h),o(x)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+j)),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 Qn({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),c=l?r.indexOf(l):-1;function i(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Ws,{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(Ys,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&i(),["pie","doughnut"].includes(a)&&o()]})}function Wn({field:t,searchQuery:a="",limit:n=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,a,n],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:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},m={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",m);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const x=t.name;return((h==null?void 0:h.records)||[]).map(b=>{const g=b[x]||b[t.alias||x]||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 Yn({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:c}){var P,L;const i=!!l,[o,d]=w.useState(i?"values":"fields"),[u,m]=w.useState(""),[h,x]=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]:[]}),j=n.filter(T=>{var p;return i?!1:!((p=r==null?void 0:r.conditions)==null?void 0:p.some(f=>f.field.id===T.id))&&T.label.toLowerCase().includes(u.toLowerCase())}),b=T=>{x({...h,field:T}),d("values")},g=()=>{if(h.field&&h.selectedValues.length>0){const T={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let N;if(i){const p=((r==null?void 0:r.conditions)||[]).map(f=>f.id===l.id?T:f);N={...r,conditions:p}}else{const p=(r==null?void 0:r.conditions)||[];N={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...p,T],groups:[]}}c(N),a(!1)}},v=()=>{if(!i||!l)return;const T=((r==null?void 0:r.conditions)||[]).filter(N=>N.id!==l.id);if(T.length>0){const N={...r,conditions:T};c(N)}else c(void 0);a(!1)},D=T=>{x({...h,selectedValues:T})},k=()=>{i&&l?(x({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(x({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return w.useEffect(()=>{t&&k()},[t,i,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(P=h.field)==null?void 0:P.label}`:o==="fields"?"Select Field to Filter":`Select Values for ${(L=h.field)==null?void 0:L.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=>m(T.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:j.map(T=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(T),children:[e.jsx(ts,{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))}),j.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),j.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Xn,{field:h.field,selectedValues:h.selectedValues,onValuesChange:D,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:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:g,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Xn({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,c]=w.useState(""),{values:i,isLoading:o,isFetching:d}=Wn({field:t,searchQuery:l,limit:500}),u=l?i.filter(x=>String(x.value).toLowerCase().includes(l.toLowerCase())):i,m=x=>{const j=a.includes(x);n(j?a.filter(b=>b!==x):[...a,x])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(x=>x.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:l,onChange:x=>c(x.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:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(x=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(x.value),children:[e.jsx(s.Checkbox,{checked:a.includes(x.value),onCheckedChange:()=>m(x.value)}),e.jsx(Ze,{className:"text-sm",children:x.label})]},x.id))})]})]})}function Zn({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:c=!1,cardType:i}){var ns,rs,ls,os;const{attributes:o,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:x}=s.useSortable({id:t.id}),j=s.useEditorStore(U=>U.card),{updateLabel:b,handleAggregationChange:g,handleDateFormatChange:v,handleGranularityChange:D,handleAliasTemplateChange:k,handleValueAliasesChange:P,removeField:L,handleKpiComparisonTypeChange:T,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:p,handleKpiTrendlineGranularityChange:f,handleKpiTargetValueChange:y}=Ye(j),[I,C]=w.useState(!1),[B,A]=w.useState(!1),[F,E]=w.useState(null),[M,S]=w.useState(t.dateFormat||"YYYY-MM-DD"),[O,R]=w.useState(t.customFormat||""),[_,G]=w.useState(!!t.customFormat),[V,J]=w.useState(t.granularity||"day"),[X,ie]=w.useState(t.aliasTemplate||""),[se,ae]=w.useState(t.valueAliases||{}),[Y,$]=w.useState((ns=t.parameters)==null?void 0:ns.filters),ee=U=>{U==="custom"?G(!0):(G(!1),S(U),a==="groupBy"&&v(n,U,""))},H=U=>{R(U),a==="groupBy"&&v(n,"custom",U)},Z=U=>{var je;J(U);const he=(je=s.getDateFormatOptionsForGranularity(U)[0])==null?void 0:je.value;he&&!_&&(S(he),a==="groupBy"&&v(n,he,"")),a==="groupBy"&&D(n,U)},te=U=>{ie(U),a==="metrics"&&k(n,U)},ne=U=>{ae(U),a==="metrics"&&P(n,U)},q=U=>{b(a,n,U)},Q=U=>{var me;if($(U),a==="metrics"){const he={...t,parameters:{...t.parameters,filters:U}},je=[...((me=j.config)==null?void 0:me.metricColumns)||[]];je[n]=he,s.useEditorStore.getState().actions.updateCardConfig(j.id,{metricColumns:je})}A(!1)},xe=()=>{L(a,n)},re={transform:s.CSS.Transform.toString(m),transition:h},fe=s.getDataType(t.dataType),ce=fe==="date",K=i==="kpi",de=s.getDateFormatOptionsForGranularity(V),z=a!=="pivotBy",le=ce&&a==="groupBy"&&(!K||((rs=j.config)==null?void 0:rs.comparisonType)==="start_vs_end"),pe=!K&&ce&&a==="groupBy",be=K&&ce&&a==="groupBy",ve=K&&a==="metrics"&&((ls=j.config)==null?void 0:ls.comparisonType)==="target",ge=a==="metrics",Ee=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:U=>{U.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),we=()=>z?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ne,{value:t.label??"",onSave:q,placeholder:"Display label...",type:"text"})]}):null,Ce=()=>le?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:V,onValueChange:Z,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(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U,children:s.toTitleCase(U)},U))})]})]}):null,W=()=>pe?e.jsxs(e.Fragment,{children:[Ce(),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:_?"custom":M,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:de.map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.value))})]}),_&&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:O,onChange:U=>{U.stopPropagation(),H(U.target.value)},onClick:U=>U.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 U,me,he,je,Se;return be?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:"Comparison Type"}),e.jsxs(s.Select,{value:((U=j.config)==null?void 0:U.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"})]})]})]}),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:((me=j.config)==null?void 0:me.showTrendline)||!1,onCheckedChange:N})]})}),((he=j.config)==null?void 0:he.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:((je=j.config)==null?void 0:je.trendlineWindow)||30,onChange:Me=>{const it=parseInt(Me.target.value)||30;p(it)},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:((Se=j.config)==null?void 0:Se.trendlineGranularity)||"day",onValueChange:f,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"})]})]})]})]})]}):null},ue=()=>{var U,me;return ve?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:((U=j.config)==null?void 0:U.targetValue)!==void 0&&((me=j.config)==null?void 0:me.targetValue)!==null?String(j.config.targetValue):"",onSave:he=>{!isNaN(Number(he))&&he!==null?y(Number(he)):y(0)},placeholder:"Enter target value...",type:"text"})]}):null},De=()=>ge?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:U=>{g(n,U)},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(U=>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(U),A(!0)},children:[e.jsxs("span",{className:"font-medium",children:[U.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(U.value)?U.value.length===1?String(U.value[0]):U.value.length<=2?U.value.join(", "):`${U.value.slice(0,2).join(", ")} +${U.value.length-2}`:String(U.value)})}),Array.isArray(U.value)&&U.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 (",U.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:U.value.map((me,he)=>e.jsx("div",{children:String(me)},he))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:me=>{var je;me.stopPropagation();const he=Y.conditions.filter(Se=>Se.id!==U.id);if(he.length>0){const Se={...Y,conditions:he};Q(Se)}else if($(void 0),a==="metrics"){const Se={...t,parameters:{...t.parameters,filters:void 0}},Me=[...((je=j.config)==null?void 0:je.metricColumns)||[]];Me[n]=Se,s.useEditorStore.getState().actions.updateCardConfig(j.id,{metricColumns:Me})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},U.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(Qn,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Hn,{aliasTemplate:X,onAliasTemplateChange:te}),e.jsx(Jn,{valueAliases:se,onValueAliasesChange:ne})]})]}):null,{columns:lt=[]}=s.useColumns(),ot=(Y==null?void 0:Y.conditions)&&Y.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:re,...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 ${x?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ts,{dataType:fe}),e.jsx(Ze,{className:s.cn("w-[140px] flex-1 text-sm",ot&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((os=Y==null?void 0:Y.conditions)==null?void 0:os.length)&&!I&&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(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),C(!I)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${I?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const me=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",me),l(me)},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:U=>{U.stopPropagation(),xe()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),I&&e.jsxs("div",{className:"space-y-3",children:[Ee(),we(),i==="kpi"&&Ce(),W(),oe(),ue(),De()]})]}),B&&e.jsx(Yn,{open:B,onOpenChange:U=>{A(U),U||E(null)},availableFields:lt,existingFilters:Y,editingCondition:F,onSave:U=>{var me;if(U)Q(U);else if($(void 0),a==="metrics"){const he={...t,parameters:{...t.parameters,filters:void 0}},je=[...((me=j.config)==null?void 0:me.metricColumns)||[]];je[n]=he,s.useEditorStore.getState().actions.updateCardConfig(j.id,{metricColumns:je})}E(null)}})]})}function er({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Oe({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:c=!1,activeField:i=null}){const{isOver:o,setNodeRef:d}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.card.type),x=a.length>0,j=w.useMemo(()=>!i||!o?!0:Fe(i,t,h).isValid,[i,o,t,h]),b=(v,D)=>{var P;!((P=m.config)!=null&&P.sortByColumns)||m.config.sortByColumns.findIndex(L=>L.id===v)===-1||u(m.id,v,{direction:D})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),g&&e.jsx(er,{concept:t})]}),e.jsx("div",{ref:d,className:s.cn("rounded-lg border-2 border-dashed p-1 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":o&&j,"border-red-500 bg-red-50 dark:bg-red-950":o&&!j,"border-blue-200 bg-blue-50/30 dark:border-blue-800 dark:bg-blue-950/30":!o&&x,"min-h-[60px] border-muted-foreground/20 bg-background":!o&&!x}),children:a.length===0?e.jsx("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:r}):e.jsx(s.SortableContext,{items:a.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((v,D)=>{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(Zn,{field:v,zone:t,index:D,sortDirection:P,onSortDirectionChange:L=>b(v.id,L),hasPivotColumns:c,cardType:h})})},v.id)})})})})]})}const vs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],sr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Ge({value:t,onChange:a,label:n}){const[r,l]=w.useState(!1),[c,i]=w.useState(!1),o=()=>{const d=vs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:vs[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 ${n}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:sr.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:()=>{a(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{i(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),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(Xs,{color:o(),onColorChange:d=>{a(d),i(!1)},onClose:()=>i(!1)})})]})]})}const ys={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 tr(){var x,j,b,g,v,D,k,P,L,T,N;const t=s.useEditorStore(p=>p.card),{setCardPreferences:a}=s.useEditorActions(),n=((x=t.config)==null?void 0:x.metricColumns)||[],r=((j=t.config)==null?void 0:j.groupByColumns)||[],l=n.length===2&&r.length===0,c=n.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=p=>{var y;const f={...t.preferences,kpiVisualOptions:{...(y=t.preferences)==null?void 0:y.kpiVisualOptions,metricComparison:{...o,...p}}};a(f)},u=c||o.enabled,m=((v=t.config)==null?void 0:v.comparisonType)||"none",h=m==="previous_period"||m==="same_period_last_year"||m==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:p=>d({enabled:p,...p&&!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 p=o.calculationType||"difference",f=ys[p];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:f==null?void 0:f.label}),e.jsx("p",{children:f==null?void 0:f.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:f==null?void 0:f.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",f==null?void 0:f.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:p=>d({calculationType:p}),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(ys).map(([p,f])=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:f.label},p))})]})]}),e.jsx(es,{formatOptions:o.formatOptions||{},onFormatOptionsChange:p=>d({formatOptions:p}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||l)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"right",onValueChange:p=>d({position:p}),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:p=>d({showArrow:p})}),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:p=>d({showColor:p})}),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:((D=o.colorConfig)==null?void 0:D.increase)||"green",onChange:p=>d({colorConfig:{...o.colorConfig,increase:p}}),label:"Primary > Secondary"}),e.jsx(Ge,{value:((k=o.colorConfig)==null?void 0:k.decrease)||"red",onChange:p=>d({colorConfig:{...o.colorConfig,decrease:p}}),label:"Primary < Secondary"}),e.jsx(Ge,{value:((P=o.colorConfig)==null?void 0:P.noChange)||"neutral",onChange:p=>d({colorConfig:{...o.colorConfig,noChange:p}}),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:p=>d({conditionalLabel:p})}),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:((L=o.conditionalLabels)==null?void 0:L.increase)??"Increase",onChange:p=>d({conditionalLabels:{...o.conditionalLabels,increase:p.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:p=>d({conditionalLabels:{...o.conditionalLabels,decrease:p.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:((N=o.conditionalLabels)==null?void 0:N.noChange)??"No change",onChange:p=>d({conditionalLabels:{...o.conditionalLabels,noChange:p.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:p=>d({labelName:p.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function ar(){var l,c;const t=s.useEditorStore(i=>i.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((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}};a(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(es,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function nr({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const c=s.useEditorStore(v=>{var D;return((D=v.card.customCardPreferences)==null?void 0:D.url)&&v.card.type==="custom"}),i=s.useEditorStore(v=>v.card),o=i==null?void 0:i.type,d=t.length>0||n.length>0,u=o!=="kpi"||n.length<=2,m=o!=="kpi",h=o!=="kpi"&&d,x=["pie","doughnut","polar","funnel","aggregateTable"].includes(o),j=m&&!x,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(Oe,{zone:"groupBy",fields:t,label:b().label,placeholder:b().placeholder,activeField:l}),j&&e.jsx(Oe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Oe,{zone:"metrics",fields:n,label:g().label,placeholder:g().placeholder,hasPivotColumns:a.length>0,activeField:l}),h&&e.jsx(Oe,{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(ar,{}),e.jsx(tr,{}),e.jsx(Zs,{}),e.jsx(et,{}),e.jsx(st,{}),e.jsx(tt,{})]})})]})]})}function rr({onEditJoins:t}){const a=s.useEditorStore(o=>o.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const c=o=>!o||o.length===0?"No conditions":o.map(d=>{var x,j,b,g;const u=`${(x=d.source)==null?void 0:x.entityName}.${(j=d.source)==null?void 0:j.name}`,m=`${(b=d.target)==null?void 0:b.entityName}.${(g=d.target)==null?void 0:g.name}`,h=d.operator||"=";return`${u} ${h} ${m}`}).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(Ut,{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),m=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children: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:m?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},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 Ns={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function lr({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:i}){var p,f;const[o,d]=w.useState(()=>Ns.getItem("chart-selector-expanded")==="true"),[u,m]=w.useState(!1),h=s.useEditorStore(y=>y.card),x=s.useEditorStore(y=>y.actions.updateCardConfig),j=n.length>0||r.length>0||l.length>0,{data:b,autoJoinMetadata:g}=s.useDashboardCardQuery(h),v=((p=h==null?void 0:h.config)==null?void 0:p.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),D=((f=h==null?void 0:h.dataSource)==null?void 0:f.selectedEntities)||[],k=y=>{x(h.id,{...h==null?void 0:h.config,joinPlan:y}),m(!1)},P=()=>{x(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),m(!1)},L=()=>{m(!1)},T=()=>{m(!0)};w.useEffect(()=>{Ns.setItem("chart-selector-expanded",String(o))},[o]);const N=()=>{d(y=>!y)};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(Gn,{selectedChart:t,onChartChange:a})}),e.jsxs("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center gap-1",children:[e.jsx(_n,{selectedChart:t,onChartChange:a}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:N,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:j||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(rr,{onEditJoins:T}),e.jsx(nr,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:c,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(He,{open:u,onOpenChange:m,joinPlan:v,availableDataSources:D,onSave:k,onCancel:L,onRemove:P,children:e.jsx("div",{})})]})}function or({initialFilters:t,availableFields:a}={}){const[n,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=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=T=>{const N=p=>{if(p.id===T){const f=o[0]||d,y=s.getDataType(f.dataType)==="date";return{...p,conditions:[...p.conditions,{id:`condition-${Date.now()}`,field:f,operator:y?"between":"=",value:y?[]:""}]}}return{...p,groups:p.groups.map(N)}};r(N(n))},m=T=>{const N=p=>{if(p.id===T){const f=o[0]||d,y=s.getDataType(f.dataType)==="date";return{...p,groups:[...p.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:f,operator:y?"between":"=",value:y?[]:""}],groups:[]}]}}return{...p,groups:p.groups.map(N)}};r(N(n))},h=(T,N)=>{const p=f=>f.id===T?{...f,conditions:f.conditions.filter(y=>y.id!==N)}:{...f,groups:f.groups.map(p)};r(p(n))},x=(T,N)=>{const p=f=>f.id===T?{...f,groups:f.groups.filter(y=>y.id!==N)}:{...f,groups:f.groups.map(p)};r(p(n))},j=(T,N,p,f)=>{if(p==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const y=I=>I.id===T?{...I,conditions:I.conditions.map(C=>C.id===N?{...C,[p]:f}:C)}:{...I,groups:I.groups.map(y)};r(y(n))},b=(T,N,p)=>{const f=y=>y.id===T?{...y,conditions:y.conditions.map(I=>I.id===N?{...I,...p}:I)}:{...y,groups:y.groups.map(f)};r(f(n))},g=(T,N)=>{const p=f=>f.id===T?{...f,logicalOperator:N}:{...f,groups:f.groups.map(p)};r(p(n))},v=(T,N)=>{const p=f=>f.id===T?{...f,negate:N}:{...f,groups:f.groups.map(p)};r(p(n))},D=(T,N,p)=>{const f=y=>y.id===T?{...y,conditions:s.arrayMove(y.conditions,N,p)}:{...y,groups:y.groups.map(f)};r(f(n))},k=(T,N,p)=>{const f=y=>y.id===T?{...y,groups:s.arrayMove(y.groups,N,p)}:{...y,groups:y.groups.map(f)};r(f(n))},P=T=>{if(!T||T.conditions.length===0&&T.groups.length===0)return"-- No filters defined";const N=f=>{let y="";typeof f.field=="object"?y=f.field.entityName?`${f.field.entityName}.${f.field.name}`:f.field.name:y=String(f.field);const I=f.operator;let C=f.value;if(f.field.dataType==="string"&&!["in","not in"].includes(f.operator))typeof C=="string"?C=`'${C}'`:Array.isArray(C)&&(C=`'${C.join(", ")}'`);else if(f.field.dataType==="date"||f.field.dataType==="datetime"||f.field.dataType==="timestamp")if(f.operator==="between"&&Array.isArray(C)&&C.length===2){const B=C[0]?`'${C[0]}'`:"NULL",A=C[1]?`'${C[1]}'`:"NULL";return`${y} BETWEEN ${B} AND ${A}`}else if((f.operator==="in"||f.operator==="not in")&&Array.isArray(C)){const B=C.map(A=>A?`'${A}'`:"NULL").join(", ");return`${y} ${I} (${B})`}else typeof C=="string"||C instanceof Date?C=`'${C}'`:Array.isArray(C)&&C.length>0&&(C=`'${C[0]}'`);else if(["in","not in"].includes(f.operator)){let B=[];Array.isArray(C)?B=C.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof C=="string"?B=C.split(",").map(A=>{const F=A.trim();return f.field.dataType==="string"?`'${F}'`:F}):typeof C=="number"&&(B=[String(C)]),C=`(${B.join(", ")})`}switch(I){case"contains":return typeof C=="string"?`${y} LIKE '%${C.replace(/'/g,"")}'`:`${y} LIKE '%${String(C)}'`;case"startsWith":return typeof C=="string"?`${y} LIKE '${C.replace(/'/g,"")}%'`:`${y} LIKE '${String(C)}%'`;case"endsWith":return typeof C=="string"?`${y} LIKE '%${C.replace(/'/g,"")}'`:`${y} LIKE '%${String(C)}'`;case"isNull":return`${y} IS NULL`;case"isNotNull":return`${y} IS NOT NULL`;default:return`${y} ${I} ${C}`}},p=f=>{const y=f.conditions.map(N),I=f.groups.map(F=>p(F)),C=[...y,...I].filter(Boolean);if(C.length===0)return"";const B=C.join(` ${f.logicalOperator} `),A=C.length>1?`(${B})`:B;return f.negate?`NOT ${A}`:A};return p(T)},L=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:o,isLoading:c,addCondition:u,addGroup:m,removeCondition:h,removeGroup:x,updateCondition:j,updateConditionFields:b,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:D,reorderGroups:k,generateSQLPreview:P,hasAnyFilters:L}}function ir({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const cr=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"})}},dr=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function ur({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[c,i]=w.useState(!1),o=w.useMemo(()=>{const d={};return n.forEach(u=>{const m=dr(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open: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(ir,{children:[t.entityName,".",t.name]})}):r,e.jsx(ht,{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(([m,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[cr(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((x,j)=>e.jsxs(s.CommandItem,{value:x.id,onSelect:()=>{a(x),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)===x.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:x.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:x.description&&e.jsx("span",{children:x.description})})]})]},x.id+j))]},`${d}-${m}`))},d))})]})})]})}function as(t){var g;const a=s.useEditorStore(v=>v.card),{authToken:n,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]},m=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:h,isPending:x,error:j}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:a.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:x,error:j}}function mr({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[c,i]=Ue.useState(!1),{filterValues:o}=as(t),d=m=>{n(a.filter(h=>h!==m))},u=m=>{a.includes(m)?n(a.filter(h=>h!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open: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:a.length>0?a.map(m=>{const h=o.find(x=>x.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:x=>{x.key==="Enter"&&d(m)},onMouseDown:x=>{x.preventDefault(),x.stopPropagation()},onClick:x=>{x.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:o.map((m,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+h))})]})]})})]})})}function hr({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:c,isPending:i,error:o}=as(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:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:c.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function xr({value:t,operator:a,onChange:n,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(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,a]),o=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),n([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),n([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:o,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const pr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],fr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],gr=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],jr=["=","!=","isNull","isNotNull"],br=["between","isNull","isNotNull"],vr={"=":"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 Cs(t){return vr[t]||s.titleCase(t)}function yr(t){switch(t){case"string":return fr;case"number":return gr;case"boolean":return jr;case"date":return br;default:return pr}}function at({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:c,onUpdateGroupOperator:i,availableFields:o,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:x,transition:j,isDragging:b}=s.useSortable({id:t.id}),{isPending:g,error:v}=as(t.field),D={transform:s.CSS.Transform.toString(x),transition:j};return e.jsxs("div",{ref:h,style:D,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:k=>i(n,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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(ur,{value:t.field,onValueChange:k=>{const P=k,L=s.getDataType(P.dataType)==="date";d(n,t.id,{field:P,value:"",operator:L?"between":"="})},availableFields:o,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:k=>{k==="in"||k==="not in"?d(n,t.id,{operator:k,value:[]}):k==="isNull"||k==="isNotNull"?d(n,t.id,{operator:k,value:null}):d(n,t.id,{operator:k,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Cs(t.operator):""})}),e.jsx(s.SelectContent,{children:yr(s.getDataType(t.field.dataType)).map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k,children:Cs(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(mr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(k=>typeof k=="string")?t.value:[],onChange:k=>d(n,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(n,t.id,{value:k.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(hr,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:k=>d(n,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(n,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(xr,{value:t.value,operator:t.operator,onChange:k=>d(n,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(n,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(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Nr({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:c,onUpdateCondition:i,onUpdateField:o,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:x,availableFields:j,renderFilterGroup:b,updateConditionFields:g}){const{attributes:v,listeners:D,setNodeRef:k,transform:P,transition:L,isDragging:T}=s.useSortable({id:t.id}),N={transform:s.CSS.Transform.toString(P),transition:L},p=y=>{const{active:I,over:C}=y;if(C&&I.id!==C.id){const B=t.conditions.findIndex(F=>F.id===I.id),A=t.conditions.findIndex(F=>F.id===C.id);B!==-1&&A!==-1&&u(t.id,B,A)}},f=y=>{const{active:I,over:C}=y;if(C&&I.id!==C.id&&n){const B=t.groups.findIndex(F=>F.id===I.id),A=t.groups.findIndex(F=>F.id===C.id);B!==-1&&A!==-1&&m(n,B,A)}};return e.jsxs("div",{ref:k,style:N,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${T?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...D,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:y=>r(t.id,y),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&c(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:p,children:e.jsx(s.SortableContext,{items:t.conditions.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((y,I)=>e.jsx(at,{condition:y,index:I,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:o,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:j,updateConditionFields:g},y.id))})}),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.groups.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(y=>b(y,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Cr({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:c,availableFields:i,isLoading:o,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:x,updateConditionFields:j,updateGroupOperator:b,updateGroupNegate:g,reorderConditions:v,reorderGroups:D,generateSQLPreview:k,hasAnyFilters:P,setCurrentFilters:L}=or({initialFilters:t,availableFields:a}),T=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[N,p]=w.useState(!1),f=(C,B,A)=>{const F=E=>E.id===C?{...E,conditions:E.conditions.map(M=>M.id===B?{...M,field:A,dataType:A.dataType}:M)}:{...E,groups:E.groups.map(F)};L(F(c))},y=(C,B=0,A)=>B===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:F=>{const{active:E,over:M}=F;if(M&&E.id!==M.id){const S=C.conditions.findIndex(R=>R.id===E.id),O=C.conditions.findIndex(R=>R.id===M.id);S!==-1&&O!==-1&&v(C.id,S,O)}},children:e.jsx(s.SortableContext,{items:C.conditions.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:C.conditions.map((F,E)=>e.jsx(at,{condition:F,index:E,groupId:C.id,groupLogicalOperator:C.logicalOperator,onUpdateCondition:x,onUpdateField:f,onRemoveCondition:m,onUpdateGroupOperator:b,availableFields:i,updateConditionFields:j},F.id))})}),e.jsx(s.DndContext,{sensors:T,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:M}=F;if(M&&E.id!==M.id){const S=C.groups.findIndex(R=>R.id===E.id),O=C.groups.findIndex(R=>R.id===M.id);S!==-1&&O!==-1&&D(C.id,S,O)}},children:e.jsx(s.SortableContext,{items:C.groups.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:C.groups.map(F=>y(F,B+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"]}),N&&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(Nr,{group:C,depth:B,parentGroupId:A,onUpdateGroupOperator:b,onUpdateGroupNegate:g,onRemoveGroup:h,onUpdateCondition:x,onUpdateField:f,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:D,onAddCondition:d,onAddGroup:u,availableFields:i,renderFilterGroup:y,updateConditionFields:j},C.id),I=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..."})]}):y(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:N,onCheckedChange:C=>p(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"}),I>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(P?c:null),children:"Apply Filters"})]})]})}function Sr({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:c,onOpenChange:i}){const o=u=>{n(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(Cr,{filters:a,availableFields:l,onSave:o,onCancel:()=>i(!1),onClearAll:d})]})]})}function wr({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var v,D;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=(D=i==null?void 0:i.dataSource)==null?void 0:D.semanticDomainId,{data:m}=We(u),h=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],x=w.useCallback(k=>k.startsWith("card-")?null:k.startsWith("source-")||a.find(P=>P.id===k)?"source":n("groupBy").find(P=>P.id===k)?"groupBy":n("metrics").find(P=>P.id===k)?"metrics":n("pivotBy").find(P=>P.id===k)?"pivotBy":n("sortBy").find(P=>P.id===k)?"sortBy":null,[a,n]),j=w.useCallback(k=>{c(k.active.id)},[]),b=w.useCallback(k=>{var y;const{active:P,over:L}=k;if(!L||!t){c(null);return}const T=P.id,N=L.id,p=x(T),f=x(N)||N;if(f==="sortBy"){if(p==="source"){const I=a.find(B=>B.id===T);if(!I){c(null);return}if(!(n("groupBy").some(B=>B.name===I.name&&B.qualifiedEntityName===I.qualifiedEntityName)||n("metrics").some(B=>B.name===I.name&&B.qualifiedEntityName===I.qualifiedEntityName))){c(null);return}}else if(p==="pivotBy"){c(null);return}else if(p!=="groupBy"&&p!=="metrics"&&p!=="sortBy"){c(null);return}}if(p==="source"&&f==="sortBy"){const I=[...a].find(F=>F.id===T);if(!I){c(null);return}const C=n("sortBy");if(s.fieldAlreadyExists(I,C)){c(null);return}const B=Fe(I,"sortBy",i.type);if(!B.isValid){s.ue.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3}),c(null);return}const A=s.getNewField(I,"sortBy",C);c(null),r("sortBy",[...C,A]);return}if(p==="source"&&f!=="source"&&f!=="sortBy"){const I=[...a].find(M=>M.id===T);if(!I){c(null);return}const C=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(C.length>0){const M=C[0].qualifiedEntityName;if(!M){c(null);return}if(M!==I.qualifiedEntityName&&I.qualifiedEntityName)if(u&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(I,{joinabilityMap:m.joinabilityMap,selectedFields:C,baseEntityName:(y=d==null?void 0:d.baseEntity)==null?void 0:y.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!d){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(M,I.qualifiedEntityName,d)){s.showJoinRequiredNotification(),c(null);return}}}const B=n(f);if(s.fieldAlreadyExists(I,B)){c(null);return}const A=Fe(I,f,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),c(null);return}const F=s.getNewField(I,f,B),E=[...B,F];c(null),r(f,E),f==="metrics"&&t&&_e(i.type,i.config,o,t,E);return}if(p&&f&&p!=="source"&&f!=="source"&&p!==f){const I=n(p),C=n(f),B=I.find(S=>S.id===T);if(!B){c(null);return}const A=Fe(B,f,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),c(null);return}const F=s.getNewField(B,f,C);if(c(null),f==="sortBy"){s.fieldAlreadyExists(B,C)||r(f,[...C,F]);return}const E=I.filter(S=>S.id!==T),M=[...C,F];r(p,E),r(f,M),f==="metrics"&&t&&_e(i.type,i.config,o,t,M);return}if(p&&f&&p===f&&p!=="source"){const I=n(p),C=I.findIndex(A=>A.id===T),B=I.findIndex(A=>A.id===N);if(C!==B){const A=s.arrayMove(I,C,B);r(p,A)}}c(null)},[t,a,n,r,x,d,u,m,i.type,o,i.config]),g=l?h.find(k=>k.id===l):null;return{activeId:l,activeField:g,handleDragStart:j,handleDragEnd:b}}function Dr({activeView:t,onViewChange:a}){const n=s.useEditorStore(i=>i.card),{config:r}=w.useContext(s.SemaphorContext).tokenProps,l=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(n);return e.jsx(s.Tabs,{value:t,onValueChange:i=>a(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"}),n.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 kr=[{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 Tr(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=w.useState(!1),[l,c]=w.useState(""),i=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},o=m=>{const h=m.target.value;c(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange: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:kr.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Er({isOpen:t,onClose:a}){const n=Ds(a,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(m=>m.card),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),i=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.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:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(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 Ir({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:c,columns:i,columnsLoading:o,columnsError:d}){var Y,$,ee;const u=s.useEditorStore(H=>H.card),m=s.useDashboardStore(H=>H.filterValues);m!=null&&m.length;const{updateCardConfig:h,setCard:x,updateCardInFrame:j,setCardId:b,setShowAIDialog:g}=s.useEditorActions(),{updateCardId:v}=s.useDashboardActions(),[D,k]=w.useState(null),P=s.useEditorStore(H=>H.showAIDialog),L=s.useDashboardStore(H=>H.isVisualEditing),[T,N]=w.useState(!1),[p,f]=w.useState(!1),[y,I]=w.useState(null),{isConsoleMode:C}=s.useDashboardPreferences(),{config:B}=w.useContext(s.SemaphorContext).tokenProps,A=(B==null?void 0:B.showInfoTab)!==!1,F=s.useEditorStore(H=>{var Z;return((Z=H.card.customCardPreferences)==null?void 0:Z.url)&&H.card.type==="custom"}),{data:E,errorMessage:M,isLoading:S,isFetching:O,errorSql:R,pagination:_,refetch:G}=s.useDashboardCardQuery(c),[V,J]=w.useState(!1);w.useEffect(()=>{O||J(!1)},[O]);const X=(H,Z)=>{const te={...c,paginationConfig:{page:H+1,pageSize:Z}};x(te),j(te)};function ie(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(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 se=H=>{if(!u.config)return;if(!H.length){h(u.id,{...u.config,sortByColumns:[]});return}const Z=u.config,te=H.map(({id:ne,desc:q})=>{var fe,ce;const Q=(fe=Z.metricColumns)==null?void 0:fe.find(K=>K.label===ne),xe=(ce=Z.groupByColumns)==null?void 0:ce.find(K=>K.label===ne),re=Q||xe;return re?{id:s.getFieldId("sortBy",re),name:re.name,dataType:re.dataType,label:re.label,qualifiedEntityName:re.qualifiedEntityName,entityId:re.entityId,entityName:re.entityName,entityType:re.entityType,role:"sortby",direction:q?"desc":"asc"}:null}).filter(ne=>ne!==null);h(u.id,{...Z,sortByColumns:te})},ae=w.useMemo(()=>{var H,Z;return(Z=(H=u.config)==null?void 0:H.sortByColumns)==null?void 0:Z.map(te=>({id:te.label,desc:te.direction==="desc"}))},[(Y=u.config)==null?void 0:Y.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":P&&L}),children:[n&&ie(),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"&&P&&e.jsx(Ks,{variant:"outline"}),e.jsx(Dr,{activeView:t,onViewChange:a}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:($=c.config)==null?void 0:$.filters,cardFilterCount:s.getFilterCount(((ee=c.config)==null?void 0:ee.filters)||null),onFiltersClick:l}),e.jsx("div",{className:"ml-2",children:e.jsx(Tr,{})}),P&&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:S||O,onClick:()=>{J(!0),G()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":V})})}),t==="chart"&&e.jsx(_s,{}),!P&&e.jsx(s.IconButton,{onClick:()=>g(!P),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!T&&F&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>N(!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 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(Hs,{})}),t==="table"&&(E==null?void 0:E.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:(E==null?void 0:E.records)||[],paginationMetadata:_,onPaginationChange:X,isLoading:S||O,onSortChange:se,sortState:ae})}),t==="info"&&A&&e.jsx("div",{className:"px-6",children:e.jsxs("div",{className:"rounded-md bg-background",children:[e.jsxs("div",{className:"mb-2",children:[C&&e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID:"}),e.jsx(s.EditableText,{value:u.id,onSave:H=>{const Z=s.sanitizeCardId(H);if(!Z){k("Card ID cannot be empty");return}const te=v(u.id,Z);if(te.success){b(Z);const ne={...u,id:Z};x(ne),j(ne),k(null),s.ue.success("Card ID updated successfully")}else k(te.error||"Failed to update Card ID"),s.ue.error(te.error||"Failed to update Card ID")},isEditable:!0,placeholder:"Enter card ID",displayClassName:"font-mono text-xs text-muted-foreground hover:text-foreground",inputClassName:"font-mono text-xs"}),e.jsx(s.CopyButton,{text:u.id,className:"h-5 w-5"})]}),D&&e.jsx("p",{className:"text-xs text-destructive",children:D})]}),M||R?e.jsx(Rs,{error:M,errorSql:R,onSendFeedback:()=>{const H=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:c.dataSource,dashboardFilters:m,errorMessage:M,errorSql:R,generatedSql:E==null?void 0:E.sql});I(H),f(!0)}}):e.jsxs(e.Fragment,{children:[(E==null?void 0:E.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(zs,{sql:E==null?void 0:E.sql,error:M,errorSql:R})]})]})})]}),e.jsx(Er,{isOpen:T,onClose:()=>N(!1)}),y&&e.jsx(s.FeedbackDialog,{open:p,onOpenChange:f,feedbackData:y})]})]})}function Ar({activeField:t}){const[a,n]=w.useState(!0);return w.useEffect(()=>{t&&n(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(ts,{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 Fr=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Lr(){var R,_;const[t,a]=w.useState("chart"),[n,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(!0),d=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:m}=s.useEditorActions(),h=s.useEditorStore(G=>G.card.type);w.useEffect(()=>Fr(),[]);const x=G=>{m(G)},j=s.useEditorStore(G=>G.frame),b=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:g,removeCard:v,updateCard:D,setActiveCard:k,updateFilters:P}=s.useEditorActions(),{columns:L=[],isLoading:T,error:N}=s.useColumns(),p=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),f=b,{getFieldsForContainer:y,setFieldsForContainer:I}=Ye(f),{activeField:C,handleDragStart:B,handleDragEnd:A}=wr({activeCardId:j.activeCardId,sourceFields:L,getFieldsForContainer:y,setFieldsForContainer:I}),F=(G,V)=>{V&&P(G,V)},E=G=>{var V;D(G,{config:{...(V=j.cards.find(J=>J.id===G))==null?void 0:V.config,filters:void 0}})},M=L,S=G=>{if(!G)return 0;let V=G.conditions.length;return G.groups.forEach(J=>{V+=S(J)}),V},O=S(((R=f==null?void 0:f.config)==null?void 0:R.filters)||null);return e.jsxs(s.DndContext,{sensors:p,collisionDetection:s.closestCenter,onDragStart:B,onDragEnd:A,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Vs,{isVisible:i,onToggleVisibility:()=>o(!i)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(lr,{selectedChart:h,onChartChange:x,groupByFields:y("groupBy"),pivotByFields:y("pivotBy"),metricsFields:y("metrics"),sortByFields:y("sortBy"),activeField:C}),e.jsx(Ir,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>c(!0),filterCount:O,activeCard:f,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:L,columnsLoading:T,columnsError:N,getFieldsForContainer:y,cards:j.cards,activeCardId:j.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"})})})]}),f&&e.jsx(Sr,{cardId:f.id,filters:((_=f.config)==null?void 0:_.filters)||null,onFiltersChange:F,onClearFilters:E,availableFields:M,isOpen:l,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ar,{activeField:C||null})})]})}function Mr({authToken:t,onSave:a,onClose:n}){const r=w.useRef(null),l=s.useEditorStore(N=>N.showAIDialog),c=s.useEditorStore(N=>N.isDevMode),i=s.useAssistantLayoutStore(N=>N.setFullscreen),o=s.useAssistantLayoutStore(N=>N.setPanelOpen),d=s.useAssistantLayoutStore(N=>N.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),x=m==="editor",j=w.useCallback(N=>{d("editor",N)},[d]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:g,setOnSave:v,setOnClose:D}=s.useEditorActions(),{setActiveAssistantType:k}=s.useAIActions();w.useEffect(()=>{a&&v(a),n&&D(n)},[a,v,n,D]),w.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),w.useEffect(()=>{var N,p;l?((N=r.current)==null||N.resize(40),o("editor",!0),k("editor")):((p=r.current)==null||p.resize(0),o("editor",!1),m==="editor"&&i(null),k(null))},[l,o,k,i,m]);function P(N){N<1?(g(!1),o("editor",!1),m==="editor"&&i(null),k(null)):(l||(g(!0),k("editor")),u.isOpen||o("editor",!0))}function L(){return e.jsxs(e.Fragment,{children:[e.jsx(Vs,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Vn,{})}),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(gs,{isFullscreen:x,onFullscreenChange:N=>i(N?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:j,className:s.cn("absolute inset-0",!x&&"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",x&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Lr,{})}),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(gs,{isFullscreen:x,onFullscreenChange:N=>i(N?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:j,className:s.cn("absolute inset-0",!x&&"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:L()}):T()})}function Pr(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(i=>i.actions),n=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function l(i){t&&(r(t,i),a(!1))}function c(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Mr,{onSave:l,onClose:c})})}function Br(){Os();const t=s.useDashboardStore(d=>d.selectedSheetId),a=s.useDashboardStore(d=>d.selectedFrameId),n=s.useDashboardStore(d=>d.dashboard),r=s.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:c}=s.useEditorActions(),i=s.useEditorStore(d=>d.card.dataSource);return w.useEffect(()=>{var u,m;let d=r();if(!d){const h=(u=n==null?void 0:n.sheets)==null?void 0:u.find(j=>j.id===t),x=(m=h==null?void 0:h.frames)==null?void 0:m[0];x&&(l(x.id),d=x)}if(d){const h=d.cards.find(x=>x.id===d.activeCardId);h&&c(h)}},[r,t,a,n,l,c]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function Or(){const t=s.useDashboardStore(n=>n.actions.setShowFilters),{hasEntities:a}=Br();return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[e.jsx(s.Label,{className:"px-2 text-base",children:"Dashboard Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),!a&&e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),a&&e.jsx("div",{className:"flex grow",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(Bs,{context:"filter"})})})})]})}function Vr(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Rr(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Vr,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Or,{})})]})}function zr(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function nt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4 py-2",children:[e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"space-y-3 pt-2",children:[...Array(3)].map((t,a)=>e.jsxs("div",{className:"flex gap-3 animate-pulse",children:[e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex-shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 w-2/3 rounded bg-muted"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted"})]})]},a))})]})})}const qr=t=>{const a=s.useDashboardStore(l=>l.isVisualEditing),n=s.useDashboardStore(l=>l.selectedFrameId),r=s.useEditorStore(l=>l.frame);return!!(a&&n&&(r==null?void 0:r.visualId)===t)};function $r({visual:t,isDeleting:a,isDuplicating:n,onAddVisual:r,onOpenVisual:l,onEditDetails:c,onDeleteClick:i,onDuplicateVisual:o,onShareVisual:d,formatDate:u}){var T,N,p,f;const{selectVisual:m}=s.useManagementActions(),h=s.useIsVisualSelected(t.id),x=qr(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),b=w.useRef(null),[g,v]=w.useState(!1),[D,k]=w.useState(!1);w.useEffect(()=>{n?(v(!0),k(!0)):D&&(v(!1),k(!1))},[n,D]),w.useEffect(()=>{x&&b.current&&b.current.scrollIntoView({behavior:"smooth",block:"center"})},[x]);const P=()=>e.jsx(Re,{className:"h-4 w-4"}),L=()=>{m(t),l==null||l(t)};return e.jsx(s.Card,{ref:b,className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",x?"border-purple-500":h&&"border-primary"),onClick:L,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children: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",h&&"visible"),onClick:y=>y.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:y=>{y.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:y=>{y.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:y=>{y.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),l==null||l(t)},children:[e.jsx(Ct,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),o(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),c==null||c(t)},children:[e.jsx(s.PenLine,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.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:y=>{y.stopPropagation(),i(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((N=t.ownership.createdBy)==null?void 0:N.type)==="tenant"||((p=t.ownership.createdBy)==null?void 0:p.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((f=t.ownership.createdBy)==null?void 0:f.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 Gr({open:t,onOpenChange:a,onSubmit:n,isCreating:r}){const[l,c]=w.useState(""),[i,o]=w.useState("");w.useEffect(()=>{t||(c(""),o(""))},[t]);const d=()=>{l.trim()&&n({title:l,description:i})},u=m=>{a(m)};return e.jsx(s.Dialog,{open:t,onOpenChange:u,children:e.jsxs(s.DialogContent,{children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create New Visual"}),e.jsx(s.DialogDescription,{children:"Add a new visual to your library. You can configure it after creation."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",children:"Visual Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:m=>c(m.target.value),disabled:r,onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),d())}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:i,onChange:m=>o(m.target.value),disabled:r})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>u(!1),disabled:r,children:"Cancel"}),e.jsx(s.Button,{onClick:d,disabled:!l.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Visual"})]})]})})}function Ur(){const[t,a]=w.useState(""),[n,r]=w.useState(!1),[l,c]=w.useState(!1),[i,o]=w.useState(null),[d,u]=w.useState(!1),[m,h]=w.useState(null),[x,j]=w.useState(null),[b,g]=w.useState(null),{selectVisual:v}=s.useManagementActions(),{handleEditLibraryVisual:D,handleAddLibraryVisual:k}=ke(),{resources:P,isLoading:L,isError:T,createResource:N,updateResource:p,deleteResource:f,duplicateResource:y,isCreating:I,isDeleting:C}=s.useVisualManagement(()=>{u(!1),h(null)},$=>{r(!1),$&&(v($),D($))});s.useCurrentUserInfo();const B=P.filter($=>{var ee,H;return((ee=$==null?void 0:$.title)==null?void 0:ee.toLowerCase().includes(t.toLowerCase()))||((H=$==null?void 0:$.description)==null?void 0:H.toLowerCase().includes(t.toLowerCase()))}),A=$=>new Date($).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),F=$=>{N({title:$.title,description:$.description,isPrivate:!1})},E=$=>{h($),u(!0)},M=()=>{m&&f(m.id)},{startUpdating:S,stopUpdating:O,isUpdating:R}=s.useResourceUpdateState(),_=($,ee,H)=>{var q;const Z=Object.fromEntries(Object.entries(ee).filter(([,Q])=>Q!==void 0));if(Object.keys(Z).length===0){(q=H==null?void 0:H.onSuccess)==null||q.call(H);return}const te=Object.keys(Z),ne=te.length===1?te[0]:void 0;S($,ne),p({resourceId:$,data:Z},{onSuccess:()=>{var Q;O($,ne),(Q=H==null?void 0:H.onSuccess)==null||Q.call(H)},onError:()=>{var Q;O($,ne),(Q=H==null?void 0:H.onError)==null||Q.call(H)}})},G=$=>{j($),y($,{onSettled:()=>j(null)})},V=$=>{D($)},J=$=>{k($)},X=$=>{const ee=P.find(H=>H.id===$);ee&&p({resourceId:$,data:{isPrivate:!ee.isPrivate}})},ie=$=>{o($),c(!0)},se=$=>{g($)},ae=()=>{g(null)},Y=({title:$,description:ee})=>{if(!b)return;const H={};$!==b.title&&(H.title=$),(b.description||"")!==ee&&(H.description=ee),_(b.id,H,{onSuccess:()=>{g(null)}})};return L?e.jsx(nt,{}):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:$=>a($.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:B.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"]})]}):B.map($=>e.jsx($r,{visual:$,onAddVisual:J,onOpenVisual:V,onEditDetails:se,onDeleteClick:E,onDuplicateVisual:G,onTogglePrivacy:X,onShareVisual:ie,isDeleting:C,isDuplicating:x===$.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:R(b.id)}),e.jsx(s.AlertDialog,{open:d,onOpenChange:$=>{!$&&C||(u($),$||h(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:C,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:$=>{$.preventDefault(),$.stopPropagation(),M()},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(Gr,{open:n,onOpenChange:r,onSubmit:F,isCreating:I}),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 Kr({dashboard:t,isDeleting:a,isDuplicating:n,onLoadDashboard:r,onEditDetails:l,onDeleteClick:c,onDuplicateDashboard:i,onShareDashboard:o,formatDate:d,onDashboardItemClick:u}){var k,P;const{selectDashboard:m}=s.useManagementActions(),h=s.useIsDashboardSelected(t.id),{userContext:x,isLoading:j}=s.useCurrentUserInfo(),b=((k=x==null?void 0:x.permissions)==null?void 0:k.canEdit)??!1,g=j||!b,v=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4"}),D=()=>{m(t),r(t.id),u==null||u(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",h&&"border-primary"),onClick:D,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:"flex min-w-0 flex-1 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",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:"line-clamp-2 flex-1 text-xs text-muted-foreground",title:t.description||"No description",children:(P=t.description)!=null&&P.trim()?t.description:"No description"}),e.jsx(s.DashboardActionsMenu,{dashboard:t,isDeleting:a,isDuplicating:n,shouldHideActions:g,onEditDetails:l,onDeleteClick:c,onDuplicateDashboard:i,onShareDashboard:o,formatDate:d})]})]})]})},t.id)}function _r({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 Hr(t){var ce;const{onLoadDashboard:a,onEditDashboard:n,onDashboardItemClick:r}=t,[l,c]=w.useState(""),[i,o]=w.useState(!1),[d,u]=w.useState(!1),[m,h]=w.useState(null),[x,j]=w.useState(!1),[b,g]=w.useState(null),[v,D]=w.useState(null),[k,P]=w.useState(null),L=s.useManagementStore(K=>K.lastSelectedDashboard),T=s.useManagementStore(K=>K.selectedDashboard),N=s.useManagementStore(K=>K.actions.selectDashboard),p=s.useManagementStore(K=>K.actions.clearSelectedDashboard),{tokenProps:f,id:y}=s.useSemaphorContext();s.useRoleAwareDisplayPreferences();const{onCreateSuccess:I}=s.useDashboardCreation({onDashboardSelect:r}),{resources:C,isLoading:B,isError:A,createResource:F,updateResource:E,deleteResource:M,duplicateResource:S,isCreating:O,isDeleting:R,refetch:_}=s.useDashboardManagement(()=>{j(!1);const K=b==null?void 0:b.id;g(null),(T==null?void 0:T.id)===K&&(!(f!=null&&f.dashboard_id)&&!y?p():L&&L.id!==K&&N(L))},K=>{o(!1),I(K,_)}),{currentUser:G,userContext:V}=s.useCurrentUserInfo(),J=((ce=V==null?void 0:V.permissions)==null?void 0:ce.canCreateDashboard)??!1,X=C.filter(K=>{var de,z;return((de=K==null?void 0:K.title)==null?void 0:de.toLowerCase().includes(l.toLowerCase()))||((z=K==null?void 0:K.description)==null?void 0:z.toLowerCase().includes(l.toLowerCase()))}),ie=K=>new Date(K).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),se=K=>{F({title:K.title,description:K.description,isPrivate:!1})},ae=K=>{a==null||a(K)},Y=K=>{g(K),j(!0)},$=()=>{b&&M(b.id)},ee=K=>{D(K),S(K,{onSettled:()=>D(null)})},{startUpdating:H,stopUpdating:Z,isUpdating:te}=s.useResourceUpdateState(),ne=(K,de,z)=>{var ve;const le=Object.fromEntries(Object.entries(de).filter(([,ge])=>ge!==void 0));if(Object.keys(le).length===0){(ve=z==null?void 0:z.onSuccess)==null||ve.call(z);return}const pe=Object.keys(le),be=pe.length===1?pe[0]:void 0;H(K,be),E({resourceId:K,data:le},{onSuccess:()=>{var ge;Z(K,be),(ge=z==null?void 0:z.onSuccess)==null||ge.call(z)},onError:()=>{var ge;Z(K,be),(ge=z==null?void 0:z.onError)==null||ge.call(z)}})},q=K=>{const de=C.find(z=>z.id===K);de&&E({resourceId:K,data:{isPrivate:!de.isPrivate}})},Q=K=>{h(K),G==null||G.type,u(!0)},xe=K=>{n==null||n(K.id),P(K)},re=()=>{P(null)},fe=({title:K,description:de})=>{if(!k)return;const z={};K!==k.title&&(z.title=K),(k.description||"")!==de&&(z.description=de),ne(k.id,z,{onSuccess:()=>{P(null)}})};return B?e.jsx(nt,{}):A?e.jsx(_r,{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:K=>c(K.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:X.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":J?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),J&&!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"]})]}):X.map(K=>e.jsx(Kr,{dashboard:K,isDeleting:R,isDuplicating:v===K.id,onLoadDashboard:ae,onEditDetails:xe,onDeleteClick:Y,onDuplicateDashboard:ee,onTogglePrivacy:q,onShareDashboard:Q,formatDate:ie,onDashboardItemClick:r},K.id))})}),d&&m&&e.jsx(s.ShareDialog,{resource:m,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:x,onOpenChange:K=>{!K&&R||(j(K),K||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:R,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:K=>{K.preventDefault(),K.stopPropagation(),$()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:R,children:[R?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"}),R?"Deleting...":"Delete"]})]})]})}),k&&e.jsx(s.ResourceEditDialog,{open:!!k,resourceLabel:"Dashboard",initialTitle:k.title||"",initialDescription:k.description||"",onClose:re,onSave:fe,isSaving:te(k.id)}),e.jsx(s.CreateDashboardDialog,{open:i,onOpenChange:o,onSubmit:se,isCreating:O}),J&&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 rt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(N=>N.dashboard);const c=s.useDashboardStore(N=>N.isDashboardEditing),{setDashboard:i,addSheet:o}=s.useDashboardStore(N=>N.actions),{currentUser:d}=s.useCurrentUserInfo(),u=d,{permissions:m}=s.useRoleAwareDisplayPreferences(),x=s.useSelectedDashboard()&&m.canAccessVisuals&&c,j="dashboards",[b,g]=ss("resource-management-active-tab",j);w.useEffect(()=>{c&&x&&g("visuals")},[c,x,g]);const v=x?b:"dashboards",D=l==="overlay",k=Ds(a,{enabled:t&&D}),P=s.cn("flex h-full flex-col border-r bg-background",D?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",n),L=N=>{},T=N=>{console.log("Editing dashboard:",N)};return e.jsx(s.TooltipProvider,{children:(!D||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:a,tooltip:"Close Sidebar",children:e.jsx(Pt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:v,onValueChange:x?g:void 0,className:"flex h-9 grow flex-col",children:[x&&e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(Hr,{onLoadDashboard:L,onEditDashboard:T,onDashboardItemClick:r})}),x&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(Ur,{})})]})})]})})}function Jr({showControls:t=!1,showFooter:a=!0,...n}){const r=s.useDashboardStore(x=>x.isDashboardPanelOpen);s.useDashboardStore(x=>x.isVisualEditing);const l=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),c=20,i=20,o=30,d=r,u=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(c),m.current.resize(100-c)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:h}=n;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:h,children:[e.jsx(zr,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Ca,{}),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(rt,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{className:s.cn("",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-c:100,minSize:d?40:100,children:e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(Pr,{}),e.jsx(Rr,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Fs;exports.DashboardPlus=Jr;exports.ResourceManagementPanel=rt;exports.ScheduleDashboard=Ts;exports.VisualBadge=Es;exports.VisualEditingControls=As;exports.cleanCard=ks;exports.getDashbaordStateWithoutData=Ve;